[Android] Refactor the native test wrappers.
[chromium-blink-merge.git] / crypto / nss_util.cc
blobdf9316054e76f97e136ec9885b7684d172225c84
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/metrics/histogram.h"
41 #include "base/native_library.h"
42 #include "base/path_service.h"
43 #include "base/stl_util.h"
44 #include "base/strings/stringprintf.h"
45 #include "base/threading/thread_checker.h"
46 #include "base/threading/thread_restrictions.h"
47 #include "base/threading/worker_pool.h"
48 #include "build/build_config.h"
50 // USE_NSS_CERTS means NSS is used for certificates and platform integration.
51 // This requires additional support to manage the platform certificate and key
52 // stores.
53 #if defined(USE_NSS_CERTS)
54 #include "base/synchronization/lock.h"
55 #include "crypto/nss_crypto_module_delegate.h"
56 #endif // defined(USE_NSS_CERTS)
58 namespace crypto {
60 namespace {
62 #if defined(OS_CHROMEOS)
63 const char kUserNSSDatabaseName[] = "UserNSSDB";
65 // Constants for loading the Chrome OS TPM-backed PKCS #11 library.
66 const char kChapsModuleName[] = "Chaps";
67 const char kChapsPath[] = "libchaps.so";
69 // Fake certificate authority database used for testing.
70 static const base::FilePath::CharType kReadOnlyCertDB[] =
71 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
72 #endif // defined(OS_CHROMEOS)
74 std::string GetNSSErrorMessage() {
75 std::string result;
76 if (PR_GetErrorTextLength()) {
77 scoped_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
78 PRInt32 copied = PR_GetErrorText(error_text.get());
79 result = std::string(error_text.get(), copied);
80 } else {
81 result = base::StringPrintf("NSS error code: %d", PR_GetError());
83 return result;
86 #if defined(USE_NSS_CERTS)
87 #if !defined(OS_CHROMEOS)
88 base::FilePath GetDefaultConfigDirectory() {
89 base::FilePath dir;
90 PathService::Get(base::DIR_HOME, &dir);
91 if (dir.empty()) {
92 LOG(ERROR) << "Failed to get home directory.";
93 return dir;
95 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
96 if (!base::CreateDirectory(dir)) {
97 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
98 dir.clear();
100 DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
101 return dir;
103 #endif // !defined(IS_CHROMEOS)
105 // On non-Chrome OS platforms, return the default config directory. On Chrome OS
106 // test images, return a read-only directory with fake root CA certs (which are
107 // used by the local Google Accounts server mock we use when testing our login
108 // code). On Chrome OS non-test images (where the read-only directory doesn't
109 // exist), return an empty path.
110 base::FilePath GetInitialConfigDirectory() {
111 #if defined(OS_CHROMEOS)
112 base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
113 if (!base::PathExists(database_dir))
114 database_dir.clear();
115 return database_dir;
116 #else
117 return GetDefaultConfigDirectory();
118 #endif // defined(OS_CHROMEOS)
121 // This callback for NSS forwards all requests to a caller-specified
122 // CryptoModuleBlockingPasswordDelegate object.
123 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
124 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
125 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
126 if (delegate) {
127 bool cancelled = false;
128 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
129 retry != PR_FALSE,
130 &cancelled);
131 if (cancelled)
132 return NULL;
133 char* result = PORT_Strdup(password.c_str());
134 password.replace(0, password.size(), password.size(), 0);
135 return result;
137 DLOG(ERROR) << "PK11 password requested with NULL arg";
138 return NULL;
141 // NSS creates a local cache of the sqlite database if it detects that the
142 // filesystem the database is on is much slower than the local disk. The
143 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
144 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
145 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
146 // detection when database_dir is on NFS. See http://crbug.com/48585.
148 // TODO(wtc): port this function to other USE_NSS_CERTS platforms. It is
149 // defined only for OS_LINUX and OS_OPENBSD simply because the statfs structure
150 // is OS-specific.
152 // Because this function sets an environment variable it must be run before we
153 // go multi-threaded.
154 void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) {
155 bool db_on_nfs = false;
156 #if defined(OS_LINUX)
157 base::FileSystemType fs_type = base::FILE_SYSTEM_UNKNOWN;
158 if (base::GetFileSystemType(database_dir, &fs_type))
159 db_on_nfs = (fs_type == base::FILE_SYSTEM_NFS);
160 #elif defined(OS_OPENBSD)
161 struct statfs buf;
162 if (statfs(database_dir.value().c_str(), &buf) == 0)
163 db_on_nfs = (strcmp(buf.f_fstypename, MOUNT_NFS) == 0);
164 #else
165 NOTIMPLEMENTED();
166 #endif
168 if (db_on_nfs) {
169 scoped_ptr<base::Environment> env(base::Environment::Create());
170 static const char kUseCacheEnvVar[] = "NSS_SDB_USE_CACHE";
171 if (!env->HasVar(kUseCacheEnvVar))
172 env->SetVar(kUseCacheEnvVar, "yes");
176 #endif // defined(USE_NSS_CERTS)
178 // A singleton to initialize/deinitialize NSPR.
179 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
180 // Now that we're leaking the singleton, we could merge back with the NSS
181 // singleton.
182 class NSPRInitSingleton {
183 private:
184 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
186 NSPRInitSingleton() {
187 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
190 // NOTE(willchan): We don't actually execute this code since we leak NSS to
191 // prevent non-joinable threads from using NSS after it's already been shut
192 // down.
193 ~NSPRInitSingleton() {
194 PL_ArenaFinish();
195 PRStatus prstatus = PR_Cleanup();
196 if (prstatus != PR_SUCCESS)
197 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
201 base::LazyInstance<NSPRInitSingleton>::Leaky
202 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
204 // Force a crash with error info on NSS_NoDB_Init failure.
205 void CrashOnNSSInitFailure() {
206 int nss_error = PR_GetError();
207 int os_error = PR_GetOSError();
208 base::debug::Alias(&nss_error);
209 base::debug::Alias(&os_error);
210 LOG(ERROR) << "Error initializing NSS without a persistent database: "
211 << GetNSSErrorMessage();
212 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
215 #if defined(OS_CHROMEOS)
216 class ChromeOSUserData {
217 public:
218 explicit ChromeOSUserData(ScopedPK11Slot public_slot)
219 : public_slot_(public_slot.Pass()),
220 private_slot_initialization_started_(false) {}
221 ~ChromeOSUserData() {
222 if (public_slot_) {
223 SECStatus status = SECMOD_CloseUserDB(public_slot_.get());
224 if (status != SECSuccess)
225 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
229 ScopedPK11Slot GetPublicSlot() {
230 return ScopedPK11Slot(
231 public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL);
234 ScopedPK11Slot GetPrivateSlot(
235 const base::Callback<void(ScopedPK11Slot)>& callback) {
236 if (private_slot_)
237 return ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get()));
238 if (!callback.is_null())
239 tpm_ready_callback_list_.push_back(callback);
240 return ScopedPK11Slot();
243 void SetPrivateSlot(ScopedPK11Slot private_slot) {
244 DCHECK(!private_slot_);
245 private_slot_ = private_slot.Pass();
247 SlotReadyCallbackList callback_list;
248 callback_list.swap(tpm_ready_callback_list_);
249 for (SlotReadyCallbackList::iterator i = callback_list.begin();
250 i != callback_list.end();
251 ++i) {
252 (*i).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get())));
256 bool private_slot_initialization_started() const {
257 return private_slot_initialization_started_;
260 void set_private_slot_initialization_started() {
261 private_slot_initialization_started_ = true;
264 private:
265 ScopedPK11Slot public_slot_;
266 ScopedPK11Slot private_slot_;
268 bool private_slot_initialization_started_;
270 typedef std::vector<base::Callback<void(ScopedPK11Slot)> >
271 SlotReadyCallbackList;
272 SlotReadyCallbackList tpm_ready_callback_list_;
275 class ScopedChapsLoadFixup {
276 public:
277 ScopedChapsLoadFixup();
278 ~ScopedChapsLoadFixup();
280 private:
281 #if defined(COMPONENT_BUILD)
282 void *chaps_handle_;
283 #endif
286 #if defined(COMPONENT_BUILD)
288 ScopedChapsLoadFixup::ScopedChapsLoadFixup() {
289 // HACK: libchaps links the system protobuf and there are symbol conflicts
290 // with the bundled copy. Load chaps with RTLD_DEEPBIND to workaround.
291 chaps_handle_ = dlopen(kChapsPath, RTLD_LOCAL | RTLD_NOW | RTLD_DEEPBIND);
294 ScopedChapsLoadFixup::~ScopedChapsLoadFixup() {
295 // LoadModule() will have taken a 2nd reference.
296 if (chaps_handle_)
297 dlclose(chaps_handle_);
300 #else
302 ScopedChapsLoadFixup::ScopedChapsLoadFixup() {}
303 ScopedChapsLoadFixup::~ScopedChapsLoadFixup() {}
305 #endif // defined(COMPONENT_BUILD)
306 #endif // defined(OS_CHROMEOS)
308 class NSSInitSingleton {
309 public:
310 #if defined(OS_CHROMEOS)
311 // Used with PostTaskAndReply to pass handles to worker thread and back.
312 struct TPMModuleAndSlot {
313 explicit TPMModuleAndSlot(SECMODModule* init_chaps_module)
314 : chaps_module(init_chaps_module) {}
315 SECMODModule* chaps_module;
316 crypto::ScopedPK11Slot tpm_slot;
319 ScopedPK11Slot OpenPersistentNSSDBForPath(const std::string& db_name,
320 const base::FilePath& path) {
321 DCHECK(thread_checker_.CalledOnValidThread());
322 // NSS is allowed to do IO on the current thread since dispatching
323 // to a dedicated thread would still have the affect of blocking
324 // the current thread, due to NSS's internal locking requirements
325 base::ThreadRestrictions::ScopedAllowIO allow_io;
327 base::FilePath nssdb_path = path.AppendASCII(".pki").AppendASCII("nssdb");
328 if (!base::CreateDirectory(nssdb_path)) {
329 LOG(ERROR) << "Failed to create " << nssdb_path.value() << " directory.";
330 return ScopedPK11Slot();
332 return OpenSoftwareNSSDB(nssdb_path, db_name);
335 void EnableTPMTokenForNSS() {
336 DCHECK(thread_checker_.CalledOnValidThread());
338 // If this gets set, then we'll use the TPM for certs with
339 // private keys, otherwise we'll fall back to the software
340 // implementation.
341 tpm_token_enabled_for_nss_ = true;
344 bool IsTPMTokenEnabledForNSS() {
345 DCHECK(thread_checker_.CalledOnValidThread());
346 return tpm_token_enabled_for_nss_;
349 void InitializeTPMTokenAndSystemSlot(
350 int system_slot_id,
351 const base::Callback<void(bool)>& callback) {
352 DCHECK(thread_checker_.CalledOnValidThread());
353 // Should not be called while there is already an initialization in
354 // progress.
355 DCHECK(!initializing_tpm_token_);
356 // If EnableTPMTokenForNSS hasn't been called, return false.
357 if (!tpm_token_enabled_for_nss_) {
358 base::MessageLoop::current()->PostTask(FROM_HERE,
359 base::Bind(callback, false));
360 return;
363 // If everything is already initialized, then return true.
364 // Note that only |tpm_slot_| is checked, since |chaps_module_| could be
365 // NULL in tests while |tpm_slot_| has been set to the test DB.
366 if (tpm_slot_) {
367 base::MessageLoop::current()->PostTask(FROM_HERE,
368 base::Bind(callback, true));
369 return;
372 // Note that a reference is not taken to chaps_module_. This is safe since
373 // NSSInitSingleton is Leaky, so the reference it holds is never released.
374 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
375 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
376 if (base::WorkerPool::PostTaskAndReply(
377 FROM_HERE,
378 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
379 system_slot_id,
380 tpm_args_ptr),
381 base::Bind(&NSSInitSingleton::OnInitializedTPMTokenAndSystemSlot,
382 base::Unretained(this), // NSSInitSingleton is leaky
383 callback,
384 base::Passed(&tpm_args)),
385 true /* task_is_slow */
386 )) {
387 initializing_tpm_token_ = true;
388 } else {
389 base::MessageLoop::current()->PostTask(FROM_HERE,
390 base::Bind(callback, false));
394 static void InitializeTPMTokenOnWorkerThread(CK_SLOT_ID token_slot_id,
395 TPMModuleAndSlot* tpm_args) {
396 // This tries to load the Chaps module so NSS can talk to the hardware
397 // TPM.
398 if (!tpm_args->chaps_module) {
399 ScopedChapsLoadFixup chaps_loader;
401 DVLOG(3) << "Loading chaps...";
402 tpm_args->chaps_module = LoadModule(
403 kChapsModuleName,
404 kChapsPath,
405 // For more details on these parameters, see:
406 // https://developer.mozilla.org/en/PKCS11_Module_Specs
407 // slotFlags=[PublicCerts] -- Certificates and public keys can be
408 // read from this slot without requiring a call to C_Login.
409 // askpw=only -- Only authenticate to the token when necessary.
410 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
412 if (tpm_args->chaps_module) {
413 tpm_args->tpm_slot =
414 GetTPMSlotForIdOnWorkerThread(tpm_args->chaps_module, token_slot_id);
418 void OnInitializedTPMTokenAndSystemSlot(
419 const base::Callback<void(bool)>& callback,
420 scoped_ptr<TPMModuleAndSlot> tpm_args) {
421 DCHECK(thread_checker_.CalledOnValidThread());
422 DVLOG(2) << "Loaded chaps: " << !!tpm_args->chaps_module
423 << ", got tpm slot: " << !!tpm_args->tpm_slot;
425 chaps_module_ = tpm_args->chaps_module;
426 tpm_slot_ = tpm_args->tpm_slot.Pass();
427 if (!chaps_module_ && test_system_slot_) {
428 // chromeos_unittests try to test the TPM initialization process. If we
429 // have a test DB open, pretend that it is the TPM slot.
430 tpm_slot_.reset(PK11_ReferenceSlot(test_system_slot_.get()));
432 initializing_tpm_token_ = false;
434 if (tpm_slot_)
435 RunAndClearTPMReadyCallbackList();
437 callback.Run(!!tpm_slot_);
440 void RunAndClearTPMReadyCallbackList() {
441 TPMReadyCallbackList callback_list;
442 callback_list.swap(tpm_ready_callback_list_);
443 for (TPMReadyCallbackList::iterator i = callback_list.begin();
444 i != callback_list.end();
445 ++i) {
446 i->Run();
450 bool IsTPMTokenReady(const base::Closure& callback) {
451 if (!callback.is_null()) {
452 // Cannot DCHECK in the general case yet, but since the callback is
453 // a new addition to the API, DCHECK to make sure at least the new uses
454 // don't regress.
455 DCHECK(thread_checker_.CalledOnValidThread());
456 } else if (!thread_checker_.CalledOnValidThread()) {
457 // TODO(mattm): Change to DCHECK when callers have been fixed.
458 DVLOG(1) << "Called on wrong thread.\n"
459 << base::debug::StackTrace().ToString();
462 if (tpm_slot_)
463 return true;
465 if (!callback.is_null())
466 tpm_ready_callback_list_.push_back(callback);
468 return false;
471 // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
472 // id as an int. This should be safe since this is only used with chaps, which
473 // we also control.
474 static crypto::ScopedPK11Slot GetTPMSlotForIdOnWorkerThread(
475 SECMODModule* chaps_module,
476 CK_SLOT_ID slot_id) {
477 DCHECK(chaps_module);
479 DVLOG(3) << "Poking chaps module.";
480 SECStatus rv = SECMOD_UpdateSlotList(chaps_module);
481 if (rv != SECSuccess)
482 PLOG(ERROR) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
484 PK11SlotInfo* slot = SECMOD_LookupSlot(chaps_module->moduleID, slot_id);
485 if (!slot)
486 LOG(ERROR) << "TPM slot " << slot_id << " not found.";
487 return crypto::ScopedPK11Slot(slot);
490 bool InitializeNSSForChromeOSUser(const std::string& username_hash,
491 const base::FilePath& path) {
492 DCHECK(thread_checker_.CalledOnValidThread());
493 if (chromeos_user_map_.find(username_hash) != chromeos_user_map_.end()) {
494 // This user already exists in our mapping.
495 DVLOG(2) << username_hash << " already initialized.";
496 return false;
499 DVLOG(2) << "Opening NSS DB " << path.value();
500 std::string db_name = base::StringPrintf(
501 "%s %s", kUserNSSDatabaseName, username_hash.c_str());
502 ScopedPK11Slot public_slot(OpenPersistentNSSDBForPath(db_name, path));
503 chromeos_user_map_[username_hash] =
504 new ChromeOSUserData(public_slot.Pass());
505 return true;
508 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
509 DCHECK(thread_checker_.CalledOnValidThread());
510 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
512 return !chromeos_user_map_[username_hash]
513 ->private_slot_initialization_started();
516 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
517 DCHECK(thread_checker_.CalledOnValidThread());
518 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
520 chromeos_user_map_[username_hash]
521 ->set_private_slot_initialization_started();
524 void InitializeTPMForChromeOSUser(const std::string& username_hash,
525 CK_SLOT_ID slot_id) {
526 DCHECK(thread_checker_.CalledOnValidThread());
527 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
528 DCHECK(chromeos_user_map_[username_hash]->
529 private_slot_initialization_started());
531 if (!chaps_module_)
532 return;
534 // Note that a reference is not taken to chaps_module_. This is safe since
535 // NSSInitSingleton is Leaky, so the reference it holds is never released.
536 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
537 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
538 base::WorkerPool::PostTaskAndReply(
539 FROM_HERE,
540 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
541 slot_id,
542 tpm_args_ptr),
543 base::Bind(&NSSInitSingleton::OnInitializedTPMForChromeOSUser,
544 base::Unretained(this), // NSSInitSingleton is leaky
545 username_hash,
546 base::Passed(&tpm_args)),
547 true /* task_is_slow */
551 void OnInitializedTPMForChromeOSUser(const std::string& username_hash,
552 scoped_ptr<TPMModuleAndSlot> tpm_args) {
553 DCHECK(thread_checker_.CalledOnValidThread());
554 DVLOG(2) << "Got tpm slot for " << username_hash << " "
555 << !!tpm_args->tpm_slot;
556 chromeos_user_map_[username_hash]->SetPrivateSlot(
557 tpm_args->tpm_slot.Pass());
560 void InitializePrivateSoftwareSlotForChromeOSUser(
561 const std::string& username_hash) {
562 DCHECK(thread_checker_.CalledOnValidThread());
563 VLOG(1) << "using software private slot for " << username_hash;
564 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
565 DCHECK(chromeos_user_map_[username_hash]->
566 private_slot_initialization_started());
568 chromeos_user_map_[username_hash]->SetPrivateSlot(
569 chromeos_user_map_[username_hash]->GetPublicSlot());
572 ScopedPK11Slot GetPublicSlotForChromeOSUser(
573 const std::string& username_hash) {
574 DCHECK(thread_checker_.CalledOnValidThread());
576 if (username_hash.empty()) {
577 DVLOG(2) << "empty username_hash";
578 return ScopedPK11Slot();
581 if (chromeos_user_map_.find(username_hash) == chromeos_user_map_.end()) {
582 LOG(ERROR) << username_hash << " not initialized.";
583 return ScopedPK11Slot();
585 return chromeos_user_map_[username_hash]->GetPublicSlot();
588 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
589 const std::string& username_hash,
590 const base::Callback<void(ScopedPK11Slot)>& callback) {
591 DCHECK(thread_checker_.CalledOnValidThread());
593 if (username_hash.empty()) {
594 DVLOG(2) << "empty username_hash";
595 if (!callback.is_null()) {
596 base::MessageLoop::current()->PostTask(
597 FROM_HERE, base::Bind(callback, base::Passed(ScopedPK11Slot())));
599 return ScopedPK11Slot();
602 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
604 return chromeos_user_map_[username_hash]->GetPrivateSlot(callback);
607 void CloseChromeOSUserForTesting(const std::string& username_hash) {
608 DCHECK(thread_checker_.CalledOnValidThread());
609 ChromeOSUserMap::iterator i = chromeos_user_map_.find(username_hash);
610 DCHECK(i != chromeos_user_map_.end());
611 delete i->second;
612 chromeos_user_map_.erase(i);
615 void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
616 // Ensure that a previous value of test_system_slot_ is not overwritten.
617 // Unsetting, i.e. setting a NULL, however is allowed.
618 DCHECK(!slot || !test_system_slot_);
619 test_system_slot_ = slot.Pass();
620 if (test_system_slot_) {
621 tpm_slot_.reset(PK11_ReferenceSlot(test_system_slot_.get()));
622 RunAndClearTPMReadyCallbackList();
623 } else {
624 tpm_slot_.reset();
627 #endif // defined(OS_CHROMEOS)
629 #if !defined(OS_CHROMEOS)
630 PK11SlotInfo* GetPersistentNSSKeySlot() {
631 // TODO(mattm): Change to DCHECK when callers have been fixed.
632 if (!thread_checker_.CalledOnValidThread()) {
633 DVLOG(1) << "Called on wrong thread.\n"
634 << base::debug::StackTrace().ToString();
637 return PK11_GetInternalKeySlot();
639 #endif
641 #if defined(OS_CHROMEOS)
642 void GetSystemNSSKeySlotCallback(
643 const base::Callback<void(ScopedPK11Slot)>& callback) {
644 callback.Run(ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_.get())));
647 ScopedPK11Slot GetSystemNSSKeySlot(
648 const base::Callback<void(ScopedPK11Slot)>& callback) {
649 DCHECK(thread_checker_.CalledOnValidThread());
650 // TODO(mattm): chromeos::TPMTokenloader always calls
651 // InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is
652 // disabled, tpm_slot_ will be the first user's slot instead. Can that be
653 // detected and return NULL instead?
655 base::Closure wrapped_callback;
656 if (!callback.is_null()) {
657 wrapped_callback =
658 base::Bind(&NSSInitSingleton::GetSystemNSSKeySlotCallback,
659 base::Unretained(this) /* singleton is leaky */,
660 callback);
662 if (IsTPMTokenReady(wrapped_callback))
663 return ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_.get()));
664 return ScopedPK11Slot();
666 #endif
668 #if defined(USE_NSS_CERTS)
669 base::Lock* write_lock() {
670 return &write_lock_;
672 #endif // defined(USE_NSS_CERTS)
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;
680 private:
681 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
683 NSSInitSingleton()
684 : tpm_token_enabled_for_nss_(false),
685 initializing_tpm_token_(false),
686 chaps_module_(NULL),
687 root_(NULL) {
688 base::TimeTicks start_time = base::TimeTicks::Now();
690 // It's safe to construct on any thread, since LazyInstance will prevent any
691 // other threads from accessing until the constructor is done.
692 thread_checker_.DetachFromThread();
694 DisableAESNIIfNeeded();
696 EnsureNSPRInit();
698 // We *must* have NSS >= 3.14.3.
699 static_assert(
700 (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
701 (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
702 (NSS_VMAJOR > 3),
703 "nss version check failed");
704 // Also check the run-time NSS version.
705 // NSS_VersionCheck is a >= check, not strict equality.
706 if (!NSS_VersionCheck("3.14.3")) {
707 LOG(FATAL) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
708 "required. Please upgrade to the latest NSS, and if you "
709 "still get this error, contact your distribution "
710 "maintainer.";
713 SECStatus status = SECFailure;
714 bool nodb_init = force_nodb_init_;
716 #if !defined(USE_NSS_CERTS)
717 // Use the system certificate store, so initialize NSS without database.
718 nodb_init = true;
719 #endif
721 if (nodb_init) {
722 status = NSS_NoDB_Init(NULL);
723 if (status != SECSuccess) {
724 CrashOnNSSInitFailure();
725 return;
727 #if defined(OS_IOS)
728 root_ = InitDefaultRootCerts();
729 #endif // defined(OS_IOS)
730 } else {
731 #if defined(USE_NSS_CERTS)
732 base::FilePath database_dir = GetInitialConfigDirectory();
733 if (!database_dir.empty()) {
734 // This duplicates the work which should have been done in
735 // EarlySetupForNSSInit. However, this function is idempotent so
736 // there's no harm done.
737 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
739 // Initialize with a persistent database (likely, ~/.pki/nssdb).
740 // Use "sql:" which can be shared by multiple processes safely.
741 std::string nss_config_dir =
742 base::StringPrintf("sql:%s", database_dir.value().c_str());
743 #if defined(OS_CHROMEOS)
744 status = NSS_Init(nss_config_dir.c_str());
745 #else
746 status = NSS_InitReadWrite(nss_config_dir.c_str());
747 #endif
748 if (status != SECSuccess) {
749 LOG(ERROR) << "Error initializing NSS with a persistent "
750 "database (" << nss_config_dir
751 << "): " << GetNSSErrorMessage();
754 if (status != SECSuccess) {
755 VLOG(1) << "Initializing NSS without a persistent database.";
756 status = NSS_NoDB_Init(NULL);
757 if (status != SECSuccess) {
758 CrashOnNSSInitFailure();
759 return;
763 PK11_SetPasswordFunc(PKCS11PasswordFunc);
765 // If we haven't initialized the password for the NSS databases,
766 // initialize an empty-string password so that we don't need to
767 // log in.
768 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
769 if (slot) {
770 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
771 // yet, so we don't need to lock.
772 if (PK11_NeedUserInit(slot))
773 PK11_InitPin(slot, NULL, NULL);
774 PK11_FreeSlot(slot);
777 root_ = InitDefaultRootCerts();
778 #endif // defined(USE_NSS_CERTS)
781 // Disable MD5 certificate signatures. (They are disabled by default in
782 // NSS 3.14.)
783 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
784 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
785 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
787 // The UMA bit is conditionally set for this histogram in
788 // components/startup_metric_utils.cc .
789 LOCAL_HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
790 base::TimeTicks::Now() - start_time,
791 base::TimeDelta::FromMilliseconds(10),
792 base::TimeDelta::FromHours(1),
793 50);
796 // NOTE(willchan): We don't actually execute this code since we leak NSS to
797 // prevent non-joinable threads from using NSS after it's already been shut
798 // down.
799 ~NSSInitSingleton() {
800 #if defined(OS_CHROMEOS)
801 STLDeleteValues(&chromeos_user_map_);
802 #endif
803 tpm_slot_.reset();
804 if (root_) {
805 SECMOD_UnloadUserModule(root_);
806 SECMOD_DestroyModule(root_);
807 root_ = NULL;
809 if (chaps_module_) {
810 SECMOD_UnloadUserModule(chaps_module_);
811 SECMOD_DestroyModule(chaps_module_);
812 chaps_module_ = NULL;
815 SECStatus status = NSS_Shutdown();
816 if (status != SECSuccess) {
817 // We VLOG(1) because this failure is relatively harmless (leaking, but
818 // we're shutting down anyway).
819 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
823 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
824 // Load nss's built-in root certs.
825 SECMODModule* InitDefaultRootCerts() {
826 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
827 if (root)
828 return root;
830 // Aw, snap. Can't find/load root cert shared library.
831 // This will make it hard to talk to anybody via https.
832 // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
833 return NULL;
836 // Load the given module for this NSS session.
837 static SECMODModule* LoadModule(const char* name,
838 const char* library_path,
839 const char* params) {
840 std::string modparams = base::StringPrintf(
841 "name=\"%s\" library=\"%s\" %s",
842 name, library_path, params ? params : "");
844 // Shouldn't need to const_cast here, but SECMOD doesn't properly
845 // declare input string arguments as const. Bug
846 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
847 // on NSS codebase to address this.
848 SECMODModule* module = SECMOD_LoadUserModule(
849 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
850 if (!module) {
851 LOG(ERROR) << "Error loading " << name << " module into NSS: "
852 << GetNSSErrorMessage();
853 return NULL;
855 if (!module->loaded) {
856 LOG(ERROR) << "After loading " << name << ", loaded==false: "
857 << GetNSSErrorMessage();
858 SECMOD_DestroyModule(module);
859 return NULL;
861 return module;
863 #endif
865 static void DisableAESNIIfNeeded() {
866 if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
867 // Some versions of NSS have a bug that causes AVX instructions to be
868 // used without testing whether XSAVE is enabled by the operating system.
869 // In order to work around this, we disable AES-NI in NSS when we find
870 // that |has_avx()| is false (which includes the XSAVE test). See
871 // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
872 base::CPU cpu;
874 if (cpu.has_avx_hardware() && !cpu.has_avx()) {
875 scoped_ptr<base::Environment> env(base::Environment::Create());
876 env->SetVar("NSS_DISABLE_HW_AES", "1");
881 // If this is set to true NSS is forced to be initialized without a DB.
882 static bool force_nodb_init_;
884 bool tpm_token_enabled_for_nss_;
885 bool initializing_tpm_token_;
886 typedef std::vector<base::Closure> TPMReadyCallbackList;
887 TPMReadyCallbackList tpm_ready_callback_list_;
888 SECMODModule* chaps_module_;
889 crypto::ScopedPK11Slot tpm_slot_;
890 SECMODModule* root_;
891 #if defined(OS_CHROMEOS)
892 typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
893 ChromeOSUserMap chromeos_user_map_;
894 ScopedPK11Slot test_system_slot_;
895 #endif
896 #if defined(USE_NSS_CERTS)
897 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
898 // is fixed, we will no longer need the lock.
899 base::Lock write_lock_;
900 #endif // defined(USE_NSS_CERTS)
902 base::ThreadChecker thread_checker_;
905 // static
906 bool NSSInitSingleton::force_nodb_init_ = false;
908 base::LazyInstance<NSSInitSingleton>::Leaky
909 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
910 } // namespace
912 #if defined(USE_NSS_CERTS)
913 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
914 const std::string& description) {
915 const std::string modspec =
916 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
917 path.value().c_str(),
918 description.c_str());
919 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
920 if (db_slot) {
921 if (PK11_NeedUserInit(db_slot))
922 PK11_InitPin(db_slot, NULL, NULL);
923 } else {
924 LOG(ERROR) << "Error opening persistent database (" << modspec
925 << "): " << GetNSSErrorMessage();
927 return ScopedPK11Slot(db_slot);
930 void EarlySetupForNSSInit() {
931 base::FilePath database_dir = GetInitialConfigDirectory();
932 if (!database_dir.empty())
933 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
935 #endif
937 void EnsureNSPRInit() {
938 g_nspr_singleton.Get();
941 void InitNSSSafely() {
942 // We might fork, but we haven't loaded any security modules.
943 DisableNSSForkCheck();
944 // If we're sandboxed, we shouldn't be able to open user security modules,
945 // but it's more correct to tell NSS to not even try.
946 // Loading user security modules would have security implications.
947 ForceNSSNoDBInit();
948 // Initialize NSS.
949 EnsureNSSInit();
952 void EnsureNSSInit() {
953 // Initializing SSL causes us to do blocking IO.
954 // Temporarily allow it until we fix
955 // http://code.google.com/p/chromium/issues/detail?id=59847
956 base::ThreadRestrictions::ScopedAllowIO allow_io;
957 g_nss_singleton.Get();
960 void ForceNSSNoDBInit() {
961 NSSInitSingleton::ForceNoDBInit();
964 void DisableNSSForkCheck() {
965 scoped_ptr<base::Environment> env(base::Environment::Create());
966 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
969 void LoadNSSLibraries() {
970 // Some NSS libraries are linked dynamically so load them here.
971 #if defined(USE_NSS_CERTS)
972 // Try to search for multiple directories to load the libraries.
973 std::vector<base::FilePath> paths;
975 // Use relative path to Search PATH for the library files.
976 paths.push_back(base::FilePath());
978 // For Debian derivatives NSS libraries are located here.
979 paths.push_back(base::FilePath("/usr/lib/nss"));
981 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
982 #if defined(ARCH_CPU_X86_64)
983 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
984 #elif defined(ARCH_CPU_X86)
985 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
986 #elif defined(ARCH_CPU_ARMEL)
987 #if defined(__ARM_PCS_VFP)
988 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
989 #else
990 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
991 #endif // defined(__ARM_PCS_VFP)
992 #elif defined(ARCH_CPU_MIPSEL)
993 paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
994 #endif // defined(ARCH_CPU_X86_64)
996 // A list of library files to load.
997 std::vector<std::string> libs;
998 libs.push_back("libsoftokn3.so");
999 libs.push_back("libfreebl3.so");
1001 // For each combination of library file and path, check for existence and
1002 // then load.
1003 size_t loaded = 0;
1004 for (size_t i = 0; i < libs.size(); ++i) {
1005 for (size_t j = 0; j < paths.size(); ++j) {
1006 base::FilePath path = paths[j].Append(libs[i]);
1007 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
1008 if (lib) {
1009 ++loaded;
1010 break;
1015 if (loaded == libs.size()) {
1016 VLOG(3) << "NSS libraries loaded.";
1017 } else {
1018 LOG(ERROR) << "Failed to load NSS libraries.";
1020 #endif // defined(USE_NSS_CERTS)
1023 bool CheckNSSVersion(const char* version) {
1024 return !!NSS_VersionCheck(version);
1027 #if defined(USE_NSS_CERTS)
1028 base::Lock* GetNSSWriteLock() {
1029 return g_nss_singleton.Get().write_lock();
1032 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
1033 // May be NULL if the lock is not needed in our version of NSS.
1034 if (lock_)
1035 lock_->Acquire();
1038 AutoNSSWriteLock::~AutoNSSWriteLock() {
1039 if (lock_) {
1040 lock_->AssertAcquired();
1041 lock_->Release();
1045 AutoSECMODListReadLock::AutoSECMODListReadLock()
1046 : lock_(SECMOD_GetDefaultModuleListLock()) {
1047 SECMOD_GetReadLock(lock_);
1050 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
1051 SECMOD_ReleaseReadLock(lock_);
1053 #endif // defined(USE_NSS_CERTS)
1055 #if defined(OS_CHROMEOS)
1056 ScopedPK11Slot GetSystemNSSKeySlot(
1057 const base::Callback<void(ScopedPK11Slot)>& callback) {
1058 return g_nss_singleton.Get().GetSystemNSSKeySlot(callback);
1061 void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
1062 g_nss_singleton.Get().SetSystemKeySlotForTesting(slot.Pass());
1065 void EnableTPMTokenForNSS() {
1066 g_nss_singleton.Get().EnableTPMTokenForNSS();
1069 bool IsTPMTokenEnabledForNSS() {
1070 return g_nss_singleton.Get().IsTPMTokenEnabledForNSS();
1073 bool IsTPMTokenReady(const base::Closure& callback) {
1074 return g_nss_singleton.Get().IsTPMTokenReady(callback);
1077 void InitializeTPMTokenAndSystemSlot(
1078 int token_slot_id,
1079 const base::Callback<void(bool)>& callback) {
1080 g_nss_singleton.Get().InitializeTPMTokenAndSystemSlot(token_slot_id,
1081 callback);
1084 bool InitializeNSSForChromeOSUser(const std::string& username_hash,
1085 const base::FilePath& path) {
1086 return g_nss_singleton.Get().InitializeNSSForChromeOSUser(username_hash,
1087 path);
1090 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
1091 return g_nss_singleton.Get().ShouldInitializeTPMForChromeOSUser(
1092 username_hash);
1095 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
1096 g_nss_singleton.Get().WillInitializeTPMForChromeOSUser(username_hash);
1099 void InitializeTPMForChromeOSUser(
1100 const std::string& username_hash,
1101 CK_SLOT_ID slot_id) {
1102 g_nss_singleton.Get().InitializeTPMForChromeOSUser(username_hash, slot_id);
1105 void InitializePrivateSoftwareSlotForChromeOSUser(
1106 const std::string& username_hash) {
1107 g_nss_singleton.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1108 username_hash);
1111 ScopedPK11Slot GetPublicSlotForChromeOSUser(const std::string& username_hash) {
1112 return g_nss_singleton.Get().GetPublicSlotForChromeOSUser(username_hash);
1115 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
1116 const std::string& username_hash,
1117 const base::Callback<void(ScopedPK11Slot)>& callback) {
1118 return g_nss_singleton.Get().GetPrivateSlotForChromeOSUser(username_hash,
1119 callback);
1122 void CloseChromeOSUserForTesting(const std::string& username_hash) {
1123 g_nss_singleton.Get().CloseChromeOSUserForTesting(username_hash);
1125 #endif // defined(OS_CHROMEOS)
1127 base::Time PRTimeToBaseTime(PRTime prtime) {
1128 return base::Time::FromInternalValue(
1129 prtime + base::Time::UnixEpoch().ToInternalValue());
1132 PRTime BaseTimeToPRTime(base::Time time) {
1133 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1136 #if !defined(OS_CHROMEOS)
1137 PK11SlotInfo* GetPersistentNSSKeySlot() {
1138 return g_nss_singleton.Get().GetPersistentNSSKeySlot();
1140 #endif
1142 } // namespace crypto