Roll src/third_party/WebKit 06cb9e9:a978ee5 (svn 202558:202559)
[chromium-blink-merge.git] / crypto / nss_util.cc
blob4e8aab4d1830278b783644e2d6bcfe02f938100c
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_OPENBSD)
17 #include <sys/mount.h>
18 #include <sys/param.h>
19 #endif
21 #if defined(OS_CHROMEOS)
22 #include <dlfcn.h>
23 #endif
25 #include <map>
26 #include <vector>
28 #include "base/base_paths.h"
29 #include "base/bind.h"
30 #include "base/cpu.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
51 // stores.
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)
57 namespace crypto {
59 namespace {
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() {
74 std::string result;
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);
79 } else {
80 result = base::StringPrintf("NSS error code: %d", PR_GetError());
82 return result;
85 #if defined(USE_NSS_CERTS)
86 #if !defined(OS_CHROMEOS)
87 base::FilePath GetDefaultConfigDirectory() {
88 base::FilePath dir;
89 PathService::Get(base::DIR_HOME, &dir);
90 if (dir.empty()) {
91 LOG(ERROR) << "Failed to get home directory.";
92 return dir;
94 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
95 if (!base::CreateDirectory(dir)) {
96 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
97 dir.clear();
99 DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
100 return dir;
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();
114 return database_dir;
115 #else
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);
125 if (delegate) {
126 bool cancelled = false;
127 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
128 retry != PR_FALSE,
129 &cancelled);
130 if (cancelled)
131 return NULL;
132 char* result = PORT_Strdup(password.c_str());
133 password.replace(0, password.size(), password.size(), 0);
134 return result;
136 DLOG(ERROR) << "PK11 password requested with NULL arg";
137 return NULL;
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
149 // is OS-specific.
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)
160 struct statfs buf;
161 if (statfs(database_dir.value().c_str(), &buf) == 0)
162 db_on_nfs = (strcmp(buf.f_fstypename, MOUNT_NFS) == 0);
163 #else
164 NOTIMPLEMENTED();
165 #endif
167 if (db_on_nfs) {
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
180 // singleton.
181 class NSPRInitSingleton {
182 private:
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
191 // down.
192 ~NSPRInitSingleton() {
193 PL_ArenaFinish();
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 {
216 public:
217 explicit ChromeOSUserData(ScopedPK11Slot public_slot)
218 : public_slot_(public_slot.Pass()),
219 private_slot_initialization_started_(false) {}
220 ~ChromeOSUserData() {
221 if (public_slot_) {
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) {
235 if (private_slot_)
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();
250 ++i) {
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;
263 private:
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 {
275 public:
276 ScopedChapsLoadFixup();
277 ~ScopedChapsLoadFixup();
279 private:
280 #if defined(COMPONENT_BUILD)
281 void *chaps_handle_;
282 #endif
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.
295 if (chaps_handle_)
296 dlclose(chaps_handle_);
299 #else
301 ScopedChapsLoadFixup::ScopedChapsLoadFixup() {}
302 ScopedChapsLoadFixup::~ScopedChapsLoadFixup() {}
304 #endif // defined(COMPONENT_BUILD)
305 #endif // defined(OS_CHROMEOS)
307 class NSSInitSingleton {
308 public:
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
339 // implementation.
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(
349 int system_slot_id,
350 const base::Callback<void(bool)>& callback) {
351 DCHECK(thread_checker_.CalledOnValidThread());
352 // Should not be called while there is already an initialization in
353 // progress.
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));
359 return;
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.
365 if (tpm_slot_) {
366 base::MessageLoop::current()->PostTask(FROM_HERE,
367 base::Bind(callback, true));
368 return;
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(
376 FROM_HERE,
377 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
378 system_slot_id,
379 tpm_args_ptr),
380 base::Bind(&NSSInitSingleton::OnInitializedTPMTokenAndSystemSlot,
381 base::Unretained(this), // NSSInitSingleton is leaky
382 callback,
383 base::Passed(&tpm_args)),
384 true /* task_is_slow */
385 )) {
386 initializing_tpm_token_ = true;
387 } else {
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
396 // TPM.
397 if (!tpm_args->chaps_module) {
398 ScopedChapsLoadFixup chaps_loader;
400 DVLOG(3) << "Loading chaps...";
401 tpm_args->chaps_module = LoadModule(
402 kChapsModuleName,
403 kChapsPath,
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) {
412 tpm_args->tpm_slot =
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;
433 if (tpm_slot_)
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();
444 ++i) {
445 i->Run();
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
453 // don't regress.
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();
461 if (tpm_slot_)
462 return true;
464 if (!callback.is_null())
465 tpm_ready_callback_list_.push_back(callback);
467 return false;
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
472 // we also control.
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);
484 if (!slot)
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.";
495 return false;
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());
504 return true;
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());
530 if (!chaps_module_)
531 return;
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(
538 FROM_HERE,
539 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
540 slot_id,
541 tpm_args_ptr),
542 base::Bind(&NSSInitSingleton::OnInitializedTPMForChromeOSUser,
543 base::Unretained(this), // NSSInitSingleton is leaky
544 username_hash,
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());
610 delete i->second;
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();
622 } else {
623 tpm_slot_.reset();
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();
638 #endif
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()) {
656 wrapped_callback =
657 base::Bind(&NSSInitSingleton::GetSystemNSSKeySlotCallback,
658 base::Unretained(this) /* singleton is leaky */,
659 callback);
661 if (IsTPMTokenReady(wrapped_callback))
662 return ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_.get()));
663 return ScopedPK11Slot();
665 #endif
667 #if defined(USE_NSS_CERTS)
668 base::Lock* write_lock() {
669 return &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;
679 #endif
681 private:
682 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
684 NSSInitSingleton()
685 : tpm_token_enabled_for_nss_(false),
686 initializing_tpm_token_(false),
687 chaps_module_(NULL),
688 root_(NULL) {
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();
695 EnsureNSPRInit();
697 // We *must* have NSS >= 3.14.3.
698 static_assert(
699 (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
700 (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
701 (NSS_VMAJOR > 3),
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 "
709 "maintainer.";
712 SECStatus status = SECFailure;
713 bool nodb_init = false;
715 #if !defined(USE_OPENSSL)
716 // ForceNoDBInit was called.
717 if (force_nodb_init_)
718 nodb_init = true;
719 #endif
721 #if !defined(USE_NSS_CERTS)
722 // Use the system certificate store, so initialize NSS without database.
723 nodb_init = true;
724 #endif
726 if (nodb_init) {
727 status = NSS_NoDB_Init(NULL);
728 if (status != SECSuccess) {
729 CrashOnNSSInitFailure();
730 return;
732 #if defined(OS_IOS)
733 root_ = InitDefaultRootCerts();
734 #endif // defined(OS_IOS)
735 } else {
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());
750 #else
751 status = NSS_InitReadWrite(nss_config_dir.c_str());
752 #endif
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();
764 return;
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
772 // log in.
773 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
774 if (slot) {
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);
779 PK11_FreeSlot(slot);
782 root_ = InitDefaultRootCerts();
783 #endif // defined(USE_NSS_CERTS)
786 // Disable MD5 certificate signatures. (They are disabled by default in
787 // NSS 3.14.)
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
795 // down.
796 ~NSSInitSingleton() {
797 #if defined(OS_CHROMEOS)
798 STLDeleteValues(&chromeos_user_map_);
799 #endif
800 tpm_slot_.reset();
801 if (root_) {
802 SECMOD_UnloadUserModule(root_);
803 SECMOD_DestroyModule(root_);
804 root_ = NULL;
806 if (chaps_module_) {
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);
824 if (root)
825 return root;
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.
830 return NULL;
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);
847 if (!module) {
848 LOG(ERROR) << "Error loading " << name << " module into NSS: "
849 << GetNSSErrorMessage();
850 return NULL;
852 if (!module->loaded) {
853 LOG(ERROR) << "After loading " << name << ", loaded==false: "
854 << GetNSSErrorMessage();
855 SECMOD_DestroyModule(module);
856 return NULL;
858 return module;
860 #endif
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
869 base::CPU cpu;
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_;
881 #endif
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_;
889 SECMODModule* root_;
890 #if defined(OS_CHROMEOS)
891 typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
892 ChromeOSUserMap chromeos_user_map_;
893 ScopedPK11Slot test_system_slot_;
894 #endif
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)
905 // static
906 bool NSSInitSingleton::force_nodb_init_ = false;
907 #endif
909 base::LazyInstance<NSSInitSingleton>::Leaky
910 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
911 } // namespace
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());
921 if (db_slot) {
922 if (PK11_NeedUserInit(db_slot))
923 PK11_InitPin(db_slot, NULL, NULL);
924 } else {
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);
936 #endif
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.
949 ForceNSSNoDBInit();
950 // Initialize NSS.
951 EnsureNSSInit();
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"));
994 #else
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
1007 // then load.
1008 size_t loaded = 0;
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);
1013 if (lib) {
1014 ++loaded;
1015 break;
1020 if (loaded == libs.size()) {
1021 VLOG(3) << "NSS libraries loaded.";
1022 } else {
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.
1041 if (lock_)
1042 lock_->Acquire();
1045 AutoNSSWriteLock::~AutoNSSWriteLock() {
1046 if (lock_) {
1047 lock_->AssertAcquired();
1048 lock_->Release();
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(
1085 int token_slot_id,
1086 const base::Callback<void(bool)>& callback) {
1087 g_nss_singleton.Get().InitializeTPMTokenAndSystemSlot(token_slot_id,
1088 callback);
1091 bool InitializeNSSForChromeOSUser(const std::string& username_hash,
1092 const base::FilePath& path) {
1093 return g_nss_singleton.Get().InitializeNSSForChromeOSUser(username_hash,
1094 path);
1097 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
1098 return g_nss_singleton.Get().ShouldInitializeTPMForChromeOSUser(
1099 username_hash);
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(
1115 username_hash);
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,
1126 callback);
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();
1147 #endif
1149 } // namespace crypto