Add some network-related PP_Error codes and conversion function to map net::Error...
[chromium-blink-merge.git] / crypto / nss_util.cc
blobbbbaa70f8221c0cd591e6df2140c42206886df99
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.
5 #include "crypto/nss_util.h"
6 #include "crypto/nss_util_internal.h"
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>
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
24 #include <vector>
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"
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)
49 namespace crypto {
51 namespace {
53 #if defined(OS_CHROMEOS)
54 const char kNSSDatabaseName[] = "Real NSS database";
56 // Constants for loading the Chrome OS TPM-backed PKCS #11 library.
57 const char kChapsModuleName[] = "Chaps";
58 const char kChapsPath[] = "libchaps.so";
60 // Fake certificate authority database used for testing.
61 static const base::FilePath::CharType kReadOnlyCertDB[] =
62 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
63 #endif // defined(OS_CHROMEOS)
65 std::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());
74 return result;
77 #if defined(USE_NSS)
78 base::FilePath GetDefaultConfigDirectory() {
79 base::FilePath dir = file_util::GetHomeDir();
80 if (dir.empty()) {
81 LOG(ERROR) << "Failed to get home directory.";
82 return dir;
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();
89 return dir;
92 // On non-chromeos platforms, return the default config directory.
93 // On chromeos, return a read-only directory with fake root CA certs for testing
94 // (which will not exist on non-testing images). These root CA certs are used
95 // by the local Google Accounts server mock we use when testing our login code.
96 // If this directory is not present, NSS_Init() will fail. It is up to the
97 // caller to failover to NSS_NoDB_Init() at that point.
98 base::FilePath GetInitialConfigDirectory() {
99 #if defined(OS_CHROMEOS)
100 return base::FilePath(kReadOnlyCertDB);
101 #else
102 return GetDefaultConfigDirectory();
103 #endif // defined(OS_CHROMEOS)
106 // This callback for NSS forwards all requests to a caller-specified
107 // CryptoModuleBlockingPasswordDelegate object.
108 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
109 #if defined(OS_CHROMEOS)
110 // If we get asked for a password for the TPM, then return the
111 // well known password we use, as long as the TPM slot has been
112 // initialized.
113 if (crypto::IsTPMTokenReady()) {
114 std::string token_name;
115 std::string user_pin;
116 crypto::GetTPMTokenInfo(&token_name, &user_pin);
117 if (PK11_GetTokenName(slot) == token_name)
118 return PORT_Strdup(user_pin.c_str());
120 #endif
121 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
122 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
123 if (delegate) {
124 bool cancelled = false;
125 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
126 retry != PR_FALSE,
127 &cancelled);
128 if (cancelled)
129 return NULL;
130 char* result = PORT_Strdup(password.c_str());
131 password.replace(0, password.size(), password.size(), 0);
132 return result;
134 DLOG(ERROR) << "PK11 password requested with NULL arg";
135 return NULL;
138 // NSS creates a local cache of the sqlite database if it detects that the
139 // filesystem the database is on is much slower than the local disk. The
140 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
141 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
142 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
143 // detection when database_dir is on NFS. See http://crbug.com/48585.
145 // TODO(wtc): port this function to other USE_NSS platforms. It is defined
146 // only for OS_LINUX and OS_OPENBSD simply because the statfs structure
147 // is OS-specific.
149 // Because this function sets an environment variable it must be run before we
150 // go multi-threaded.
151 void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) {
152 #if defined(OS_LINUX) || defined(OS_OPENBSD)
153 struct statfs buf;
154 if (statfs(database_dir.value().c_str(), &buf) == 0) {
155 #if defined(OS_LINUX)
156 if (buf.f_type == NFS_SUPER_MAGIC) {
157 #elif defined(OS_OPENBSD)
158 if (strcmp(buf.f_fstypename, MOUNT_NFS) == 0) {
159 #endif
160 scoped_ptr<base::Environment> env(base::Environment::Create());
161 const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
162 if (!env->HasVar(use_cache_env_var))
163 env->SetVar(use_cache_env_var, "yes");
166 #endif // defined(OS_LINUX) || defined(OS_OPENBSD)
169 PK11SlotInfo* FindSlotWithTokenName(const std::string& token_name) {
170 AutoSECMODListReadLock auto_lock;
171 SECMODModuleList* head = SECMOD_GetDefaultModuleList();
172 for (SECMODModuleList* item = head; item != NULL; item = item->next) {
173 int slot_count = item->module->loaded ? item->module->slotCount : 0;
174 for (int i = 0; i < slot_count; i++) {
175 PK11SlotInfo* slot = item->module->slots[i];
176 if (PK11_GetTokenName(slot) == token_name)
177 return PK11_ReferenceSlot(slot);
180 return NULL;
183 #endif // defined(USE_NSS)
185 // A singleton to initialize/deinitialize NSPR.
186 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
187 // Now that we're leaking the singleton, we could merge back with the NSS
188 // singleton.
189 class NSPRInitSingleton {
190 private:
191 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
193 NSPRInitSingleton() {
194 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
197 // NOTE(willchan): We don't actually execute this code since we leak NSS to
198 // prevent non-joinable threads from using NSS after it's already been shut
199 // down.
200 ~NSPRInitSingleton() {
201 PL_ArenaFinish();
202 PRStatus prstatus = PR_Cleanup();
203 if (prstatus != PR_SUCCESS)
204 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
208 base::LazyInstance<NSPRInitSingleton>::Leaky
209 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
211 // This is a LazyInstance so that it will be deleted automatically when the
212 // unittest exits. NSSInitSingleton is a LeakySingleton, so it would not be
213 // deleted if it were a regular member.
214 base::LazyInstance<base::ScopedTempDir> g_test_nss_db_dir =
215 LAZY_INSTANCE_INITIALIZER;
217 // Force a crash with error info on NSS_NoDB_Init failure.
218 void CrashOnNSSInitFailure() {
219 int nss_error = PR_GetError();
220 int os_error = PR_GetOSError();
221 base::debug::Alias(&nss_error);
222 base::debug::Alias(&os_error);
223 LOG(ERROR) << "Error initializing NSS without a persistent database: "
224 << GetNSSErrorMessage();
225 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
228 class NSSInitSingleton {
229 public:
230 #if defined(OS_CHROMEOS)
231 void OpenPersistentNSSDB() {
232 if (!chromeos_user_logged_in_) {
233 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
234 // Temporarily allow it until we fix http://crbug.com/70119
235 base::ThreadRestrictions::ScopedAllowIO allow_io;
236 chromeos_user_logged_in_ = true;
238 // This creates another DB slot in NSS that is read/write, unlike
239 // the fake root CA cert DB and the "default" crypto key
240 // provider, which are still read-only (because we initialized
241 // NSS before we had a cryptohome mounted).
242 software_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
243 kNSSDatabaseName);
247 void EnableTPMTokenForNSS() {
248 tpm_token_enabled_for_nss_ = true;
251 bool InitializeTPMToken(const std::string& token_name,
252 const std::string& user_pin) {
253 // If EnableTPMTokenForNSS hasn't been called, return false.
254 if (!tpm_token_enabled_for_nss_)
255 return false;
257 // If everything is already initialized, then return true.
258 if (chaps_module_ && tpm_slot_)
259 return true;
261 tpm_token_name_ = token_name;
262 tpm_user_pin_ = user_pin;
264 // This tries to load the Chaps module so NSS can talk to the hardware
265 // TPM.
266 if (!chaps_module_) {
267 chaps_module_ = LoadModule(
268 kChapsModuleName,
269 kChapsPath,
270 // For more details on these parameters, see:
271 // https://developer.mozilla.org/en/PKCS11_Module_Specs
272 // slotFlags=[PublicCerts] -- Certificates and public keys can be
273 // read from this slot without requiring a call to C_Login.
274 // askpw=only -- Only authenticate to the token when necessary.
275 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
277 if (chaps_module_){
278 // If this gets set, then we'll use the TPM for certs with
279 // private keys, otherwise we'll fall back to the software
280 // implementation.
281 tpm_slot_ = GetTPMSlot();
283 return tpm_slot_ != NULL;
285 return false;
288 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
289 if (!tpm_token_enabled_for_nss_) {
290 LOG(ERROR) << "GetTPMTokenInfo called before TPM Token is ready.";
291 return;
293 if (token_name)
294 *token_name = tpm_token_name_;
295 if (user_pin)
296 *user_pin = tpm_user_pin_;
299 bool IsTPMTokenReady() {
300 return tpm_slot_ != NULL;
303 PK11SlotInfo* GetTPMSlot() {
304 std::string token_name;
305 GetTPMTokenInfo(&token_name, NULL);
306 return FindSlotWithTokenName(token_name);
308 #endif // defined(OS_CHROMEOS)
311 bool OpenTestNSSDB() {
312 if (test_slot_)
313 return true;
314 if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
315 return false;
316 test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), "Test DB");
317 return !!test_slot_;
320 void CloseTestNSSDB() {
321 if (test_slot_) {
322 SECStatus status = SECMOD_CloseUserDB(test_slot_);
323 if (status != SECSuccess)
324 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
325 PK11_FreeSlot(test_slot_);
326 test_slot_ = NULL;
327 ignore_result(g_test_nss_db_dir.Get().Delete());
331 PK11SlotInfo* GetPublicNSSKeySlot() {
332 if (test_slot_)
333 return PK11_ReferenceSlot(test_slot_);
334 if (software_slot_)
335 return PK11_ReferenceSlot(software_slot_);
336 return PK11_GetInternalKeySlot();
339 PK11SlotInfo* GetPrivateNSSKeySlot() {
340 if (test_slot_)
341 return PK11_ReferenceSlot(test_slot_);
343 #if defined(OS_CHROMEOS)
344 if (tpm_token_enabled_for_nss_) {
345 if (IsTPMTokenReady()) {
346 return PK11_ReferenceSlot(tpm_slot_);
347 } else {
348 // If we were supposed to get the hardware token, but were
349 // unable to, return NULL rather than fall back to sofware.
350 return NULL;
353 #endif
354 // If we weren't supposed to enable the TPM for NSS, then return
355 // the software slot.
356 if (software_slot_)
357 return PK11_ReferenceSlot(software_slot_);
358 return PK11_GetInternalKeySlot();
361 #if defined(USE_NSS)
362 base::Lock* write_lock() {
363 return &write_lock_;
365 #endif // defined(USE_NSS)
367 // This method is used to force NSS to be initialized without a DB.
368 // Call this method before NSSInitSingleton() is constructed.
369 static void ForceNoDBInit() {
370 force_nodb_init_ = true;
373 private:
374 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
376 NSSInitSingleton()
377 : tpm_token_enabled_for_nss_(false),
378 chaps_module_(NULL),
379 software_slot_(NULL),
380 test_slot_(NULL),
381 tpm_slot_(NULL),
382 root_(NULL),
383 chromeos_user_logged_in_(false) {
384 base::TimeTicks start_time = base::TimeTicks::Now();
385 EnsureNSPRInit();
387 // We *must* have NSS >= 3.12.3. See bug 26448.
388 COMPILE_ASSERT(
389 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
390 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
391 (NSS_VMAJOR > 3),
392 nss_version_check_failed);
393 // Also check the run-time NSS version.
394 // NSS_VersionCheck is a >= check, not strict equality.
395 if (!NSS_VersionCheck("3.12.3")) {
396 // It turns out many people have misconfigured NSS setups, where
397 // their run-time NSPR doesn't match the one their NSS was compiled
398 // against. So rather than aborting, complain loudly.
399 LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed. "
400 "We depend on NSS >= 3.12.3, and this error is not fatal "
401 "only because many people have busted NSS setups (for "
402 "example, using the wrong version of NSPR). "
403 "Please upgrade to the latest NSS and NSPR, and if you "
404 "still get this error, contact your distribution "
405 "maintainer.";
408 SECStatus status = SECFailure;
409 bool nodb_init = force_nodb_init_;
411 #if !defined(USE_NSS)
412 // Use the system certificate store, so initialize NSS without database.
413 nodb_init = true;
414 #endif
416 if (nodb_init) {
417 status = NSS_NoDB_Init(NULL);
418 if (status != SECSuccess) {
419 CrashOnNSSInitFailure();
420 return;
422 #if defined(OS_IOS)
423 root_ = InitDefaultRootCerts();
424 #endif // defined(OS_IOS)
425 } else {
426 #if defined(USE_NSS)
427 base::FilePath database_dir = GetInitialConfigDirectory();
428 if (!database_dir.empty()) {
429 // This duplicates the work which should have been done in
430 // EarlySetupForNSSInit. However, this function is idempotent so
431 // there's no harm done.
432 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
434 // Initialize with a persistent database (likely, ~/.pki/nssdb).
435 // Use "sql:" which can be shared by multiple processes safely.
436 std::string nss_config_dir =
437 base::StringPrintf("sql:%s", database_dir.value().c_str());
438 #if defined(OS_CHROMEOS)
439 status = NSS_Init(nss_config_dir.c_str());
440 #else
441 status = NSS_InitReadWrite(nss_config_dir.c_str());
442 #endif
443 if (status != SECSuccess) {
444 LOG(ERROR) << "Error initializing NSS with a persistent "
445 "database (" << nss_config_dir
446 << "): " << GetNSSErrorMessage();
449 if (status != SECSuccess) {
450 VLOG(1) << "Initializing NSS without a persistent database.";
451 status = NSS_NoDB_Init(NULL);
452 if (status != SECSuccess) {
453 CrashOnNSSInitFailure();
454 return;
458 PK11_SetPasswordFunc(PKCS11PasswordFunc);
460 // If we haven't initialized the password for the NSS databases,
461 // initialize an empty-string password so that we don't need to
462 // log in.
463 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
464 if (slot) {
465 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
466 // yet, so we don't need to lock.
467 if (PK11_NeedUserInit(slot))
468 PK11_InitPin(slot, NULL, NULL);
469 PK11_FreeSlot(slot);
472 root_ = InitDefaultRootCerts();
473 #endif // defined(USE_NSS)
476 // Disable MD5 certificate signatures. (They are disabled by default in
477 // NSS 3.14.)
478 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
479 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
480 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
482 // The UMA bit is conditionally set for this histogram in
483 // chrome/common/startup_metric_utils.cc .
484 HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
485 base::TimeTicks::Now() - start_time,
486 base::TimeDelta::FromMilliseconds(10),
487 base::TimeDelta::FromHours(1),
488 50);
491 // NOTE(willchan): We don't actually execute this code since we leak NSS to
492 // prevent non-joinable threads from using NSS after it's already been shut
493 // down.
494 ~NSSInitSingleton() {
495 if (tpm_slot_) {
496 PK11_FreeSlot(tpm_slot_);
497 tpm_slot_ = NULL;
499 if (software_slot_) {
500 SECMOD_CloseUserDB(software_slot_);
501 PK11_FreeSlot(software_slot_);
502 software_slot_ = NULL;
504 CloseTestNSSDB();
505 if (root_) {
506 SECMOD_UnloadUserModule(root_);
507 SECMOD_DestroyModule(root_);
508 root_ = NULL;
510 if (chaps_module_) {
511 SECMOD_UnloadUserModule(chaps_module_);
512 SECMOD_DestroyModule(chaps_module_);
513 chaps_module_ = NULL;
516 SECStatus status = NSS_Shutdown();
517 if (status != SECSuccess) {
518 // We VLOG(1) because this failure is relatively harmless (leaking, but
519 // we're shutting down anyway).
520 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
524 #if defined(USE_NSS) || defined(OS_IOS)
525 // Load nss's built-in root certs.
526 SECMODModule* InitDefaultRootCerts() {
527 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
528 if (root)
529 return root;
531 // Aw, snap. Can't find/load root cert shared library.
532 // This will make it hard to talk to anybody via https.
533 NOTREACHED();
534 return NULL;
537 // Load the given module for this NSS session.
538 SECMODModule* LoadModule(const char* name,
539 const char* library_path,
540 const char* params) {
541 std::string modparams = base::StringPrintf(
542 "name=\"%s\" library=\"%s\" %s",
543 name, library_path, params ? params : "");
545 // Shouldn't need to const_cast here, but SECMOD doesn't properly
546 // declare input string arguments as const. Bug
547 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
548 // on NSS codebase to address this.
549 SECMODModule* module = SECMOD_LoadUserModule(
550 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
551 if (!module) {
552 LOG(ERROR) << "Error loading " << name << " module into NSS: "
553 << GetNSSErrorMessage();
554 return NULL;
556 return module;
558 #endif
560 static PK11SlotInfo* OpenUserDB(const base::FilePath& path,
561 const char* description) {
562 const std::string modspec =
563 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
564 path.value().c_str(), description);
565 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
566 if (db_slot) {
567 if (PK11_NeedUserInit(db_slot))
568 PK11_InitPin(db_slot, NULL, NULL);
570 else {
571 LOG(ERROR) << "Error opening persistent database (" << modspec
572 << "): " << GetNSSErrorMessage();
574 return db_slot;
577 // If this is set to true NSS is forced to be initialized without a DB.
578 static bool force_nodb_init_;
580 bool tpm_token_enabled_for_nss_;
581 std::string tpm_token_name_;
582 std::string tpm_user_pin_;
583 SECMODModule* chaps_module_;
584 PK11SlotInfo* software_slot_;
585 PK11SlotInfo* test_slot_;
586 PK11SlotInfo* tpm_slot_;
587 SECMODModule* root_;
588 bool chromeos_user_logged_in_;
589 #if defined(USE_NSS)
590 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
591 // is fixed, we will no longer need the lock.
592 base::Lock write_lock_;
593 #endif // defined(USE_NSS)
596 // static
597 bool NSSInitSingleton::force_nodb_init_ = false;
599 base::LazyInstance<NSSInitSingleton>::Leaky
600 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
601 } // namespace
603 #if defined(USE_NSS)
604 void EarlySetupForNSSInit() {
605 base::FilePath database_dir = GetInitialConfigDirectory();
606 if (!database_dir.empty())
607 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
609 #endif
611 void EnsureNSPRInit() {
612 g_nspr_singleton.Get();
615 void InitNSSSafely() {
616 // We might fork, but we haven't loaded any security modules.
617 DisableNSSForkCheck();
618 // If we're sandboxed, we shouldn't be able to open user security modules,
619 // but it's more correct to tell NSS to not even try.
620 // Loading user security modules would have security implications.
621 ForceNSSNoDBInit();
622 // Initialize NSS.
623 EnsureNSSInit();
626 void EnsureNSSInit() {
627 // Initializing SSL causes us to do blocking IO.
628 // Temporarily allow it until we fix
629 // http://code.google.com/p/chromium/issues/detail?id=59847
630 base::ThreadRestrictions::ScopedAllowIO allow_io;
631 g_nss_singleton.Get();
634 void ForceNSSNoDBInit() {
635 NSSInitSingleton::ForceNoDBInit();
638 void DisableNSSForkCheck() {
639 scoped_ptr<base::Environment> env(base::Environment::Create());
640 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
643 void LoadNSSLibraries() {
644 // Some NSS libraries are linked dynamically so load them here.
645 #if defined(USE_NSS)
646 // Try to search for multiple directories to load the libraries.
647 std::vector<base::FilePath> paths;
649 // Use relative path to Search PATH for the library files.
650 paths.push_back(base::FilePath());
652 // For Debian derivatives NSS libraries are located here.
653 paths.push_back(base::FilePath("/usr/lib/nss"));
655 // Ubuntu 11.10 (Oneiric) places the libraries here.
656 #if defined(ARCH_CPU_X86_64)
657 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
658 #elif defined(ARCH_CPU_X86)
659 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
660 #elif defined(ARCH_CPU_ARMEL)
661 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
662 #endif
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");
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;
683 if (loaded == libs.size()) {
684 VLOG(3) << "NSS libraries loaded.";
685 } else {
686 LOG(ERROR) << "Failed to load NSS libraries.";
688 #endif
691 bool CheckNSSVersion(const char* version) {
692 return !!NSS_VersionCheck(version);
695 #if defined(USE_NSS)
696 ScopedTestNSSDB::ScopedTestNSSDB()
697 : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
700 ScopedTestNSSDB::~ScopedTestNSSDB() {
701 // TODO(mattm): Close the dababase once NSS 3.14 is required,
702 // which fixes https://bugzilla.mozilla.org/show_bug.cgi?id=588269
703 // Resource leaks are suppressed. http://crbug.com/156433 .
706 base::Lock* GetNSSWriteLock() {
707 return g_nss_singleton.Get().write_lock();
710 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
711 // May be NULL if the lock is not needed in our version of NSS.
712 if (lock_)
713 lock_->Acquire();
716 AutoNSSWriteLock::~AutoNSSWriteLock() {
717 if (lock_) {
718 lock_->AssertAcquired();
719 lock_->Release();
723 AutoSECMODListReadLock::AutoSECMODListReadLock()
724 : lock_(SECMOD_GetDefaultModuleListLock()) {
725 SECMOD_GetReadLock(lock_);
728 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
729 SECMOD_ReleaseReadLock(lock_);
732 #endif // defined(USE_NSS)
734 #if defined(OS_CHROMEOS)
735 void OpenPersistentNSSDB() {
736 g_nss_singleton.Get().OpenPersistentNSSDB();
739 void EnableTPMTokenForNSS() {
740 g_nss_singleton.Get().EnableTPMTokenForNSS();
743 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
744 g_nss_singleton.Get().GetTPMTokenInfo(token_name, user_pin);
747 bool IsTPMTokenReady() {
748 return g_nss_singleton.Get().IsTPMTokenReady();
751 bool InitializeTPMToken(const std::string& token_name,
752 const std::string& user_pin) {
753 return g_nss_singleton.Get().InitializeTPMToken(token_name, user_pin);
755 #endif // defined(OS_CHROMEOS)
757 base::Time PRTimeToBaseTime(PRTime prtime) {
758 return base::Time::FromInternalValue(
759 prtime + base::Time::UnixEpoch().ToInternalValue());
762 PRTime BaseTimeToPRTime(base::Time time) {
763 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
766 PK11SlotInfo* GetPublicNSSKeySlot() {
767 return g_nss_singleton.Get().GetPublicNSSKeySlot();
770 PK11SlotInfo* GetPrivateNSSKeySlot() {
771 return g_nss_singleton.Get().GetPrivateNSSKeySlot();
774 } // namespace crypto