cros: Show terminated/disabled app in launcher bar.
[chromium-blink-merge.git] / crypto / nss_util.cc
blob69d74f555cfe434b501f9abd3cce1de28ff3583c
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_path.h"
29 #include "base/file_util.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/native_library.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<base::ScopedTempDir> g_test_nss_db_dir =
227 LAZY_INSTANCE_INITIALIZER;
229 // Force a crash with error info on NSS_NoDB_Init failure.
230 void CrashOnNSSInitFailure() {
231 int nss_error = PR_GetError();
232 int os_error = PR_GetOSError();
233 base::debug::Alias(&nss_error);
234 base::debug::Alias(&os_error);
235 LOG(ERROR) << "Error initializing NSS without a persistent database: "
236 << GetNSSErrorMessage();
237 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
240 class NSSInitSingleton {
241 public:
242 #if defined(OS_CHROMEOS)
243 void OpenPersistentNSSDB() {
244 if (!chromeos_user_logged_in_) {
245 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
246 // Temporarily allow it until we fix http://crbug.com/70119
247 base::ThreadRestrictions::ScopedAllowIO allow_io;
248 chromeos_user_logged_in_ = true;
250 // This creates another DB slot in NSS that is read/write, unlike
251 // the fake root CA cert DB and the "default" crypto key
252 // provider, which are still read-only (because we initialized
253 // NSS before we had a cryptohome mounted).
254 software_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
255 kNSSDatabaseName);
259 void EnableTPMTokenForNSS() {
260 tpm_token_enabled_for_nss_ = true;
263 bool InitializeTPMToken(const std::string& token_name,
264 const std::string& user_pin) {
265 // If EnableTPMTokenForNSS hasn't been called, return false.
266 if (!tpm_token_enabled_for_nss_)
267 return false;
269 // If everything is already initialized, then return true.
270 if (chaps_module_ && tpm_slot_)
271 return true;
273 tpm_token_name_ = token_name;
274 tpm_user_pin_ = user_pin;
276 // This tries to load the Chaps module so NSS can talk to the hardware
277 // TPM.
278 if (!chaps_module_) {
279 chaps_module_ = LoadModule(
280 kChapsModuleName,
281 kChapsPath,
282 // For more details on these parameters, see:
283 // https://developer.mozilla.org/en/PKCS11_Module_Specs
284 // slotFlags=[PublicCerts] -- Certificates and public keys can be
285 // read from this slot without requiring a call to C_Login.
286 // askpw=only -- Only authenticate to the token when necessary.
287 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
289 if (chaps_module_){
290 // If this gets set, then we'll use the TPM for certs with
291 // private keys, otherwise we'll fall back to the software
292 // implementation.
293 tpm_slot_ = GetTPMSlot();
295 return tpm_slot_ != NULL;
297 return false;
300 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
301 if (!tpm_token_enabled_for_nss_) {
302 LOG(ERROR) << "GetTPMTokenInfo called before TPM Token is ready.";
303 return;
305 if (token_name)
306 *token_name = tpm_token_name_;
307 if (user_pin)
308 *user_pin = tpm_user_pin_;
311 bool IsTPMTokenReady() {
312 return tpm_slot_ != NULL;
315 PK11SlotInfo* GetTPMSlot() {
316 std::string token_name;
317 GetTPMTokenInfo(&token_name, NULL);
318 return FindSlotWithTokenName(token_name);
321 SymmetricKey* GetSupplementalUserKey() {
322 DCHECK(chromeos_user_logged_in_);
324 PK11SlotInfo* slot = NULL;
325 PK11SymKey* key = NULL;
326 SECItem keyID;
327 CK_MECHANISM_TYPE type = CKM_AES_ECB;
329 slot = GetPublicNSSKeySlot();
330 if (!slot)
331 goto done;
333 if (PK11_Authenticate(slot, PR_TRUE, NULL) != SECSuccess)
334 goto done;
336 keyID.type = siBuffer;
337 keyID.data = kSupplementalUserKeyId;
338 keyID.len = static_cast<int>(sizeof(kSupplementalUserKeyId));
340 // Find/generate AES key.
341 key = PK11_FindFixedKey(slot, type, &keyID, NULL);
342 if (!key) {
343 const int kKeySizeInBytes = 32;
344 key = PK11_TokenKeyGen(slot, type, NULL,
345 kKeySizeInBytes,
346 &keyID, PR_TRUE, NULL);
349 done:
350 if (slot)
351 PK11_FreeSlot(slot);
353 return key ? SymmetricKey::CreateFromKey(key) : NULL;
355 #endif // defined(OS_CHROMEOS)
358 bool OpenTestNSSDB() {
359 if (test_slot_)
360 return true;
361 if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
362 return false;
363 test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), "Test DB");
364 return !!test_slot_;
367 void CloseTestNSSDB() {
368 if (test_slot_) {
369 SECStatus status = SECMOD_CloseUserDB(test_slot_);
370 if (status != SECSuccess)
371 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
372 PK11_FreeSlot(test_slot_);
373 test_slot_ = NULL;
374 ignore_result(g_test_nss_db_dir.Get().Delete());
378 PK11SlotInfo* GetPublicNSSKeySlot() {
379 if (test_slot_)
380 return PK11_ReferenceSlot(test_slot_);
381 if (software_slot_)
382 return PK11_ReferenceSlot(software_slot_);
383 return PK11_GetInternalKeySlot();
386 PK11SlotInfo* GetPrivateNSSKeySlot() {
387 if (test_slot_)
388 return PK11_ReferenceSlot(test_slot_);
390 #if defined(OS_CHROMEOS)
391 if (tpm_token_enabled_for_nss_) {
392 if (IsTPMTokenReady()) {
393 return PK11_ReferenceSlot(tpm_slot_);
394 } else {
395 // If we were supposed to get the hardware token, but were
396 // unable to, return NULL rather than fall back to sofware.
397 return NULL;
400 #endif
401 // If we weren't supposed to enable the TPM for NSS, then return
402 // the software slot.
403 if (software_slot_)
404 return PK11_ReferenceSlot(software_slot_);
405 return PK11_GetInternalKeySlot();
408 #if defined(USE_NSS)
409 base::Lock* write_lock() {
410 return &write_lock_;
412 #endif // defined(USE_NSS)
414 // This method is used to force NSS to be initialized without a DB.
415 // Call this method before NSSInitSingleton() is constructed.
416 static void ForceNoDBInit() {
417 force_nodb_init_ = true;
420 private:
421 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
423 NSSInitSingleton()
424 : tpm_token_enabled_for_nss_(false),
425 chaps_module_(NULL),
426 software_slot_(NULL),
427 test_slot_(NULL),
428 tpm_slot_(NULL),
429 root_(NULL),
430 chromeos_user_logged_in_(false) {
431 EnsureNSPRInit();
433 // We *must* have NSS >= 3.12.3. See bug 26448.
434 COMPILE_ASSERT(
435 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
436 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
437 (NSS_VMAJOR > 3),
438 nss_version_check_failed);
439 // Also check the run-time NSS version.
440 // NSS_VersionCheck is a >= check, not strict equality.
441 if (!NSS_VersionCheck("3.12.3")) {
442 // It turns out many people have misconfigured NSS setups, where
443 // their run-time NSPR doesn't match the one their NSS was compiled
444 // against. So rather than aborting, complain loudly.
445 LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed. "
446 "We depend on NSS >= 3.12.3, and this error is not fatal "
447 "only because many people have busted NSS setups (for "
448 "example, using the wrong version of NSPR). "
449 "Please upgrade to the latest NSS and NSPR, and if you "
450 "still get this error, contact your distribution "
451 "maintainer.";
454 SECStatus status = SECFailure;
455 bool nodb_init = force_nodb_init_;
457 #if !defined(USE_NSS)
458 // Use the system certificate store, so initialize NSS without database.
459 nodb_init = true;
460 #endif
462 if (nodb_init) {
463 status = NSS_NoDB_Init(NULL);
464 if (status != SECSuccess) {
465 CrashOnNSSInitFailure();
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 CrashOnNSSInitFailure();
500 return;
504 PK11_SetPasswordFunc(PKCS11PasswordFunc);
506 // If we haven't initialized the password for the NSS databases,
507 // initialize an empty-string password so that we don't need to
508 // log in.
509 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
510 if (slot) {
511 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
512 // yet, so we don't need to lock.
513 if (PK11_NeedUserInit(slot))
514 PK11_InitPin(slot, NULL, NULL);
515 PK11_FreeSlot(slot);
518 root_ = InitDefaultRootCerts();
519 #endif // defined(USE_NSS)
522 // Disable MD5 certificate signatures. (They are disabled by default in
523 // NSS 3.14.)
524 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
525 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
526 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
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 InitNSSSafely() {
654 // We might fork, but we haven't loaded any security modules.
655 DisableNSSForkCheck();
656 // If we're sandboxed, we shouldn't be able to open user security modules,
657 // but it's more correct to tell NSS to not even try.
658 // Loading user security modules would have security implications.
659 ForceNSSNoDBInit();
660 // Initialize NSS.
661 EnsureNSSInit();
664 void EnsureNSSInit() {
665 // Initializing SSL causes us to do blocking IO.
666 // Temporarily allow it until we fix
667 // http://code.google.com/p/chromium/issues/detail?id=59847
668 base::ThreadRestrictions::ScopedAllowIO allow_io;
669 g_nss_singleton.Get();
672 void ForceNSSNoDBInit() {
673 NSSInitSingleton::ForceNoDBInit();
676 void DisableNSSForkCheck() {
677 scoped_ptr<base::Environment> env(base::Environment::Create());
678 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
681 void LoadNSSLibraries() {
682 // Some NSS libraries are linked dynamically so load them here.
683 #if defined(USE_NSS)
684 // Try to search for multiple directories to load the libraries.
685 std::vector<FilePath> paths;
687 // Use relative path to Search PATH for the library files.
688 paths.push_back(FilePath());
690 // For Debian derivatives NSS libraries are located here.
691 paths.push_back(FilePath("/usr/lib/nss"));
693 // Ubuntu 11.10 (Oneiric) places the libraries here.
694 #if defined(ARCH_CPU_X86_64)
695 paths.push_back(FilePath("/usr/lib/x86_64-linux-gnu/nss"));
696 #elif defined(ARCH_CPU_X86)
697 paths.push_back(FilePath("/usr/lib/i386-linux-gnu/nss"));
698 #elif defined(ARCH_CPU_ARMEL)
699 paths.push_back(FilePath("/usr/lib/arm-linux-gnueabi/nss"));
700 #endif
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");
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 FilePath path = paths[j].Append(libs[i]);
713 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
714 if (lib) {
715 ++loaded;
716 break;
721 if (loaded == libs.size()) {
722 VLOG(3) << "NSS libraries loaded.";
723 } else {
724 LOG(ERROR) << "Failed to load NSS libraries.";
726 #endif
729 bool CheckNSSVersion(const char* version) {
730 return !!NSS_VersionCheck(version);
733 #if defined(USE_NSS)
734 ScopedTestNSSDB::ScopedTestNSSDB()
735 : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
738 ScopedTestNSSDB::~ScopedTestNSSDB() {
739 // TODO(mattm): Close the dababase once NSS 3.14 is required,
740 // which fixes https://bugzilla.mozilla.org/show_bug.cgi?id=588269
741 // Resource leaks are suppressed. http://crbug.com/156433 .
744 base::Lock* GetNSSWriteLock() {
745 return g_nss_singleton.Get().write_lock();
748 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
749 // May be NULL if the lock is not needed in our version of NSS.
750 if (lock_)
751 lock_->Acquire();
754 AutoNSSWriteLock::~AutoNSSWriteLock() {
755 if (lock_) {
756 lock_->AssertAcquired();
757 lock_->Release();
761 AutoSECMODListReadLock::AutoSECMODListReadLock()
762 : lock_(SECMOD_GetDefaultModuleListLock()) {
763 SECMOD_GetReadLock(lock_);
766 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
767 SECMOD_ReleaseReadLock(lock_);
770 #endif // defined(USE_NSS)
772 #if defined(OS_CHROMEOS)
773 void OpenPersistentNSSDB() {
774 g_nss_singleton.Get().OpenPersistentNSSDB();
777 void EnableTPMTokenForNSS() {
778 g_nss_singleton.Get().EnableTPMTokenForNSS();
781 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
782 g_nss_singleton.Get().GetTPMTokenInfo(token_name, user_pin);
785 bool IsTPMTokenReady() {
786 return g_nss_singleton.Get().IsTPMTokenReady();
789 bool InitializeTPMToken(const std::string& token_name,
790 const std::string& user_pin) {
791 return g_nss_singleton.Get().InitializeTPMToken(token_name, user_pin);
794 SymmetricKey* GetSupplementalUserKey() {
795 return g_nss_singleton.Get().GetSupplementalUserKey();
797 #endif // defined(OS_CHROMEOS)
799 base::Time PRTimeToBaseTime(PRTime prtime) {
800 return base::Time::FromInternalValue(
801 prtime + base::Time::UnixEpoch().ToInternalValue());
804 PRTime BaseTimeToPRTime(base::Time time) {
805 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
808 PK11SlotInfo* GetPublicNSSKeySlot() {
809 return g_nss_singleton.Get().GetPublicNSSKeySlot();
812 PK11SlotInfo* GetPrivateNSSKeySlot() {
813 return g_nss_singleton.Get().GetPrivateNSSKeySlot();
816 } // namespace crypto