Move GN build files for cacheinvalidation into the main tree.
[chromium-blink-merge.git] / crypto / nss_util.cc
blob125591c73f6b984dde574826e7817d2ce22242ce
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 // This method is used to force NSS to be initialized without a DB.
674 // Call this method before NSSInitSingleton() is constructed.
675 static void ForceNoDBInit() {
676 force_nodb_init_ = true;
679 private:
680 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
682 NSSInitSingleton()
683 : tpm_token_enabled_for_nss_(false),
684 initializing_tpm_token_(false),
685 chaps_module_(NULL),
686 root_(NULL) {
687 // It's safe to construct on any thread, since LazyInstance will prevent any
688 // other threads from accessing until the constructor is done.
689 thread_checker_.DetachFromThread();
691 DisableAESNIIfNeeded();
693 EnsureNSPRInit();
695 // We *must* have NSS >= 3.14.3.
696 static_assert(
697 (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
698 (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
699 (NSS_VMAJOR > 3),
700 "nss version check failed");
701 // Also check the run-time NSS version.
702 // NSS_VersionCheck is a >= check, not strict equality.
703 if (!NSS_VersionCheck("3.14.3")) {
704 LOG(FATAL) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
705 "required. Please upgrade to the latest NSS, and if you "
706 "still get this error, contact your distribution "
707 "maintainer.";
710 SECStatus status = SECFailure;
711 bool nodb_init = force_nodb_init_;
713 #if !defined(USE_NSS_CERTS)
714 // Use the system certificate store, so initialize NSS without database.
715 nodb_init = true;
716 #endif
718 if (nodb_init) {
719 status = NSS_NoDB_Init(NULL);
720 if (status != SECSuccess) {
721 CrashOnNSSInitFailure();
722 return;
724 #if defined(OS_IOS)
725 root_ = InitDefaultRootCerts();
726 #endif // defined(OS_IOS)
727 } else {
728 #if defined(USE_NSS_CERTS)
729 base::FilePath database_dir = GetInitialConfigDirectory();
730 if (!database_dir.empty()) {
731 // This duplicates the work which should have been done in
732 // EarlySetupForNSSInit. However, this function is idempotent so
733 // there's no harm done.
734 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
736 // Initialize with a persistent database (likely, ~/.pki/nssdb).
737 // Use "sql:" which can be shared by multiple processes safely.
738 std::string nss_config_dir =
739 base::StringPrintf("sql:%s", database_dir.value().c_str());
740 #if defined(OS_CHROMEOS)
741 status = NSS_Init(nss_config_dir.c_str());
742 #else
743 status = NSS_InitReadWrite(nss_config_dir.c_str());
744 #endif
745 if (status != SECSuccess) {
746 LOG(ERROR) << "Error initializing NSS with a persistent "
747 "database (" << nss_config_dir
748 << "): " << GetNSSErrorMessage();
751 if (status != SECSuccess) {
752 VLOG(1) << "Initializing NSS without a persistent database.";
753 status = NSS_NoDB_Init(NULL);
754 if (status != SECSuccess) {
755 CrashOnNSSInitFailure();
756 return;
760 PK11_SetPasswordFunc(PKCS11PasswordFunc);
762 // If we haven't initialized the password for the NSS databases,
763 // initialize an empty-string password so that we don't need to
764 // log in.
765 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
766 if (slot) {
767 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
768 // yet, so we don't need to lock.
769 if (PK11_NeedUserInit(slot))
770 PK11_InitPin(slot, NULL, NULL);
771 PK11_FreeSlot(slot);
774 root_ = InitDefaultRootCerts();
775 #endif // defined(USE_NSS_CERTS)
778 // Disable MD5 certificate signatures. (They are disabled by default in
779 // NSS 3.14.)
780 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
781 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
782 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
785 // NOTE(willchan): We don't actually execute this code since we leak NSS to
786 // prevent non-joinable threads from using NSS after it's already been shut
787 // down.
788 ~NSSInitSingleton() {
789 #if defined(OS_CHROMEOS)
790 STLDeleteValues(&chromeos_user_map_);
791 #endif
792 tpm_slot_.reset();
793 if (root_) {
794 SECMOD_UnloadUserModule(root_);
795 SECMOD_DestroyModule(root_);
796 root_ = NULL;
798 if (chaps_module_) {
799 SECMOD_UnloadUserModule(chaps_module_);
800 SECMOD_DestroyModule(chaps_module_);
801 chaps_module_ = NULL;
804 SECStatus status = NSS_Shutdown();
805 if (status != SECSuccess) {
806 // We VLOG(1) because this failure is relatively harmless (leaking, but
807 // we're shutting down anyway).
808 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
812 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
813 // Load nss's built-in root certs.
814 SECMODModule* InitDefaultRootCerts() {
815 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
816 if (root)
817 return root;
819 // Aw, snap. Can't find/load root cert shared library.
820 // This will make it hard to talk to anybody via https.
821 // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
822 return NULL;
825 // Load the given module for this NSS session.
826 static SECMODModule* LoadModule(const char* name,
827 const char* library_path,
828 const char* params) {
829 std::string modparams = base::StringPrintf(
830 "name=\"%s\" library=\"%s\" %s",
831 name, library_path, params ? params : "");
833 // Shouldn't need to const_cast here, but SECMOD doesn't properly
834 // declare input string arguments as const. Bug
835 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
836 // on NSS codebase to address this.
837 SECMODModule* module = SECMOD_LoadUserModule(
838 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
839 if (!module) {
840 LOG(ERROR) << "Error loading " << name << " module into NSS: "
841 << GetNSSErrorMessage();
842 return NULL;
844 if (!module->loaded) {
845 LOG(ERROR) << "After loading " << name << ", loaded==false: "
846 << GetNSSErrorMessage();
847 SECMOD_DestroyModule(module);
848 return NULL;
850 return module;
852 #endif
854 static void DisableAESNIIfNeeded() {
855 if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
856 // Some versions of NSS have a bug that causes AVX instructions to be
857 // used without testing whether XSAVE is enabled by the operating system.
858 // In order to work around this, we disable AES-NI in NSS when we find
859 // that |has_avx()| is false (which includes the XSAVE test). See
860 // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
861 base::CPU cpu;
863 if (cpu.has_avx_hardware() && !cpu.has_avx()) {
864 scoped_ptr<base::Environment> env(base::Environment::Create());
865 env->SetVar("NSS_DISABLE_HW_AES", "1");
870 // If this is set to true NSS is forced to be initialized without a DB.
871 static bool force_nodb_init_;
873 bool tpm_token_enabled_for_nss_;
874 bool initializing_tpm_token_;
875 typedef std::vector<base::Closure> TPMReadyCallbackList;
876 TPMReadyCallbackList tpm_ready_callback_list_;
877 SECMODModule* chaps_module_;
878 crypto::ScopedPK11Slot tpm_slot_;
879 SECMODModule* root_;
880 #if defined(OS_CHROMEOS)
881 typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
882 ChromeOSUserMap chromeos_user_map_;
883 ScopedPK11Slot test_system_slot_;
884 #endif
885 #if defined(USE_NSS_CERTS)
886 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
887 // is fixed, we will no longer need the lock.
888 base::Lock write_lock_;
889 #endif // defined(USE_NSS_CERTS)
891 base::ThreadChecker thread_checker_;
894 // static
895 bool NSSInitSingleton::force_nodb_init_ = false;
897 base::LazyInstance<NSSInitSingleton>::Leaky
898 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
899 } // namespace
901 #if defined(USE_NSS_CERTS)
902 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
903 const std::string& description) {
904 const std::string modspec =
905 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
906 path.value().c_str(),
907 description.c_str());
908 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
909 if (db_slot) {
910 if (PK11_NeedUserInit(db_slot))
911 PK11_InitPin(db_slot, NULL, NULL);
912 } else {
913 LOG(ERROR) << "Error opening persistent database (" << modspec
914 << "): " << GetNSSErrorMessage();
916 return ScopedPK11Slot(db_slot);
919 void EarlySetupForNSSInit() {
920 base::FilePath database_dir = GetInitialConfigDirectory();
921 if (!database_dir.empty())
922 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
924 #endif
926 void EnsureNSPRInit() {
927 g_nspr_singleton.Get();
930 void InitNSSSafely() {
931 // We might fork, but we haven't loaded any security modules.
932 DisableNSSForkCheck();
933 // If we're sandboxed, we shouldn't be able to open user security modules,
934 // but it's more correct to tell NSS to not even try.
935 // Loading user security modules would have security implications.
936 ForceNSSNoDBInit();
937 // Initialize NSS.
938 EnsureNSSInit();
941 void EnsureNSSInit() {
942 // Initializing SSL causes us to do blocking IO.
943 // Temporarily allow it until we fix
944 // http://code.google.com/p/chromium/issues/detail?id=59847
945 base::ThreadRestrictions::ScopedAllowIO allow_io;
946 g_nss_singleton.Get();
949 void ForceNSSNoDBInit() {
950 NSSInitSingleton::ForceNoDBInit();
953 void DisableNSSForkCheck() {
954 scoped_ptr<base::Environment> env(base::Environment::Create());
955 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
958 void LoadNSSLibraries() {
959 // Some NSS libraries are linked dynamically so load them here.
960 #if defined(USE_NSS_CERTS)
961 // Try to search for multiple directories to load the libraries.
962 std::vector<base::FilePath> paths;
964 // Use relative path to Search PATH for the library files.
965 paths.push_back(base::FilePath());
967 // For Debian derivatives NSS libraries are located here.
968 paths.push_back(base::FilePath("/usr/lib/nss"));
970 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
971 #if defined(ARCH_CPU_X86_64)
972 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
973 #elif defined(ARCH_CPU_X86)
974 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
975 #elif defined(ARCH_CPU_ARMEL)
976 #if defined(__ARM_PCS_VFP)
977 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
978 #else
979 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
980 #endif // defined(__ARM_PCS_VFP)
981 #elif defined(ARCH_CPU_MIPSEL)
982 paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
983 #endif // defined(ARCH_CPU_X86_64)
985 // A list of library files to load.
986 std::vector<std::string> libs;
987 libs.push_back("libsoftokn3.so");
988 libs.push_back("libfreebl3.so");
990 // For each combination of library file and path, check for existence and
991 // then load.
992 size_t loaded = 0;
993 for (size_t i = 0; i < libs.size(); ++i) {
994 for (size_t j = 0; j < paths.size(); ++j) {
995 base::FilePath path = paths[j].Append(libs[i]);
996 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
997 if (lib) {
998 ++loaded;
999 break;
1004 if (loaded == libs.size()) {
1005 VLOG(3) << "NSS libraries loaded.";
1006 } else {
1007 LOG(ERROR) << "Failed to load NSS libraries.";
1009 #endif // defined(USE_NSS_CERTS)
1012 bool CheckNSSVersion(const char* version) {
1013 return !!NSS_VersionCheck(version);
1016 #if defined(USE_NSS_CERTS)
1017 base::Lock* GetNSSWriteLock() {
1018 return g_nss_singleton.Get().write_lock();
1021 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
1022 // May be NULL if the lock is not needed in our version of NSS.
1023 if (lock_)
1024 lock_->Acquire();
1027 AutoNSSWriteLock::~AutoNSSWriteLock() {
1028 if (lock_) {
1029 lock_->AssertAcquired();
1030 lock_->Release();
1034 AutoSECMODListReadLock::AutoSECMODListReadLock()
1035 : lock_(SECMOD_GetDefaultModuleListLock()) {
1036 SECMOD_GetReadLock(lock_);
1039 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
1040 SECMOD_ReleaseReadLock(lock_);
1042 #endif // defined(USE_NSS_CERTS)
1044 #if defined(OS_CHROMEOS)
1045 ScopedPK11Slot GetSystemNSSKeySlot(
1046 const base::Callback<void(ScopedPK11Slot)>& callback) {
1047 return g_nss_singleton.Get().GetSystemNSSKeySlot(callback);
1050 void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
1051 g_nss_singleton.Get().SetSystemKeySlotForTesting(slot.Pass());
1054 void EnableTPMTokenForNSS() {
1055 g_nss_singleton.Get().EnableTPMTokenForNSS();
1058 bool IsTPMTokenEnabledForNSS() {
1059 return g_nss_singleton.Get().IsTPMTokenEnabledForNSS();
1062 bool IsTPMTokenReady(const base::Closure& callback) {
1063 return g_nss_singleton.Get().IsTPMTokenReady(callback);
1066 void InitializeTPMTokenAndSystemSlot(
1067 int token_slot_id,
1068 const base::Callback<void(bool)>& callback) {
1069 g_nss_singleton.Get().InitializeTPMTokenAndSystemSlot(token_slot_id,
1070 callback);
1073 bool InitializeNSSForChromeOSUser(const std::string& username_hash,
1074 const base::FilePath& path) {
1075 return g_nss_singleton.Get().InitializeNSSForChromeOSUser(username_hash,
1076 path);
1079 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
1080 return g_nss_singleton.Get().ShouldInitializeTPMForChromeOSUser(
1081 username_hash);
1084 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
1085 g_nss_singleton.Get().WillInitializeTPMForChromeOSUser(username_hash);
1088 void InitializeTPMForChromeOSUser(
1089 const std::string& username_hash,
1090 CK_SLOT_ID slot_id) {
1091 g_nss_singleton.Get().InitializeTPMForChromeOSUser(username_hash, slot_id);
1094 void InitializePrivateSoftwareSlotForChromeOSUser(
1095 const std::string& username_hash) {
1096 g_nss_singleton.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1097 username_hash);
1100 ScopedPK11Slot GetPublicSlotForChromeOSUser(const std::string& username_hash) {
1101 return g_nss_singleton.Get().GetPublicSlotForChromeOSUser(username_hash);
1104 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
1105 const std::string& username_hash,
1106 const base::Callback<void(ScopedPK11Slot)>& callback) {
1107 return g_nss_singleton.Get().GetPrivateSlotForChromeOSUser(username_hash,
1108 callback);
1111 void CloseChromeOSUserForTesting(const std::string& username_hash) {
1112 g_nss_singleton.Get().CloseChromeOSUserForTesting(username_hash);
1114 #endif // defined(OS_CHROMEOS)
1116 base::Time PRTimeToBaseTime(PRTime prtime) {
1117 return base::Time::FromInternalValue(
1118 prtime + base::Time::UnixEpoch().ToInternalValue());
1121 PRTime BaseTimeToPRTime(base::Time time) {
1122 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1125 #if !defined(OS_CHROMEOS)
1126 PK11SlotInfo* GetPersistentNSSKeySlot() {
1127 return g_nss_singleton.Get().GetPersistentNSSKeySlot();
1129 #endif
1131 } // namespace crypto