Remove DEPRECATED extension notification from background_contents_service.*
[chromium-blink-merge.git] / crypto / nss_util.cc
blob6ab07bc8ca47b819222d0a5893eba5df25707eae
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 // This is a LazyInstance so that it will be deleted automatically when the
202 // unittest exits. NSSInitSingleton is a LeakySingleton, so it would not be
203 // deleted if it were a regular member.
204 base::LazyInstance<base::ScopedTempDir> g_test_nss_db_dir =
205 LAZY_INSTANCE_INITIALIZER;
207 // Force a crash with error info on NSS_NoDB_Init failure.
208 void CrashOnNSSInitFailure() {
209 int nss_error = PR_GetError();
210 int os_error = PR_GetOSError();
211 base::debug::Alias(&nss_error);
212 base::debug::Alias(&os_error);
213 LOG(ERROR) << "Error initializing NSS without a persistent database: "
214 << GetNSSErrorMessage();
215 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
218 #if defined(OS_CHROMEOS)
219 class ChromeOSUserData {
220 public:
221 explicit ChromeOSUserData(ScopedPK11Slot public_slot)
222 : public_slot_(public_slot.Pass()),
223 private_slot_initialization_started_(false) {}
224 ~ChromeOSUserData() {
225 if (public_slot_) {
226 SECStatus status = SECMOD_CloseUserDB(public_slot_.get());
227 if (status != SECSuccess)
228 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
232 ScopedPK11Slot GetPublicSlot() {
233 return ScopedPK11Slot(
234 public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL);
237 ScopedPK11Slot GetPrivateSlot(
238 const base::Callback<void(ScopedPK11Slot)>& callback) {
239 if (private_slot_)
240 return ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get()));
241 if (!callback.is_null())
242 tpm_ready_callback_list_.push_back(callback);
243 return ScopedPK11Slot();
246 void SetPrivateSlot(ScopedPK11Slot private_slot) {
247 DCHECK(!private_slot_);
248 private_slot_ = private_slot.Pass();
250 SlotReadyCallbackList callback_list;
251 callback_list.swap(tpm_ready_callback_list_);
252 for (SlotReadyCallbackList::iterator i = callback_list.begin();
253 i != callback_list.end();
254 ++i) {
255 (*i).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get())));
259 bool private_slot_initialization_started() const {
260 return private_slot_initialization_started_;
263 void set_private_slot_initialization_started() {
264 private_slot_initialization_started_ = true;
267 private:
268 ScopedPK11Slot public_slot_;
269 ScopedPK11Slot private_slot_;
271 bool private_slot_initialization_started_;
273 typedef std::vector<base::Callback<void(ScopedPK11Slot)> >
274 SlotReadyCallbackList;
275 SlotReadyCallbackList tpm_ready_callback_list_;
277 #endif // defined(OS_CHROMEOS)
279 class NSSInitSingleton {
280 public:
281 #if defined(OS_CHROMEOS)
282 // Used with PostTaskAndReply to pass handles to worker thread and back.
283 struct TPMModuleAndSlot {
284 explicit TPMModuleAndSlot(SECMODModule* init_chaps_module)
285 : chaps_module(init_chaps_module), tpm_slot(NULL) {}
286 SECMODModule* chaps_module;
287 PK11SlotInfo* tpm_slot;
290 PK11SlotInfo* OpenPersistentNSSDBForPath(const std::string& db_name,
291 const base::FilePath& path) {
292 DCHECK(thread_checker_.CalledOnValidThread());
293 // NSS is allowed to do IO on the current thread since dispatching
294 // to a dedicated thread would still have the affect of blocking
295 // the current thread, due to NSS's internal locking requirements
296 base::ThreadRestrictions::ScopedAllowIO allow_io;
298 base::FilePath nssdb_path = path.AppendASCII(".pki").AppendASCII("nssdb");
299 if (!base::CreateDirectory(nssdb_path)) {
300 LOG(ERROR) << "Failed to create " << nssdb_path.value() << " directory.";
301 return NULL;
303 return OpenUserDB(nssdb_path, db_name);
306 void EnableTPMTokenForNSS() {
307 DCHECK(thread_checker_.CalledOnValidThread());
309 // If this gets set, then we'll use the TPM for certs with
310 // private keys, otherwise we'll fall back to the software
311 // implementation.
312 tpm_token_enabled_for_nss_ = true;
315 bool IsTPMTokenEnabledForNSS() {
316 DCHECK(thread_checker_.CalledOnValidThread());
317 return tpm_token_enabled_for_nss_;
320 void InitializeTPMTokenAndSystemSlot(
321 int system_slot_id,
322 const base::Callback<void(bool)>& callback) {
323 DCHECK(thread_checker_.CalledOnValidThread());
324 // Should not be called while there is already an initialization in
325 // progress.
326 DCHECK(!initializing_tpm_token_);
327 // If EnableTPMTokenForNSS hasn't been called, return false.
328 if (!tpm_token_enabled_for_nss_) {
329 base::MessageLoop::current()->PostTask(FROM_HERE,
330 base::Bind(callback, false));
331 return;
334 // If everything is already initialized, then return true.
335 // Note that only |tpm_slot_| is checked, since |chaps_module_| could be
336 // NULL in tests while |tpm_slot_| has been set to the test DB.
337 if (tpm_slot_) {
338 base::MessageLoop::current()->PostTask(FROM_HERE,
339 base::Bind(callback, true));
340 return;
343 // Note that a reference is not taken to chaps_module_. This is safe since
344 // NSSInitSingleton is Leaky, so the reference it holds is never released.
345 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
346 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
347 if (base::WorkerPool::PostTaskAndReply(
348 FROM_HERE,
349 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
350 system_slot_id,
351 tpm_args_ptr),
352 base::Bind(&NSSInitSingleton::OnInitializedTPMTokenAndSystemSlot,
353 base::Unretained(this), // NSSInitSingleton is leaky
354 callback,
355 base::Passed(&tpm_args)),
356 true /* task_is_slow */
357 )) {
358 initializing_tpm_token_ = true;
359 } else {
360 base::MessageLoop::current()->PostTask(FROM_HERE,
361 base::Bind(callback, false));
365 static void InitializeTPMTokenOnWorkerThread(CK_SLOT_ID token_slot_id,
366 TPMModuleAndSlot* tpm_args) {
367 // This tries to load the Chaps module so NSS can talk to the hardware
368 // TPM.
369 if (!tpm_args->chaps_module) {
370 DVLOG(3) << "Loading chaps...";
371 tpm_args->chaps_module = LoadModule(
372 kChapsModuleName,
373 kChapsPath,
374 // For more details on these parameters, see:
375 // https://developer.mozilla.org/en/PKCS11_Module_Specs
376 // slotFlags=[PublicCerts] -- Certificates and public keys can be
377 // read from this slot without requiring a call to C_Login.
378 // askpw=only -- Only authenticate to the token when necessary.
379 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
381 if (tpm_args->chaps_module) {
382 tpm_args->tpm_slot =
383 GetTPMSlotForIdOnWorkerThread(tpm_args->chaps_module, token_slot_id);
387 void OnInitializedTPMTokenAndSystemSlot(
388 const base::Callback<void(bool)>& callback,
389 scoped_ptr<TPMModuleAndSlot> tpm_args) {
390 DCHECK(thread_checker_.CalledOnValidThread());
391 DVLOG(2) << "Loaded chaps: " << !!tpm_args->chaps_module
392 << ", got tpm slot: " << !!tpm_args->tpm_slot;
394 chaps_module_ = tpm_args->chaps_module;
395 tpm_slot_ = tpm_args->tpm_slot;
396 if (!chaps_module_ && test_slot_) {
397 // chromeos_unittests try to test the TPM initialization process. If we
398 // have a test DB open, pretend that it is the TPM slot.
399 tpm_slot_ = PK11_ReferenceSlot(test_slot_);
401 initializing_tpm_token_ = false;
403 if (tpm_slot_) {
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 callback.Run(!!tpm_slot_);
416 bool IsTPMTokenReady(const base::Closure& callback) {
417 if (!callback.is_null()) {
418 // Cannot DCHECK in the general case yet, but since the callback is
419 // a new addition to the API, DCHECK to make sure at least the new uses
420 // don't regress.
421 DCHECK(thread_checker_.CalledOnValidThread());
422 } else if (!thread_checker_.CalledOnValidThread()) {
423 // TODO(mattm): Change to DCHECK when callers have been fixed.
424 DVLOG(1) << "Called on wrong thread.\n"
425 << base::debug::StackTrace().ToString();
428 if (tpm_slot_ != NULL)
429 return true;
431 if (!callback.is_null())
432 tpm_ready_callback_list_.push_back(callback);
434 return false;
437 // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
438 // id as an int. This should be safe since this is only used with chaps, which
439 // we also control.
440 static PK11SlotInfo* GetTPMSlotForIdOnWorkerThread(SECMODModule* chaps_module,
441 CK_SLOT_ID slot_id) {
442 DCHECK(chaps_module);
444 DVLOG(3) << "Poking chaps module.";
445 SECStatus rv = SECMOD_UpdateSlotList(chaps_module);
446 if (rv != SECSuccess)
447 PLOG(ERROR) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
449 PK11SlotInfo* slot = SECMOD_LookupSlot(chaps_module->moduleID, slot_id);
450 if (!slot)
451 LOG(ERROR) << "TPM slot " << slot_id << " not found.";
452 return slot;
455 bool InitializeNSSForChromeOSUser(
456 const std::string& email,
457 const std::string& username_hash,
458 const base::FilePath& path) {
459 DCHECK(thread_checker_.CalledOnValidThread());
460 if (chromeos_user_map_.find(username_hash) != chromeos_user_map_.end()) {
461 // This user already exists in our mapping.
462 DVLOG(2) << username_hash << " already initialized.";
463 return false;
466 // If test slot is set, slot getter methods will short circuit
467 // checking |chromeos_user_map_|, so there is nothing left to be
468 // initialized.
469 if (test_slot_)
470 return false;
472 DVLOG(2) << "Opening NSS DB " << path.value();
473 std::string db_name = base::StringPrintf(
474 "%s %s", kUserNSSDatabaseName, username_hash.c_str());
475 ScopedPK11Slot public_slot(OpenPersistentNSSDBForPath(db_name, path));
476 chromeos_user_map_[username_hash] =
477 new ChromeOSUserData(public_slot.Pass());
478 return true;
481 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
482 DCHECK(thread_checker_.CalledOnValidThread());
483 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
485 return !chromeos_user_map_[username_hash]
486 ->private_slot_initialization_started();
489 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
490 DCHECK(thread_checker_.CalledOnValidThread());
491 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
493 chromeos_user_map_[username_hash]
494 ->set_private_slot_initialization_started();
497 void InitializeTPMForChromeOSUser(const std::string& username_hash,
498 CK_SLOT_ID slot_id) {
499 DCHECK(thread_checker_.CalledOnValidThread());
500 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
501 DCHECK(chromeos_user_map_[username_hash]->
502 private_slot_initialization_started());
504 if (!chaps_module_)
505 return;
507 // Note that a reference is not taken to chaps_module_. This is safe since
508 // NSSInitSingleton is Leaky, so the reference it holds is never released.
509 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
510 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
511 base::WorkerPool::PostTaskAndReply(
512 FROM_HERE,
513 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
514 slot_id,
515 tpm_args_ptr),
516 base::Bind(&NSSInitSingleton::OnInitializedTPMForChromeOSUser,
517 base::Unretained(this), // NSSInitSingleton is leaky
518 username_hash,
519 base::Passed(&tpm_args)),
520 true /* task_is_slow */
524 void OnInitializedTPMForChromeOSUser(const std::string& username_hash,
525 scoped_ptr<TPMModuleAndSlot> tpm_args) {
526 DCHECK(thread_checker_.CalledOnValidThread());
527 DVLOG(2) << "Got tpm slot for " << username_hash << " "
528 << !!tpm_args->tpm_slot;
529 chromeos_user_map_[username_hash]->SetPrivateSlot(
530 ScopedPK11Slot(tpm_args->tpm_slot));
533 void InitializePrivateSoftwareSlotForChromeOSUser(
534 const std::string& username_hash) {
535 DCHECK(thread_checker_.CalledOnValidThread());
536 VLOG(1) << "using software private slot for " << username_hash;
537 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
538 DCHECK(chromeos_user_map_[username_hash]->
539 private_slot_initialization_started());
541 chromeos_user_map_[username_hash]->SetPrivateSlot(
542 chromeos_user_map_[username_hash]->GetPublicSlot());
545 ScopedPK11Slot GetPublicSlotForChromeOSUser(
546 const std::string& username_hash) {
547 DCHECK(thread_checker_.CalledOnValidThread());
549 if (username_hash.empty()) {
550 DVLOG(2) << "empty username_hash";
551 return ScopedPK11Slot();
554 if (test_slot_) {
555 DVLOG(2) << "returning test_slot_ for " << username_hash;
556 return ScopedPK11Slot(PK11_ReferenceSlot(test_slot_));
559 if (chromeos_user_map_.find(username_hash) == chromeos_user_map_.end()) {
560 LOG(ERROR) << username_hash << " not initialized.";
561 return ScopedPK11Slot();
563 return chromeos_user_map_[username_hash]->GetPublicSlot();
566 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
567 const std::string& username_hash,
568 const base::Callback<void(ScopedPK11Slot)>& callback) {
569 DCHECK(thread_checker_.CalledOnValidThread());
571 if (username_hash.empty()) {
572 DVLOG(2) << "empty username_hash";
573 if (!callback.is_null()) {
574 base::MessageLoop::current()->PostTask(
575 FROM_HERE, base::Bind(callback, base::Passed(ScopedPK11Slot())));
577 return ScopedPK11Slot();
580 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
582 if (test_slot_) {
583 DVLOG(2) << "returning test_slot_ for " << username_hash;
584 return ScopedPK11Slot(PK11_ReferenceSlot(test_slot_));
587 return chromeos_user_map_[username_hash]->GetPrivateSlot(callback);
590 void CloseTestChromeOSUser(const std::string& username_hash) {
591 DCHECK(thread_checker_.CalledOnValidThread());
592 ChromeOSUserMap::iterator i = chromeos_user_map_.find(username_hash);
593 DCHECK(i != chromeos_user_map_.end());
594 delete i->second;
595 chromeos_user_map_.erase(i);
597 #endif // defined(OS_CHROMEOS)
600 bool OpenTestNSSDB() {
601 DCHECK(thread_checker_.CalledOnValidThread());
602 // NSS is allowed to do IO on the current thread since dispatching
603 // to a dedicated thread would still have the affect of blocking
604 // the current thread, due to NSS's internal locking requirements
605 base::ThreadRestrictions::ScopedAllowIO allow_io;
607 if (test_slot_)
608 return true;
609 if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
610 return false;
611 test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), kTestTPMTokenName);
612 return !!test_slot_;
615 void CloseTestNSSDB() {
616 DCHECK(thread_checker_.CalledOnValidThread());
617 // NSS is allowed to do IO on the current thread since dispatching
618 // to a dedicated thread would still have the affect of blocking
619 // the current thread, due to NSS's internal locking requirements
620 base::ThreadRestrictions::ScopedAllowIO allow_io;
622 if (!test_slot_)
623 return;
624 SECStatus status = SECMOD_CloseUserDB(test_slot_);
625 if (status != SECSuccess)
626 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
627 PK11_FreeSlot(test_slot_);
628 test_slot_ = NULL;
629 ignore_result(g_test_nss_db_dir.Get().Delete());
632 PK11SlotInfo* GetPersistentNSSKeySlot() {
633 // TODO(mattm): Change to DCHECK when callers have been fixed.
634 if (!thread_checker_.CalledOnValidThread()) {
635 DVLOG(1) << "Called on wrong thread.\n"
636 << base::debug::StackTrace().ToString();
639 if (test_slot_)
640 return PK11_ReferenceSlot(test_slot_);
641 return PK11_GetInternalKeySlot();
644 #if defined(OS_CHROMEOS)
645 PK11SlotInfo* GetSystemNSSKeySlot() {
646 DCHECK(thread_checker_.CalledOnValidThread());
648 if (test_slot_)
649 return PK11_ReferenceSlot(test_slot_);
651 // TODO(mattm): chromeos::TPMTokenloader always calls
652 // InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is
653 // disabled, tpm_slot_ will be the first user's slot instead. Can that be
654 // detected and return NULL instead?
655 if (tpm_token_enabled_for_nss_ && IsTPMTokenReady(base::Closure()))
656 return PK11_ReferenceSlot(tpm_slot_);
657 // If we were supposed to get the hardware token, but were
658 // unable to, return NULL rather than fall back to sofware.
659 return NULL;
661 #endif
663 #if defined(USE_NSS)
664 base::Lock* write_lock() {
665 return &write_lock_;
667 #endif // defined(USE_NSS)
669 // This method is used to force NSS to be initialized without a DB.
670 // Call this method before NSSInitSingleton() is constructed.
671 static void ForceNoDBInit() {
672 force_nodb_init_ = true;
675 private:
676 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
678 NSSInitSingleton()
679 : tpm_token_enabled_for_nss_(false),
680 initializing_tpm_token_(false),
681 chaps_module_(NULL),
682 test_slot_(NULL),
683 tpm_slot_(NULL),
684 root_(NULL) {
685 base::TimeTicks start_time = base::TimeTicks::Now();
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 COMPILE_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)
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)
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)
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);
784 // The UMA bit is conditionally set for this histogram in
785 // chrome/common/startup_metric_utils.cc .
786 HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
787 base::TimeTicks::Now() - start_time,
788 base::TimeDelta::FromMilliseconds(10),
789 base::TimeDelta::FromHours(1),
790 50);
793 // NOTE(willchan): We don't actually execute this code since we leak NSS to
794 // prevent non-joinable threads from using NSS after it's already been shut
795 // down.
796 ~NSSInitSingleton() {
797 #if defined(OS_CHROMEOS)
798 STLDeleteValues(&chromeos_user_map_);
799 #endif
800 if (tpm_slot_) {
801 PK11_FreeSlot(tpm_slot_);
802 tpm_slot_ = NULL;
804 CloseTestNSSDB();
805 if (root_) {
806 SECMOD_UnloadUserModule(root_);
807 SECMOD_DestroyModule(root_);
808 root_ = NULL;
810 if (chaps_module_) {
811 SECMOD_UnloadUserModule(chaps_module_);
812 SECMOD_DestroyModule(chaps_module_);
813 chaps_module_ = NULL;
816 SECStatus status = NSS_Shutdown();
817 if (status != SECSuccess) {
818 // We VLOG(1) because this failure is relatively harmless (leaking, but
819 // we're shutting down anyway).
820 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
824 #if defined(USE_NSS) || defined(OS_IOS)
825 // Load nss's built-in root certs.
826 SECMODModule* InitDefaultRootCerts() {
827 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
828 if (root)
829 return root;
831 // Aw, snap. Can't find/load root cert shared library.
832 // This will make it hard to talk to anybody via https.
833 // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
834 return NULL;
837 // Load the given module for this NSS session.
838 static SECMODModule* LoadModule(const char* name,
839 const char* library_path,
840 const char* params) {
841 std::string modparams = base::StringPrintf(
842 "name=\"%s\" library=\"%s\" %s",
843 name, library_path, params ? params : "");
845 // Shouldn't need to const_cast here, but SECMOD doesn't properly
846 // declare input string arguments as const. Bug
847 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
848 // on NSS codebase to address this.
849 SECMODModule* module = SECMOD_LoadUserModule(
850 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
851 if (!module) {
852 LOG(ERROR) << "Error loading " << name << " module into NSS: "
853 << GetNSSErrorMessage();
854 return NULL;
856 if (!module->loaded) {
857 LOG(ERROR) << "After loading " << name << ", loaded==false: "
858 << GetNSSErrorMessage();
859 SECMOD_DestroyModule(module);
860 return NULL;
862 return module;
864 #endif
866 static PK11SlotInfo* OpenUserDB(const base::FilePath& path,
867 const std::string& description) {
868 const std::string modspec =
869 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
870 path.value().c_str(),
871 description.c_str());
872 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
873 if (db_slot) {
874 if (PK11_NeedUserInit(db_slot))
875 PK11_InitPin(db_slot, NULL, NULL);
876 } else {
877 LOG(ERROR) << "Error opening persistent database (" << modspec
878 << "): " << GetNSSErrorMessage();
880 return db_slot;
883 static void DisableAESNIIfNeeded() {
884 if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
885 // Some versions of NSS have a bug that causes AVX instructions to be
886 // used without testing whether XSAVE is enabled by the operating system.
887 // In order to work around this, we disable AES-NI in NSS when we find
888 // that |has_avx()| is false (which includes the XSAVE test). See
889 // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
890 base::CPU cpu;
892 if (cpu.has_avx_hardware() && !cpu.has_avx()) {
893 base::Environment::Create()->SetVar("NSS_DISABLE_HW_AES", "1");
898 // If this is set to true NSS is forced to be initialized without a DB.
899 static bool force_nodb_init_;
901 bool tpm_token_enabled_for_nss_;
902 bool initializing_tpm_token_;
903 typedef std::vector<base::Closure> TPMReadyCallbackList;
904 TPMReadyCallbackList tpm_ready_callback_list_;
905 SECMODModule* chaps_module_;
906 PK11SlotInfo* test_slot_;
907 PK11SlotInfo* tpm_slot_;
908 SECMODModule* root_;
909 #if defined(OS_CHROMEOS)
910 typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
911 ChromeOSUserMap chromeos_user_map_;
912 #endif
913 #if defined(USE_NSS)
914 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
915 // is fixed, we will no longer need the lock.
916 base::Lock write_lock_;
917 #endif // defined(USE_NSS)
919 base::ThreadChecker thread_checker_;
922 // static
923 bool NSSInitSingleton::force_nodb_init_ = false;
925 base::LazyInstance<NSSInitSingleton>::Leaky
926 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
927 } // namespace
929 const char kTestTPMTokenName[] = "Test DB";
931 #if defined(USE_NSS)
932 void EarlySetupForNSSInit() {
933 base::FilePath database_dir = GetInitialConfigDirectory();
934 if (!database_dir.empty())
935 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
937 #endif
939 void EnsureNSPRInit() {
940 g_nspr_singleton.Get();
943 void InitNSSSafely() {
944 // We might fork, but we haven't loaded any security modules.
945 DisableNSSForkCheck();
946 // If we're sandboxed, we shouldn't be able to open user security modules,
947 // but it's more correct to tell NSS to not even try.
948 // Loading user security modules would have security implications.
949 ForceNSSNoDBInit();
950 // Initialize NSS.
951 EnsureNSSInit();
954 void EnsureNSSInit() {
955 // Initializing SSL causes us to do blocking IO.
956 // Temporarily allow it until we fix
957 // http://code.google.com/p/chromium/issues/detail?id=59847
958 base::ThreadRestrictions::ScopedAllowIO allow_io;
959 g_nss_singleton.Get();
962 void ForceNSSNoDBInit() {
963 NSSInitSingleton::ForceNoDBInit();
966 void DisableNSSForkCheck() {
967 scoped_ptr<base::Environment> env(base::Environment::Create());
968 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
971 void LoadNSSLibraries() {
972 // Some NSS libraries are linked dynamically so load them here.
973 #if defined(USE_NSS)
974 // Try to search for multiple directories to load the libraries.
975 std::vector<base::FilePath> paths;
977 // Use relative path to Search PATH for the library files.
978 paths.push_back(base::FilePath());
980 // For Debian derivatives NSS libraries are located here.
981 paths.push_back(base::FilePath("/usr/lib/nss"));
983 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
984 #if defined(ARCH_CPU_X86_64)
985 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
986 #elif defined(ARCH_CPU_X86)
987 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
988 #elif defined(ARCH_CPU_ARMEL)
989 #if defined(__ARM_PCS_VFP)
990 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
991 #else
992 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
993 #endif // defined(__ARM_PCS_VFP)
994 #elif defined(ARCH_CPU_MIPSEL)
995 paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
996 #endif // defined(ARCH_CPU_X86_64)
998 // A list of library files to load.
999 std::vector<std::string> libs;
1000 libs.push_back("libsoftokn3.so");
1001 libs.push_back("libfreebl3.so");
1003 // For each combination of library file and path, check for existence and
1004 // then load.
1005 size_t loaded = 0;
1006 for (size_t i = 0; i < libs.size(); ++i) {
1007 for (size_t j = 0; j < paths.size(); ++j) {
1008 base::FilePath path = paths[j].Append(libs[i]);
1009 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
1010 if (lib) {
1011 ++loaded;
1012 break;
1017 if (loaded == libs.size()) {
1018 VLOG(3) << "NSS libraries loaded.";
1019 } else {
1020 LOG(ERROR) << "Failed to load NSS libraries.";
1022 #endif // defined(USE_NSS)
1025 bool CheckNSSVersion(const char* version) {
1026 return !!NSS_VersionCheck(version);
1029 #if defined(USE_NSS)
1030 ScopedTestNSSDB::ScopedTestNSSDB()
1031 : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
1034 ScopedTestNSSDB::~ScopedTestNSSDB() {
1035 // Don't close when NSS is < 3.15.1, because it would require an additional
1036 // sleep for 1 second after closing the database, due to
1037 // http://bugzil.la/875601.
1038 if (NSS_VersionCheck("3.15.1")) {
1039 g_nss_singleton.Get().CloseTestNSSDB();
1043 base::Lock* GetNSSWriteLock() {
1044 return g_nss_singleton.Get().write_lock();
1047 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
1048 // May be NULL if the lock is not needed in our version of NSS.
1049 if (lock_)
1050 lock_->Acquire();
1053 AutoNSSWriteLock::~AutoNSSWriteLock() {
1054 if (lock_) {
1055 lock_->AssertAcquired();
1056 lock_->Release();
1060 AutoSECMODListReadLock::AutoSECMODListReadLock()
1061 : lock_(SECMOD_GetDefaultModuleListLock()) {
1062 SECMOD_GetReadLock(lock_);
1065 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
1066 SECMOD_ReleaseReadLock(lock_);
1069 #endif // defined(USE_NSS)
1071 #if defined(OS_CHROMEOS)
1072 PK11SlotInfo* GetSystemNSSKeySlot() {
1073 return g_nss_singleton.Get().GetSystemNSSKeySlot();
1076 void EnableTPMTokenForNSS() {
1077 g_nss_singleton.Get().EnableTPMTokenForNSS();
1080 bool IsTPMTokenEnabledForNSS() {
1081 return g_nss_singleton.Get().IsTPMTokenEnabledForNSS();
1084 bool IsTPMTokenReady(const base::Closure& callback) {
1085 return g_nss_singleton.Get().IsTPMTokenReady(callback);
1088 void InitializeTPMTokenAndSystemSlot(
1089 int token_slot_id,
1090 const base::Callback<void(bool)>& callback) {
1091 g_nss_singleton.Get().InitializeTPMTokenAndSystemSlot(token_slot_id,
1092 callback);
1095 ScopedTestNSSChromeOSUser::ScopedTestNSSChromeOSUser(
1096 const std::string& username_hash)
1097 : username_hash_(username_hash), constructed_successfully_(false) {
1098 if (!temp_dir_.CreateUniqueTempDir())
1099 return;
1100 constructed_successfully_ =
1101 InitializeNSSForChromeOSUser(username_hash,
1102 username_hash,
1103 temp_dir_.path());
1106 ScopedTestNSSChromeOSUser::~ScopedTestNSSChromeOSUser() {
1107 if (constructed_successfully_)
1108 g_nss_singleton.Get().CloseTestChromeOSUser(username_hash_);
1111 void ScopedTestNSSChromeOSUser::FinishInit() {
1112 DCHECK(constructed_successfully_);
1113 if (!ShouldInitializeTPMForChromeOSUser(username_hash_))
1114 return;
1115 WillInitializeTPMForChromeOSUser(username_hash_);
1116 InitializePrivateSoftwareSlotForChromeOSUser(username_hash_);
1119 bool InitializeNSSForChromeOSUser(
1120 const std::string& email,
1121 const std::string& username_hash,
1122 const base::FilePath& path) {
1123 return g_nss_singleton.Get().InitializeNSSForChromeOSUser(
1124 email, username_hash, path);
1127 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
1128 return g_nss_singleton.Get().ShouldInitializeTPMForChromeOSUser(
1129 username_hash);
1132 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
1133 g_nss_singleton.Get().WillInitializeTPMForChromeOSUser(username_hash);
1136 void InitializeTPMForChromeOSUser(
1137 const std::string& username_hash,
1138 CK_SLOT_ID slot_id) {
1139 g_nss_singleton.Get().InitializeTPMForChromeOSUser(username_hash, slot_id);
1141 void InitializePrivateSoftwareSlotForChromeOSUser(
1142 const std::string& username_hash) {
1143 g_nss_singleton.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1144 username_hash);
1146 ScopedPK11Slot GetPublicSlotForChromeOSUser(const std::string& username_hash) {
1147 return g_nss_singleton.Get().GetPublicSlotForChromeOSUser(username_hash);
1149 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
1150 const std::string& username_hash,
1151 const base::Callback<void(ScopedPK11Slot)>& callback) {
1152 return g_nss_singleton.Get().GetPrivateSlotForChromeOSUser(username_hash,
1153 callback);
1155 #endif // defined(OS_CHROMEOS)
1157 base::Time PRTimeToBaseTime(PRTime prtime) {
1158 return base::Time::FromInternalValue(
1159 prtime + base::Time::UnixEpoch().ToInternalValue());
1162 PRTime BaseTimeToPRTime(base::Time time) {
1163 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1166 PK11SlotInfo* GetPersistentNSSKeySlot() {
1167 return g_nss_singleton.Get().GetPersistentNSSKeySlot();
1170 } // namespace crypto