Reduce binary size impact of synthetic delays
[chromium-blink-merge.git] / crypto / nss_util.cc
blob76153a54a01647f83cb5f962a26ae2c7b0f29c0c
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 <map>
25 #include <vector>
27 #include "base/bind.h"
28 #include "base/callback.h"
29 #include "base/cpu.h"
30 #include "base/debug/alias.h"
31 #include "base/debug/stack_trace.h"
32 #include "base/environment.h"
33 #include "base/file_util.h"
34 #include "base/files/file_path.h"
35 #include "base/lazy_instance.h"
36 #include "base/logging.h"
37 #include "base/memory/scoped_ptr.h"
38 #include "base/message_loop/message_loop.h"
39 #include "base/metrics/histogram.h"
40 #include "base/native_library.h"
41 #include "base/stl_util.h"
42 #include "base/strings/stringprintf.h"
43 #include "base/threading/thread_checker.h"
44 #include "base/threading/thread_restrictions.h"
45 #include "build/build_config.h"
47 // USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not
48 // defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
49 // use NSS for crypto or certificate verification, and we don't use the NSS
50 // certificate and key databases.
51 #if defined(USE_NSS)
52 #include "base/synchronization/lock.h"
53 #include "crypto/nss_crypto_module_delegate.h"
54 #endif // defined(USE_NSS)
56 namespace crypto {
58 namespace {
60 #if defined(OS_CHROMEOS)
61 const char kNSSDatabaseName[] = "Real NSS database";
63 // Constants for loading the Chrome OS TPM-backed PKCS #11 library.
64 const char kChapsModuleName[] = "Chaps";
65 const char kChapsPath[] = "libchaps.so";
67 // Fake certificate authority database used for testing.
68 static const base::FilePath::CharType kReadOnlyCertDB[] =
69 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
70 #endif // defined(OS_CHROMEOS)
72 std::string GetNSSErrorMessage() {
73 std::string result;
74 if (PR_GetErrorTextLength()) {
75 scoped_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
76 PRInt32 copied = PR_GetErrorText(error_text.get());
77 result = std::string(error_text.get(), copied);
78 } else {
79 result = base::StringPrintf("NSS error code: %d", PR_GetError());
81 return result;
84 #if defined(USE_NSS)
85 base::FilePath GetDefaultConfigDirectory() {
86 base::FilePath dir = base::GetHomeDir();
87 if (dir.empty()) {
88 LOG(ERROR) << "Failed to get home directory.";
89 return dir;
91 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
92 if (!base::CreateDirectory(dir)) {
93 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
94 dir.clear();
96 DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
97 return dir;
100 // On non-Chrome OS platforms, return the default config directory. On Chrome OS
101 // test images, return a read-only directory with fake root CA certs (which are
102 // used by the local Google Accounts server mock we use when testing our login
103 // code). On Chrome OS non-test images (where the read-only directory doesn't
104 // exist), return an empty path.
105 base::FilePath GetInitialConfigDirectory() {
106 #if defined(OS_CHROMEOS)
107 base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
108 if (!base::PathExists(database_dir))
109 database_dir.clear();
110 return database_dir;
111 #else
112 return GetDefaultConfigDirectory();
113 #endif // defined(OS_CHROMEOS)
116 // This callback for NSS forwards all requests to a caller-specified
117 // CryptoModuleBlockingPasswordDelegate object.
118 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
119 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
120 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
121 if (delegate) {
122 bool cancelled = false;
123 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
124 retry != PR_FALSE,
125 &cancelled);
126 if (cancelled)
127 return NULL;
128 char* result = PORT_Strdup(password.c_str());
129 password.replace(0, password.size(), password.size(), 0);
130 return result;
132 DLOG(ERROR) << "PK11 password requested with NULL arg";
133 return NULL;
136 // NSS creates a local cache of the sqlite database if it detects that the
137 // filesystem the database is on is much slower than the local disk. The
138 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
139 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
140 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
141 // detection when database_dir is on NFS. See http://crbug.com/48585.
143 // TODO(wtc): port this function to other USE_NSS platforms. It is defined
144 // only for OS_LINUX and OS_OPENBSD simply because the statfs structure
145 // is OS-specific.
147 // Because this function sets an environment variable it must be run before we
148 // go multi-threaded.
149 void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) {
150 #if defined(OS_LINUX) || defined(OS_OPENBSD)
151 struct statfs buf;
152 if (statfs(database_dir.value().c_str(), &buf) == 0) {
153 #if defined(OS_LINUX)
154 if (buf.f_type == NFS_SUPER_MAGIC) {
155 #elif defined(OS_OPENBSD)
156 if (strcmp(buf.f_fstypename, MOUNT_NFS) == 0) {
157 #endif
158 scoped_ptr<base::Environment> env(base::Environment::Create());
159 const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
160 if (!env->HasVar(use_cache_env_var))
161 env->SetVar(use_cache_env_var, "yes");
164 #endif // defined(OS_LINUX) || defined(OS_OPENBSD)
167 #endif // defined(USE_NSS)
169 // A singleton to initialize/deinitialize NSPR.
170 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
171 // Now that we're leaking the singleton, we could merge back with the NSS
172 // singleton.
173 class NSPRInitSingleton {
174 private:
175 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
177 NSPRInitSingleton() {
178 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
181 // NOTE(willchan): We don't actually execute this code since we leak NSS to
182 // prevent non-joinable threads from using NSS after it's already been shut
183 // down.
184 ~NSPRInitSingleton() {
185 PL_ArenaFinish();
186 PRStatus prstatus = PR_Cleanup();
187 if (prstatus != PR_SUCCESS)
188 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
192 base::LazyInstance<NSPRInitSingleton>::Leaky
193 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
195 // This is a LazyInstance so that it will be deleted automatically when the
196 // unittest exits. NSSInitSingleton is a LeakySingleton, so it would not be
197 // deleted if it were a regular member.
198 base::LazyInstance<base::ScopedTempDir> g_test_nss_db_dir =
199 LAZY_INSTANCE_INITIALIZER;
201 // Force a crash with error info on NSS_NoDB_Init failure.
202 void CrashOnNSSInitFailure() {
203 int nss_error = PR_GetError();
204 int os_error = PR_GetOSError();
205 base::debug::Alias(&nss_error);
206 base::debug::Alias(&os_error);
207 LOG(ERROR) << "Error initializing NSS without a persistent database: "
208 << GetNSSErrorMessage();
209 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
212 #if defined(OS_CHROMEOS)
213 class ChromeOSUserData {
214 public:
215 ChromeOSUserData(ScopedPK11Slot public_slot, bool is_primary_user)
216 : public_slot_(public_slot.Pass()),
217 is_primary_user_(is_primary_user) {}
218 ~ChromeOSUserData() {
219 if (public_slot_ && !is_primary_user_) {
220 SECStatus status = SECMOD_CloseUserDB(public_slot_.get());
221 if (status != SECSuccess)
222 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
226 ScopedPK11Slot GetPublicSlot() {
227 return ScopedPK11Slot(
228 public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL);
231 ScopedPK11Slot GetPrivateSlot(
232 const base::Callback<void(ScopedPK11Slot)>& callback) {
233 if (private_slot_)
234 return ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get()));
235 if (!callback.is_null())
236 tpm_ready_callback_list_.push_back(callback);
237 return ScopedPK11Slot();
240 void SetPrivateSlot(ScopedPK11Slot private_slot) {
241 DCHECK(!private_slot_);
242 private_slot_ = private_slot.Pass();
244 SlotReadyCallbackList callback_list;
245 callback_list.swap(tpm_ready_callback_list_);
246 for (SlotReadyCallbackList::iterator i = callback_list.begin();
247 i != callback_list.end();
248 ++i) {
249 (*i).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get())));
253 private:
254 ScopedPK11Slot public_slot_;
255 ScopedPK11Slot private_slot_;
256 bool is_primary_user_;
258 typedef std::vector<base::Callback<void(ScopedPK11Slot)> >
259 SlotReadyCallbackList;
260 SlotReadyCallbackList tpm_ready_callback_list_;
262 #endif // defined(OS_CHROMEOS)
264 class NSSInitSingleton {
265 public:
266 #if defined(OS_CHROMEOS)
267 void OpenPersistentNSSDB() {
268 DCHECK(thread_checker_.CalledOnValidThread());
270 if (!chromeos_user_logged_in_) {
271 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
272 // Temporarily allow it until we fix http://crbug.com/70119
273 base::ThreadRestrictions::ScopedAllowIO allow_io;
274 chromeos_user_logged_in_ = true;
276 // This creates another DB slot in NSS that is read/write, unlike
277 // the fake root CA cert DB and the "default" crypto key
278 // provider, which are still read-only (because we initialized
279 // NSS before we had a cryptohome mounted).
280 software_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
281 kNSSDatabaseName);
285 PK11SlotInfo* OpenPersistentNSSDBForPath(const base::FilePath& path) {
286 DCHECK(thread_checker_.CalledOnValidThread());
287 // NSS is allowed to do IO on the current thread since dispatching
288 // to a dedicated thread would still have the affect of blocking
289 // the current thread, due to NSS's internal locking requirements
290 base::ThreadRestrictions::ScopedAllowIO allow_io;
292 base::FilePath nssdb_path = path.AppendASCII(".pki").AppendASCII("nssdb");
293 if (!base::CreateDirectory(nssdb_path)) {
294 LOG(ERROR) << "Failed to create " << nssdb_path.value() << " directory.";
295 return NULL;
297 return OpenUserDB(nssdb_path, kNSSDatabaseName);
300 void EnableTPMTokenForNSS() {
301 DCHECK(thread_checker_.CalledOnValidThread());
303 // If this gets set, then we'll use the TPM for certs with
304 // private keys, otherwise we'll fall back to the software
305 // implementation.
306 tpm_token_enabled_for_nss_ = true;
309 bool IsTPMTokenEnabledForNSS() {
310 DCHECK(thread_checker_.CalledOnValidThread());
311 return tpm_token_enabled_for_nss_;
314 bool InitializeTPMToken(int token_slot_id) {
315 DCHECK(thread_checker_.CalledOnValidThread());
317 // If EnableTPMTokenForNSS hasn't been called, return false.
318 if (!tpm_token_enabled_for_nss_)
319 return false;
321 // If everything is already initialized, then return true.
322 if (chaps_module_ && tpm_slot_)
323 return true;
325 // This tries to load the Chaps module so NSS can talk to the hardware
326 // TPM.
327 if (!chaps_module_) {
328 chaps_module_ = LoadModule(
329 kChapsModuleName,
330 kChapsPath,
331 // For more details on these parameters, see:
332 // https://developer.mozilla.org/en/PKCS11_Module_Specs
333 // slotFlags=[PublicCerts] -- Certificates and public keys can be
334 // read from this slot without requiring a call to C_Login.
335 // askpw=only -- Only authenticate to the token when necessary.
336 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
337 if (!chaps_module_ && test_slot_) {
338 // chromeos_unittests try to test the TPM initialization process. If we
339 // have a test DB open, pretend that it is the TPM slot.
340 tpm_slot_ = PK11_ReferenceSlot(test_slot_);
341 return true;
344 if (chaps_module_){
345 tpm_slot_ = GetTPMSlotForId(token_slot_id);
347 if (!tpm_slot_)
348 return false;
350 TPMReadyCallbackList callback_list;
351 callback_list.swap(tpm_ready_callback_list_);
352 for (TPMReadyCallbackList::iterator i =
353 callback_list.begin();
354 i != callback_list.end();
355 ++i) {
356 (*i).Run();
359 return true;
361 return false;
364 bool IsTPMTokenReady(const base::Closure& callback) {
365 if (!callback.is_null()) {
366 // Cannot DCHECK in the general case yet, but since the callback is
367 // a new addition to the API, DCHECK to make sure at least the new uses
368 // don't regress.
369 DCHECK(thread_checker_.CalledOnValidThread());
370 } else if (!thread_checker_.CalledOnValidThread()) {
371 // TODO(mattm): Change to DCHECK when callers have been fixed.
372 DVLOG(1) << "Called on wrong thread.\n"
373 << base::debug::StackTrace().ToString();
376 if (tpm_slot_ != NULL)
377 return true;
379 if (!callback.is_null())
380 tpm_ready_callback_list_.push_back(callback);
382 return false;
385 // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
386 // id as an int. This should be safe since this is only used with chaps, which
387 // we also control.
388 PK11SlotInfo* GetTPMSlotForId(CK_SLOT_ID slot_id) {
389 DCHECK(thread_checker_.CalledOnValidThread());
391 if (!chaps_module_)
392 return NULL;
394 DVLOG(3) << "Poking chaps module.";
395 SECStatus rv = SECMOD_UpdateSlotList(chaps_module_);
396 if (rv != SECSuccess)
397 PLOG(ERROR) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
399 PK11SlotInfo* slot = SECMOD_LookupSlot(chaps_module_->moduleID, slot_id);
400 if (!slot)
401 LOG(ERROR) << "TPM slot " << slot_id << " not found.";
402 return slot;
405 bool InitializeNSSForChromeOSUser(
406 const std::string& email,
407 const std::string& username_hash,
408 bool is_primary_user,
409 const base::FilePath& path) {
410 DCHECK(thread_checker_.CalledOnValidThread());
411 if (chromeos_user_map_.find(username_hash) != chromeos_user_map_.end()) {
412 // This user already exists in our mapping.
413 DVLOG(2) << username_hash << " already initialized.";
414 return false;
416 ScopedPK11Slot public_slot;
417 if (is_primary_user) {
418 DVLOG(2) << "Primary user, using GetPublicNSSKeySlot()";
419 public_slot.reset(GetPublicNSSKeySlot());
420 } else {
421 DVLOG(2) << "Opening NSS DB " << path.value();
422 public_slot.reset(OpenPersistentNSSDBForPath(path));
424 chromeos_user_map_[username_hash] =
425 new ChromeOSUserData(public_slot.Pass(), is_primary_user);
426 return true;
429 void InitializeTPMForChromeOSUser(const std::string& username_hash,
430 CK_SLOT_ID slot_id) {
431 DCHECK(thread_checker_.CalledOnValidThread());
432 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
433 chromeos_user_map_[username_hash]
434 ->SetPrivateSlot(ScopedPK11Slot(GetTPMSlotForId(slot_id)));
437 void InitializePrivateSoftwareSlotForChromeOSUser(
438 const std::string& username_hash) {
439 DCHECK(thread_checker_.CalledOnValidThread());
440 LOG(WARNING) << "using software private slot for " << username_hash;
441 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
442 chromeos_user_map_[username_hash]->SetPrivateSlot(
443 chromeos_user_map_[username_hash]->GetPublicSlot());
446 ScopedPK11Slot GetPublicSlotForChromeOSUser(
447 const std::string& username_hash) {
448 DCHECK(thread_checker_.CalledOnValidThread());
450 if (username_hash.empty()) {
451 DVLOG(2) << "empty username_hash";
452 return ScopedPK11Slot();
455 if (test_slot_) {
456 DVLOG(2) << "returning test_slot_ for " << username_hash;
457 return ScopedPK11Slot(PK11_ReferenceSlot(test_slot_));
460 if (chromeos_user_map_.find(username_hash) == chromeos_user_map_.end()) {
461 LOG(ERROR) << username_hash << " not initialized.";
462 return ScopedPK11Slot();
464 return chromeos_user_map_[username_hash]->GetPublicSlot();
467 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
468 const std::string& username_hash,
469 const base::Callback<void(ScopedPK11Slot)>& callback) {
470 DCHECK(thread_checker_.CalledOnValidThread());
472 if (username_hash.empty()) {
473 DVLOG(2) << "empty username_hash";
474 if (!callback.is_null()) {
475 base::MessageLoop::current()->PostTask(
476 FROM_HERE, base::Bind(callback, base::Passed(ScopedPK11Slot())));
478 return ScopedPK11Slot();
481 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
483 if (test_slot_) {
484 DVLOG(2) << "returning test_slot_ for " << username_hash;
485 return ScopedPK11Slot(PK11_ReferenceSlot(test_slot_));
488 return chromeos_user_map_[username_hash]->GetPrivateSlot(callback);
491 void CloseTestChromeOSUser(const std::string& username_hash) {
492 DCHECK(thread_checker_.CalledOnValidThread());
493 ChromeOSUserMap::iterator i = chromeos_user_map_.find(username_hash);
494 DCHECK(i != chromeos_user_map_.end());
495 delete i->second;
496 chromeos_user_map_.erase(i);
498 #endif // defined(OS_CHROMEOS)
501 bool OpenTestNSSDB() {
502 DCHECK(thread_checker_.CalledOnValidThread());
503 // NSS is allowed to do IO on the current thread since dispatching
504 // to a dedicated thread would still have the affect of blocking
505 // the current thread, due to NSS's internal locking requirements
506 base::ThreadRestrictions::ScopedAllowIO allow_io;
508 if (test_slot_)
509 return true;
510 if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
511 return false;
512 test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), kTestTPMTokenName);
513 return !!test_slot_;
516 void CloseTestNSSDB() {
517 DCHECK(thread_checker_.CalledOnValidThread());
518 // NSS is allowed to do IO on the current thread since dispatching
519 // to a dedicated thread would still have the affect of blocking
520 // the current thread, due to NSS's internal locking requirements
521 base::ThreadRestrictions::ScopedAllowIO allow_io;
523 if (!test_slot_)
524 return;
525 SECStatus status = SECMOD_CloseUserDB(test_slot_);
526 if (status != SECSuccess)
527 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
528 PK11_FreeSlot(test_slot_);
529 test_slot_ = NULL;
530 ignore_result(g_test_nss_db_dir.Get().Delete());
533 PK11SlotInfo* GetPublicNSSKeySlot() {
534 // TODO(mattm): Change to DCHECK when callers have been fixed.
535 if (!thread_checker_.CalledOnValidThread()) {
536 DVLOG(1) << "Called on wrong thread.\n"
537 << base::debug::StackTrace().ToString();
540 if (test_slot_)
541 return PK11_ReferenceSlot(test_slot_);
542 if (software_slot_)
543 return PK11_ReferenceSlot(software_slot_);
544 return PK11_GetInternalKeySlot();
547 PK11SlotInfo* GetPrivateNSSKeySlot() {
548 // TODO(mattm): Change to DCHECK when callers have been fixed.
549 if (!thread_checker_.CalledOnValidThread()) {
550 DVLOG(1) << "Called on wrong thread.\n"
551 << base::debug::StackTrace().ToString();
554 if (test_slot_)
555 return PK11_ReferenceSlot(test_slot_);
557 #if defined(OS_CHROMEOS)
558 if (tpm_token_enabled_for_nss_) {
559 if (IsTPMTokenReady(base::Closure())) {
560 return PK11_ReferenceSlot(tpm_slot_);
561 } else {
562 // If we were supposed to get the hardware token, but were
563 // unable to, return NULL rather than fall back to sofware.
564 return NULL;
567 #endif
568 // If we weren't supposed to enable the TPM for NSS, then return
569 // the software slot.
570 if (software_slot_)
571 return PK11_ReferenceSlot(software_slot_);
572 return PK11_GetInternalKeySlot();
575 #if defined(USE_NSS)
576 base::Lock* write_lock() {
577 return &write_lock_;
579 #endif // defined(USE_NSS)
581 // This method is used to force NSS to be initialized without a DB.
582 // Call this method before NSSInitSingleton() is constructed.
583 static void ForceNoDBInit() {
584 force_nodb_init_ = true;
587 private:
588 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
590 NSSInitSingleton()
591 : tpm_token_enabled_for_nss_(false),
592 chaps_module_(NULL),
593 software_slot_(NULL),
594 test_slot_(NULL),
595 tpm_slot_(NULL),
596 root_(NULL),
597 chromeos_user_logged_in_(false) {
598 base::TimeTicks start_time = base::TimeTicks::Now();
600 // It's safe to construct on any thread, since LazyInstance will prevent any
601 // other threads from accessing until the constructor is done.
602 thread_checker_.DetachFromThread();
604 DisableAESNIIfNeeded();
606 EnsureNSPRInit();
608 // We *must* have NSS >= 3.14.3.
609 COMPILE_ASSERT(
610 (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
611 (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
612 (NSS_VMAJOR > 3),
613 nss_version_check_failed);
614 // Also check the run-time NSS version.
615 // NSS_VersionCheck is a >= check, not strict equality.
616 if (!NSS_VersionCheck("3.14.3")) {
617 LOG(FATAL) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
618 "required. Please upgrade to the latest NSS, and if you "
619 "still get this error, contact your distribution "
620 "maintainer.";
623 SECStatus status = SECFailure;
624 bool nodb_init = force_nodb_init_;
626 #if !defined(USE_NSS)
627 // Use the system certificate store, so initialize NSS without database.
628 nodb_init = true;
629 #endif
631 if (nodb_init) {
632 status = NSS_NoDB_Init(NULL);
633 if (status != SECSuccess) {
634 CrashOnNSSInitFailure();
635 return;
637 #if defined(OS_IOS)
638 root_ = InitDefaultRootCerts();
639 #endif // defined(OS_IOS)
640 } else {
641 #if defined(USE_NSS)
642 base::FilePath database_dir = GetInitialConfigDirectory();
643 if (!database_dir.empty()) {
644 // This duplicates the work which should have been done in
645 // EarlySetupForNSSInit. However, this function is idempotent so
646 // there's no harm done.
647 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
649 // Initialize with a persistent database (likely, ~/.pki/nssdb).
650 // Use "sql:" which can be shared by multiple processes safely.
651 std::string nss_config_dir =
652 base::StringPrintf("sql:%s", database_dir.value().c_str());
653 #if defined(OS_CHROMEOS)
654 status = NSS_Init(nss_config_dir.c_str());
655 #else
656 status = NSS_InitReadWrite(nss_config_dir.c_str());
657 #endif
658 if (status != SECSuccess) {
659 LOG(ERROR) << "Error initializing NSS with a persistent "
660 "database (" << nss_config_dir
661 << "): " << GetNSSErrorMessage();
664 if (status != SECSuccess) {
665 VLOG(1) << "Initializing NSS without a persistent database.";
666 status = NSS_NoDB_Init(NULL);
667 if (status != SECSuccess) {
668 CrashOnNSSInitFailure();
669 return;
673 PK11_SetPasswordFunc(PKCS11PasswordFunc);
675 // If we haven't initialized the password for the NSS databases,
676 // initialize an empty-string password so that we don't need to
677 // log in.
678 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
679 if (slot) {
680 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
681 // yet, so we don't need to lock.
682 if (PK11_NeedUserInit(slot))
683 PK11_InitPin(slot, NULL, NULL);
684 PK11_FreeSlot(slot);
687 root_ = InitDefaultRootCerts();
688 #endif // defined(USE_NSS)
691 // Disable MD5 certificate signatures. (They are disabled by default in
692 // NSS 3.14.)
693 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
694 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
695 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
697 // The UMA bit is conditionally set for this histogram in
698 // chrome/common/startup_metric_utils.cc .
699 HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
700 base::TimeTicks::Now() - start_time,
701 base::TimeDelta::FromMilliseconds(10),
702 base::TimeDelta::FromHours(1),
703 50);
706 // NOTE(willchan): We don't actually execute this code since we leak NSS to
707 // prevent non-joinable threads from using NSS after it's already been shut
708 // down.
709 ~NSSInitSingleton() {
710 #if defined(OS_CHROMEOS)
711 STLDeleteValues(&chromeos_user_map_);
712 #endif
713 if (tpm_slot_) {
714 PK11_FreeSlot(tpm_slot_);
715 tpm_slot_ = NULL;
717 if (software_slot_) {
718 SECMOD_CloseUserDB(software_slot_);
719 PK11_FreeSlot(software_slot_);
720 software_slot_ = NULL;
722 CloseTestNSSDB();
723 if (root_) {
724 SECMOD_UnloadUserModule(root_);
725 SECMOD_DestroyModule(root_);
726 root_ = NULL;
728 if (chaps_module_) {
729 SECMOD_UnloadUserModule(chaps_module_);
730 SECMOD_DestroyModule(chaps_module_);
731 chaps_module_ = NULL;
734 SECStatus status = NSS_Shutdown();
735 if (status != SECSuccess) {
736 // We VLOG(1) because this failure is relatively harmless (leaking, but
737 // we're shutting down anyway).
738 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
742 #if defined(USE_NSS) || defined(OS_IOS)
743 // Load nss's built-in root certs.
744 SECMODModule* InitDefaultRootCerts() {
745 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
746 if (root)
747 return root;
749 // Aw, snap. Can't find/load root cert shared library.
750 // This will make it hard to talk to anybody via https.
751 // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
752 return NULL;
755 // Load the given module for this NSS session.
756 SECMODModule* LoadModule(const char* name,
757 const char* library_path,
758 const char* params) {
759 std::string modparams = base::StringPrintf(
760 "name=\"%s\" library=\"%s\" %s",
761 name, library_path, params ? params : "");
763 // Shouldn't need to const_cast here, but SECMOD doesn't properly
764 // declare input string arguments as const. Bug
765 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
766 // on NSS codebase to address this.
767 SECMODModule* module = SECMOD_LoadUserModule(
768 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
769 if (!module) {
770 LOG(ERROR) << "Error loading " << name << " module into NSS: "
771 << GetNSSErrorMessage();
772 return NULL;
774 if (!module->loaded) {
775 LOG(ERROR) << "After loading " << name << ", loaded==false: "
776 << GetNSSErrorMessage();
777 SECMOD_DestroyModule(module);
778 return NULL;
780 return module;
782 #endif
784 static PK11SlotInfo* OpenUserDB(const base::FilePath& path,
785 const char* description) {
786 const std::string modspec =
787 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
788 path.value().c_str(), description);
789 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
790 if (db_slot) {
791 if (PK11_NeedUserInit(db_slot))
792 PK11_InitPin(db_slot, NULL, NULL);
794 else {
795 LOG(ERROR) << "Error opening persistent database (" << modspec
796 << "): " << GetNSSErrorMessage();
798 return db_slot;
801 static void DisableAESNIIfNeeded() {
802 if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
803 // Some versions of NSS have a bug that causes AVX instructions to be
804 // used without testing whether XSAVE is enabled by the operating system.
805 // In order to work around this, we disable AES-NI in NSS when we find
806 // that |has_avx()| is false (which includes the XSAVE test). See
807 // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
808 base::CPU cpu;
810 if (cpu.has_avx_hardware() && !cpu.has_avx()) {
811 base::Environment::Create()->SetVar("NSS_DISABLE_HW_AES", "1");
816 // If this is set to true NSS is forced to be initialized without a DB.
817 static bool force_nodb_init_;
819 bool tpm_token_enabled_for_nss_;
820 typedef std::vector<base::Closure> TPMReadyCallbackList;
821 TPMReadyCallbackList tpm_ready_callback_list_;
822 SECMODModule* chaps_module_;
823 PK11SlotInfo* software_slot_;
824 PK11SlotInfo* test_slot_;
825 PK11SlotInfo* tpm_slot_;
826 SECMODModule* root_;
827 bool chromeos_user_logged_in_;
828 #if defined(OS_CHROMEOS)
829 typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
830 ChromeOSUserMap chromeos_user_map_;
831 #endif
832 #if defined(USE_NSS)
833 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
834 // is fixed, we will no longer need the lock.
835 base::Lock write_lock_;
836 #endif // defined(USE_NSS)
838 base::ThreadChecker thread_checker_;
841 // static
842 bool NSSInitSingleton::force_nodb_init_ = false;
844 base::LazyInstance<NSSInitSingleton>::Leaky
845 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
846 } // namespace
848 const char kTestTPMTokenName[] = "Test DB";
850 #if defined(USE_NSS)
851 void EarlySetupForNSSInit() {
852 base::FilePath database_dir = GetInitialConfigDirectory();
853 if (!database_dir.empty())
854 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
856 #endif
858 void EnsureNSPRInit() {
859 g_nspr_singleton.Get();
862 void InitNSSSafely() {
863 // We might fork, but we haven't loaded any security modules.
864 DisableNSSForkCheck();
865 // If we're sandboxed, we shouldn't be able to open user security modules,
866 // but it's more correct to tell NSS to not even try.
867 // Loading user security modules would have security implications.
868 ForceNSSNoDBInit();
869 // Initialize NSS.
870 EnsureNSSInit();
873 void EnsureNSSInit() {
874 // Initializing SSL causes us to do blocking IO.
875 // Temporarily allow it until we fix
876 // http://code.google.com/p/chromium/issues/detail?id=59847
877 base::ThreadRestrictions::ScopedAllowIO allow_io;
878 g_nss_singleton.Get();
881 void ForceNSSNoDBInit() {
882 NSSInitSingleton::ForceNoDBInit();
885 void DisableNSSForkCheck() {
886 scoped_ptr<base::Environment> env(base::Environment::Create());
887 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
890 void LoadNSSLibraries() {
891 // Some NSS libraries are linked dynamically so load them here.
892 #if defined(USE_NSS)
893 // Try to search for multiple directories to load the libraries.
894 std::vector<base::FilePath> paths;
896 // Use relative path to Search PATH for the library files.
897 paths.push_back(base::FilePath());
899 // For Debian derivatives NSS libraries are located here.
900 paths.push_back(base::FilePath("/usr/lib/nss"));
902 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
903 #if defined(ARCH_CPU_X86_64)
904 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
905 #elif defined(ARCH_CPU_X86)
906 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
907 #elif defined(ARCH_CPU_ARMEL)
908 #if defined(__ARM_PCS_VFP)
909 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
910 #else
911 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
912 #endif
913 #elif defined(ARCH_CPU_MIPSEL)
914 paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
915 #endif
917 // A list of library files to load.
918 std::vector<std::string> libs;
919 libs.push_back("libsoftokn3.so");
920 libs.push_back("libfreebl3.so");
922 // For each combination of library file and path, check for existence and
923 // then load.
924 size_t loaded = 0;
925 for (size_t i = 0; i < libs.size(); ++i) {
926 for (size_t j = 0; j < paths.size(); ++j) {
927 base::FilePath path = paths[j].Append(libs[i]);
928 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
929 if (lib) {
930 ++loaded;
931 break;
936 if (loaded == libs.size()) {
937 VLOG(3) << "NSS libraries loaded.";
938 } else {
939 LOG(ERROR) << "Failed to load NSS libraries.";
941 #endif
944 bool CheckNSSVersion(const char* version) {
945 return !!NSS_VersionCheck(version);
948 #if defined(USE_NSS)
949 ScopedTestNSSDB::ScopedTestNSSDB()
950 : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
953 ScopedTestNSSDB::~ScopedTestNSSDB() {
954 // Don't close when NSS is < 3.15.1, because it would require an additional
955 // sleep for 1 second after closing the database, due to
956 // http://bugzil.la/875601.
957 if (NSS_VersionCheck("3.15.1")) {
958 g_nss_singleton.Get().CloseTestNSSDB();
962 base::Lock* GetNSSWriteLock() {
963 return g_nss_singleton.Get().write_lock();
966 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
967 // May be NULL if the lock is not needed in our version of NSS.
968 if (lock_)
969 lock_->Acquire();
972 AutoNSSWriteLock::~AutoNSSWriteLock() {
973 if (lock_) {
974 lock_->AssertAcquired();
975 lock_->Release();
979 AutoSECMODListReadLock::AutoSECMODListReadLock()
980 : lock_(SECMOD_GetDefaultModuleListLock()) {
981 SECMOD_GetReadLock(lock_);
984 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
985 SECMOD_ReleaseReadLock(lock_);
988 #endif // defined(USE_NSS)
990 #if defined(OS_CHROMEOS)
991 void OpenPersistentNSSDB() {
992 g_nss_singleton.Get().OpenPersistentNSSDB();
995 void EnableTPMTokenForNSS() {
996 g_nss_singleton.Get().EnableTPMTokenForNSS();
999 bool IsTPMTokenEnabledForNSS() {
1000 return g_nss_singleton.Get().IsTPMTokenEnabledForNSS();
1003 bool IsTPMTokenReady(const base::Closure& callback) {
1004 return g_nss_singleton.Get().IsTPMTokenReady(callback);
1007 bool InitializeTPMToken(int token_slot_id) {
1008 return g_nss_singleton.Get().InitializeTPMToken(token_slot_id);
1011 ScopedTestNSSChromeOSUser::ScopedTestNSSChromeOSUser(
1012 const std::string& username_hash)
1013 : username_hash_(username_hash), constructed_successfully_(false) {
1014 if (!temp_dir_.CreateUniqueTempDir())
1015 return;
1016 constructed_successfully_ =
1017 InitializeNSSForChromeOSUser(username_hash,
1018 username_hash,
1019 false /* is_primary_user */,
1020 temp_dir_.path());
1023 ScopedTestNSSChromeOSUser::~ScopedTestNSSChromeOSUser() {
1024 if (constructed_successfully_)
1025 g_nss_singleton.Get().CloseTestChromeOSUser(username_hash_);
1028 void ScopedTestNSSChromeOSUser::FinishInit() {
1029 InitializePrivateSoftwareSlotForChromeOSUser(username_hash_);
1032 bool InitializeNSSForChromeOSUser(
1033 const std::string& email,
1034 const std::string& username_hash,
1035 bool is_primary_user,
1036 const base::FilePath& path) {
1037 return g_nss_singleton.Get().InitializeNSSForChromeOSUser(
1038 email, username_hash, is_primary_user, path);
1040 void InitializeTPMForChromeOSUser(
1041 const std::string& username_hash,
1042 CK_SLOT_ID slot_id) {
1043 g_nss_singleton.Get().InitializeTPMForChromeOSUser(username_hash, slot_id);
1045 void InitializePrivateSoftwareSlotForChromeOSUser(
1046 const std::string& username_hash) {
1047 g_nss_singleton.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1048 username_hash);
1050 ScopedPK11Slot GetPublicSlotForChromeOSUser(const std::string& username_hash) {
1051 return g_nss_singleton.Get().GetPublicSlotForChromeOSUser(username_hash);
1053 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
1054 const std::string& username_hash,
1055 const base::Callback<void(ScopedPK11Slot)>& callback) {
1056 return g_nss_singleton.Get().GetPrivateSlotForChromeOSUser(username_hash,
1057 callback);
1059 #endif // defined(OS_CHROMEOS)
1061 base::Time PRTimeToBaseTime(PRTime prtime) {
1062 return base::Time::FromInternalValue(
1063 prtime + base::Time::UnixEpoch().ToInternalValue());
1066 PRTime BaseTimeToPRTime(base::Time time) {
1067 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1070 PK11SlotInfo* GetPublicNSSKeySlot() {
1071 return g_nss_singleton.Get().GetPublicNSSKeySlot();
1074 PK11SlotInfo* GetPrivateNSSKeySlot() {
1075 return g_nss_singleton.Get().GetPrivateNSSKeySlot();
1078 } // namespace crypto