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"
16 #if defined(OS_OPENBSD)
17 #include <sys/mount.h>
18 #include <sys/param.h>
21 #if defined(OS_CHROMEOS)
28 #include "base/base_paths.h"
29 #include "base/bind.h"
31 #include "base/debug/alias.h"
32 #include "base/debug/stack_trace.h"
33 #include "base/environment.h"
34 #include "base/files/file_path.h"
35 #include "base/files/file_util.h"
36 #include "base/lazy_instance.h"
37 #include "base/logging.h"
38 #include "base/memory/scoped_ptr.h"
39 #include "base/message_loop/message_loop.h"
40 #include "base/native_library.h"
41 #include "base/path_service.h"
42 #include "base/stl_util.h"
43 #include "base/strings/stringprintf.h"
44 #include "base/threading/thread_checker.h"
45 #include "base/threading/thread_restrictions.h"
46 #include "base/threading/worker_pool.h"
47 #include "build/build_config.h"
49 // USE_NSS_CERTS means NSS is used for certificates and platform integration.
50 // This requires additional support to manage the platform certificate and key
52 #if defined(USE_NSS_CERTS)
53 #include "base/synchronization/lock.h"
54 #include "crypto/nss_crypto_module_delegate.h"
55 #endif // defined(USE_NSS_CERTS)
61 #if defined(OS_CHROMEOS)
62 const char kUserNSSDatabaseName
[] = "UserNSSDB";
64 // Constants for loading the Chrome OS TPM-backed PKCS #11 library.
65 const char kChapsModuleName
[] = "Chaps";
66 const char kChapsPath
[] = "libchaps.so";
68 // Fake certificate authority database used for testing.
69 static const base::FilePath::CharType kReadOnlyCertDB
[] =
70 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
71 #endif // defined(OS_CHROMEOS)
73 std::string
GetNSSErrorMessage() {
75 if (PR_GetErrorTextLength()) {
76 scoped_ptr
<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
77 PRInt32 copied
= PR_GetErrorText(error_text
.get());
78 result
= std::string(error_text
.get(), copied
);
80 result
= base::StringPrintf("NSS error code: %d", PR_GetError());
85 #if defined(USE_NSS_CERTS)
86 #if !defined(OS_CHROMEOS)
87 base::FilePath
GetDefaultConfigDirectory() {
89 PathService::Get(base::DIR_HOME
, &dir
);
91 LOG(ERROR
) << "Failed to get home directory.";
94 dir
= dir
.AppendASCII(".pki").AppendASCII("nssdb");
95 if (!base::CreateDirectory(dir
)) {
96 LOG(ERROR
) << "Failed to create " << dir
.value() << " directory.";
99 DVLOG(2) << "DefaultConfigDirectory: " << dir
.value();
102 #endif // !defined(IS_CHROMEOS)
104 // On non-Chrome OS platforms, return the default config directory. On Chrome OS
105 // test images, return a read-only directory with fake root CA certs (which are
106 // used by the local Google Accounts server mock we use when testing our login
107 // code). On Chrome OS non-test images (where the read-only directory doesn't
108 // exist), return an empty path.
109 base::FilePath
GetInitialConfigDirectory() {
110 #if defined(OS_CHROMEOS)
111 base::FilePath database_dir
= base::FilePath(kReadOnlyCertDB
);
112 if (!base::PathExists(database_dir
))
113 database_dir
.clear();
116 return GetDefaultConfigDirectory();
117 #endif // defined(OS_CHROMEOS)
120 // This callback for NSS forwards all requests to a caller-specified
121 // CryptoModuleBlockingPasswordDelegate object.
122 char* PKCS11PasswordFunc(PK11SlotInfo
* slot
, PRBool retry
, void* arg
) {
123 crypto::CryptoModuleBlockingPasswordDelegate
* delegate
=
124 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate
*>(arg
);
126 bool cancelled
= false;
127 std::string password
= delegate
->RequestPassword(PK11_GetTokenName(slot
),
132 char* result
= PORT_Strdup(password
.c_str());
133 password
.replace(0, password
.size(), password
.size(), 0);
136 DLOG(ERROR
) << "PK11 password requested with NULL arg";
140 // NSS creates a local cache of the sqlite database if it detects that the
141 // filesystem the database is on is much slower than the local disk. The
142 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
143 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
144 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
145 // detection when database_dir is on NFS. See http://crbug.com/48585.
147 // TODO(wtc): port this function to other USE_NSS_CERTS platforms. It is
148 // defined only for OS_LINUX and OS_OPENBSD simply because the statfs structure
151 // Because this function sets an environment variable it must be run before we
152 // go multi-threaded.
153 void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath
& database_dir
) {
154 bool db_on_nfs
= false;
155 #if defined(OS_LINUX)
156 base::FileSystemType fs_type
= base::FILE_SYSTEM_UNKNOWN
;
157 if (base::GetFileSystemType(database_dir
, &fs_type
))
158 db_on_nfs
= (fs_type
== base::FILE_SYSTEM_NFS
);
159 #elif defined(OS_OPENBSD)
161 if (statfs(database_dir
.value().c_str(), &buf
) == 0)
162 db_on_nfs
= (strcmp(buf
.f_fstypename
, MOUNT_NFS
) == 0);
168 scoped_ptr
<base::Environment
> env(base::Environment::Create());
169 static const char kUseCacheEnvVar
[] = "NSS_SDB_USE_CACHE";
170 if (!env
->HasVar(kUseCacheEnvVar
))
171 env
->SetVar(kUseCacheEnvVar
, "yes");
175 #endif // defined(USE_NSS_CERTS)
177 // A singleton to initialize/deinitialize NSPR.
178 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
179 // Now that we're leaking the singleton, we could merge back with the NSS
181 class NSPRInitSingleton
{
183 friend struct base::DefaultLazyInstanceTraits
<NSPRInitSingleton
>;
185 NSPRInitSingleton() {
186 PR_Init(PR_USER_THREAD
, PR_PRIORITY_NORMAL
, 0);
189 // NOTE(willchan): We don't actually execute this code since we leak NSS to
190 // prevent non-joinable threads from using NSS after it's already been shut
192 ~NSPRInitSingleton() {
194 PRStatus prstatus
= PR_Cleanup();
195 if (prstatus
!= PR_SUCCESS
)
196 LOG(ERROR
) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
200 base::LazyInstance
<NSPRInitSingleton
>::Leaky
201 g_nspr_singleton
= LAZY_INSTANCE_INITIALIZER
;
203 // Force a crash with error info on NSS_NoDB_Init failure.
204 void CrashOnNSSInitFailure() {
205 int nss_error
= PR_GetError();
206 int os_error
= PR_GetOSError();
207 base::debug::Alias(&nss_error
);
208 base::debug::Alias(&os_error
);
209 LOG(ERROR
) << "Error initializing NSS without a persistent database: "
210 << GetNSSErrorMessage();
211 LOG(FATAL
) << "nss_error=" << nss_error
<< ", os_error=" << os_error
;
214 #if defined(OS_CHROMEOS)
215 class ChromeOSUserData
{
217 explicit ChromeOSUserData(ScopedPK11Slot public_slot
)
218 : public_slot_(public_slot
.Pass()),
219 private_slot_initialization_started_(false) {}
220 ~ChromeOSUserData() {
222 SECStatus status
= SECMOD_CloseUserDB(public_slot_
.get());
223 if (status
!= SECSuccess
)
224 PLOG(ERROR
) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
228 ScopedPK11Slot
GetPublicSlot() {
229 return ScopedPK11Slot(
230 public_slot_
? PK11_ReferenceSlot(public_slot_
.get()) : NULL
);
233 ScopedPK11Slot
GetPrivateSlot(
234 const base::Callback
<void(ScopedPK11Slot
)>& callback
) {
236 return ScopedPK11Slot(PK11_ReferenceSlot(private_slot_
.get()));
237 if (!callback
.is_null())
238 tpm_ready_callback_list_
.push_back(callback
);
239 return ScopedPK11Slot();
242 void SetPrivateSlot(ScopedPK11Slot private_slot
) {
243 DCHECK(!private_slot_
);
244 private_slot_
= private_slot
.Pass();
246 SlotReadyCallbackList callback_list
;
247 callback_list
.swap(tpm_ready_callback_list_
);
248 for (SlotReadyCallbackList::iterator i
= callback_list
.begin();
249 i
!= callback_list
.end();
251 (*i
).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_
.get())));
255 bool private_slot_initialization_started() const {
256 return private_slot_initialization_started_
;
259 void set_private_slot_initialization_started() {
260 private_slot_initialization_started_
= true;
264 ScopedPK11Slot public_slot_
;
265 ScopedPK11Slot private_slot_
;
267 bool private_slot_initialization_started_
;
269 typedef std::vector
<base::Callback
<void(ScopedPK11Slot
)> >
270 SlotReadyCallbackList
;
271 SlotReadyCallbackList tpm_ready_callback_list_
;
274 class ScopedChapsLoadFixup
{
276 ScopedChapsLoadFixup();
277 ~ScopedChapsLoadFixup();
280 #if defined(COMPONENT_BUILD)
285 #if defined(COMPONENT_BUILD)
287 ScopedChapsLoadFixup::ScopedChapsLoadFixup() {
288 // HACK: libchaps links the system protobuf and there are symbol conflicts
289 // with the bundled copy. Load chaps with RTLD_DEEPBIND to workaround.
290 chaps_handle_
= dlopen(kChapsPath
, RTLD_LOCAL
| RTLD_NOW
| RTLD_DEEPBIND
);
293 ScopedChapsLoadFixup::~ScopedChapsLoadFixup() {
294 // LoadModule() will have taken a 2nd reference.
296 dlclose(chaps_handle_
);
301 ScopedChapsLoadFixup::ScopedChapsLoadFixup() {}
302 ScopedChapsLoadFixup::~ScopedChapsLoadFixup() {}
304 #endif // defined(COMPONENT_BUILD)
305 #endif // defined(OS_CHROMEOS)
307 class NSSInitSingleton
{
309 #if defined(OS_CHROMEOS)
310 // Used with PostTaskAndReply to pass handles to worker thread and back.
311 struct TPMModuleAndSlot
{
312 explicit TPMModuleAndSlot(SECMODModule
* init_chaps_module
)
313 : chaps_module(init_chaps_module
) {}
314 SECMODModule
* chaps_module
;
315 crypto::ScopedPK11Slot tpm_slot
;
318 ScopedPK11Slot
OpenPersistentNSSDBForPath(const std::string
& db_name
,
319 const base::FilePath
& path
) {
320 DCHECK(thread_checker_
.CalledOnValidThread());
321 // NSS is allowed to do IO on the current thread since dispatching
322 // to a dedicated thread would still have the affect of blocking
323 // the current thread, due to NSS's internal locking requirements
324 base::ThreadRestrictions::ScopedAllowIO allow_io
;
326 base::FilePath nssdb_path
= path
.AppendASCII(".pki").AppendASCII("nssdb");
327 if (!base::CreateDirectory(nssdb_path
)) {
328 LOG(ERROR
) << "Failed to create " << nssdb_path
.value() << " directory.";
329 return ScopedPK11Slot();
331 return OpenSoftwareNSSDB(nssdb_path
, db_name
);
334 void EnableTPMTokenForNSS() {
335 DCHECK(thread_checker_
.CalledOnValidThread());
337 // If this gets set, then we'll use the TPM for certs with
338 // private keys, otherwise we'll fall back to the software
340 tpm_token_enabled_for_nss_
= true;
343 bool IsTPMTokenEnabledForNSS() {
344 DCHECK(thread_checker_
.CalledOnValidThread());
345 return tpm_token_enabled_for_nss_
;
348 void InitializeTPMTokenAndSystemSlot(
350 const base::Callback
<void(bool)>& callback
) {
351 DCHECK(thread_checker_
.CalledOnValidThread());
352 // Should not be called while there is already an initialization in
354 DCHECK(!initializing_tpm_token_
);
355 // If EnableTPMTokenForNSS hasn't been called, return false.
356 if (!tpm_token_enabled_for_nss_
) {
357 base::MessageLoop::current()->PostTask(FROM_HERE
,
358 base::Bind(callback
, false));
362 // If everything is already initialized, then return true.
363 // Note that only |tpm_slot_| is checked, since |chaps_module_| could be
364 // NULL in tests while |tpm_slot_| has been set to the test DB.
366 base::MessageLoop::current()->PostTask(FROM_HERE
,
367 base::Bind(callback
, true));
371 // Note that a reference is not taken to chaps_module_. This is safe since
372 // NSSInitSingleton is Leaky, so the reference it holds is never released.
373 scoped_ptr
<TPMModuleAndSlot
> tpm_args(new TPMModuleAndSlot(chaps_module_
));
374 TPMModuleAndSlot
* tpm_args_ptr
= tpm_args
.get();
375 if (base::WorkerPool::PostTaskAndReply(
377 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread
,
380 base::Bind(&NSSInitSingleton::OnInitializedTPMTokenAndSystemSlot
,
381 base::Unretained(this), // NSSInitSingleton is leaky
383 base::Passed(&tpm_args
)),
384 true /* task_is_slow */
386 initializing_tpm_token_
= true;
388 base::MessageLoop::current()->PostTask(FROM_HERE
,
389 base::Bind(callback
, false));
393 static void InitializeTPMTokenOnWorkerThread(CK_SLOT_ID token_slot_id
,
394 TPMModuleAndSlot
* tpm_args
) {
395 // This tries to load the Chaps module so NSS can talk to the hardware
397 if (!tpm_args
->chaps_module
) {
398 ScopedChapsLoadFixup chaps_loader
;
400 DVLOG(3) << "Loading chaps...";
401 tpm_args
->chaps_module
= LoadModule(
404 // For more details on these parameters, see:
405 // https://developer.mozilla.org/en/PKCS11_Module_Specs
406 // slotFlags=[PublicCerts] -- Certificates and public keys can be
407 // read from this slot without requiring a call to C_Login.
408 // askpw=only -- Only authenticate to the token when necessary.
409 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
411 if (tpm_args
->chaps_module
) {
413 GetTPMSlotForIdOnWorkerThread(tpm_args
->chaps_module
, token_slot_id
);
417 void OnInitializedTPMTokenAndSystemSlot(
418 const base::Callback
<void(bool)>& callback
,
419 scoped_ptr
<TPMModuleAndSlot
> tpm_args
) {
420 DCHECK(thread_checker_
.CalledOnValidThread());
421 DVLOG(2) << "Loaded chaps: " << !!tpm_args
->chaps_module
422 << ", got tpm slot: " << !!tpm_args
->tpm_slot
;
424 chaps_module_
= tpm_args
->chaps_module
;
425 tpm_slot_
= tpm_args
->tpm_slot
.Pass();
426 if (!chaps_module_
&& test_system_slot_
) {
427 // chromeos_unittests try to test the TPM initialization process. If we
428 // have a test DB open, pretend that it is the TPM slot.
429 tpm_slot_
.reset(PK11_ReferenceSlot(test_system_slot_
.get()));
431 initializing_tpm_token_
= false;
434 RunAndClearTPMReadyCallbackList();
436 callback
.Run(!!tpm_slot_
);
439 void RunAndClearTPMReadyCallbackList() {
440 TPMReadyCallbackList callback_list
;
441 callback_list
.swap(tpm_ready_callback_list_
);
442 for (TPMReadyCallbackList::iterator i
= callback_list
.begin();
443 i
!= callback_list
.end();
449 bool IsTPMTokenReady(const base::Closure
& callback
) {
450 if (!callback
.is_null()) {
451 // Cannot DCHECK in the general case yet, but since the callback is
452 // a new addition to the API, DCHECK to make sure at least the new uses
454 DCHECK(thread_checker_
.CalledOnValidThread());
455 } else if (!thread_checker_
.CalledOnValidThread()) {
456 // TODO(mattm): Change to DCHECK when callers have been fixed.
457 DVLOG(1) << "Called on wrong thread.\n"
458 << base::debug::StackTrace().ToString();
464 if (!callback
.is_null())
465 tpm_ready_callback_list_
.push_back(callback
);
470 // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
471 // id as an int. This should be safe since this is only used with chaps, which
473 static crypto::ScopedPK11Slot
GetTPMSlotForIdOnWorkerThread(
474 SECMODModule
* chaps_module
,
475 CK_SLOT_ID slot_id
) {
476 DCHECK(chaps_module
);
478 DVLOG(3) << "Poking chaps module.";
479 SECStatus rv
= SECMOD_UpdateSlotList(chaps_module
);
480 if (rv
!= SECSuccess
)
481 PLOG(ERROR
) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
483 PK11SlotInfo
* slot
= SECMOD_LookupSlot(chaps_module
->moduleID
, slot_id
);
485 LOG(ERROR
) << "TPM slot " << slot_id
<< " not found.";
486 return crypto::ScopedPK11Slot(slot
);
489 bool InitializeNSSForChromeOSUser(const std::string
& username_hash
,
490 const base::FilePath
& path
) {
491 DCHECK(thread_checker_
.CalledOnValidThread());
492 if (chromeos_user_map_
.find(username_hash
) != chromeos_user_map_
.end()) {
493 // This user already exists in our mapping.
494 DVLOG(2) << username_hash
<< " already initialized.";
498 DVLOG(2) << "Opening NSS DB " << path
.value();
499 std::string db_name
= base::StringPrintf(
500 "%s %s", kUserNSSDatabaseName
, username_hash
.c_str());
501 ScopedPK11Slot
public_slot(OpenPersistentNSSDBForPath(db_name
, path
));
502 chromeos_user_map_
[username_hash
] =
503 new ChromeOSUserData(public_slot
.Pass());
507 bool ShouldInitializeTPMForChromeOSUser(const std::string
& username_hash
) {
508 DCHECK(thread_checker_
.CalledOnValidThread());
509 DCHECK(chromeos_user_map_
.find(username_hash
) != chromeos_user_map_
.end());
511 return !chromeos_user_map_
[username_hash
]
512 ->private_slot_initialization_started();
515 void WillInitializeTPMForChromeOSUser(const std::string
& username_hash
) {
516 DCHECK(thread_checker_
.CalledOnValidThread());
517 DCHECK(chromeos_user_map_
.find(username_hash
) != chromeos_user_map_
.end());
519 chromeos_user_map_
[username_hash
]
520 ->set_private_slot_initialization_started();
523 void InitializeTPMForChromeOSUser(const std::string
& username_hash
,
524 CK_SLOT_ID slot_id
) {
525 DCHECK(thread_checker_
.CalledOnValidThread());
526 DCHECK(chromeos_user_map_
.find(username_hash
) != chromeos_user_map_
.end());
527 DCHECK(chromeos_user_map_
[username_hash
]->
528 private_slot_initialization_started());
533 // Note that a reference is not taken to chaps_module_. This is safe since
534 // NSSInitSingleton is Leaky, so the reference it holds is never released.
535 scoped_ptr
<TPMModuleAndSlot
> tpm_args(new TPMModuleAndSlot(chaps_module_
));
536 TPMModuleAndSlot
* tpm_args_ptr
= tpm_args
.get();
537 base::WorkerPool::PostTaskAndReply(
539 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread
,
542 base::Bind(&NSSInitSingleton::OnInitializedTPMForChromeOSUser
,
543 base::Unretained(this), // NSSInitSingleton is leaky
545 base::Passed(&tpm_args
)),
546 true /* task_is_slow */
550 void OnInitializedTPMForChromeOSUser(const std::string
& username_hash
,
551 scoped_ptr
<TPMModuleAndSlot
> tpm_args
) {
552 DCHECK(thread_checker_
.CalledOnValidThread());
553 DVLOG(2) << "Got tpm slot for " << username_hash
<< " "
554 << !!tpm_args
->tpm_slot
;
555 chromeos_user_map_
[username_hash
]->SetPrivateSlot(
556 tpm_args
->tpm_slot
.Pass());
559 void InitializePrivateSoftwareSlotForChromeOSUser(
560 const std::string
& username_hash
) {
561 DCHECK(thread_checker_
.CalledOnValidThread());
562 VLOG(1) << "using software private slot for " << username_hash
;
563 DCHECK(chromeos_user_map_
.find(username_hash
) != chromeos_user_map_
.end());
564 DCHECK(chromeos_user_map_
[username_hash
]->
565 private_slot_initialization_started());
567 chromeos_user_map_
[username_hash
]->SetPrivateSlot(
568 chromeos_user_map_
[username_hash
]->GetPublicSlot());
571 ScopedPK11Slot
GetPublicSlotForChromeOSUser(
572 const std::string
& username_hash
) {
573 DCHECK(thread_checker_
.CalledOnValidThread());
575 if (username_hash
.empty()) {
576 DVLOG(2) << "empty username_hash";
577 return ScopedPK11Slot();
580 if (chromeos_user_map_
.find(username_hash
) == chromeos_user_map_
.end()) {
581 LOG(ERROR
) << username_hash
<< " not initialized.";
582 return ScopedPK11Slot();
584 return chromeos_user_map_
[username_hash
]->GetPublicSlot();
587 ScopedPK11Slot
GetPrivateSlotForChromeOSUser(
588 const std::string
& username_hash
,
589 const base::Callback
<void(ScopedPK11Slot
)>& callback
) {
590 DCHECK(thread_checker_
.CalledOnValidThread());
592 if (username_hash
.empty()) {
593 DVLOG(2) << "empty username_hash";
594 if (!callback
.is_null()) {
595 base::MessageLoop::current()->PostTask(
596 FROM_HERE
, base::Bind(callback
, base::Passed(ScopedPK11Slot())));
598 return ScopedPK11Slot();
601 DCHECK(chromeos_user_map_
.find(username_hash
) != chromeos_user_map_
.end());
603 return chromeos_user_map_
[username_hash
]->GetPrivateSlot(callback
);
606 void CloseChromeOSUserForTesting(const std::string
& username_hash
) {
607 DCHECK(thread_checker_
.CalledOnValidThread());
608 ChromeOSUserMap::iterator i
= chromeos_user_map_
.find(username_hash
);
609 DCHECK(i
!= chromeos_user_map_
.end());
611 chromeos_user_map_
.erase(i
);
614 void SetSystemKeySlotForTesting(ScopedPK11Slot slot
) {
615 // Ensure that a previous value of test_system_slot_ is not overwritten.
616 // Unsetting, i.e. setting a NULL, however is allowed.
617 DCHECK(!slot
|| !test_system_slot_
);
618 test_system_slot_
= slot
.Pass();
619 if (test_system_slot_
) {
620 tpm_slot_
.reset(PK11_ReferenceSlot(test_system_slot_
.get()));
621 RunAndClearTPMReadyCallbackList();
626 #endif // defined(OS_CHROMEOS)
628 #if !defined(OS_CHROMEOS)
629 PK11SlotInfo
* GetPersistentNSSKeySlot() {
630 // TODO(mattm): Change to DCHECK when callers have been fixed.
631 if (!thread_checker_
.CalledOnValidThread()) {
632 DVLOG(1) << "Called on wrong thread.\n"
633 << base::debug::StackTrace().ToString();
636 return PK11_GetInternalKeySlot();
640 #if defined(OS_CHROMEOS)
641 void GetSystemNSSKeySlotCallback(
642 const base::Callback
<void(ScopedPK11Slot
)>& callback
) {
643 callback
.Run(ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_
.get())));
646 ScopedPK11Slot
GetSystemNSSKeySlot(
647 const base::Callback
<void(ScopedPK11Slot
)>& callback
) {
648 DCHECK(thread_checker_
.CalledOnValidThread());
649 // TODO(mattm): chromeos::TPMTokenloader always calls
650 // InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is
651 // disabled, tpm_slot_ will be the first user's slot instead. Can that be
652 // detected and return NULL instead?
654 base::Closure wrapped_callback
;
655 if (!callback
.is_null()) {
657 base::Bind(&NSSInitSingleton::GetSystemNSSKeySlotCallback
,
658 base::Unretained(this) /* singleton is leaky */,
661 if (IsTPMTokenReady(wrapped_callback
))
662 return ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_
.get()));
663 return ScopedPK11Slot();
667 #if defined(USE_NSS_CERTS)
668 base::Lock
* write_lock() {
671 #endif // defined(USE_NSS_CERTS)
673 #if !defined(USE_OPENSSL)
674 // This method is used to force NSS to be initialized without a DB.
675 // Call this method before NSSInitSingleton() is constructed.
676 static void ForceNoDBInit() {
677 force_nodb_init_
= true;
682 friend struct base::DefaultLazyInstanceTraits
<NSSInitSingleton
>;
685 : tpm_token_enabled_for_nss_(false),
686 initializing_tpm_token_(false),
689 // It's safe to construct on any thread, since LazyInstance will prevent any
690 // other threads from accessing until the constructor is done.
691 thread_checker_
.DetachFromThread();
693 DisableAESNIIfNeeded();
697 // We *must* have NSS >= 3.14.3.
699 (NSS_VMAJOR
== 3 && NSS_VMINOR
== 14 && NSS_VPATCH
>= 3) ||
700 (NSS_VMAJOR
== 3 && NSS_VMINOR
> 14) ||
702 "nss version check failed");
703 // Also check the run-time NSS version.
704 // NSS_VersionCheck is a >= check, not strict equality.
705 if (!NSS_VersionCheck("3.14.3")) {
706 LOG(FATAL
) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
707 "required. Please upgrade to the latest NSS, and if you "
708 "still get this error, contact your distribution "
712 SECStatus status
= SECFailure
;
713 bool nodb_init
= false;
715 #if !defined(USE_OPENSSL)
716 // ForceNoDBInit was called.
717 if (force_nodb_init_
)
721 #if !defined(USE_NSS_CERTS)
722 // Use the system certificate store, so initialize NSS without database.
727 status
= NSS_NoDB_Init(NULL
);
728 if (status
!= SECSuccess
) {
729 CrashOnNSSInitFailure();
733 root_
= InitDefaultRootCerts();
734 #endif // defined(OS_IOS)
736 #if defined(USE_NSS_CERTS)
737 base::FilePath database_dir
= GetInitialConfigDirectory();
738 if (!database_dir
.empty()) {
739 // This duplicates the work which should have been done in
740 // EarlySetupForNSSInit. However, this function is idempotent so
741 // there's no harm done.
742 UseLocalCacheOfNSSDatabaseIfNFS(database_dir
);
744 // Initialize with a persistent database (likely, ~/.pki/nssdb).
745 // Use "sql:" which can be shared by multiple processes safely.
746 std::string nss_config_dir
=
747 base::StringPrintf("sql:%s", database_dir
.value().c_str());
748 #if defined(OS_CHROMEOS)
749 status
= NSS_Init(nss_config_dir
.c_str());
751 status
= NSS_InitReadWrite(nss_config_dir
.c_str());
753 if (status
!= SECSuccess
) {
754 LOG(ERROR
) << "Error initializing NSS with a persistent "
755 "database (" << nss_config_dir
756 << "): " << GetNSSErrorMessage();
759 if (status
!= SECSuccess
) {
760 VLOG(1) << "Initializing NSS without a persistent database.";
761 status
= NSS_NoDB_Init(NULL
);
762 if (status
!= SECSuccess
) {
763 CrashOnNSSInitFailure();
768 PK11_SetPasswordFunc(PKCS11PasswordFunc
);
770 // If we haven't initialized the password for the NSS databases,
771 // initialize an empty-string password so that we don't need to
773 PK11SlotInfo
* slot
= PK11_GetInternalKeySlot();
775 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
776 // yet, so we don't need to lock.
777 if (PK11_NeedUserInit(slot
))
778 PK11_InitPin(slot
, NULL
, NULL
);
782 root_
= InitDefaultRootCerts();
783 #endif // defined(USE_NSS_CERTS)
786 // Disable MD5 certificate signatures. (They are disabled by default in
788 NSS_SetAlgorithmPolicy(SEC_OID_MD5
, 0, NSS_USE_ALG_IN_CERT_SIGNATURE
);
789 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION
,
790 0, NSS_USE_ALG_IN_CERT_SIGNATURE
);
793 // NOTE(willchan): We don't actually execute this code since we leak NSS to
794 // prevent non-joinable threads from using NSS after it's already been shut
796 ~NSSInitSingleton() {
797 #if defined(OS_CHROMEOS)
798 STLDeleteValues(&chromeos_user_map_
);
802 SECMOD_UnloadUserModule(root_
);
803 SECMOD_DestroyModule(root_
);
807 SECMOD_UnloadUserModule(chaps_module_
);
808 SECMOD_DestroyModule(chaps_module_
);
809 chaps_module_
= NULL
;
812 SECStatus status
= NSS_Shutdown();
813 if (status
!= SECSuccess
) {
814 // We VLOG(1) because this failure is relatively harmless (leaking, but
815 // we're shutting down anyway).
816 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
820 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
821 // Load nss's built-in root certs.
822 SECMODModule
* InitDefaultRootCerts() {
823 SECMODModule
* root
= LoadModule("Root Certs", "libnssckbi.so", NULL
);
827 // Aw, snap. Can't find/load root cert shared library.
828 // This will make it hard to talk to anybody via https.
829 // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
833 // Load the given module for this NSS session.
834 static SECMODModule
* LoadModule(const char* name
,
835 const char* library_path
,
836 const char* params
) {
837 std::string modparams
= base::StringPrintf(
838 "name=\"%s\" library=\"%s\" %s",
839 name
, library_path
, params
? params
: "");
841 // Shouldn't need to const_cast here, but SECMOD doesn't properly
842 // declare input string arguments as const. Bug
843 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
844 // on NSS codebase to address this.
845 SECMODModule
* module
= SECMOD_LoadUserModule(
846 const_cast<char*>(modparams
.c_str()), NULL
, PR_FALSE
);
848 LOG(ERROR
) << "Error loading " << name
<< " module into NSS: "
849 << GetNSSErrorMessage();
852 if (!module
->loaded
) {
853 LOG(ERROR
) << "After loading " << name
<< ", loaded==false: "
854 << GetNSSErrorMessage();
855 SECMOD_DestroyModule(module
);
862 static void DisableAESNIIfNeeded() {
863 if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
864 // Some versions of NSS have a bug that causes AVX instructions to be
865 // used without testing whether XSAVE is enabled by the operating system.
866 // In order to work around this, we disable AES-NI in NSS when we find
867 // that |has_avx()| is false (which includes the XSAVE test). See
868 // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
871 if (cpu
.has_avx_hardware() && !cpu
.has_avx()) {
872 scoped_ptr
<base::Environment
> env(base::Environment::Create());
873 env
->SetVar("NSS_DISABLE_HW_AES", "1");
878 #if !defined(USE_OPENSSL)
879 // If this is set to true NSS is forced to be initialized without a DB.
880 static bool force_nodb_init_
;
883 bool tpm_token_enabled_for_nss_
;
884 bool initializing_tpm_token_
;
885 typedef std::vector
<base::Closure
> TPMReadyCallbackList
;
886 TPMReadyCallbackList tpm_ready_callback_list_
;
887 SECMODModule
* chaps_module_
;
888 crypto::ScopedPK11Slot tpm_slot_
;
890 #if defined(OS_CHROMEOS)
891 typedef std::map
<std::string
, ChromeOSUserData
*> ChromeOSUserMap
;
892 ChromeOSUserMap chromeos_user_map_
;
893 ScopedPK11Slot test_system_slot_
;
895 #if defined(USE_NSS_CERTS)
896 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
897 // is fixed, we will no longer need the lock.
898 base::Lock write_lock_
;
899 #endif // defined(USE_NSS_CERTS)
901 base::ThreadChecker thread_checker_
;
904 #if !defined(USE_OPENSSL)
906 bool NSSInitSingleton::force_nodb_init_
= false;
909 base::LazyInstance
<NSSInitSingleton
>::Leaky
910 g_nss_singleton
= LAZY_INSTANCE_INITIALIZER
;
913 #if defined(USE_NSS_CERTS)
914 ScopedPK11Slot
OpenSoftwareNSSDB(const base::FilePath
& path
,
915 const std::string
& description
) {
916 const std::string modspec
=
917 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
918 path
.value().c_str(),
919 description
.c_str());
920 PK11SlotInfo
* db_slot
= SECMOD_OpenUserDB(modspec
.c_str());
922 if (PK11_NeedUserInit(db_slot
))
923 PK11_InitPin(db_slot
, NULL
, NULL
);
925 LOG(ERROR
) << "Error opening persistent database (" << modspec
926 << "): " << GetNSSErrorMessage();
928 return ScopedPK11Slot(db_slot
);
931 void EarlySetupForNSSInit() {
932 base::FilePath database_dir
= GetInitialConfigDirectory();
933 if (!database_dir
.empty())
934 UseLocalCacheOfNSSDatabaseIfNFS(database_dir
);
938 void EnsureNSPRInit() {
939 g_nspr_singleton
.Get();
942 #if !defined(USE_OPENSSL)
943 void InitNSSSafely() {
944 // We might fork, but we haven't loaded any security modules.
945 DisableNSSForkCheck();
946 // If we're sandboxed, we shouldn't be able to open user security modules,
947 // but it's more correct to tell NSS to not even try.
948 // Loading user security modules would have security implications.
953 #endif // !defined(USE_OPENSSL)
955 void EnsureNSSInit() {
956 // Initializing SSL causes us to do blocking IO.
957 // Temporarily allow it until we fix
958 // http://code.google.com/p/chromium/issues/detail?id=59847
959 base::ThreadRestrictions::ScopedAllowIO allow_io
;
960 g_nss_singleton
.Get();
963 #if !defined(USE_OPENSSL)
965 void ForceNSSNoDBInit() {
966 NSSInitSingleton::ForceNoDBInit();
969 void DisableNSSForkCheck() {
970 scoped_ptr
<base::Environment
> env(base::Environment::Create());
971 env
->SetVar("NSS_STRICT_NOFORK", "DISABLED");
974 void LoadNSSLibraries() {
975 // Some NSS libraries are linked dynamically so load them here.
976 #if defined(USE_NSS_CERTS)
977 // Try to search for multiple directories to load the libraries.
978 std::vector
<base::FilePath
> paths
;
980 // Use relative path to Search PATH for the library files.
981 paths
.push_back(base::FilePath());
983 // For Debian derivatives NSS libraries are located here.
984 paths
.push_back(base::FilePath("/usr/lib/nss"));
986 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
987 #if defined(ARCH_CPU_X86_64)
988 paths
.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
989 #elif defined(ARCH_CPU_X86)
990 paths
.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
991 #elif defined(ARCH_CPU_ARMEL)
992 #if defined(__ARM_PCS_VFP)
993 paths
.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
995 paths
.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
996 #endif // defined(__ARM_PCS_VFP)
997 #elif defined(ARCH_CPU_MIPSEL)
998 paths
.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
999 #endif // defined(ARCH_CPU_X86_64)
1001 // A list of library files to load.
1002 std::vector
<std::string
> libs
;
1003 libs
.push_back("libsoftokn3.so");
1004 libs
.push_back("libfreebl3.so");
1006 // For each combination of library file and path, check for existence and
1009 for (size_t i
= 0; i
< libs
.size(); ++i
) {
1010 for (size_t j
= 0; j
< paths
.size(); ++j
) {
1011 base::FilePath path
= paths
[j
].Append(libs
[i
]);
1012 base::NativeLibrary lib
= base::LoadNativeLibrary(path
, NULL
);
1020 if (loaded
== libs
.size()) {
1021 VLOG(3) << "NSS libraries loaded.";
1023 LOG(ERROR
) << "Failed to load NSS libraries.";
1025 #endif // defined(USE_NSS_CERTS)
1028 #endif // !defined(USE_OPENSSL)
1030 bool CheckNSSVersion(const char* version
) {
1031 return !!NSS_VersionCheck(version
);
1034 #if defined(USE_NSS_CERTS)
1035 base::Lock
* GetNSSWriteLock() {
1036 return g_nss_singleton
.Get().write_lock();
1039 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
1040 // May be NULL if the lock is not needed in our version of NSS.
1045 AutoNSSWriteLock::~AutoNSSWriteLock() {
1047 lock_
->AssertAcquired();
1052 AutoSECMODListReadLock::AutoSECMODListReadLock()
1053 : lock_(SECMOD_GetDefaultModuleListLock()) {
1054 SECMOD_GetReadLock(lock_
);
1057 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
1058 SECMOD_ReleaseReadLock(lock_
);
1060 #endif // defined(USE_NSS_CERTS)
1062 #if defined(OS_CHROMEOS)
1063 ScopedPK11Slot
GetSystemNSSKeySlot(
1064 const base::Callback
<void(ScopedPK11Slot
)>& callback
) {
1065 return g_nss_singleton
.Get().GetSystemNSSKeySlot(callback
);
1068 void SetSystemKeySlotForTesting(ScopedPK11Slot slot
) {
1069 g_nss_singleton
.Get().SetSystemKeySlotForTesting(slot
.Pass());
1072 void EnableTPMTokenForNSS() {
1073 g_nss_singleton
.Get().EnableTPMTokenForNSS();
1076 bool IsTPMTokenEnabledForNSS() {
1077 return g_nss_singleton
.Get().IsTPMTokenEnabledForNSS();
1080 bool IsTPMTokenReady(const base::Closure
& callback
) {
1081 return g_nss_singleton
.Get().IsTPMTokenReady(callback
);
1084 void InitializeTPMTokenAndSystemSlot(
1086 const base::Callback
<void(bool)>& callback
) {
1087 g_nss_singleton
.Get().InitializeTPMTokenAndSystemSlot(token_slot_id
,
1091 bool InitializeNSSForChromeOSUser(const std::string
& username_hash
,
1092 const base::FilePath
& path
) {
1093 return g_nss_singleton
.Get().InitializeNSSForChromeOSUser(username_hash
,
1097 bool ShouldInitializeTPMForChromeOSUser(const std::string
& username_hash
) {
1098 return g_nss_singleton
.Get().ShouldInitializeTPMForChromeOSUser(
1102 void WillInitializeTPMForChromeOSUser(const std::string
& username_hash
) {
1103 g_nss_singleton
.Get().WillInitializeTPMForChromeOSUser(username_hash
);
1106 void InitializeTPMForChromeOSUser(
1107 const std::string
& username_hash
,
1108 CK_SLOT_ID slot_id
) {
1109 g_nss_singleton
.Get().InitializeTPMForChromeOSUser(username_hash
, slot_id
);
1112 void InitializePrivateSoftwareSlotForChromeOSUser(
1113 const std::string
& username_hash
) {
1114 g_nss_singleton
.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1118 ScopedPK11Slot
GetPublicSlotForChromeOSUser(const std::string
& username_hash
) {
1119 return g_nss_singleton
.Get().GetPublicSlotForChromeOSUser(username_hash
);
1122 ScopedPK11Slot
GetPrivateSlotForChromeOSUser(
1123 const std::string
& username_hash
,
1124 const base::Callback
<void(ScopedPK11Slot
)>& callback
) {
1125 return g_nss_singleton
.Get().GetPrivateSlotForChromeOSUser(username_hash
,
1129 void CloseChromeOSUserForTesting(const std::string
& username_hash
) {
1130 g_nss_singleton
.Get().CloseChromeOSUserForTesting(username_hash
);
1132 #endif // defined(OS_CHROMEOS)
1134 base::Time
PRTimeToBaseTime(PRTime prtime
) {
1135 return base::Time::FromInternalValue(
1136 prtime
+ base::Time::UnixEpoch().ToInternalValue());
1139 PRTime
BaseTimeToPRTime(base::Time time
) {
1140 return time
.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1143 #if !defined(OS_CHROMEOS)
1144 PK11SlotInfo
* GetPersistentNSSKeySlot() {
1145 return g_nss_singleton
.Get().GetPersistentNSSKeySlot();
1149 } // namespace crypto