Reland 189a2ed4d209231d517b0e64a722722dead3f17a Fixes HasEventListener check in Exten...
[chromium-blink-merge.git] / crypto / nss_util.cc
blobf0c726d4796437ef9cf2046e21dbc75ffe0009ec
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 #include <map>
22 #include <vector>
24 #include "base/base_paths.h"
25 #include "base/bind.h"
26 #include "base/cpu.h"
27 #include "base/debug/alias.h"
28 #include "base/debug/stack_trace.h"
29 #include "base/environment.h"
30 #include "base/file_util.h"
31 #include "base/files/file_path.h"
32 #include "base/lazy_instance.h"
33 #include "base/logging.h"
34 #include "base/memory/scoped_ptr.h"
35 #include "base/message_loop/message_loop.h"
36 #include "base/metrics/histogram.h"
37 #include "base/native_library.h"
38 #include "base/path_service.h"
39 #include "base/stl_util.h"
40 #include "base/strings/stringprintf.h"
41 #include "base/threading/thread_checker.h"
42 #include "base/threading/thread_restrictions.h"
43 #include "base/threading/worker_pool.h"
44 #include "build/build_config.h"
46 // USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not
47 // defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
48 // use NSS for crypto or certificate verification, and we don't use the NSS
49 // certificate and key databases.
50 #if defined(USE_NSS)
51 #include "base/synchronization/lock.h"
52 #include "crypto/nss_crypto_module_delegate.h"
53 #endif // defined(USE_NSS)
55 namespace crypto {
57 namespace {
59 #if defined(OS_CHROMEOS)
60 const char kUserNSSDatabaseName[] = "UserNSSDB";
62 // Constants for loading the Chrome OS TPM-backed PKCS #11 library.
63 const char kChapsModuleName[] = "Chaps";
64 const char kChapsPath[] = "libchaps.so";
66 // Fake certificate authority database used for testing.
67 static const base::FilePath::CharType kReadOnlyCertDB[] =
68 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
69 #endif // defined(OS_CHROMEOS)
71 std::string GetNSSErrorMessage() {
72 std::string result;
73 if (PR_GetErrorTextLength()) {
74 scoped_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
75 PRInt32 copied = PR_GetErrorText(error_text.get());
76 result = std::string(error_text.get(), copied);
77 } else {
78 result = base::StringPrintf("NSS error code: %d", PR_GetError());
80 return result;
83 #if defined(USE_NSS)
84 #if !defined(OS_CHROMEOS)
85 base::FilePath GetDefaultConfigDirectory() {
86 base::FilePath dir;
87 PathService::Get(base::DIR_HOME, &dir);
88 if (dir.empty()) {
89 LOG(ERROR) << "Failed to get home directory.";
90 return dir;
92 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
93 if (!base::CreateDirectory(dir)) {
94 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
95 dir.clear();
97 DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
98 return dir;
100 #endif // !defined(IS_CHROMEOS)
102 // On non-Chrome OS platforms, return the default config directory. On Chrome OS
103 // test images, return a read-only directory with fake root CA certs (which are
104 // used by the local Google Accounts server mock we use when testing our login
105 // code). On Chrome OS non-test images (where the read-only directory doesn't
106 // exist), return an empty path.
107 base::FilePath GetInitialConfigDirectory() {
108 #if defined(OS_CHROMEOS)
109 base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
110 if (!base::PathExists(database_dir))
111 database_dir.clear();
112 return database_dir;
113 #else
114 return GetDefaultConfigDirectory();
115 #endif // defined(OS_CHROMEOS)
118 // This callback for NSS forwards all requests to a caller-specified
119 // CryptoModuleBlockingPasswordDelegate object.
120 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
121 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
122 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
123 if (delegate) {
124 bool cancelled = false;
125 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
126 retry != PR_FALSE,
127 &cancelled);
128 if (cancelled)
129 return NULL;
130 char* result = PORT_Strdup(password.c_str());
131 password.replace(0, password.size(), password.size(), 0);
132 return result;
134 DLOG(ERROR) << "PK11 password requested with NULL arg";
135 return NULL;
138 // NSS creates a local cache of the sqlite database if it detects that the
139 // filesystem the database is on is much slower than the local disk. The
140 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
141 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
142 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
143 // detection when database_dir is on NFS. See http://crbug.com/48585.
145 // TODO(wtc): port this function to other USE_NSS platforms. It is defined
146 // only for OS_LINUX and OS_OPENBSD simply because the statfs structure
147 // is OS-specific.
149 // Because this function sets an environment variable it must be run before we
150 // go multi-threaded.
151 void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) {
152 bool db_on_nfs = false;
153 #if defined(OS_LINUX)
154 base::FileSystemType fs_type = base::FILE_SYSTEM_UNKNOWN;
155 if (base::GetFileSystemType(database_dir, &fs_type))
156 db_on_nfs = (fs_type == base::FILE_SYSTEM_NFS);
157 #elif defined(OS_OPENBSD)
158 struct statfs buf;
159 if (statfs(database_dir.value().c_str(), &buf) == 0)
160 db_on_nfs = (strcmp(buf.f_fstypename, MOUNT_NFS) == 0);
161 #else
162 NOTIMPLEMENTED();
163 #endif
165 if (db_on_nfs) {
166 scoped_ptr<base::Environment> env(base::Environment::Create());
167 static const char kUseCacheEnvVar[] = "NSS_SDB_USE_CACHE";
168 if (!env->HasVar(kUseCacheEnvVar))
169 env->SetVar(kUseCacheEnvVar, "yes");
173 #endif // defined(USE_NSS)
175 // A singleton to initialize/deinitialize NSPR.
176 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
177 // Now that we're leaking the singleton, we could merge back with the NSS
178 // singleton.
179 class NSPRInitSingleton {
180 private:
181 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
183 NSPRInitSingleton() {
184 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
187 // NOTE(willchan): We don't actually execute this code since we leak NSS to
188 // prevent non-joinable threads from using NSS after it's already been shut
189 // down.
190 ~NSPRInitSingleton() {
191 PL_ArenaFinish();
192 PRStatus prstatus = PR_Cleanup();
193 if (prstatus != PR_SUCCESS)
194 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
198 base::LazyInstance<NSPRInitSingleton>::Leaky
199 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
201 // Force a crash with error info on NSS_NoDB_Init failure.
202 void CrashOnNSSInitFailure() {
203 int nss_error = PR_GetError();
204 int os_error = PR_GetOSError();
205 base::debug::Alias(&nss_error);
206 base::debug::Alias(&os_error);
207 LOG(ERROR) << "Error initializing NSS without a persistent database: "
208 << GetNSSErrorMessage();
209 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
212 #if defined(OS_CHROMEOS)
213 class ChromeOSUserData {
214 public:
215 explicit ChromeOSUserData(ScopedPK11Slot public_slot)
216 : public_slot_(public_slot.Pass()),
217 private_slot_initialization_started_(false) {}
218 ~ChromeOSUserData() {
219 if (public_slot_) {
220 SECStatus status = SECMOD_CloseUserDB(public_slot_.get());
221 if (status != SECSuccess)
222 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
226 ScopedPK11Slot GetPublicSlot() {
227 return ScopedPK11Slot(
228 public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL);
231 ScopedPK11Slot GetPrivateSlot(
232 const base::Callback<void(ScopedPK11Slot)>& callback) {
233 if (private_slot_)
234 return ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get()));
235 if (!callback.is_null())
236 tpm_ready_callback_list_.push_back(callback);
237 return ScopedPK11Slot();
240 void SetPrivateSlot(ScopedPK11Slot private_slot) {
241 DCHECK(!private_slot_);
242 private_slot_ = private_slot.Pass();
244 SlotReadyCallbackList callback_list;
245 callback_list.swap(tpm_ready_callback_list_);
246 for (SlotReadyCallbackList::iterator i = callback_list.begin();
247 i != callback_list.end();
248 ++i) {
249 (*i).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get())));
253 bool private_slot_initialization_started() const {
254 return private_slot_initialization_started_;
257 void set_private_slot_initialization_started() {
258 private_slot_initialization_started_ = true;
261 private:
262 ScopedPK11Slot public_slot_;
263 ScopedPK11Slot private_slot_;
265 bool private_slot_initialization_started_;
267 typedef std::vector<base::Callback<void(ScopedPK11Slot)> >
268 SlotReadyCallbackList;
269 SlotReadyCallbackList tpm_ready_callback_list_;
271 #endif // defined(OS_CHROMEOS)
273 class NSSInitSingleton {
274 public:
275 #if defined(OS_CHROMEOS)
276 // Used with PostTaskAndReply to pass handles to worker thread and back.
277 struct TPMModuleAndSlot {
278 explicit TPMModuleAndSlot(SECMODModule* init_chaps_module)
279 : chaps_module(init_chaps_module) {}
280 SECMODModule* chaps_module;
281 crypto::ScopedPK11Slot tpm_slot;
284 ScopedPK11Slot OpenPersistentNSSDBForPath(const std::string& db_name,
285 const base::FilePath& path) {
286 DCHECK(thread_checker_.CalledOnValidThread());
287 // NSS is allowed to do IO on the current thread since dispatching
288 // to a dedicated thread would still have the affect of blocking
289 // the current thread, due to NSS's internal locking requirements
290 base::ThreadRestrictions::ScopedAllowIO allow_io;
292 base::FilePath nssdb_path = path.AppendASCII(".pki").AppendASCII("nssdb");
293 if (!base::CreateDirectory(nssdb_path)) {
294 LOG(ERROR) << "Failed to create " << nssdb_path.value() << " directory.";
295 return ScopedPK11Slot();
297 return OpenSoftwareNSSDB(nssdb_path, db_name);
300 void EnableTPMTokenForNSS() {
301 DCHECK(thread_checker_.CalledOnValidThread());
303 // If this gets set, then we'll use the TPM for certs with
304 // private keys, otherwise we'll fall back to the software
305 // implementation.
306 tpm_token_enabled_for_nss_ = true;
309 bool IsTPMTokenEnabledForNSS() {
310 DCHECK(thread_checker_.CalledOnValidThread());
311 return tpm_token_enabled_for_nss_;
314 void InitializeTPMTokenAndSystemSlot(
315 int system_slot_id,
316 const base::Callback<void(bool)>& callback) {
317 DCHECK(thread_checker_.CalledOnValidThread());
318 // Should not be called while there is already an initialization in
319 // progress.
320 DCHECK(!initializing_tpm_token_);
321 // If EnableTPMTokenForNSS hasn't been called, return false.
322 if (!tpm_token_enabled_for_nss_) {
323 base::MessageLoop::current()->PostTask(FROM_HERE,
324 base::Bind(callback, false));
325 return;
328 // If everything is already initialized, then return true.
329 // Note that only |tpm_slot_| is checked, since |chaps_module_| could be
330 // NULL in tests while |tpm_slot_| has been set to the test DB.
331 if (tpm_slot_) {
332 base::MessageLoop::current()->PostTask(FROM_HERE,
333 base::Bind(callback, true));
334 return;
337 // Note that a reference is not taken to chaps_module_. This is safe since
338 // NSSInitSingleton is Leaky, so the reference it holds is never released.
339 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
340 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
341 if (base::WorkerPool::PostTaskAndReply(
342 FROM_HERE,
343 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
344 system_slot_id,
345 tpm_args_ptr),
346 base::Bind(&NSSInitSingleton::OnInitializedTPMTokenAndSystemSlot,
347 base::Unretained(this), // NSSInitSingleton is leaky
348 callback,
349 base::Passed(&tpm_args)),
350 true /* task_is_slow */
351 )) {
352 initializing_tpm_token_ = true;
353 } else {
354 base::MessageLoop::current()->PostTask(FROM_HERE,
355 base::Bind(callback, false));
359 static void InitializeTPMTokenOnWorkerThread(CK_SLOT_ID token_slot_id,
360 TPMModuleAndSlot* tpm_args) {
361 // This tries to load the Chaps module so NSS can talk to the hardware
362 // TPM.
363 if (!tpm_args->chaps_module) {
364 DVLOG(3) << "Loading chaps...";
365 tpm_args->chaps_module = LoadModule(
366 kChapsModuleName,
367 kChapsPath,
368 // For more details on these parameters, see:
369 // https://developer.mozilla.org/en/PKCS11_Module_Specs
370 // slotFlags=[PublicCerts] -- Certificates and public keys can be
371 // read from this slot without requiring a call to C_Login.
372 // askpw=only -- Only authenticate to the token when necessary.
373 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
375 if (tpm_args->chaps_module) {
376 tpm_args->tpm_slot =
377 GetTPMSlotForIdOnWorkerThread(tpm_args->chaps_module, token_slot_id);
381 void OnInitializedTPMTokenAndSystemSlot(
382 const base::Callback<void(bool)>& callback,
383 scoped_ptr<TPMModuleAndSlot> tpm_args) {
384 DCHECK(thread_checker_.CalledOnValidThread());
385 DVLOG(2) << "Loaded chaps: " << !!tpm_args->chaps_module
386 << ", got tpm slot: " << !!tpm_args->tpm_slot;
388 chaps_module_ = tpm_args->chaps_module;
389 tpm_slot_ = tpm_args->tpm_slot.Pass();
390 if (!chaps_module_ && test_system_slot_) {
391 // chromeos_unittests try to test the TPM initialization process. If we
392 // have a test DB open, pretend that it is the TPM slot.
393 tpm_slot_.reset(PK11_ReferenceSlot(test_system_slot_.get()));
395 initializing_tpm_token_ = false;
397 if (tpm_slot_)
398 RunAndClearTPMReadyCallbackList();
400 callback.Run(!!tpm_slot_);
403 void RunAndClearTPMReadyCallbackList() {
404 TPMReadyCallbackList callback_list;
405 callback_list.swap(tpm_ready_callback_list_);
406 for (TPMReadyCallbackList::iterator i = callback_list.begin();
407 i != callback_list.end();
408 ++i) {
409 i->Run();
413 bool IsTPMTokenReady(const base::Closure& callback) {
414 if (!callback.is_null()) {
415 // Cannot DCHECK in the general case yet, but since the callback is
416 // a new addition to the API, DCHECK to make sure at least the new uses
417 // don't regress.
418 DCHECK(thread_checker_.CalledOnValidThread());
419 } else if (!thread_checker_.CalledOnValidThread()) {
420 // TODO(mattm): Change to DCHECK when callers have been fixed.
421 DVLOG(1) << "Called on wrong thread.\n"
422 << base::debug::StackTrace().ToString();
425 if (tpm_slot_)
426 return true;
428 if (!callback.is_null())
429 tpm_ready_callback_list_.push_back(callback);
431 return false;
434 // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
435 // id as an int. This should be safe since this is only used with chaps, which
436 // we also control.
437 static crypto::ScopedPK11Slot GetTPMSlotForIdOnWorkerThread(
438 SECMODModule* chaps_module,
439 CK_SLOT_ID slot_id) {
440 DCHECK(chaps_module);
442 DVLOG(3) << "Poking chaps module.";
443 SECStatus rv = SECMOD_UpdateSlotList(chaps_module);
444 if (rv != SECSuccess)
445 PLOG(ERROR) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
447 PK11SlotInfo* slot = SECMOD_LookupSlot(chaps_module->moduleID, slot_id);
448 if (!slot)
449 LOG(ERROR) << "TPM slot " << slot_id << " not found.";
450 return crypto::ScopedPK11Slot(slot);
453 bool InitializeNSSForChromeOSUser(
454 const std::string& email,
455 const std::string& username_hash,
456 const base::FilePath& path) {
457 DCHECK(thread_checker_.CalledOnValidThread());
458 if (chromeos_user_map_.find(username_hash) != chromeos_user_map_.end()) {
459 // This user already exists in our mapping.
460 DVLOG(2) << username_hash << " already initialized.";
461 return false;
464 DVLOG(2) << "Opening NSS DB " << path.value();
465 std::string db_name = base::StringPrintf(
466 "%s %s", kUserNSSDatabaseName, username_hash.c_str());
467 ScopedPK11Slot public_slot(OpenPersistentNSSDBForPath(db_name, path));
468 chromeos_user_map_[username_hash] =
469 new ChromeOSUserData(public_slot.Pass());
470 return true;
473 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
474 DCHECK(thread_checker_.CalledOnValidThread());
475 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
477 return !chromeos_user_map_[username_hash]
478 ->private_slot_initialization_started();
481 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
482 DCHECK(thread_checker_.CalledOnValidThread());
483 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
485 chromeos_user_map_[username_hash]
486 ->set_private_slot_initialization_started();
489 void InitializeTPMForChromeOSUser(const std::string& username_hash,
490 CK_SLOT_ID slot_id) {
491 DCHECK(thread_checker_.CalledOnValidThread());
492 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
493 DCHECK(chromeos_user_map_[username_hash]->
494 private_slot_initialization_started());
496 if (!chaps_module_)
497 return;
499 // Note that a reference is not taken to chaps_module_. This is safe since
500 // NSSInitSingleton is Leaky, so the reference it holds is never released.
501 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
502 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
503 base::WorkerPool::PostTaskAndReply(
504 FROM_HERE,
505 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
506 slot_id,
507 tpm_args_ptr),
508 base::Bind(&NSSInitSingleton::OnInitializedTPMForChromeOSUser,
509 base::Unretained(this), // NSSInitSingleton is leaky
510 username_hash,
511 base::Passed(&tpm_args)),
512 true /* task_is_slow */
516 void OnInitializedTPMForChromeOSUser(const std::string& username_hash,
517 scoped_ptr<TPMModuleAndSlot> tpm_args) {
518 DCHECK(thread_checker_.CalledOnValidThread());
519 DVLOG(2) << "Got tpm slot for " << username_hash << " "
520 << !!tpm_args->tpm_slot;
521 chromeos_user_map_[username_hash]->SetPrivateSlot(
522 tpm_args->tpm_slot.Pass());
525 void InitializePrivateSoftwareSlotForChromeOSUser(
526 const std::string& username_hash) {
527 DCHECK(thread_checker_.CalledOnValidThread());
528 VLOG(1) << "using software private slot for " << username_hash;
529 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
530 DCHECK(chromeos_user_map_[username_hash]->
531 private_slot_initialization_started());
533 chromeos_user_map_[username_hash]->SetPrivateSlot(
534 chromeos_user_map_[username_hash]->GetPublicSlot());
537 ScopedPK11Slot GetPublicSlotForChromeOSUser(
538 const std::string& username_hash) {
539 DCHECK(thread_checker_.CalledOnValidThread());
541 if (username_hash.empty()) {
542 DVLOG(2) << "empty username_hash";
543 return ScopedPK11Slot();
546 if (chromeos_user_map_.find(username_hash) == chromeos_user_map_.end()) {
547 LOG(ERROR) << username_hash << " not initialized.";
548 return ScopedPK11Slot();
550 return chromeos_user_map_[username_hash]->GetPublicSlot();
553 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
554 const std::string& username_hash,
555 const base::Callback<void(ScopedPK11Slot)>& callback) {
556 DCHECK(thread_checker_.CalledOnValidThread());
558 if (username_hash.empty()) {
559 DVLOG(2) << "empty username_hash";
560 if (!callback.is_null()) {
561 base::MessageLoop::current()->PostTask(
562 FROM_HERE, base::Bind(callback, base::Passed(ScopedPK11Slot())));
564 return ScopedPK11Slot();
567 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
569 return chromeos_user_map_[username_hash]->GetPrivateSlot(callback);
572 void CloseChromeOSUserForTesting(const std::string& username_hash) {
573 DCHECK(thread_checker_.CalledOnValidThread());
574 ChromeOSUserMap::iterator i = chromeos_user_map_.find(username_hash);
575 DCHECK(i != chromeos_user_map_.end());
576 delete i->second;
577 chromeos_user_map_.erase(i);
580 void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
581 // Ensure that a previous value of test_system_slot_ is not overwritten.
582 // Unsetting, i.e. setting a NULL, however is allowed.
583 DCHECK(!slot || !test_system_slot_);
584 test_system_slot_ = slot.Pass();
585 if (test_system_slot_) {
586 tpm_slot_.reset(PK11_ReferenceSlot(test_system_slot_.get()));
587 RunAndClearTPMReadyCallbackList();
588 } else {
589 tpm_slot_.reset();
592 #endif // defined(OS_CHROMEOS)
594 #if !defined(OS_CHROMEOS)
595 PK11SlotInfo* GetPersistentNSSKeySlot() {
596 // TODO(mattm): Change to DCHECK when callers have been fixed.
597 if (!thread_checker_.CalledOnValidThread()) {
598 DVLOG(1) << "Called on wrong thread.\n"
599 << base::debug::StackTrace().ToString();
602 return PK11_GetInternalKeySlot();
604 #endif
606 #if defined(OS_CHROMEOS)
607 void GetSystemNSSKeySlotCallback(
608 const base::Callback<void(ScopedPK11Slot)>& callback) {
609 callback.Run(ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_.get())));
612 ScopedPK11Slot GetSystemNSSKeySlot(
613 const base::Callback<void(ScopedPK11Slot)>& callback) {
614 DCHECK(thread_checker_.CalledOnValidThread());
615 // TODO(mattm): chromeos::TPMTokenloader always calls
616 // InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is
617 // disabled, tpm_slot_ will be the first user's slot instead. Can that be
618 // detected and return NULL instead?
620 base::Closure wrapped_callback;
621 if (!callback.is_null()) {
622 wrapped_callback =
623 base::Bind(&NSSInitSingleton::GetSystemNSSKeySlotCallback,
624 base::Unretained(this) /* singleton is leaky */,
625 callback);
627 if (IsTPMTokenReady(wrapped_callback))
628 return ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_.get()));
629 return ScopedPK11Slot();
631 #endif
633 #if defined(USE_NSS)
634 base::Lock* write_lock() {
635 return &write_lock_;
637 #endif // defined(USE_NSS)
639 // This method is used to force NSS to be initialized without a DB.
640 // Call this method before NSSInitSingleton() is constructed.
641 static void ForceNoDBInit() {
642 force_nodb_init_ = true;
645 private:
646 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
648 NSSInitSingleton()
649 : tpm_token_enabled_for_nss_(false),
650 initializing_tpm_token_(false),
651 chaps_module_(NULL),
652 root_(NULL) {
653 base::TimeTicks start_time = base::TimeTicks::Now();
655 // It's safe to construct on any thread, since LazyInstance will prevent any
656 // other threads from accessing until the constructor is done.
657 thread_checker_.DetachFromThread();
659 DisableAESNIIfNeeded();
661 EnsureNSPRInit();
663 // We *must* have NSS >= 3.14.3.
664 COMPILE_ASSERT(
665 (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
666 (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
667 (NSS_VMAJOR > 3),
668 nss_version_check_failed);
669 // Also check the run-time NSS version.
670 // NSS_VersionCheck is a >= check, not strict equality.
671 if (!NSS_VersionCheck("3.14.3")) {
672 LOG(FATAL) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
673 "required. Please upgrade to the latest NSS, and if you "
674 "still get this error, contact your distribution "
675 "maintainer.";
678 SECStatus status = SECFailure;
679 bool nodb_init = force_nodb_init_;
681 #if !defined(USE_NSS)
682 // Use the system certificate store, so initialize NSS without database.
683 nodb_init = true;
684 #endif
686 if (nodb_init) {
687 status = NSS_NoDB_Init(NULL);
688 if (status != SECSuccess) {
689 CrashOnNSSInitFailure();
690 return;
692 #if defined(OS_IOS)
693 root_ = InitDefaultRootCerts();
694 #endif // defined(OS_IOS)
695 } else {
696 #if defined(USE_NSS)
697 base::FilePath database_dir = GetInitialConfigDirectory();
698 if (!database_dir.empty()) {
699 // This duplicates the work which should have been done in
700 // EarlySetupForNSSInit. However, this function is idempotent so
701 // there's no harm done.
702 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
704 // Initialize with a persistent database (likely, ~/.pki/nssdb).
705 // Use "sql:" which can be shared by multiple processes safely.
706 std::string nss_config_dir =
707 base::StringPrintf("sql:%s", database_dir.value().c_str());
708 #if defined(OS_CHROMEOS)
709 status = NSS_Init(nss_config_dir.c_str());
710 #else
711 status = NSS_InitReadWrite(nss_config_dir.c_str());
712 #endif
713 if (status != SECSuccess) {
714 LOG(ERROR) << "Error initializing NSS with a persistent "
715 "database (" << nss_config_dir
716 << "): " << GetNSSErrorMessage();
719 if (status != SECSuccess) {
720 VLOG(1) << "Initializing NSS without a persistent database.";
721 status = NSS_NoDB_Init(NULL);
722 if (status != SECSuccess) {
723 CrashOnNSSInitFailure();
724 return;
728 PK11_SetPasswordFunc(PKCS11PasswordFunc);
730 // If we haven't initialized the password for the NSS databases,
731 // initialize an empty-string password so that we don't need to
732 // log in.
733 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
734 if (slot) {
735 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
736 // yet, so we don't need to lock.
737 if (PK11_NeedUserInit(slot))
738 PK11_InitPin(slot, NULL, NULL);
739 PK11_FreeSlot(slot);
742 root_ = InitDefaultRootCerts();
743 #endif // defined(USE_NSS)
746 // Disable MD5 certificate signatures. (They are disabled by default in
747 // NSS 3.14.)
748 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
749 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
750 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
752 // The UMA bit is conditionally set for this histogram in
753 // components/startup_metric_utils.cc .
754 LOCAL_HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
755 base::TimeTicks::Now() - start_time,
756 base::TimeDelta::FromMilliseconds(10),
757 base::TimeDelta::FromHours(1),
758 50);
761 // NOTE(willchan): We don't actually execute this code since we leak NSS to
762 // prevent non-joinable threads from using NSS after it's already been shut
763 // down.
764 ~NSSInitSingleton() {
765 #if defined(OS_CHROMEOS)
766 STLDeleteValues(&chromeos_user_map_);
767 #endif
768 tpm_slot_.reset();
769 if (root_) {
770 SECMOD_UnloadUserModule(root_);
771 SECMOD_DestroyModule(root_);
772 root_ = NULL;
774 if (chaps_module_) {
775 SECMOD_UnloadUserModule(chaps_module_);
776 SECMOD_DestroyModule(chaps_module_);
777 chaps_module_ = NULL;
780 SECStatus status = NSS_Shutdown();
781 if (status != SECSuccess) {
782 // We VLOG(1) because this failure is relatively harmless (leaking, but
783 // we're shutting down anyway).
784 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
788 #if defined(USE_NSS) || defined(OS_IOS)
789 // Load nss's built-in root certs.
790 SECMODModule* InitDefaultRootCerts() {
791 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
792 if (root)
793 return root;
795 // Aw, snap. Can't find/load root cert shared library.
796 // This will make it hard to talk to anybody via https.
797 // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
798 return NULL;
801 // Load the given module for this NSS session.
802 static SECMODModule* LoadModule(const char* name,
803 const char* library_path,
804 const char* params) {
805 std::string modparams = base::StringPrintf(
806 "name=\"%s\" library=\"%s\" %s",
807 name, library_path, params ? params : "");
809 // Shouldn't need to const_cast here, but SECMOD doesn't properly
810 // declare input string arguments as const. Bug
811 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
812 // on NSS codebase to address this.
813 SECMODModule* module = SECMOD_LoadUserModule(
814 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
815 if (!module) {
816 LOG(ERROR) << "Error loading " << name << " module into NSS: "
817 << GetNSSErrorMessage();
818 return NULL;
820 if (!module->loaded) {
821 LOG(ERROR) << "After loading " << name << ", loaded==false: "
822 << GetNSSErrorMessage();
823 SECMOD_DestroyModule(module);
824 return NULL;
826 return module;
828 #endif
830 static void DisableAESNIIfNeeded() {
831 if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
832 // Some versions of NSS have a bug that causes AVX instructions to be
833 // used without testing whether XSAVE is enabled by the operating system.
834 // In order to work around this, we disable AES-NI in NSS when we find
835 // that |has_avx()| is false (which includes the XSAVE test). See
836 // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
837 base::CPU cpu;
839 if (cpu.has_avx_hardware() && !cpu.has_avx()) {
840 base::Environment::Create()->SetVar("NSS_DISABLE_HW_AES", "1");
845 // If this is set to true NSS is forced to be initialized without a DB.
846 static bool force_nodb_init_;
848 bool tpm_token_enabled_for_nss_;
849 bool initializing_tpm_token_;
850 typedef std::vector<base::Closure> TPMReadyCallbackList;
851 TPMReadyCallbackList tpm_ready_callback_list_;
852 SECMODModule* chaps_module_;
853 crypto::ScopedPK11Slot tpm_slot_;
854 SECMODModule* root_;
855 #if defined(OS_CHROMEOS)
856 typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
857 ChromeOSUserMap chromeos_user_map_;
858 ScopedPK11Slot test_system_slot_;
859 #endif
860 #if defined(USE_NSS)
861 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
862 // is fixed, we will no longer need the lock.
863 base::Lock write_lock_;
864 #endif // defined(USE_NSS)
866 base::ThreadChecker thread_checker_;
869 // static
870 bool NSSInitSingleton::force_nodb_init_ = false;
872 base::LazyInstance<NSSInitSingleton>::Leaky
873 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
874 } // namespace
876 #if defined(USE_NSS)
877 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
878 const std::string& description) {
879 const std::string modspec =
880 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
881 path.value().c_str(),
882 description.c_str());
883 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
884 if (db_slot) {
885 if (PK11_NeedUserInit(db_slot))
886 PK11_InitPin(db_slot, NULL, NULL);
887 } else {
888 LOG(ERROR) << "Error opening persistent database (" << modspec
889 << "): " << GetNSSErrorMessage();
891 return ScopedPK11Slot(db_slot);
894 void EarlySetupForNSSInit() {
895 base::FilePath database_dir = GetInitialConfigDirectory();
896 if (!database_dir.empty())
897 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
899 #endif
901 void EnsureNSPRInit() {
902 g_nspr_singleton.Get();
905 void InitNSSSafely() {
906 // We might fork, but we haven't loaded any security modules.
907 DisableNSSForkCheck();
908 // If we're sandboxed, we shouldn't be able to open user security modules,
909 // but it's more correct to tell NSS to not even try.
910 // Loading user security modules would have security implications.
911 ForceNSSNoDBInit();
912 // Initialize NSS.
913 EnsureNSSInit();
916 void EnsureNSSInit() {
917 // Initializing SSL causes us to do blocking IO.
918 // Temporarily allow it until we fix
919 // http://code.google.com/p/chromium/issues/detail?id=59847
920 base::ThreadRestrictions::ScopedAllowIO allow_io;
921 g_nss_singleton.Get();
924 void ForceNSSNoDBInit() {
925 NSSInitSingleton::ForceNoDBInit();
928 void DisableNSSForkCheck() {
929 scoped_ptr<base::Environment> env(base::Environment::Create());
930 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
933 void LoadNSSLibraries() {
934 // Some NSS libraries are linked dynamically so load them here.
935 #if defined(USE_NSS)
936 // Try to search for multiple directories to load the libraries.
937 std::vector<base::FilePath> paths;
939 // Use relative path to Search PATH for the library files.
940 paths.push_back(base::FilePath());
942 // For Debian derivatives NSS libraries are located here.
943 paths.push_back(base::FilePath("/usr/lib/nss"));
945 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
946 #if defined(ARCH_CPU_X86_64)
947 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
948 #elif defined(ARCH_CPU_X86)
949 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
950 #elif defined(ARCH_CPU_ARMEL)
951 #if defined(__ARM_PCS_VFP)
952 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
953 #else
954 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
955 #endif // defined(__ARM_PCS_VFP)
956 #elif defined(ARCH_CPU_MIPSEL)
957 paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
958 #endif // defined(ARCH_CPU_X86_64)
960 // A list of library files to load.
961 std::vector<std::string> libs;
962 libs.push_back("libsoftokn3.so");
963 libs.push_back("libfreebl3.so");
965 // For each combination of library file and path, check for existence and
966 // then load.
967 size_t loaded = 0;
968 for (size_t i = 0; i < libs.size(); ++i) {
969 for (size_t j = 0; j < paths.size(); ++j) {
970 base::FilePath path = paths[j].Append(libs[i]);
971 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
972 if (lib) {
973 ++loaded;
974 break;
979 if (loaded == libs.size()) {
980 VLOG(3) << "NSS libraries loaded.";
981 } else {
982 LOG(ERROR) << "Failed to load NSS libraries.";
984 #endif // defined(USE_NSS)
987 bool CheckNSSVersion(const char* version) {
988 return !!NSS_VersionCheck(version);
991 #if defined(USE_NSS)
992 base::Lock* GetNSSWriteLock() {
993 return g_nss_singleton.Get().write_lock();
996 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
997 // May be NULL if the lock is not needed in our version of NSS.
998 if (lock_)
999 lock_->Acquire();
1002 AutoNSSWriteLock::~AutoNSSWriteLock() {
1003 if (lock_) {
1004 lock_->AssertAcquired();
1005 lock_->Release();
1009 AutoSECMODListReadLock::AutoSECMODListReadLock()
1010 : lock_(SECMOD_GetDefaultModuleListLock()) {
1011 SECMOD_GetReadLock(lock_);
1014 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
1015 SECMOD_ReleaseReadLock(lock_);
1017 #endif // defined(USE_NSS)
1019 #if defined(OS_CHROMEOS)
1020 ScopedPK11Slot GetSystemNSSKeySlot(
1021 const base::Callback<void(ScopedPK11Slot)>& callback) {
1022 return g_nss_singleton.Get().GetSystemNSSKeySlot(callback);
1025 void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
1026 g_nss_singleton.Get().SetSystemKeySlotForTesting(slot.Pass());
1029 void EnableTPMTokenForNSS() {
1030 g_nss_singleton.Get().EnableTPMTokenForNSS();
1033 bool IsTPMTokenEnabledForNSS() {
1034 return g_nss_singleton.Get().IsTPMTokenEnabledForNSS();
1037 bool IsTPMTokenReady(const base::Closure& callback) {
1038 return g_nss_singleton.Get().IsTPMTokenReady(callback);
1041 void InitializeTPMTokenAndSystemSlot(
1042 int token_slot_id,
1043 const base::Callback<void(bool)>& callback) {
1044 g_nss_singleton.Get().InitializeTPMTokenAndSystemSlot(token_slot_id,
1045 callback);
1048 bool InitializeNSSForChromeOSUser(
1049 const std::string& email,
1050 const std::string& username_hash,
1051 const base::FilePath& path) {
1052 return g_nss_singleton.Get().InitializeNSSForChromeOSUser(
1053 email, username_hash, path);
1056 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
1057 return g_nss_singleton.Get().ShouldInitializeTPMForChromeOSUser(
1058 username_hash);
1061 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
1062 g_nss_singleton.Get().WillInitializeTPMForChromeOSUser(username_hash);
1065 void InitializeTPMForChromeOSUser(
1066 const std::string& username_hash,
1067 CK_SLOT_ID slot_id) {
1068 g_nss_singleton.Get().InitializeTPMForChromeOSUser(username_hash, slot_id);
1071 void InitializePrivateSoftwareSlotForChromeOSUser(
1072 const std::string& username_hash) {
1073 g_nss_singleton.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1074 username_hash);
1077 ScopedPK11Slot GetPublicSlotForChromeOSUser(const std::string& username_hash) {
1078 return g_nss_singleton.Get().GetPublicSlotForChromeOSUser(username_hash);
1081 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
1082 const std::string& username_hash,
1083 const base::Callback<void(ScopedPK11Slot)>& callback) {
1084 return g_nss_singleton.Get().GetPrivateSlotForChromeOSUser(username_hash,
1085 callback);
1088 void CloseChromeOSUserForTesting(const std::string& username_hash) {
1089 g_nss_singleton.Get().CloseChromeOSUserForTesting(username_hash);
1091 #endif // defined(OS_CHROMEOS)
1093 base::Time PRTimeToBaseTime(PRTime prtime) {
1094 return base::Time::FromInternalValue(
1095 prtime + base::Time::UnixEpoch().ToInternalValue());
1098 PRTime BaseTimeToPRTime(base::Time time) {
1099 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1102 #if !defined(OS_CHROMEOS)
1103 PK11SlotInfo* GetPersistentNSSKeySlot() {
1104 return g_nss_singleton.Get().GetPersistentNSSKeySlot();
1106 #endif
1108 } // namespace crypto