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"
17 #include <linux/nfs_fs.h>
19 #elif defined(OS_OPENBSD)
20 #include <sys/mount.h>
21 #include <sys/param.h>
27 #include "base/bind.h"
28 #include "base/callback.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.
52 #include "base/synchronization/lock.h"
53 #include "crypto/nss_crypto_module_delegate.h"
54 #endif // defined(USE_NSS)
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() {
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
);
79 result
= base::StringPrintf("NSS error code: %d", PR_GetError());
85 base::FilePath
GetDefaultConfigDirectory() {
86 base::FilePath dir
= base::GetHomeDir();
88 LOG(ERROR
) << "Failed to get home directory.";
91 dir
= dir
.AppendASCII(".pki").AppendASCII("nssdb");
92 if (!base::CreateDirectory(dir
)) {
93 LOG(ERROR
) << "Failed to create " << dir
.value() << " directory.";
96 DVLOG(2) << "DefaultConfigDirectory: " << dir
.value();
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();
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
);
122 bool cancelled
= false;
123 std::string password
= delegate
->RequestPassword(PK11_GetTokenName(slot
),
128 char* result
= PORT_Strdup(password
.c_str());
129 password
.replace(0, password
.size(), password
.size(), 0);
132 DLOG(ERROR
) << "PK11 password requested with NULL arg";
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
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)
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) {
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
173 class NSPRInitSingleton
{
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
184 ~NSPRInitSingleton() {
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
{
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
) {
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();
249 (*i
).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_
.get())));
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
{
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(),
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.";
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
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_
)
321 // If everything is already initialized, then return true.
322 if (chaps_module_
&& tpm_slot_
)
325 // This tries to load the Chaps module so NSS can talk to the hardware
327 if (!chaps_module_
) {
328 chaps_module_
= LoadModule(
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_
);
345 tpm_slot_
= GetTPMSlotForId(token_slot_id
);
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();
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
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
)
379 if (!callback
.is_null())
380 tpm_ready_callback_list_
.push_back(callback
);
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
388 PK11SlotInfo
* GetTPMSlotForId(CK_SLOT_ID slot_id
) {
389 DCHECK(thread_checker_
.CalledOnValidThread());
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
);
401 LOG(ERROR
) << "TPM slot " << slot_id
<< " not found.";
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.";
416 ScopedPK11Slot public_slot
;
417 if (is_primary_user
) {
418 DVLOG(2) << "Primary user, using GetPublicNSSKeySlot()";
419 public_slot
.reset(GetPublicNSSKeySlot());
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
);
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();
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());
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());
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
;
510 if (!g_test_nss_db_dir
.Get().CreateUniqueTempDir())
512 test_slot_
= OpenUserDB(g_test_nss_db_dir
.Get().path(), kTestTPMTokenName
);
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
;
525 SECStatus status
= SECMOD_CloseUserDB(test_slot_
);
526 if (status
!= SECSuccess
)
527 PLOG(ERROR
) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
528 PK11_FreeSlot(test_slot_
);
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();
541 return PK11_ReferenceSlot(test_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();
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_
);
562 // If we were supposed to get the hardware token, but were
563 // unable to, return NULL rather than fall back to sofware.
568 // If we weren't supposed to enable the TPM for NSS, then return
569 // the software slot.
571 return PK11_ReferenceSlot(software_slot_
);
572 return PK11_GetInternalKeySlot();
576 base::Lock
* 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;
588 friend struct base::DefaultLazyInstanceTraits
<NSSInitSingleton
>;
591 : tpm_token_enabled_for_nss_(false),
593 software_slot_(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();
608 // We *must* have NSS >= 3.14.3.
610 (NSS_VMAJOR
== 3 && NSS_VMINOR
== 14 && NSS_VPATCH
>= 3) ||
611 (NSS_VMAJOR
== 3 && NSS_VMINOR
> 14) ||
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 "
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.
632 status
= NSS_NoDB_Init(NULL
);
633 if (status
!= SECSuccess
) {
634 CrashOnNSSInitFailure();
638 root_
= InitDefaultRootCerts();
639 #endif // defined(OS_IOS)
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());
656 status
= NSS_InitReadWrite(nss_config_dir
.c_str());
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();
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
678 PK11SlotInfo
* slot
= PK11_GetInternalKeySlot();
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
);
687 root_
= InitDefaultRootCerts();
688 #endif // defined(USE_NSS)
691 // Disable MD5 certificate signatures. (They are disabled by default in
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),
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
709 ~NSSInitSingleton() {
710 #if defined(OS_CHROMEOS)
711 STLDeleteValues(&chromeos_user_map_
);
714 PK11_FreeSlot(tpm_slot_
);
717 if (software_slot_
) {
718 SECMOD_CloseUserDB(software_slot_
);
719 PK11_FreeSlot(software_slot_
);
720 software_slot_
= NULL
;
724 SECMOD_UnloadUserModule(root_
);
725 SECMOD_DestroyModule(root_
);
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
);
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.
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
);
770 LOG(ERROR
) << "Error loading " << name
<< " module into NSS: "
771 << GetNSSErrorMessage();
774 if (!module
->loaded
) {
775 LOG(ERROR
) << "After loading " << name
<< ", loaded==false: "
776 << GetNSSErrorMessage();
777 SECMOD_DestroyModule(module
);
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());
791 if (PK11_NeedUserInit(db_slot
))
792 PK11_InitPin(db_slot
, NULL
, NULL
);
795 LOG(ERROR
) << "Error opening persistent database (" << modspec
796 << "): " << GetNSSErrorMessage();
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
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_
;
827 bool chromeos_user_logged_in_
;
828 #if defined(OS_CHROMEOS)
829 typedef std::map
<std::string
, ChromeOSUserData
*> ChromeOSUserMap
;
830 ChromeOSUserMap chromeos_user_map_
;
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_
;
842 bool NSSInitSingleton::force_nodb_init_
= false;
844 base::LazyInstance
<NSSInitSingleton
>::Leaky
845 g_nss_singleton
= LAZY_INSTANCE_INITIALIZER
;
848 const char kTestTPMTokenName
[] = "Test DB";
851 void EarlySetupForNSSInit() {
852 base::FilePath database_dir
= GetInitialConfigDirectory();
853 if (!database_dir
.empty())
854 UseLocalCacheOfNSSDatabaseIfNFS(database_dir
);
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.
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.
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"));
911 paths
.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
913 #elif defined(ARCH_CPU_MIPSEL)
914 paths
.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
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
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
);
936 if (loaded
== libs
.size()) {
937 VLOG(3) << "NSS libraries loaded.";
939 LOG(ERROR
) << "Failed to load NSS libraries.";
944 bool CheckNSSVersion(const char* version
) {
945 return !!NSS_VersionCheck(version
);
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.
972 AutoNSSWriteLock::~AutoNSSWriteLock() {
974 lock_
->AssertAcquired();
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())
1016 constructed_successfully_
=
1017 InitializeNSSForChromeOSUser(username_hash
,
1019 false /* is_primary_user */,
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(
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
,
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