Extract SIGPIPE ignoring code to a common place.
[chromium-blink-merge.git] / crypto / nss_util.cc
blob26626e7f7d5c5811ff386e4a8418953aae809b3c
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 <plarena.h>
10 #include <prerror.h>
11 #include <prinit.h>
12 #include <prtime.h>
13 #include <pk11pub.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_path.h"
29 #include "base/file_util.h"
30 #include "base/lazy_instance.h"
31 #include "base/logging.h"
32 #include "base/memory/scoped_ptr.h"
33 #include "base/native_library.h"
34 #include "base/scoped_temp_dir.h"
35 #include "base/stringprintf.h"
36 #include "base/threading/thread_restrictions.h"
37 #include "build/build_config.h"
39 #if defined(OS_CHROMEOS)
40 #include "crypto/symmetric_key.h"
41 #endif
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)
52 namespace crypto {
54 namespace {
56 #if defined(OS_CHROMEOS)
57 const char kNSSDatabaseName[] = "Real NSS database";
59 // Constants for loading the Chrome OS TPM-backed PKCS #11 library.
60 const char kChapsModuleName[] = "Chaps";
61 const char kChapsPath[] = "libchaps.so";
63 // Fake certificate authority database used for testing.
64 static const FilePath::CharType kReadOnlyCertDB[] =
65 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
66 #endif // defined(OS_CHROMEOS)
68 std::string GetNSSErrorMessage() {
69 std::string result;
70 if (PR_GetErrorTextLength()) {
71 scoped_array<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 = StringPrintf("NSS error code: %d", PR_GetError());
77 return result;
80 #if defined(USE_NSS)
81 FilePath GetDefaultConfigDirectory() {
82 FilePath dir = file_util::GetHomeDir();
83 if (dir.empty()) {
84 LOG(ERROR) << "Failed to get home directory.";
85 return dir;
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();
92 return dir;
95 #if defined(OS_CHROMEOS)
96 // Supplemental user key id.
97 unsigned char kSupplementalUserKeyId[] = {
98 0xCC, 0x13, 0x19, 0xDE, 0x75, 0x5E, 0xFE, 0xFA,
99 0x5E, 0x71, 0xD4, 0xA6, 0xFB, 0x00, 0x00, 0xCC
101 #endif // defined(OS_CHROMEOS)
104 // On non-chromeos platforms, return the default config directory.
105 // On chromeos, return a read-only directory with fake root CA certs for testing
106 // (which will not exist on non-testing images). These root CA certs are used
107 // by the local Google Accounts server mock we use when testing our login code.
108 // If this directory is not present, NSS_Init() will fail. It is up to the
109 // caller to failover to NSS_NoDB_Init() at that point.
110 FilePath GetInitialConfigDirectory() {
111 #if defined(OS_CHROMEOS)
112 return FilePath(kReadOnlyCertDB);
113 #else
114 return GetDefaultConfigDirectory();
115 #endif // defined(OS_CHROMEOS)
118 // This callback for NSS forwards all requests to a caller-specified
119 // CryptoModuleBlockingPasswordDelegate object.
120 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
121 #if defined(OS_CHROMEOS)
122 // If we get asked for a password for the TPM, then return the
123 // well known password we use, as long as the TPM slot has been
124 // initialized.
125 if (crypto::IsTPMTokenReady()) {
126 std::string token_name;
127 std::string user_pin;
128 crypto::GetTPMTokenInfo(&token_name, &user_pin);
129 if (PK11_GetTokenName(slot) == token_name)
130 return PORT_Strdup(user_pin.c_str());
132 #endif
133 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
134 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
135 if (delegate) {
136 bool cancelled = false;
137 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
138 retry != PR_FALSE,
139 &cancelled);
140 if (cancelled)
141 return NULL;
142 char* result = PORT_Strdup(password.c_str());
143 password.replace(0, password.size(), password.size(), 0);
144 return result;
146 DLOG(ERROR) << "PK11 password requested with NULL arg";
147 return NULL;
150 // NSS creates a local cache of the sqlite database if it detects that the
151 // filesystem the database is on is much slower than the local disk. The
152 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
153 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
154 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
155 // detection when database_dir is on NFS. See http://crbug.com/48585.
157 // TODO(wtc): port this function to other USE_NSS platforms. It is defined
158 // only for OS_LINUX and OS_OPENBSD simply because the statfs structure
159 // is OS-specific.
161 // Because this function sets an environment variable it must be run before we
162 // go multi-threaded.
163 void UseLocalCacheOfNSSDatabaseIfNFS(const FilePath& database_dir) {
164 #if defined(OS_LINUX) || defined(OS_OPENBSD)
165 struct statfs buf;
166 if (statfs(database_dir.value().c_str(), &buf) == 0) {
167 #if defined(OS_LINUX)
168 if (buf.f_type == NFS_SUPER_MAGIC) {
169 #elif defined(OS_OPENBSD)
170 if (strcmp(buf.f_fstypename, MOUNT_NFS) == 0) {
171 #endif
172 scoped_ptr<base::Environment> env(base::Environment::Create());
173 const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
174 if (!env->HasVar(use_cache_env_var))
175 env->SetVar(use_cache_env_var, "yes");
178 #endif // defined(OS_LINUX) || defined(OS_OPENBSD)
181 PK11SlotInfo* FindSlotWithTokenName(const std::string& token_name) {
182 AutoSECMODListReadLock auto_lock;
183 SECMODModuleList* head = SECMOD_GetDefaultModuleList();
184 for (SECMODModuleList* item = head; item != NULL; item = item->next) {
185 int slot_count = item->module->loaded ? item->module->slotCount : 0;
186 for (int i = 0; i < slot_count; i++) {
187 PK11SlotInfo* slot = item->module->slots[i];
188 if (PK11_GetTokenName(slot) == token_name)
189 return PK11_ReferenceSlot(slot);
192 return NULL;
195 #endif // defined(USE_NSS)
197 // A singleton to initialize/deinitialize NSPR.
198 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
199 // Now that we're leaking the singleton, we could merge back with the NSS
200 // singleton.
201 class NSPRInitSingleton {
202 private:
203 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
205 NSPRInitSingleton() {
206 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
209 // NOTE(willchan): We don't actually execute this code since we leak NSS to
210 // prevent non-joinable threads from using NSS after it's already been shut
211 // down.
212 ~NSPRInitSingleton() {
213 PL_ArenaFinish();
214 PRStatus prstatus = PR_Cleanup();
215 if (prstatus != PR_SUCCESS)
216 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
220 base::LazyInstance<NSPRInitSingleton>::Leaky
221 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
223 // This is a LazyInstance so that it will be deleted automatically when the
224 // unittest exits. NSSInitSingleton is a LeakySingleton, so it would not be
225 // deleted if it were a regular member.
226 base::LazyInstance<ScopedTempDir> g_test_nss_db_dir = LAZY_INSTANCE_INITIALIZER;
228 // Force a crash to debug http://crbug.com/153281.
229 void CrashWithErrors(int nss_error, int os_error) {
230 base::debug::Alias(&nss_error);
231 base::debug::Alias(&os_error);
232 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
235 class NSSInitSingleton {
236 public:
237 #if defined(OS_CHROMEOS)
238 void OpenPersistentNSSDB() {
239 if (!chromeos_user_logged_in_) {
240 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
241 // Temporarily allow it until we fix http://crbug.com/70119
242 base::ThreadRestrictions::ScopedAllowIO allow_io;
243 chromeos_user_logged_in_ = true;
245 // This creates another DB slot in NSS that is read/write, unlike
246 // the fake root CA cert DB and the "default" crypto key
247 // provider, which are still read-only (because we initialized
248 // NSS before we had a cryptohome mounted).
249 software_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
250 kNSSDatabaseName);
254 void EnableTPMTokenForNSS() {
255 tpm_token_enabled_for_nss_ = true;
258 bool InitializeTPMToken(const std::string& token_name,
259 const std::string& user_pin) {
260 // If EnableTPMTokenForNSS hasn't been called, return false.
261 if (!tpm_token_enabled_for_nss_)
262 return false;
264 // If everything is already initialized, then return true.
265 if (chaps_module_ && tpm_slot_)
266 return true;
268 tpm_token_name_ = token_name;
269 tpm_user_pin_ = user_pin;
271 // This tries to load the Chaps module so NSS can talk to the hardware
272 // TPM.
273 if (!chaps_module_) {
274 chaps_module_ = LoadModule(
275 kChapsModuleName,
276 kChapsPath,
277 // For more details on these parameters, see:
278 // https://developer.mozilla.org/en/PKCS11_Module_Specs
279 // slotFlags=[PublicCerts] -- Certificates and public keys can be
280 // read from this slot without requiring a call to C_Login.
281 // askpw=only -- Only authenticate to the token when necessary.
282 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
284 if (chaps_module_){
285 // If this gets set, then we'll use the TPM for certs with
286 // private keys, otherwise we'll fall back to the software
287 // implementation.
288 tpm_slot_ = GetTPMSlot();
290 return tpm_slot_ != NULL;
292 return false;
295 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
296 if (!tpm_token_enabled_for_nss_) {
297 LOG(ERROR) << "GetTPMTokenInfo called before TPM Token is ready.";
298 return;
300 if (token_name)
301 *token_name = tpm_token_name_;
302 if (user_pin)
303 *user_pin = tpm_user_pin_;
306 bool IsTPMTokenReady() {
307 return tpm_slot_ != NULL;
310 PK11SlotInfo* GetTPMSlot() {
311 std::string token_name;
312 GetTPMTokenInfo(&token_name, NULL);
313 return FindSlotWithTokenName(token_name);
316 SymmetricKey* GetSupplementalUserKey() {
317 DCHECK(chromeos_user_logged_in_);
319 PK11SlotInfo* slot = NULL;
320 PK11SymKey* key = NULL;
321 SECItem keyID;
322 CK_MECHANISM_TYPE type = CKM_AES_ECB;
324 slot = GetPublicNSSKeySlot();
325 if (!slot)
326 goto done;
328 if (PK11_Authenticate(slot, PR_TRUE, NULL) != SECSuccess)
329 goto done;
331 keyID.type = siBuffer;
332 keyID.data = kSupplementalUserKeyId;
333 keyID.len = static_cast<int>(sizeof(kSupplementalUserKeyId));
335 // Find/generate AES key.
336 key = PK11_FindFixedKey(slot, type, &keyID, NULL);
337 if (!key) {
338 const int kKeySizeInBytes = 32;
339 key = PK11_TokenKeyGen(slot, type, NULL,
340 kKeySizeInBytes,
341 &keyID, PR_TRUE, NULL);
344 done:
345 if (slot)
346 PK11_FreeSlot(slot);
348 return key ? SymmetricKey::CreateFromKey(key) : NULL;
350 #endif // defined(OS_CHROMEOS)
353 bool OpenTestNSSDB() {
354 if (test_slot_)
355 return true;
356 if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
357 return false;
358 test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), "Test DB");
359 return !!test_slot_;
362 void CloseTestNSSDB() {
363 if (test_slot_) {
364 SECStatus status = SECMOD_CloseUserDB(test_slot_);
365 if (status != SECSuccess)
366 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
367 PK11_FreeSlot(test_slot_);
368 test_slot_ = NULL;
369 ignore_result(g_test_nss_db_dir.Get().Delete());
373 PK11SlotInfo* GetPublicNSSKeySlot() {
374 if (test_slot_)
375 return PK11_ReferenceSlot(test_slot_);
376 if (software_slot_)
377 return PK11_ReferenceSlot(software_slot_);
378 return PK11_GetInternalKeySlot();
381 PK11SlotInfo* GetPrivateNSSKeySlot() {
382 if (test_slot_)
383 return PK11_ReferenceSlot(test_slot_);
385 #if defined(OS_CHROMEOS)
386 if (tpm_token_enabled_for_nss_) {
387 if (IsTPMTokenReady()) {
388 return PK11_ReferenceSlot(tpm_slot_);
389 } else {
390 // If we were supposed to get the hardware token, but were
391 // unable to, return NULL rather than fall back to sofware.
392 return NULL;
395 #endif
396 // If we weren't supposed to enable the TPM for NSS, then return
397 // the software slot.
398 if (software_slot_)
399 return PK11_ReferenceSlot(software_slot_);
400 return PK11_GetInternalKeySlot();
403 #if defined(USE_NSS)
404 base::Lock* write_lock() {
405 return &write_lock_;
407 #endif // defined(USE_NSS)
409 // This method is used to force NSS to be initialized without a DB.
410 // Call this method before NSSInitSingleton() is constructed.
411 static void ForceNoDBInit() {
412 force_nodb_init_ = true;
415 private:
416 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
418 NSSInitSingleton()
419 : tpm_token_enabled_for_nss_(false),
420 chaps_module_(NULL),
421 software_slot_(NULL),
422 test_slot_(NULL),
423 tpm_slot_(NULL),
424 root_(NULL),
425 chromeos_user_logged_in_(false) {
426 EnsureNSPRInit();
428 // We *must* have NSS >= 3.12.3. See bug 26448.
429 COMPILE_ASSERT(
430 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
431 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
432 (NSS_VMAJOR > 3),
433 nss_version_check_failed);
434 // Also check the run-time NSS version.
435 // NSS_VersionCheck is a >= check, not strict equality.
436 if (!NSS_VersionCheck("3.12.3")) {
437 // It turns out many people have misconfigured NSS setups, where
438 // their run-time NSPR doesn't match the one their NSS was compiled
439 // against. So rather than aborting, complain loudly.
440 LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed. "
441 "We depend on NSS >= 3.12.3, and this error is not fatal "
442 "only because many people have busted NSS setups (for "
443 "example, using the wrong version of NSPR). "
444 "Please upgrade to the latest NSS and NSPR, and if you "
445 "still get this error, contact your distribution "
446 "maintainer.";
449 SECStatus status = SECFailure;
450 bool nodb_init = force_nodb_init_;
452 #if !defined(USE_NSS)
453 // Use the system certificate store, so initialize NSS without database.
454 nodb_init = true;
455 #endif
457 if (nodb_init) {
458 status = NSS_NoDB_Init(NULL);
459 if (status != SECSuccess) {
460 // Force a crash with error info to debug http://crbug.com/153281.
461 int nss_error = PR_GetError();
462 int os_error = PR_GetOSError();
463 LOG(ERROR) << "Error initializing NSS without a persistent "
464 "database: " << GetNSSErrorMessage();
465 CrashWithErrors(nss_error, os_error);
466 return;
468 #if defined(OS_IOS)
469 root_ = InitDefaultRootCerts();
470 #endif // defined(OS_IOS)
471 } else {
472 #if defined(USE_NSS)
473 FilePath database_dir = GetInitialConfigDirectory();
474 if (!database_dir.empty()) {
475 // This duplicates the work which should have been done in
476 // EarlySetupForNSSInit. However, this function is idempotent so
477 // there's no harm done.
478 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
480 // Initialize with a persistent database (likely, ~/.pki/nssdb).
481 // Use "sql:" which can be shared by multiple processes safely.
482 std::string nss_config_dir =
483 StringPrintf("sql:%s", database_dir.value().c_str());
484 #if defined(OS_CHROMEOS)
485 status = NSS_Init(nss_config_dir.c_str());
486 #else
487 status = NSS_InitReadWrite(nss_config_dir.c_str());
488 #endif
489 if (status != SECSuccess) {
490 LOG(ERROR) << "Error initializing NSS with a persistent "
491 "database (" << nss_config_dir
492 << "): " << GetNSSErrorMessage();
495 if (status != SECSuccess) {
496 VLOG(1) << "Initializing NSS without a persistent database.";
497 status = NSS_NoDB_Init(NULL);
498 if (status != SECSuccess) {
499 LOG(ERROR) << "Error initializing NSS without a persistent "
500 "database: " << GetNSSErrorMessage();
501 return;
505 PK11_SetPasswordFunc(PKCS11PasswordFunc);
507 // If we haven't initialized the password for the NSS databases,
508 // initialize an empty-string password so that we don't need to
509 // log in.
510 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
511 if (slot) {
512 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
513 // yet, so we don't need to lock.
514 if (PK11_NeedUserInit(slot))
515 PK11_InitPin(slot, NULL, NULL);
516 PK11_FreeSlot(slot);
519 root_ = InitDefaultRootCerts();
521 // MD5 certificate signatures are disabled by default in NSS 3.14.
522 // Enable MD5 certificate signatures until we figure out how to deal
523 // with the weak certificate signature unit tests.
524 NSS_SetAlgorithmPolicy(SEC_OID_MD5, NSS_USE_ALG_IN_CERT_SIGNATURE, 0);
525 #endif // defined(USE_NSS)
529 // NOTE(willchan): We don't actually execute this code since we leak NSS to
530 // prevent non-joinable threads from using NSS after it's already been shut
531 // down.
532 ~NSSInitSingleton() {
533 if (tpm_slot_) {
534 PK11_FreeSlot(tpm_slot_);
535 tpm_slot_ = NULL;
537 if (software_slot_) {
538 SECMOD_CloseUserDB(software_slot_);
539 PK11_FreeSlot(software_slot_);
540 software_slot_ = NULL;
542 CloseTestNSSDB();
543 if (root_) {
544 SECMOD_UnloadUserModule(root_);
545 SECMOD_DestroyModule(root_);
546 root_ = NULL;
548 if (chaps_module_) {
549 SECMOD_UnloadUserModule(chaps_module_);
550 SECMOD_DestroyModule(chaps_module_);
551 chaps_module_ = NULL;
554 SECStatus status = NSS_Shutdown();
555 if (status != SECSuccess) {
556 // We VLOG(1) because this failure is relatively harmless (leaking, but
557 // we're shutting down anyway).
558 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
562 #if defined(USE_NSS) || defined(OS_IOS)
563 // Load nss's built-in root certs.
564 SECMODModule* InitDefaultRootCerts() {
565 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
566 if (root)
567 return root;
569 // Aw, snap. Can't find/load root cert shared library.
570 // This will make it hard to talk to anybody via https.
571 NOTREACHED();
572 return NULL;
575 // Load the given module for this NSS session.
576 SECMODModule* LoadModule(const char* name,
577 const char* library_path,
578 const char* params) {
579 std::string modparams = StringPrintf(
580 "name=\"%s\" library=\"%s\" %s",
581 name, library_path, params ? params : "");
583 // Shouldn't need to const_cast here, but SECMOD doesn't properly
584 // declare input string arguments as const. Bug
585 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
586 // on NSS codebase to address this.
587 SECMODModule* module = SECMOD_LoadUserModule(
588 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
589 if (!module) {
590 LOG(ERROR) << "Error loading " << name << " module into NSS: "
591 << GetNSSErrorMessage();
592 return NULL;
594 return module;
596 #endif
598 static PK11SlotInfo* OpenUserDB(const FilePath& path,
599 const char* description) {
600 const std::string modspec =
601 StringPrintf("configDir='sql:%s' tokenDescription='%s'",
602 path.value().c_str(), description);
603 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
604 if (db_slot) {
605 if (PK11_NeedUserInit(db_slot))
606 PK11_InitPin(db_slot, NULL, NULL);
608 else {
609 LOG(ERROR) << "Error opening persistent database (" << modspec
610 << "): " << GetNSSErrorMessage();
612 return db_slot;
615 // If this is set to true NSS is forced to be initialized without a DB.
616 static bool force_nodb_init_;
618 bool tpm_token_enabled_for_nss_;
619 std::string tpm_token_name_;
620 std::string tpm_user_pin_;
621 SECMODModule* chaps_module_;
622 PK11SlotInfo* software_slot_;
623 PK11SlotInfo* test_slot_;
624 PK11SlotInfo* tpm_slot_;
625 SECMODModule* root_;
626 bool chromeos_user_logged_in_;
627 #if defined(USE_NSS)
628 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
629 // is fixed, we will no longer need the lock.
630 base::Lock write_lock_;
631 #endif // defined(USE_NSS)
634 // static
635 bool NSSInitSingleton::force_nodb_init_ = false;
637 base::LazyInstance<NSSInitSingleton>::Leaky
638 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
639 } // namespace
641 #if defined(USE_NSS)
642 void EarlySetupForNSSInit() {
643 FilePath database_dir = GetInitialConfigDirectory();
644 if (!database_dir.empty())
645 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
647 #endif
649 void EnsureNSPRInit() {
650 g_nspr_singleton.Get();
653 void EnsureNSSInit() {
654 // Initializing SSL causes us to do blocking IO.
655 // Temporarily allow it until we fix
656 // http://code.google.com/p/chromium/issues/detail?id=59847
657 base::ThreadRestrictions::ScopedAllowIO allow_io;
658 g_nss_singleton.Get();
661 void ForceNSSNoDBInit() {
662 NSSInitSingleton::ForceNoDBInit();
665 void DisableNSSForkCheck() {
666 scoped_ptr<base::Environment> env(base::Environment::Create());
667 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
670 void LoadNSSLibraries() {
671 // Some NSS libraries are linked dynamically so load them here.
672 #if defined(USE_NSS)
673 // Try to search for multiple directories to load the libraries.
674 std::vector<FilePath> paths;
676 // Use relative path to Search PATH for the library files.
677 paths.push_back(FilePath());
679 // For Debian derivatives NSS libraries are located here.
680 paths.push_back(FilePath("/usr/lib/nss"));
682 // Ubuntu 11.10 (Oneiric) places the libraries here.
683 #if defined(ARCH_CPU_X86_64)
684 paths.push_back(FilePath("/usr/lib/x86_64-linux-gnu/nss"));
685 #elif defined(ARCH_CPU_X86)
686 paths.push_back(FilePath("/usr/lib/i386-linux-gnu/nss"));
687 #elif defined(ARCH_CPU_ARMEL)
688 paths.push_back(FilePath("/usr/lib/arm-linux-gnueabi/nss"));
689 #endif
691 // A list of library files to load.
692 std::vector<std::string> libs;
693 libs.push_back("libsoftokn3.so");
694 libs.push_back("libfreebl3.so");
696 // For each combination of library file and path, check for existence and
697 // then load.
698 size_t loaded = 0;
699 for (size_t i = 0; i < libs.size(); ++i) {
700 for (size_t j = 0; j < paths.size(); ++j) {
701 FilePath path = paths[j].Append(libs[i]);
702 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
703 if (lib) {
704 ++loaded;
705 break;
710 if (loaded == libs.size()) {
711 VLOG(3) << "NSS libraries loaded.";
712 } else {
713 LOG(ERROR) << "Failed to load NSS libraries.";
715 #endif
718 bool CheckNSSVersion(const char* version) {
719 return !!NSS_VersionCheck(version);
722 #if defined(USE_NSS)
723 ScopedTestNSSDB::ScopedTestNSSDB()
724 : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
727 ScopedTestNSSDB::~ScopedTestNSSDB() {
728 // TODO(mattm): Close the dababase once NSS 3.14 is required,
729 // which fixes https://bugzilla.mozilla.org/show_bug.cgi?id=588269
730 // Resource leaks are suppressed. http://crbug.com/156433 .
733 base::Lock* GetNSSWriteLock() {
734 return g_nss_singleton.Get().write_lock();
737 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
738 // May be NULL if the lock is not needed in our version of NSS.
739 if (lock_)
740 lock_->Acquire();
743 AutoNSSWriteLock::~AutoNSSWriteLock() {
744 if (lock_) {
745 lock_->AssertAcquired();
746 lock_->Release();
750 AutoSECMODListReadLock::AutoSECMODListReadLock()
751 : lock_(SECMOD_GetDefaultModuleListLock()) {
752 SECMOD_GetReadLock(lock_);
755 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
756 SECMOD_ReleaseReadLock(lock_);
759 #endif // defined(USE_NSS)
761 #if defined(OS_CHROMEOS)
762 void OpenPersistentNSSDB() {
763 g_nss_singleton.Get().OpenPersistentNSSDB();
766 void EnableTPMTokenForNSS() {
767 g_nss_singleton.Get().EnableTPMTokenForNSS();
770 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
771 g_nss_singleton.Get().GetTPMTokenInfo(token_name, user_pin);
774 bool IsTPMTokenReady() {
775 return g_nss_singleton.Get().IsTPMTokenReady();
778 bool InitializeTPMToken(const std::string& token_name,
779 const std::string& user_pin) {
780 return g_nss_singleton.Get().InitializeTPMToken(token_name, user_pin);
783 SymmetricKey* GetSupplementalUserKey() {
784 return g_nss_singleton.Get().GetSupplementalUserKey();
786 #endif // defined(OS_CHROMEOS)
788 base::Time PRTimeToBaseTime(PRTime prtime) {
789 return base::Time::FromInternalValue(
790 prtime + base::Time::UnixEpoch().ToInternalValue());
793 PRTime BaseTimeToPRTime(base::Time time) {
794 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
797 PK11SlotInfo* GetPublicNSSKeySlot() {
798 return g_nss_singleton.Get().GetPublicNSSKeySlot();
801 PK11SlotInfo* GetPrivateNSSKeySlot() {
802 return g_nss_singleton.Get().GetPrivateNSSKeySlot();
805 } // namespace crypto