Revert of [MemSheriff] Suppress use-after-free in content::RenderFrameImpl::~RenderFr...
[chromium-blink-merge.git] / crypto / nss_util.cc
blobcd7bd448d934483a3ec2febdb9a1c4e2f2351c53
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/files/file_path.h"
31 #include "base/files/file_util.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_CERTS means NSS is used for certificates and platform integration.
47 // This requires additional support to manage the platform certificate and key
48 // stores.
49 #if defined(USE_NSS_CERTS)
50 #include "base/synchronization/lock.h"
51 #include "crypto/nss_crypto_module_delegate.h"
52 #endif // defined(USE_NSS_CERTS)
54 namespace crypto {
56 namespace {
58 #if defined(OS_CHROMEOS)
59 const char kUserNSSDatabaseName[] = "UserNSSDB";
61 // Constants for loading the Chrome OS TPM-backed PKCS #11 library.
62 const char kChapsModuleName[] = "Chaps";
63 const char kChapsPath[] = "libchaps.so";
65 // Fake certificate authority database used for testing.
66 static const base::FilePath::CharType kReadOnlyCertDB[] =
67 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
68 #endif // defined(OS_CHROMEOS)
70 std::string GetNSSErrorMessage() {
71 std::string result;
72 if (PR_GetErrorTextLength()) {
73 scoped_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
74 PRInt32 copied = PR_GetErrorText(error_text.get());
75 result = std::string(error_text.get(), copied);
76 } else {
77 result = base::StringPrintf("NSS error code: %d", PR_GetError());
79 return result;
82 #if defined(USE_NSS_CERTS)
83 #if !defined(OS_CHROMEOS)
84 base::FilePath GetDefaultConfigDirectory() {
85 base::FilePath dir;
86 PathService::Get(base::DIR_HOME, &dir);
87 if (dir.empty()) {
88 LOG(ERROR) << "Failed to get home directory.";
89 return dir;
91 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
92 if (!base::CreateDirectory(dir)) {
93 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
94 dir.clear();
96 DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
97 return dir;
99 #endif // !defined(IS_CHROMEOS)
101 // On non-Chrome OS platforms, return the default config directory. On Chrome OS
102 // test images, return a read-only directory with fake root CA certs (which are
103 // used by the local Google Accounts server mock we use when testing our login
104 // code). On Chrome OS non-test images (where the read-only directory doesn't
105 // exist), return an empty path.
106 base::FilePath GetInitialConfigDirectory() {
107 #if defined(OS_CHROMEOS)
108 base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
109 if (!base::PathExists(database_dir))
110 database_dir.clear();
111 return database_dir;
112 #else
113 return GetDefaultConfigDirectory();
114 #endif // defined(OS_CHROMEOS)
117 // This callback for NSS forwards all requests to a caller-specified
118 // CryptoModuleBlockingPasswordDelegate object.
119 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
120 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
121 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
122 if (delegate) {
123 bool cancelled = false;
124 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
125 retry != PR_FALSE,
126 &cancelled);
127 if (cancelled)
128 return NULL;
129 char* result = PORT_Strdup(password.c_str());
130 password.replace(0, password.size(), password.size(), 0);
131 return result;
133 DLOG(ERROR) << "PK11 password requested with NULL arg";
134 return NULL;
137 // NSS creates a local cache of the sqlite database if it detects that the
138 // filesystem the database is on is much slower than the local disk. The
139 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
140 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
141 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
142 // detection when database_dir is on NFS. See http://crbug.com/48585.
144 // TODO(wtc): port this function to other USE_NSS_CERTS platforms. It is
145 // defined only for OS_LINUX and OS_OPENBSD simply because the statfs structure
146 // is OS-specific.
148 // Because this function sets an environment variable it must be run before we
149 // go multi-threaded.
150 void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) {
151 bool db_on_nfs = false;
152 #if defined(OS_LINUX)
153 base::FileSystemType fs_type = base::FILE_SYSTEM_UNKNOWN;
154 if (base::GetFileSystemType(database_dir, &fs_type))
155 db_on_nfs = (fs_type == base::FILE_SYSTEM_NFS);
156 #elif defined(OS_OPENBSD)
157 struct statfs buf;
158 if (statfs(database_dir.value().c_str(), &buf) == 0)
159 db_on_nfs = (strcmp(buf.f_fstypename, MOUNT_NFS) == 0);
160 #else
161 NOTIMPLEMENTED();
162 #endif
164 if (db_on_nfs) {
165 scoped_ptr<base::Environment> env(base::Environment::Create());
166 static const char kUseCacheEnvVar[] = "NSS_SDB_USE_CACHE";
167 if (!env->HasVar(kUseCacheEnvVar))
168 env->SetVar(kUseCacheEnvVar, "yes");
172 #endif // defined(USE_NSS_CERTS)
174 // A singleton to initialize/deinitialize NSPR.
175 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
176 // Now that we're leaking the singleton, we could merge back with the NSS
177 // singleton.
178 class NSPRInitSingleton {
179 private:
180 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
182 NSPRInitSingleton() {
183 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
186 // NOTE(willchan): We don't actually execute this code since we leak NSS to
187 // prevent non-joinable threads from using NSS after it's already been shut
188 // down.
189 ~NSPRInitSingleton() {
190 PL_ArenaFinish();
191 PRStatus prstatus = PR_Cleanup();
192 if (prstatus != PR_SUCCESS)
193 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
197 base::LazyInstance<NSPRInitSingleton>::Leaky
198 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
200 // Force a crash with error info on NSS_NoDB_Init failure.
201 void CrashOnNSSInitFailure() {
202 int nss_error = PR_GetError();
203 int os_error = PR_GetOSError();
204 base::debug::Alias(&nss_error);
205 base::debug::Alias(&os_error);
206 LOG(ERROR) << "Error initializing NSS without a persistent database: "
207 << GetNSSErrorMessage();
208 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
211 #if defined(OS_CHROMEOS)
212 class ChromeOSUserData {
213 public:
214 explicit ChromeOSUserData(ScopedPK11Slot public_slot)
215 : public_slot_(public_slot.Pass()),
216 private_slot_initialization_started_(false) {}
217 ~ChromeOSUserData() {
218 if (public_slot_) {
219 SECStatus status = SECMOD_CloseUserDB(public_slot_.get());
220 if (status != SECSuccess)
221 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
225 ScopedPK11Slot GetPublicSlot() {
226 return ScopedPK11Slot(
227 public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL);
230 ScopedPK11Slot GetPrivateSlot(
231 const base::Callback<void(ScopedPK11Slot)>& callback) {
232 if (private_slot_)
233 return ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get()));
234 if (!callback.is_null())
235 tpm_ready_callback_list_.push_back(callback);
236 return ScopedPK11Slot();
239 void SetPrivateSlot(ScopedPK11Slot private_slot) {
240 DCHECK(!private_slot_);
241 private_slot_ = private_slot.Pass();
243 SlotReadyCallbackList callback_list;
244 callback_list.swap(tpm_ready_callback_list_);
245 for (SlotReadyCallbackList::iterator i = callback_list.begin();
246 i != callback_list.end();
247 ++i) {
248 (*i).Run(ScopedPK11Slot(PK11_ReferenceSlot(private_slot_.get())));
252 bool private_slot_initialization_started() const {
253 return private_slot_initialization_started_;
256 void set_private_slot_initialization_started() {
257 private_slot_initialization_started_ = true;
260 private:
261 ScopedPK11Slot public_slot_;
262 ScopedPK11Slot private_slot_;
264 bool private_slot_initialization_started_;
266 typedef std::vector<base::Callback<void(ScopedPK11Slot)> >
267 SlotReadyCallbackList;
268 SlotReadyCallbackList tpm_ready_callback_list_;
270 #endif // defined(OS_CHROMEOS)
272 class NSSInitSingleton {
273 public:
274 #if defined(OS_CHROMEOS)
275 // Used with PostTaskAndReply to pass handles to worker thread and back.
276 struct TPMModuleAndSlot {
277 explicit TPMModuleAndSlot(SECMODModule* init_chaps_module)
278 : chaps_module(init_chaps_module) {}
279 SECMODModule* chaps_module;
280 crypto::ScopedPK11Slot tpm_slot;
283 ScopedPK11Slot OpenPersistentNSSDBForPath(const std::string& db_name,
284 const base::FilePath& path) {
285 DCHECK(thread_checker_.CalledOnValidThread());
286 // NSS is allowed to do IO on the current thread since dispatching
287 // to a dedicated thread would still have the affect of blocking
288 // the current thread, due to NSS's internal locking requirements
289 base::ThreadRestrictions::ScopedAllowIO allow_io;
291 base::FilePath nssdb_path = path.AppendASCII(".pki").AppendASCII("nssdb");
292 if (!base::CreateDirectory(nssdb_path)) {
293 LOG(ERROR) << "Failed to create " << nssdb_path.value() << " directory.";
294 return ScopedPK11Slot();
296 return OpenSoftwareNSSDB(nssdb_path, db_name);
299 void EnableTPMTokenForNSS() {
300 DCHECK(thread_checker_.CalledOnValidThread());
302 // If this gets set, then we'll use the TPM for certs with
303 // private keys, otherwise we'll fall back to the software
304 // implementation.
305 tpm_token_enabled_for_nss_ = true;
308 bool IsTPMTokenEnabledForNSS() {
309 DCHECK(thread_checker_.CalledOnValidThread());
310 return tpm_token_enabled_for_nss_;
313 void InitializeTPMTokenAndSystemSlot(
314 int system_slot_id,
315 const base::Callback<void(bool)>& callback) {
316 DCHECK(thread_checker_.CalledOnValidThread());
317 // Should not be called while there is already an initialization in
318 // progress.
319 DCHECK(!initializing_tpm_token_);
320 // If EnableTPMTokenForNSS hasn't been called, return false.
321 if (!tpm_token_enabled_for_nss_) {
322 base::MessageLoop::current()->PostTask(FROM_HERE,
323 base::Bind(callback, false));
324 return;
327 // If everything is already initialized, then return true.
328 // Note that only |tpm_slot_| is checked, since |chaps_module_| could be
329 // NULL in tests while |tpm_slot_| has been set to the test DB.
330 if (tpm_slot_) {
331 base::MessageLoop::current()->PostTask(FROM_HERE,
332 base::Bind(callback, true));
333 return;
336 // Note that a reference is not taken to chaps_module_. This is safe since
337 // NSSInitSingleton is Leaky, so the reference it holds is never released.
338 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
339 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
340 if (base::WorkerPool::PostTaskAndReply(
341 FROM_HERE,
342 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
343 system_slot_id,
344 tpm_args_ptr),
345 base::Bind(&NSSInitSingleton::OnInitializedTPMTokenAndSystemSlot,
346 base::Unretained(this), // NSSInitSingleton is leaky
347 callback,
348 base::Passed(&tpm_args)),
349 true /* task_is_slow */
350 )) {
351 initializing_tpm_token_ = true;
352 } else {
353 base::MessageLoop::current()->PostTask(FROM_HERE,
354 base::Bind(callback, false));
358 static void InitializeTPMTokenOnWorkerThread(CK_SLOT_ID token_slot_id,
359 TPMModuleAndSlot* tpm_args) {
360 // This tries to load the Chaps module so NSS can talk to the hardware
361 // TPM.
362 if (!tpm_args->chaps_module) {
363 DVLOG(3) << "Loading chaps...";
364 tpm_args->chaps_module = LoadModule(
365 kChapsModuleName,
366 kChapsPath,
367 // For more details on these parameters, see:
368 // https://developer.mozilla.org/en/PKCS11_Module_Specs
369 // slotFlags=[PublicCerts] -- Certificates and public keys can be
370 // read from this slot without requiring a call to C_Login.
371 // askpw=only -- Only authenticate to the token when necessary.
372 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
374 if (tpm_args->chaps_module) {
375 tpm_args->tpm_slot =
376 GetTPMSlotForIdOnWorkerThread(tpm_args->chaps_module, token_slot_id);
380 void OnInitializedTPMTokenAndSystemSlot(
381 const base::Callback<void(bool)>& callback,
382 scoped_ptr<TPMModuleAndSlot> tpm_args) {
383 DCHECK(thread_checker_.CalledOnValidThread());
384 DVLOG(2) << "Loaded chaps: " << !!tpm_args->chaps_module
385 << ", got tpm slot: " << !!tpm_args->tpm_slot;
387 chaps_module_ = tpm_args->chaps_module;
388 tpm_slot_ = tpm_args->tpm_slot.Pass();
389 if (!chaps_module_ && test_system_slot_) {
390 // chromeos_unittests try to test the TPM initialization process. If we
391 // have a test DB open, pretend that it is the TPM slot.
392 tpm_slot_.reset(PK11_ReferenceSlot(test_system_slot_.get()));
394 initializing_tpm_token_ = false;
396 if (tpm_slot_)
397 RunAndClearTPMReadyCallbackList();
399 callback.Run(!!tpm_slot_);
402 void RunAndClearTPMReadyCallbackList() {
403 TPMReadyCallbackList callback_list;
404 callback_list.swap(tpm_ready_callback_list_);
405 for (TPMReadyCallbackList::iterator i = callback_list.begin();
406 i != callback_list.end();
407 ++i) {
408 i->Run();
412 bool IsTPMTokenReady(const base::Closure& callback) {
413 if (!callback.is_null()) {
414 // Cannot DCHECK in the general case yet, but since the callback is
415 // a new addition to the API, DCHECK to make sure at least the new uses
416 // don't regress.
417 DCHECK(thread_checker_.CalledOnValidThread());
418 } else if (!thread_checker_.CalledOnValidThread()) {
419 // TODO(mattm): Change to DCHECK when callers have been fixed.
420 DVLOG(1) << "Called on wrong thread.\n"
421 << base::debug::StackTrace().ToString();
424 if (tpm_slot_)
425 return true;
427 if (!callback.is_null())
428 tpm_ready_callback_list_.push_back(callback);
430 return false;
433 // Note that CK_SLOT_ID is an unsigned long, but cryptohome gives us the slot
434 // id as an int. This should be safe since this is only used with chaps, which
435 // we also control.
436 static crypto::ScopedPK11Slot GetTPMSlotForIdOnWorkerThread(
437 SECMODModule* chaps_module,
438 CK_SLOT_ID slot_id) {
439 DCHECK(chaps_module);
441 DVLOG(3) << "Poking chaps module.";
442 SECStatus rv = SECMOD_UpdateSlotList(chaps_module);
443 if (rv != SECSuccess)
444 PLOG(ERROR) << "SECMOD_UpdateSlotList failed: " << PORT_GetError();
446 PK11SlotInfo* slot = SECMOD_LookupSlot(chaps_module->moduleID, slot_id);
447 if (!slot)
448 LOG(ERROR) << "TPM slot " << slot_id << " not found.";
449 return crypto::ScopedPK11Slot(slot);
452 bool InitializeNSSForChromeOSUser(const std::string& username_hash,
453 const base::FilePath& path) {
454 DCHECK(thread_checker_.CalledOnValidThread());
455 if (chromeos_user_map_.find(username_hash) != chromeos_user_map_.end()) {
456 // This user already exists in our mapping.
457 DVLOG(2) << username_hash << " already initialized.";
458 return false;
461 DVLOG(2) << "Opening NSS DB " << path.value();
462 std::string db_name = base::StringPrintf(
463 "%s %s", kUserNSSDatabaseName, username_hash.c_str());
464 ScopedPK11Slot public_slot(OpenPersistentNSSDBForPath(db_name, path));
465 chromeos_user_map_[username_hash] =
466 new ChromeOSUserData(public_slot.Pass());
467 return true;
470 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
471 DCHECK(thread_checker_.CalledOnValidThread());
472 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
474 return !chromeos_user_map_[username_hash]
475 ->private_slot_initialization_started();
478 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
479 DCHECK(thread_checker_.CalledOnValidThread());
480 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
482 chromeos_user_map_[username_hash]
483 ->set_private_slot_initialization_started();
486 void InitializeTPMForChromeOSUser(const std::string& username_hash,
487 CK_SLOT_ID slot_id) {
488 DCHECK(thread_checker_.CalledOnValidThread());
489 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
490 DCHECK(chromeos_user_map_[username_hash]->
491 private_slot_initialization_started());
493 if (!chaps_module_)
494 return;
496 // Note that a reference is not taken to chaps_module_. This is safe since
497 // NSSInitSingleton is Leaky, so the reference it holds is never released.
498 scoped_ptr<TPMModuleAndSlot> tpm_args(new TPMModuleAndSlot(chaps_module_));
499 TPMModuleAndSlot* tpm_args_ptr = tpm_args.get();
500 base::WorkerPool::PostTaskAndReply(
501 FROM_HERE,
502 base::Bind(&NSSInitSingleton::InitializeTPMTokenOnWorkerThread,
503 slot_id,
504 tpm_args_ptr),
505 base::Bind(&NSSInitSingleton::OnInitializedTPMForChromeOSUser,
506 base::Unretained(this), // NSSInitSingleton is leaky
507 username_hash,
508 base::Passed(&tpm_args)),
509 true /* task_is_slow */
513 void OnInitializedTPMForChromeOSUser(const std::string& username_hash,
514 scoped_ptr<TPMModuleAndSlot> tpm_args) {
515 DCHECK(thread_checker_.CalledOnValidThread());
516 DVLOG(2) << "Got tpm slot for " << username_hash << " "
517 << !!tpm_args->tpm_slot;
518 chromeos_user_map_[username_hash]->SetPrivateSlot(
519 tpm_args->tpm_slot.Pass());
522 void InitializePrivateSoftwareSlotForChromeOSUser(
523 const std::string& username_hash) {
524 DCHECK(thread_checker_.CalledOnValidThread());
525 VLOG(1) << "using software private slot for " << username_hash;
526 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
527 DCHECK(chromeos_user_map_[username_hash]->
528 private_slot_initialization_started());
530 chromeos_user_map_[username_hash]->SetPrivateSlot(
531 chromeos_user_map_[username_hash]->GetPublicSlot());
534 ScopedPK11Slot GetPublicSlotForChromeOSUser(
535 const std::string& username_hash) {
536 DCHECK(thread_checker_.CalledOnValidThread());
538 if (username_hash.empty()) {
539 DVLOG(2) << "empty username_hash";
540 return ScopedPK11Slot();
543 if (chromeos_user_map_.find(username_hash) == chromeos_user_map_.end()) {
544 LOG(ERROR) << username_hash << " not initialized.";
545 return ScopedPK11Slot();
547 return chromeos_user_map_[username_hash]->GetPublicSlot();
550 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
551 const std::string& username_hash,
552 const base::Callback<void(ScopedPK11Slot)>& callback) {
553 DCHECK(thread_checker_.CalledOnValidThread());
555 if (username_hash.empty()) {
556 DVLOG(2) << "empty username_hash";
557 if (!callback.is_null()) {
558 base::MessageLoop::current()->PostTask(
559 FROM_HERE, base::Bind(callback, base::Passed(ScopedPK11Slot())));
561 return ScopedPK11Slot();
564 DCHECK(chromeos_user_map_.find(username_hash) != chromeos_user_map_.end());
566 return chromeos_user_map_[username_hash]->GetPrivateSlot(callback);
569 void CloseChromeOSUserForTesting(const std::string& username_hash) {
570 DCHECK(thread_checker_.CalledOnValidThread());
571 ChromeOSUserMap::iterator i = chromeos_user_map_.find(username_hash);
572 DCHECK(i != chromeos_user_map_.end());
573 delete i->second;
574 chromeos_user_map_.erase(i);
577 void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
578 // Ensure that a previous value of test_system_slot_ is not overwritten.
579 // Unsetting, i.e. setting a NULL, however is allowed.
580 DCHECK(!slot || !test_system_slot_);
581 test_system_slot_ = slot.Pass();
582 if (test_system_slot_) {
583 tpm_slot_.reset(PK11_ReferenceSlot(test_system_slot_.get()));
584 RunAndClearTPMReadyCallbackList();
585 } else {
586 tpm_slot_.reset();
589 #endif // defined(OS_CHROMEOS)
591 #if !defined(OS_CHROMEOS)
592 PK11SlotInfo* GetPersistentNSSKeySlot() {
593 // TODO(mattm): Change to DCHECK when callers have been fixed.
594 if (!thread_checker_.CalledOnValidThread()) {
595 DVLOG(1) << "Called on wrong thread.\n"
596 << base::debug::StackTrace().ToString();
599 return PK11_GetInternalKeySlot();
601 #endif
603 #if defined(OS_CHROMEOS)
604 void GetSystemNSSKeySlotCallback(
605 const base::Callback<void(ScopedPK11Slot)>& callback) {
606 callback.Run(ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_.get())));
609 ScopedPK11Slot GetSystemNSSKeySlot(
610 const base::Callback<void(ScopedPK11Slot)>& callback) {
611 DCHECK(thread_checker_.CalledOnValidThread());
612 // TODO(mattm): chromeos::TPMTokenloader always calls
613 // InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is
614 // disabled, tpm_slot_ will be the first user's slot instead. Can that be
615 // detected and return NULL instead?
617 base::Closure wrapped_callback;
618 if (!callback.is_null()) {
619 wrapped_callback =
620 base::Bind(&NSSInitSingleton::GetSystemNSSKeySlotCallback,
621 base::Unretained(this) /* singleton is leaky */,
622 callback);
624 if (IsTPMTokenReady(wrapped_callback))
625 return ScopedPK11Slot(PK11_ReferenceSlot(tpm_slot_.get()));
626 return ScopedPK11Slot();
628 #endif
630 #if defined(USE_NSS_CERTS)
631 base::Lock* write_lock() {
632 return &write_lock_;
634 #endif // defined(USE_NSS_CERTS)
636 // This method is used to force NSS to be initialized without a DB.
637 // Call this method before NSSInitSingleton() is constructed.
638 static void ForceNoDBInit() {
639 force_nodb_init_ = true;
642 private:
643 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
645 NSSInitSingleton()
646 : tpm_token_enabled_for_nss_(false),
647 initializing_tpm_token_(false),
648 chaps_module_(NULL),
649 root_(NULL) {
650 base::TimeTicks start_time = base::TimeTicks::Now();
652 // It's safe to construct on any thread, since LazyInstance will prevent any
653 // other threads from accessing until the constructor is done.
654 thread_checker_.DetachFromThread();
656 DisableAESNIIfNeeded();
658 EnsureNSPRInit();
660 // We *must* have NSS >= 3.14.3.
661 static_assert(
662 (NSS_VMAJOR == 3 && NSS_VMINOR == 14 && NSS_VPATCH >= 3) ||
663 (NSS_VMAJOR == 3 && NSS_VMINOR > 14) ||
664 (NSS_VMAJOR > 3),
665 "nss version check failed");
666 // Also check the run-time NSS version.
667 // NSS_VersionCheck is a >= check, not strict equality.
668 if (!NSS_VersionCheck("3.14.3")) {
669 LOG(FATAL) << "NSS_VersionCheck(\"3.14.3\") failed. NSS >= 3.14.3 is "
670 "required. Please upgrade to the latest NSS, and if you "
671 "still get this error, contact your distribution "
672 "maintainer.";
675 SECStatus status = SECFailure;
676 bool nodb_init = force_nodb_init_;
678 #if !defined(USE_NSS_CERTS)
679 // Use the system certificate store, so initialize NSS without database.
680 nodb_init = true;
681 #endif
683 if (nodb_init) {
684 status = NSS_NoDB_Init(NULL);
685 if (status != SECSuccess) {
686 CrashOnNSSInitFailure();
687 return;
689 #if defined(OS_IOS)
690 root_ = InitDefaultRootCerts();
691 #endif // defined(OS_IOS)
692 } else {
693 #if defined(USE_NSS_CERTS)
694 base::FilePath database_dir = GetInitialConfigDirectory();
695 if (!database_dir.empty()) {
696 // This duplicates the work which should have been done in
697 // EarlySetupForNSSInit. However, this function is idempotent so
698 // there's no harm done.
699 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
701 // Initialize with a persistent database (likely, ~/.pki/nssdb).
702 // Use "sql:" which can be shared by multiple processes safely.
703 std::string nss_config_dir =
704 base::StringPrintf("sql:%s", database_dir.value().c_str());
705 #if defined(OS_CHROMEOS)
706 status = NSS_Init(nss_config_dir.c_str());
707 #else
708 status = NSS_InitReadWrite(nss_config_dir.c_str());
709 #endif
710 if (status != SECSuccess) {
711 LOG(ERROR) << "Error initializing NSS with a persistent "
712 "database (" << nss_config_dir
713 << "): " << GetNSSErrorMessage();
716 if (status != SECSuccess) {
717 VLOG(1) << "Initializing NSS without a persistent database.";
718 status = NSS_NoDB_Init(NULL);
719 if (status != SECSuccess) {
720 CrashOnNSSInitFailure();
721 return;
725 PK11_SetPasswordFunc(PKCS11PasswordFunc);
727 // If we haven't initialized the password for the NSS databases,
728 // initialize an empty-string password so that we don't need to
729 // log in.
730 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
731 if (slot) {
732 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
733 // yet, so we don't need to lock.
734 if (PK11_NeedUserInit(slot))
735 PK11_InitPin(slot, NULL, NULL);
736 PK11_FreeSlot(slot);
739 root_ = InitDefaultRootCerts();
740 #endif // defined(USE_NSS_CERTS)
743 // Disable MD5 certificate signatures. (They are disabled by default in
744 // NSS 3.14.)
745 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
746 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,
747 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
749 // The UMA bit is conditionally set for this histogram in
750 // components/startup_metric_utils.cc .
751 LOCAL_HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit",
752 base::TimeTicks::Now() - start_time,
753 base::TimeDelta::FromMilliseconds(10),
754 base::TimeDelta::FromHours(1),
755 50);
758 // NOTE(willchan): We don't actually execute this code since we leak NSS to
759 // prevent non-joinable threads from using NSS after it's already been shut
760 // down.
761 ~NSSInitSingleton() {
762 #if defined(OS_CHROMEOS)
763 STLDeleteValues(&chromeos_user_map_);
764 #endif
765 tpm_slot_.reset();
766 if (root_) {
767 SECMOD_UnloadUserModule(root_);
768 SECMOD_DestroyModule(root_);
769 root_ = NULL;
771 if (chaps_module_) {
772 SECMOD_UnloadUserModule(chaps_module_);
773 SECMOD_DestroyModule(chaps_module_);
774 chaps_module_ = NULL;
777 SECStatus status = NSS_Shutdown();
778 if (status != SECSuccess) {
779 // We VLOG(1) because this failure is relatively harmless (leaking, but
780 // we're shutting down anyway).
781 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
785 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
786 // Load nss's built-in root certs.
787 SECMODModule* InitDefaultRootCerts() {
788 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
789 if (root)
790 return root;
792 // Aw, snap. Can't find/load root cert shared library.
793 // This will make it hard to talk to anybody via https.
794 // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
795 return NULL;
798 // Load the given module for this NSS session.
799 static SECMODModule* LoadModule(const char* name,
800 const char* library_path,
801 const char* params) {
802 std::string modparams = base::StringPrintf(
803 "name=\"%s\" library=\"%s\" %s",
804 name, library_path, params ? params : "");
806 // Shouldn't need to const_cast here, but SECMOD doesn't properly
807 // declare input string arguments as const. Bug
808 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
809 // on NSS codebase to address this.
810 SECMODModule* module = SECMOD_LoadUserModule(
811 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
812 if (!module) {
813 LOG(ERROR) << "Error loading " << name << " module into NSS: "
814 << GetNSSErrorMessage();
815 return NULL;
817 if (!module->loaded) {
818 LOG(ERROR) << "After loading " << name << ", loaded==false: "
819 << GetNSSErrorMessage();
820 SECMOD_DestroyModule(module);
821 return NULL;
823 return module;
825 #endif
827 static void DisableAESNIIfNeeded() {
828 if (NSS_VersionCheck("3.15") && !NSS_VersionCheck("3.15.4")) {
829 // Some versions of NSS have a bug that causes AVX instructions to be
830 // used without testing whether XSAVE is enabled by the operating system.
831 // In order to work around this, we disable AES-NI in NSS when we find
832 // that |has_avx()| is false (which includes the XSAVE test). See
833 // https://bugzilla.mozilla.org/show_bug.cgi?id=940794
834 base::CPU cpu;
836 if (cpu.has_avx_hardware() && !cpu.has_avx()) {
837 scoped_ptr<base::Environment> env(base::Environment::Create());
838 env->SetVar("NSS_DISABLE_HW_AES", "1");
843 // If this is set to true NSS is forced to be initialized without a DB.
844 static bool force_nodb_init_;
846 bool tpm_token_enabled_for_nss_;
847 bool initializing_tpm_token_;
848 typedef std::vector<base::Closure> TPMReadyCallbackList;
849 TPMReadyCallbackList tpm_ready_callback_list_;
850 SECMODModule* chaps_module_;
851 crypto::ScopedPK11Slot tpm_slot_;
852 SECMODModule* root_;
853 #if defined(OS_CHROMEOS)
854 typedef std::map<std::string, ChromeOSUserData*> ChromeOSUserMap;
855 ChromeOSUserMap chromeos_user_map_;
856 ScopedPK11Slot test_system_slot_;
857 #endif
858 #if defined(USE_NSS_CERTS)
859 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
860 // is fixed, we will no longer need the lock.
861 base::Lock write_lock_;
862 #endif // defined(USE_NSS_CERTS)
864 base::ThreadChecker thread_checker_;
867 // static
868 bool NSSInitSingleton::force_nodb_init_ = false;
870 base::LazyInstance<NSSInitSingleton>::Leaky
871 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
872 } // namespace
874 #if defined(USE_NSS_CERTS)
875 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
876 const std::string& description) {
877 const std::string modspec =
878 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
879 path.value().c_str(),
880 description.c_str());
881 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
882 if (db_slot) {
883 if (PK11_NeedUserInit(db_slot))
884 PK11_InitPin(db_slot, NULL, NULL);
885 } else {
886 LOG(ERROR) << "Error opening persistent database (" << modspec
887 << "): " << GetNSSErrorMessage();
889 return ScopedPK11Slot(db_slot);
892 void EarlySetupForNSSInit() {
893 base::FilePath database_dir = GetInitialConfigDirectory();
894 if (!database_dir.empty())
895 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
897 #endif
899 void EnsureNSPRInit() {
900 g_nspr_singleton.Get();
903 void InitNSSSafely() {
904 // We might fork, but we haven't loaded any security modules.
905 DisableNSSForkCheck();
906 // If we're sandboxed, we shouldn't be able to open user security modules,
907 // but it's more correct to tell NSS to not even try.
908 // Loading user security modules would have security implications.
909 ForceNSSNoDBInit();
910 // Initialize NSS.
911 EnsureNSSInit();
914 void EnsureNSSInit() {
915 // Initializing SSL causes us to do blocking IO.
916 // Temporarily allow it until we fix
917 // http://code.google.com/p/chromium/issues/detail?id=59847
918 base::ThreadRestrictions::ScopedAllowIO allow_io;
919 g_nss_singleton.Get();
922 void ForceNSSNoDBInit() {
923 NSSInitSingleton::ForceNoDBInit();
926 void DisableNSSForkCheck() {
927 scoped_ptr<base::Environment> env(base::Environment::Create());
928 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
931 void LoadNSSLibraries() {
932 // Some NSS libraries are linked dynamically so load them here.
933 #if defined(USE_NSS_CERTS)
934 // Try to search for multiple directories to load the libraries.
935 std::vector<base::FilePath> paths;
937 // Use relative path to Search PATH for the library files.
938 paths.push_back(base::FilePath());
940 // For Debian derivatives NSS libraries are located here.
941 paths.push_back(base::FilePath("/usr/lib/nss"));
943 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here.
944 #if defined(ARCH_CPU_X86_64)
945 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss"));
946 #elif defined(ARCH_CPU_X86)
947 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss"));
948 #elif defined(ARCH_CPU_ARMEL)
949 #if defined(__ARM_PCS_VFP)
950 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabihf/nss"));
951 #else
952 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss"));
953 #endif // defined(__ARM_PCS_VFP)
954 #elif defined(ARCH_CPU_MIPSEL)
955 paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss"));
956 #endif // defined(ARCH_CPU_X86_64)
958 // A list of library files to load.
959 std::vector<std::string> libs;
960 libs.push_back("libsoftokn3.so");
961 libs.push_back("libfreebl3.so");
963 // For each combination of library file and path, check for existence and
964 // then load.
965 size_t loaded = 0;
966 for (size_t i = 0; i < libs.size(); ++i) {
967 for (size_t j = 0; j < paths.size(); ++j) {
968 base::FilePath path = paths[j].Append(libs[i]);
969 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
970 if (lib) {
971 ++loaded;
972 break;
977 if (loaded == libs.size()) {
978 VLOG(3) << "NSS libraries loaded.";
979 } else {
980 LOG(ERROR) << "Failed to load NSS libraries.";
982 #endif // defined(USE_NSS_CERTS)
985 bool CheckNSSVersion(const char* version) {
986 return !!NSS_VersionCheck(version);
989 #if defined(USE_NSS_CERTS)
990 base::Lock* GetNSSWriteLock() {
991 return g_nss_singleton.Get().write_lock();
994 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
995 // May be NULL if the lock is not needed in our version of NSS.
996 if (lock_)
997 lock_->Acquire();
1000 AutoNSSWriteLock::~AutoNSSWriteLock() {
1001 if (lock_) {
1002 lock_->AssertAcquired();
1003 lock_->Release();
1007 AutoSECMODListReadLock::AutoSECMODListReadLock()
1008 : lock_(SECMOD_GetDefaultModuleListLock()) {
1009 SECMOD_GetReadLock(lock_);
1012 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
1013 SECMOD_ReleaseReadLock(lock_);
1015 #endif // defined(USE_NSS_CERTS)
1017 #if defined(OS_CHROMEOS)
1018 ScopedPK11Slot GetSystemNSSKeySlot(
1019 const base::Callback<void(ScopedPK11Slot)>& callback) {
1020 return g_nss_singleton.Get().GetSystemNSSKeySlot(callback);
1023 void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
1024 g_nss_singleton.Get().SetSystemKeySlotForTesting(slot.Pass());
1027 void EnableTPMTokenForNSS() {
1028 g_nss_singleton.Get().EnableTPMTokenForNSS();
1031 bool IsTPMTokenEnabledForNSS() {
1032 return g_nss_singleton.Get().IsTPMTokenEnabledForNSS();
1035 bool IsTPMTokenReady(const base::Closure& callback) {
1036 return g_nss_singleton.Get().IsTPMTokenReady(callback);
1039 void InitializeTPMTokenAndSystemSlot(
1040 int token_slot_id,
1041 const base::Callback<void(bool)>& callback) {
1042 g_nss_singleton.Get().InitializeTPMTokenAndSystemSlot(token_slot_id,
1043 callback);
1046 bool InitializeNSSForChromeOSUser(const std::string& username_hash,
1047 const base::FilePath& path) {
1048 return g_nss_singleton.Get().InitializeNSSForChromeOSUser(username_hash,
1049 path);
1052 bool ShouldInitializeTPMForChromeOSUser(const std::string& username_hash) {
1053 return g_nss_singleton.Get().ShouldInitializeTPMForChromeOSUser(
1054 username_hash);
1057 void WillInitializeTPMForChromeOSUser(const std::string& username_hash) {
1058 g_nss_singleton.Get().WillInitializeTPMForChromeOSUser(username_hash);
1061 void InitializeTPMForChromeOSUser(
1062 const std::string& username_hash,
1063 CK_SLOT_ID slot_id) {
1064 g_nss_singleton.Get().InitializeTPMForChromeOSUser(username_hash, slot_id);
1067 void InitializePrivateSoftwareSlotForChromeOSUser(
1068 const std::string& username_hash) {
1069 g_nss_singleton.Get().InitializePrivateSoftwareSlotForChromeOSUser(
1070 username_hash);
1073 ScopedPK11Slot GetPublicSlotForChromeOSUser(const std::string& username_hash) {
1074 return g_nss_singleton.Get().GetPublicSlotForChromeOSUser(username_hash);
1077 ScopedPK11Slot GetPrivateSlotForChromeOSUser(
1078 const std::string& username_hash,
1079 const base::Callback<void(ScopedPK11Slot)>& callback) {
1080 return g_nss_singleton.Get().GetPrivateSlotForChromeOSUser(username_hash,
1081 callback);
1084 void CloseChromeOSUserForTesting(const std::string& username_hash) {
1085 g_nss_singleton.Get().CloseChromeOSUserForTesting(username_hash);
1087 #endif // defined(OS_CHROMEOS)
1089 base::Time PRTimeToBaseTime(PRTime prtime) {
1090 return base::Time::FromInternalValue(
1091 prtime + base::Time::UnixEpoch().ToInternalValue());
1094 PRTime BaseTimeToPRTime(base::Time time) {
1095 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
1098 #if !defined(OS_CHROMEOS)
1099 PK11SlotInfo* GetPersistentNSSKeySlot() {
1100 return g_nss_singleton.Get().GetPersistentNSSKeySlot();
1102 #endif
1104 } // namespace crypto