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