nss_util.cc revision f2477e01787aa58f445919b809d89e252beef54f
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "crypto/nss_util.h"
6#include "crypto/nss_util_internal.h"
7
8#include <nss.h>
9#include <pk11pub.h>
10#include <plarena.h>
11#include <prerror.h>
12#include <prinit.h>
13#include <prtime.h>
14#include <secmod.h>
15
16#if defined(OS_LINUX)
17#include <linux/nfs_fs.h>
18#include <sys/vfs.h>
19#elif defined(OS_OPENBSD)
20#include <sys/mount.h>
21#include <sys/param.h>
22#endif
23
24#include <vector>
25
26#include "base/cpu.h"
27#include "base/debug/alias.h"
28#include "base/debug/stack_trace.h"
29#include "base/environment.h"
30#include "base/file_util.h"
31#include "base/files/file_path.h"
32#include "base/files/scoped_temp_dir.h"
33#include "base/lazy_instance.h"
34#include "base/logging.h"
35#include "base/memory/scoped_ptr.h"
36#include "base/metrics/histogram.h"
37#include "base/native_library.h"
38#include "base/strings/stringprintf.h"
39#include "base/threading/thread_checker.h"
40#include "base/threading/thread_restrictions.h"
41#include "build/build_config.h"
42
43// USE_NSS means we use NSS for everything crypto-related.  If USE_NSS is not
44// defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
45// use NSS for crypto or certificate verification, and we don't use the NSS
46// certificate and key databases.
47#if defined(USE_NSS)
48#include "base/synchronization/lock.h"
49#include "crypto/crypto_module_blocking_password_delegate.h"
50#endif  // defined(USE_NSS)
51
52namespace crypto {
53
54namespace {
55
56#if defined(OS_CHROMEOS)
57const char kNSSDatabaseName[] = "Real NSS database";
58
59// Constants for loading the Chrome OS TPM-backed PKCS #11 library.
60const char kChapsModuleName[] = "Chaps";
61const char kChapsPath[] = "libchaps.so";
62
63// Fake certificate authority database used for testing.
64static const base::FilePath::CharType kReadOnlyCertDB[] =
65    FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
66#endif  // defined(OS_CHROMEOS)
67
68std::string GetNSSErrorMessage() {
69  std::string result;
70  if (PR_GetErrorTextLength()) {
71    scoped_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
72    PRInt32 copied = PR_GetErrorText(error_text.get());
73    result = std::string(error_text.get(), copied);
74  } else {
75    result = base::StringPrintf("NSS error code: %d", PR_GetError());
76  }
77  return result;
78}
79
80#if defined(USE_NSS)
81base::FilePath GetDefaultConfigDirectory() {
82  base::FilePath dir = file_util::GetHomeDir();
83  if (dir.empty()) {
84    LOG(ERROR) << "Failed to get home directory.";
85    return dir;
86  }
87  dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
88  if (!file_util::CreateDirectory(dir)) {
89    LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
90    dir.clear();
91  }
92  return dir;
93}
94
95// On non-Chrome OS platforms, return the default config directory. On Chrome OS
96// test images, return a read-only directory with fake root CA certs (which are
97// used by the local Google Accounts server mock we use when testing our login
98// code). On Chrome OS non-test images (where the read-only directory doesn't
99// exist), return an empty path.
100base::FilePath GetInitialConfigDirectory() {
101#if defined(OS_CHROMEOS)
102  base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
103  if (!base::PathExists(database_dir))
104    database_dir.clear();
105  return database_dir;
106#else
107  return GetDefaultConfigDirectory();
108#endif  // defined(OS_CHROMEOS)
109}
110
111// This callback for NSS forwards all requests to a caller-specified
112// CryptoModuleBlockingPasswordDelegate object.
113char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
114  crypto::CryptoModuleBlockingPasswordDelegate* delegate =
115      reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
116  if (delegate) {
117    bool cancelled = false;
118    std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
119                                                     retry != PR_FALSE,
120                                                     &cancelled);
121    if (cancelled)
122      return NULL;
123    char* result = PORT_Strdup(password.c_str());
124    password.replace(0, password.size(), password.size(), 0);
125    return result;
126  }
127  DLOG(ERROR) << "PK11 password requested with NULL arg";
128  return NULL;
129}
130
131// NSS creates a local cache of the sqlite database if it detects that the
132// filesystem the database is on is much slower than the local disk.  The
133// detection doesn't work with the latest versions of sqlite, such as 3.6.22
134// (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561).  So we set
135// the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
136// detection when database_dir is on NFS.  See http://crbug.com/48585.
137//
138// TODO(wtc): port this function to other USE_NSS platforms.  It is defined
139// only for OS_LINUX and OS_OPENBSD simply because the statfs structure
140// is OS-specific.
141//
142// Because this function sets an environment variable it must be run before we
143// go multi-threaded.
144void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) {
145#if defined(OS_LINUX) || defined(OS_OPENBSD)
146  struct statfs buf;
147  if (statfs(database_dir.value().c_str(), &buf) == 0) {
148#if defined(OS_LINUX)
149    if (buf.f_type == NFS_SUPER_MAGIC) {
150#elif defined(OS_OPENBSD)
151    if (strcmp(buf.f_fstypename, MOUNT_NFS) == 0) {
152#endif
153      scoped_ptr<base::Environment> env(base::Environment::Create());
154      const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
155      if (!env->HasVar(use_cache_env_var))
156        env->SetVar(use_cache_env_var, "yes");
157    }
158  }
159#endif  // defined(OS_LINUX) || defined(OS_OPENBSD)
160}
161
162#endif  // defined(USE_NSS)
163
164// A singleton to initialize/deinitialize NSPR.
165// Separate from the NSS singleton because we initialize NSPR on the UI thread.
166// Now that we're leaking the singleton, we could merge back with the NSS
167// singleton.
168class NSPRInitSingleton {
169 private:
170  friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
171
172  NSPRInitSingleton() {
173    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
174  }
175
176  // NOTE(willchan): We don't actually execute this code since we leak NSS to
177  // prevent non-joinable threads from using NSS after it's already been shut
178  // down.
179  ~NSPRInitSingleton() {
180    PL_ArenaFinish();
181    PRStatus prstatus = PR_Cleanup();
182    if (prstatus != PR_SUCCESS)
183      LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
184  }
185};
186
187base::LazyInstance<NSPRInitSingleton>::Leaky
188    g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
189
190// This is a LazyInstance so that it will be deleted automatically when the
191// unittest exits.  NSSInitSingleton is a LeakySingleton, so it would not be
192// deleted if it were a regular member.
193base::LazyInstance<base::ScopedTempDir> g_test_nss_db_dir =
194    LAZY_INSTANCE_INITIALIZER;
195
196// Force a crash with error info on NSS_NoDB_Init failure.
197void CrashOnNSSInitFailure() {
198  int nss_error = PR_GetError();
199  int os_error = PR_GetOSError();
200  base::debug::Alias(&nss_error);
201  base::debug::Alias(&os_error);
202  LOG(ERROR) << "Error initializing NSS without a persistent database: "
203             << GetNSSErrorMessage();
204  LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
205}
206
207class NSSInitSingleton {
208 public:
209#if defined(OS_CHROMEOS)
210  void OpenPersistentNSSDB() {
211    DCHECK(thread_checker_.CalledOnValidThread());
212
213    if (!chromeos_user_logged_in_) {
214      // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
215      // Temporarily allow it until we fix http://crbug.com/70119
216      base::ThreadRestrictions::ScopedAllowIO allow_io;
217      chromeos_user_logged_in_ = true;
218
219      // This creates another DB slot in NSS that is read/write, unlike
220      // the fake root CA cert DB and the "default" crypto key
221      // provider, which are still read-only (because we initialized
222      // NSS before we had a cryptohome mounted).
223      software_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
224                                  kNSSDatabaseName);
225    }
226  }
227
228  void EnableTPMTokenForNSS() {
229    DCHECK(thread_checker_.CalledOnValidThread());
230
231    // If this gets set, then we'll use the TPM for certs with
232    // private keys, otherwise we'll fall back to the software
233    // implementation.
234    tpm_token_enabled_for_nss_ = true;
235  }
236
237  bool InitializeTPMToken(int token_slot_id) {
238    DCHECK(thread_checker_.CalledOnValidThread());
239
240    // If EnableTPMTokenForNSS hasn't been called, return false.
241    if (!tpm_token_enabled_for_nss_)
242      return false;
243
244    // If everything is already initialized, then return true.
245    if (chaps_module_ && tpm_slot_)
246      return true;
247
248    // This tries to load the Chaps module so NSS can talk to the hardware
249    // TPM.
250    if (!chaps_module_) {
251      chaps_module_ = LoadModule(
252          kChapsModuleName,
253          kChapsPath,
254          // For more details on these parameters, see:
255          // https://developer.mozilla.org/en/PKCS11_Module_Specs
256          // slotFlags=[PublicCerts] -- Certificates and public keys can be
257          //   read from this slot without requiring a call to C_Login.
258          // askpw=only -- Only authenticate to the token when necessary.
259          "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
260      if (!chaps_module_ && test_slot_) {
261        // chromeos_unittests try to test the TPM initialization process. If we
262        // have a test DB open, pretend that it is the TPM slot.
263        tpm_slot_ = PK11_ReferenceSlot(test_slot_);
264        return true;
265      }
266    }
267    if (chaps_module_){
268      tpm_slot_ = GetTPMSlotForId(token_slot_id);
269
270      return tpm_slot_ != NULL;
271    }
272    return false;
273  }
274
275  bool IsTPMTokenReady() {
276    // TODO(mattm): Change to DCHECK when callers have been fixed.
277    if (!thread_checker_.CalledOnValidThread()) {
278      DVLOG(1) << "Called on wrong thread.\n"
279               << base::debug::StackTrace().ToString();
280    }
281
282    return tpm_slot_ != NULL;
283  }
284
285  // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
286  // id as an int. This should be safe since this is only used with chaps, which
287  // we also control.
288  PK11SlotInfo* GetTPMSlotForId(CK_SLOT_ID slot_id) {
289    DCHECK(thread_checker_.CalledOnValidThread());
290
291    if (!chaps_module_)
292      return NULL;
293
294    VLOG(1) << "Poking chaps module.";
295    SECStatus rv = SECMOD_UpdateSlotList(chaps_module_);
296    if (rv != SECSuccess)
297      PLOG(ERROR) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
298
299    PK11SlotInfo* slot = SECMOD_LookupSlot(chaps_module_->moduleID, slot_id);
300    if (!slot)
301      LOG(ERROR) << "TPM slot " << slot_id << " not found.";
302    return slot;
303  }
304#endif  // defined(OS_CHROMEOS)
305
306
307  bool OpenTestNSSDB() {
308    DCHECK(thread_checker_.CalledOnValidThread());
309
310    if (test_slot_)
311      return true;
312    if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
313      return false;
314    test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), kTestTPMTokenName);
315    return !!test_slot_;
316  }
317
318  void CloseTestNSSDB() {
319    DCHECK(thread_checker_.CalledOnValidThread());
320
321    if (!test_slot_)
322      return;
323    SECStatus status = SECMOD_CloseUserDB(test_slot_);
324    if (status != SECSuccess)
325      PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
326    PK11_FreeSlot(test_slot_);
327    test_slot_ = NULL;
328    ignore_result(g_test_nss_db_dir.Get().Delete());
329  }
330
331  PK11SlotInfo* GetPublicNSSKeySlot() {
332    // TODO(mattm): Change to DCHECK when callers have been fixed.
333    if (!thread_checker_.CalledOnValidThread()) {
334      DVLOG(1) << "Called on wrong thread.\n"
335               << base::debug::StackTrace().ToString();
336    }
337
338    if (test_slot_)
339      return PK11_ReferenceSlot(test_slot_);
340    if (software_slot_)
341      return PK11_ReferenceSlot(software_slot_);
342    return PK11_GetInternalKeySlot();
343  }
344
345  PK11SlotInfo* GetPrivateNSSKeySlot() {
346    // TODO(mattm): Change to DCHECK when callers have been fixed.
347    if (!thread_checker_.CalledOnValidThread()) {
348      DVLOG(1) << "Called on wrong thread.\n"
349               << base::debug::StackTrace().ToString();
350    }
351
352    if (test_slot_)
353      return PK11_ReferenceSlot(test_slot_);
354
355#if defined(OS_CHROMEOS)
356    if (tpm_token_enabled_for_nss_) {
357      if (IsTPMTokenReady()) {
358        return PK11_ReferenceSlot(tpm_slot_);
359      } else {
360        // If we were supposed to get the hardware token, but were
361        // unable to, return NULL rather than fall back to sofware.
362        return NULL;
363      }
364    }
365#endif
366    // If we weren't supposed to enable the TPM for NSS, then return
367    // the software slot.
368    if (software_slot_)
369      return PK11_ReferenceSlot(software_slot_);
370    return PK11_GetInternalKeySlot();
371  }
372
373#if defined(USE_NSS)
374  base::Lock* write_lock() {
375    return &write_lock_;
376  }
377#endif  // defined(USE_NSS)
378
379  // This method is used to force NSS to be initialized without a DB.
380  // Call this method before NSSInitSingleton() is constructed.
381  static void ForceNoDBInit() {
382    force_nodb_init_ = true;
383  }
384
385 private:
386  friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
387
388  NSSInitSingleton()
389      : tpm_token_enabled_for_nss_(false),
390        chaps_module_(NULL),
391        software_slot_(NULL),
392        test_slot_(NULL),
393        tpm_slot_(NULL),
394        root_(NULL),
395        chromeos_user_logged_in_(false) {
396    base::TimeTicks start_time = base::TimeTicks::Now();
397
398    // It's safe to construct on any thread, since LazyInstance will prevent any
399    // other threads from accessing until the constructor is done.
400    thread_checker_.DetachFromThread();
401
402    DisableAESNIIfNeeded();
403
404    EnsureNSPRInit();
405
406    // We *must* have NSS >= 3.14.3.
407    COMPILE_ASSERT(
408        (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
409        (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
410        (NSS_VMAJOR > 3),
411        nss_version_check_failed);
412    // Also check the run-time NSS version.
413    // NSS_VersionCheck is a >= check, not strict equality.
414    if (!NSS_VersionCheck("3.14.3")) {
415      LOG(FATAL) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
416                    "required. Please upgrade to the latest NSS, and if you "
417                    "still get this error, contact your distribution "
418                    "maintainer.";
419    }
420
421    SECStatus status = SECFailure;
422    bool nodb_init = force_nodb_init_;
423
424#if !defined(USE_NSS)
425    // Use the system certificate store, so initialize NSS without database.
426    nodb_init = true;
427#endif
428
429    if (nodb_init) {
430      status = NSS_NoDB_Init(NULL);
431      if (status != SECSuccess) {
432        CrashOnNSSInitFailure();
433        return;
434      }
435#if defined(OS_IOS)
436      root_ = InitDefaultRootCerts();
437#endif  // defined(OS_IOS)
438    } else {
439#if defined(USE_NSS)
440      base::FilePath database_dir = GetInitialConfigDirectory();
441      if (!database_dir.empty()) {
442        // This duplicates the work which should have been done in
443        // EarlySetupForNSSInit. However, this function is idempotent so
444        // there's no harm done.
445        UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
446
447        // Initialize with a persistent database (likely, ~/.pki/nssdb).
448        // Use "sql:" which can be shared by multiple processes safely.
449        std::string nss_config_dir =
450            base::StringPrintf("sql:%s", database_dir.value().c_str());
451#if defined(OS_CHROMEOS)
452        status = NSS_Init(nss_config_dir.c_str());
453#else
454        status = NSS_InitReadWrite(nss_config_dir.c_str());
455#endif
456        if (status != SECSuccess) {
457          LOG(ERROR) << "Error initializing NSS with a persistent "
458                        "database (" << nss_config_dir
459                     << "): " << GetNSSErrorMessage();
460        }
461      }
462      if (status != SECSuccess) {
463        VLOG(1) << "Initializing NSS without a persistent database.";
464        status = NSS_NoDB_Init(NULL);
465        if (status != SECSuccess) {
466          CrashOnNSSInitFailure();
467          return;
468        }
469      }
470
471      PK11_SetPasswordFunc(PKCS11PasswordFunc);
472
473      // If we haven't initialized the password for the NSS databases,
474      // initialize an empty-string password so that we don't need to
475      // log in.
476      PK11SlotInfo* slot = PK11_GetInternalKeySlot();
477      if (slot) {
478        // PK11_InitPin may write to the keyDB, but no other thread can use NSS
479        // yet, so we don't need to lock.
480        if (PK11_NeedUserInit(slot))
481          PK11_InitPin(slot, NULL, NULL);
482        PK11_FreeSlot(slot);
483      }
484
485      root_ = InitDefaultRootCerts();
486#endif  // defined(USE_NSS)
487    }
488
489    // Disable MD5 certificate signatures. (They are disabled by default in
490    // NSS 3.14.)
491    NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
492    NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
493                           0, NSS_USE_ALG_IN_CERT_SIGNATURE);
494
495    // The UMA bit is conditionally set for this histogram in
496    // chrome/common/startup_metric_utils.cc .
497    HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
498                           base::TimeTicks::Now() - start_time,
499                           base::TimeDelta::FromMilliseconds(10),
500                           base::TimeDelta::FromHours(1),
501                           50);
502  }
503
504  // NOTE(willchan): We don't actually execute this code since we leak NSS to
505  // prevent non-joinable threads from using NSS after it's already been shut
506  // down.
507  ~NSSInitSingleton() {
508    if (tpm_slot_) {
509      PK11_FreeSlot(tpm_slot_);
510      tpm_slot_ = NULL;
511    }
512    if (software_slot_) {
513      SECMOD_CloseUserDB(software_slot_);
514      PK11_FreeSlot(software_slot_);
515      software_slot_ = NULL;
516    }
517    CloseTestNSSDB();
518    if (root_) {
519      SECMOD_UnloadUserModule(root_);
520      SECMOD_DestroyModule(root_);
521      root_ = NULL;
522    }
523    if (chaps_module_) {
524      SECMOD_UnloadUserModule(chaps_module_);
525      SECMOD_DestroyModule(chaps_module_);
526      chaps_module_ = NULL;
527    }
528
529    SECStatus status = NSS_Shutdown();
530    if (status != SECSuccess) {
531      // We VLOG(1) because this failure is relatively harmless (leaking, but
532      // we're shutting down anyway).
533      VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
534    }
535  }
536
537#if defined(USE_NSS) || defined(OS_IOS)
538  // Load nss's built-in root certs.
539  SECMODModule* InitDefaultRootCerts() {
540    SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
541    if (root)
542      return root;
543
544    // Aw, snap.  Can't find/load root cert shared library.
545    // This will make it hard to talk to anybody via https.
546    // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
547    return NULL;
548  }
549
550  // Load the given module for this NSS session.
551  SECMODModule* LoadModule(const char* name,
552                           const char* library_path,
553                           const char* params) {
554    std::string modparams = base::StringPrintf(
555        "name=\"%s\" library=\"%s\" %s",
556        name, library_path, params ? params : "");
557
558    // Shouldn't need to const_cast here, but SECMOD doesn't properly
559    // declare input string arguments as const.  Bug
560    // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
561    // on NSS codebase to address this.
562    SECMODModule* module = SECMOD_LoadUserModule(
563        const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
564    if (!module) {
565      LOG(ERROR) << "Error loading " << name << " module into NSS: "
566                 << GetNSSErrorMessage();
567      return NULL;
568    }
569    if (!module->loaded) {
570      LOG(ERROR) << "After loading " << name << ", loaded==false: "
571                 << GetNSSErrorMessage();
572      SECMOD_DestroyModule(module);
573      return NULL;
574    }
575    return module;
576  }
577#endif
578
579  static PK11SlotInfo* OpenUserDB(const base::FilePath& path,
580                                  const char* description) {
581    const std::string modspec =
582        base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
583                           path.value().c_str(), description);
584    PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
585    if (db_slot) {
586      if (PK11_NeedUserInit(db_slot))
587        PK11_InitPin(db_slot, NULL, NULL);
588    }
589    else {
590      LOG(ERROR) << "Error opening persistent database (" << modspec
591                 << "): " << GetNSSErrorMessage();
592    }
593    return db_slot;
594  }
595
596  static void DisableAESNIIfNeeded() {
597    if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
598      // Some versions of NSS have a bug that causes AVX instructions to be
599      // used without testing whether XSAVE is enabled by the operating system.
600      // In order to work around this, we disable AES-NI in NSS when we find
601      // that |has_avx()| is false (which includes the XSAVE test). See
602      // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
603      base::CPU cpu;
604
605      if (cpu.has_avx_hardware() && !cpu.has_avx()) {
606        base::Environment::Create()->SetVar("NSS_DISABLE_HW_AES", "1");
607      }
608    }
609  }
610
611  // If this is set to true NSS is forced to be initialized without a DB.
612  static bool force_nodb_init_;
613
614  bool tpm_token_enabled_for_nss_;
615  SECMODModule* chaps_module_;
616  PK11SlotInfo* software_slot_;
617  PK11SlotInfo* test_slot_;
618  PK11SlotInfo* tpm_slot_;
619  SECMODModule* root_;
620  bool chromeos_user_logged_in_;
621#if defined(USE_NSS)
622  // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
623  // is fixed, we will no longer need the lock.
624  base::Lock write_lock_;
625#endif  // defined(USE_NSS)
626
627  base::ThreadChecker thread_checker_;
628};
629
630// static
631bool NSSInitSingleton::force_nodb_init_ = false;
632
633base::LazyInstance<NSSInitSingleton>::Leaky
634    g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
635}  // namespace
636
637const char kTestTPMTokenName[] = "Test DB";
638
639#if defined(USE_NSS)
640void EarlySetupForNSSInit() {
641  base::FilePath database_dir = GetInitialConfigDirectory();
642  if (!database_dir.empty())
643    UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
644}
645#endif
646
647void EnsureNSPRInit() {
648  g_nspr_singleton.Get();
649}
650
651void InitNSSSafely() {
652  // We might fork, but we haven't loaded any security modules.
653  DisableNSSForkCheck();
654  // If we're sandboxed, we shouldn't be able to open user security modules,
655  // but it's more correct to tell NSS to not even try.
656  // Loading user security modules would have security implications.
657  ForceNSSNoDBInit();
658  // Initialize NSS.
659  EnsureNSSInit();
660}
661
662void EnsureNSSInit() {
663  // Initializing SSL causes us to do blocking IO.
664  // Temporarily allow it until we fix
665  //   http://code.google.com/p/chromium/issues/detail?id=59847
666  base::ThreadRestrictions::ScopedAllowIO allow_io;
667  g_nss_singleton.Get();
668}
669
670void ForceNSSNoDBInit() {
671  NSSInitSingleton::ForceNoDBInit();
672}
673
674void DisableNSSForkCheck() {
675  scoped_ptr<base::Environment> env(base::Environment::Create());
676  env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
677}
678
679void LoadNSSLibraries() {
680  // Some NSS libraries are linked dynamically so load them here.
681#if defined(USE_NSS)
682  // Try to search for multiple directories to load the libraries.
683  std::vector<base::FilePath> paths;
684
685  // Use relative path to Search PATH for the library files.
686  paths.push_back(base::FilePath());
687
688  // For Debian derivatives NSS libraries are located here.
689  paths.push_back(base::FilePath("/usr/lib/nss"));
690
691  // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
692#if defined(ARCH_CPU_X86_64)
693  paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
694#elif defined(ARCH_CPU_X86)
695  paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
696#elif defined(ARCH_CPU_ARMEL)
697  paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
698#elif defined(ARCH_CPU_MIPSEL)
699  paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
700#endif
701
702  // A list of library files to load.
703  std::vector<std::string> libs;
704  libs.push_back("libsoftokn3.so");
705  libs.push_back("libfreebl3.so");
706
707  // For each combination of library file and path, check for existence and
708  // then load.
709  size_t loaded = 0;
710  for (size_t i = 0; i < libs.size(); ++i) {
711    for (size_t j = 0; j < paths.size(); ++j) {
712      base::FilePath path = paths[j].Append(libs[i]);
713      base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
714      if (lib) {
715        ++loaded;
716        break;
717      }
718    }
719  }
720
721  if (loaded == libs.size()) {
722    VLOG(3) << "NSS libraries loaded.";
723  } else {
724    LOG(ERROR) << "Failed to load NSS libraries.";
725  }
726#endif
727}
728
729bool CheckNSSVersion(const char* version) {
730  return !!NSS_VersionCheck(version);
731}
732
733#if defined(USE_NSS)
734ScopedTestNSSDB::ScopedTestNSSDB()
735  : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
736}
737
738ScopedTestNSSDB::~ScopedTestNSSDB() {
739  // Don't close when NSS is < 3.15.1, because it would require an additional
740  // sleep for 1 second after closing the database, due to
741  // http://bugzil.la/875601.
742  if (NSS_VersionCheck("3.15.1")) {
743    g_nss_singleton.Get().CloseTestNSSDB();
744  }
745}
746
747base::Lock* GetNSSWriteLock() {
748  return g_nss_singleton.Get().write_lock();
749}
750
751AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
752  // May be NULL if the lock is not needed in our version of NSS.
753  if (lock_)
754    lock_->Acquire();
755}
756
757AutoNSSWriteLock::~AutoNSSWriteLock() {
758  if (lock_) {
759    lock_->AssertAcquired();
760    lock_->Release();
761  }
762}
763
764AutoSECMODListReadLock::AutoSECMODListReadLock()
765      : lock_(SECMOD_GetDefaultModuleListLock()) {
766    SECMOD_GetReadLock(lock_);
767  }
768
769AutoSECMODListReadLock::~AutoSECMODListReadLock() {
770  SECMOD_ReleaseReadLock(lock_);
771}
772
773#endif  // defined(USE_NSS)
774
775#if defined(OS_CHROMEOS)
776void OpenPersistentNSSDB() {
777  g_nss_singleton.Get().OpenPersistentNSSDB();
778}
779
780void EnableTPMTokenForNSS() {
781  g_nss_singleton.Get().EnableTPMTokenForNSS();
782}
783
784bool IsTPMTokenReady() {
785  return g_nss_singleton.Get().IsTPMTokenReady();
786}
787
788bool InitializeTPMToken(int token_slot_id) {
789  return g_nss_singleton.Get().InitializeTPMToken(token_slot_id);
790}
791#endif  // defined(OS_CHROMEOS)
792
793base::Time PRTimeToBaseTime(PRTime prtime) {
794  return base::Time::FromInternalValue(
795      prtime + base::Time::UnixEpoch().ToInternalValue());
796}
797
798PRTime BaseTimeToPRTime(base::Time time) {
799  return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
800}
801
802PK11SlotInfo* GetPublicNSSKeySlot() {
803  return g_nss_singleton.Get().GetPublicNSSKeySlot();
804}
805
806PK11SlotInfo* GetPrivateNSSKeySlot() {
807  return g_nss_singleton.Get().GetPrivateNSSKeySlot();
808}
809
810}  // namespace crypto
811