nss_util.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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. 4 5#include "crypto/nss_util.h" 6#include "crypto/nss_util_internal.h" 7 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> 15 16#if defined(OS_LINUX) 17#include <linux/nfs_fs.h> 18#include <sys/vfs.h> 19#elif defined(OS_OPENBSD) 20#include <sys/mount.h> 21#include <sys/param.h> 22#endif 23 24#include <vector> 25 26#include "base/debug/alias.h" 27#include "base/environment.h" 28#include "base/file_util.h" 29#include "base/files/file_path.h" 30#include "base/files/scoped_temp_dir.h" 31#include "base/lazy_instance.h" 32#include "base/logging.h" 33#include "base/memory/scoped_ptr.h" 34#include "base/metrics/histogram.h" 35#include "base/native_library.h" 36#include "base/strings/stringprintf.h" 37#include "base/threading/thread_restrictions.h" 38#include "build/build_config.h" 39 40// USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not 41// defined, such as on Mac and Windows, we use NSS for SSL only -- we don't 42// use NSS for crypto or certificate verification, and we don't use the NSS 43// certificate and key databases. 44#if defined(USE_NSS) 45#include "base/synchronization/lock.h" 46#include "crypto/crypto_module_blocking_password_delegate.h" 47#endif // defined(USE_NSS) 48 49namespace crypto { 50 51namespace { 52 53#if defined(OS_CHROMEOS) 54const char kNSSDatabaseName[] = "Real NSS database"; 55 56// Constants for loading the Chrome OS TPM-backed PKCS #11 library. 57const char kChapsModuleName[] = "Chaps"; 58const char kChapsPath[] = "libchaps.so"; 59 60// Fake certificate authority database used for testing. 61static const base::FilePath::CharType kReadOnlyCertDB[] = 62 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb"); 63#endif // defined(OS_CHROMEOS) 64 65std::string GetNSSErrorMessage() { 66 std::string result; 67 if (PR_GetErrorTextLength()) { 68 scoped_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]); 69 PRInt32 copied = PR_GetErrorText(error_text.get()); 70 result = std::string(error_text.get(), copied); 71 } else { 72 result = base::StringPrintf("NSS error code: %d", PR_GetError()); 73 } 74 return result; 75} 76 77#if defined(USE_NSS) 78base::FilePath GetDefaultConfigDirectory() { 79 base::FilePath dir = file_util::GetHomeDir(); 80 if (dir.empty()) { 81 LOG(ERROR) << "Failed to get home directory."; 82 return dir; 83 } 84 dir = dir.AppendASCII(".pki").AppendASCII("nssdb"); 85 if (!file_util::CreateDirectory(dir)) { 86 LOG(ERROR) << "Failed to create " << dir.value() << " directory."; 87 dir.clear(); 88 } 89 return dir; 90} 91 92// On non-chromeos platforms, return the default config directory. 93// On chromeos, return a read-only directory with fake root CA certs for testing 94// (which will not exist on non-testing images). These root CA certs are used 95// by the local Google Accounts server mock we use when testing our login code. 96// If this directory is not present, NSS_Init() will fail. It is up to the 97// caller to failover to NSS_NoDB_Init() at that point. 98base::FilePath GetInitialConfigDirectory() { 99#if defined(OS_CHROMEOS) 100 return base::FilePath(kReadOnlyCertDB); 101#else 102 return GetDefaultConfigDirectory(); 103#endif // defined(OS_CHROMEOS) 104} 105 106// This callback for NSS forwards all requests to a caller-specified 107// CryptoModuleBlockingPasswordDelegate object. 108char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) { 109#if defined(OS_CHROMEOS) 110 // If we get asked for a password for the TPM, then return the 111 // well known password we use, as long as the TPM slot has been 112 // initialized. 113 if (crypto::IsTPMTokenReady()) { 114 std::string token_name; 115 std::string user_pin; 116 crypto::GetTPMTokenInfo(&token_name, &user_pin); 117 if (PK11_GetTokenName(slot) == token_name) 118 return PORT_Strdup(user_pin.c_str()); 119 } 120#endif 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; 133 } 134 DLOG(ERROR) << "PK11 password requested with NULL arg"; 135 return NULL; 136} 137 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. 144// 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. 148// 149// Because this function sets an environment variable it must be run before we 150// go multi-threaded. 151void UseLocalCacheOfNSSDatabaseIfNFS(const base::FilePath& database_dir) { 152#if defined(OS_LINUX) || defined(OS_OPENBSD) 153 struct statfs buf; 154 if (statfs(database_dir.value().c_str(), &buf) == 0) { 155#if defined(OS_LINUX) 156 if (buf.f_type == NFS_SUPER_MAGIC) { 157#elif defined(OS_OPENBSD) 158 if (strcmp(buf.f_fstypename, MOUNT_NFS) == 0) { 159#endif 160 scoped_ptr<base::Environment> env(base::Environment::Create()); 161 const char* use_cache_env_var = "NSS_SDB_USE_CACHE"; 162 if (!env->HasVar(use_cache_env_var)) 163 env->SetVar(use_cache_env_var, "yes"); 164 } 165 } 166#endif // defined(OS_LINUX) || defined(OS_OPENBSD) 167} 168 169PK11SlotInfo* FindSlotWithTokenName(const std::string& token_name) { 170 AutoSECMODListReadLock auto_lock; 171 SECMODModuleList* head = SECMOD_GetDefaultModuleList(); 172 for (SECMODModuleList* item = head; item != NULL; item = item->next) { 173 int slot_count = item->module->loaded ? item->module->slotCount : 0; 174 for (int i = 0; i < slot_count; i++) { 175 PK11SlotInfo* slot = item->module->slots[i]; 176 if (PK11_GetTokenName(slot) == token_name) 177 return PK11_ReferenceSlot(slot); 178 } 179 } 180 return NULL; 181} 182 183#endif // defined(USE_NSS) 184 185// A singleton to initialize/deinitialize NSPR. 186// Separate from the NSS singleton because we initialize NSPR on the UI thread. 187// Now that we're leaking the singleton, we could merge back with the NSS 188// singleton. 189class NSPRInitSingleton { 190 private: 191 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>; 192 193 NSPRInitSingleton() { 194 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); 195 } 196 197 // NOTE(willchan): We don't actually execute this code since we leak NSS to 198 // prevent non-joinable threads from using NSS after it's already been shut 199 // down. 200 ~NSPRInitSingleton() { 201 PL_ArenaFinish(); 202 PRStatus prstatus = PR_Cleanup(); 203 if (prstatus != PR_SUCCESS) 204 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?"; 205 } 206}; 207 208base::LazyInstance<NSPRInitSingleton>::Leaky 209 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER; 210 211// This is a LazyInstance so that it will be deleted automatically when the 212// unittest exits. NSSInitSingleton is a LeakySingleton, so it would not be 213// deleted if it were a regular member. 214base::LazyInstance<base::ScopedTempDir> g_test_nss_db_dir = 215 LAZY_INSTANCE_INITIALIZER; 216 217// Force a crash with error info on NSS_NoDB_Init failure. 218void CrashOnNSSInitFailure() { 219 int nss_error = PR_GetError(); 220 int os_error = PR_GetOSError(); 221 base::debug::Alias(&nss_error); 222 base::debug::Alias(&os_error); 223 LOG(ERROR) << "Error initializing NSS without a persistent database: " 224 << GetNSSErrorMessage(); 225 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error; 226} 227 228class NSSInitSingleton { 229 public: 230#if defined(OS_CHROMEOS) 231 void OpenPersistentNSSDB() { 232 if (!chromeos_user_logged_in_) { 233 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread. 234 // Temporarily allow it until we fix http://crbug.com/70119 235 base::ThreadRestrictions::ScopedAllowIO allow_io; 236 chromeos_user_logged_in_ = true; 237 238 // This creates another DB slot in NSS that is read/write, unlike 239 // the fake root CA cert DB and the "default" crypto key 240 // provider, which are still read-only (because we initialized 241 // NSS before we had a cryptohome mounted). 242 software_slot_ = OpenUserDB(GetDefaultConfigDirectory(), 243 kNSSDatabaseName); 244 } 245 } 246 247 void EnableTPMTokenForNSS() { 248 tpm_token_enabled_for_nss_ = true; 249 } 250 251 bool InitializeTPMToken(const std::string& token_name, 252 const std::string& user_pin) { 253 // If EnableTPMTokenForNSS hasn't been called, return false. 254 if (!tpm_token_enabled_for_nss_) 255 return false; 256 257 // If everything is already initialized, then return true. 258 if (chaps_module_ && tpm_slot_) 259 return true; 260 261 tpm_token_name_ = token_name; 262 tpm_user_pin_ = user_pin; 263 264 // This tries to load the Chaps module so NSS can talk to the hardware 265 // TPM. 266 if (!chaps_module_) { 267 chaps_module_ = LoadModule( 268 kChapsModuleName, 269 kChapsPath, 270 // For more details on these parameters, see: 271 // https://developer.mozilla.org/en/PKCS11_Module_Specs 272 // slotFlags=[PublicCerts] -- Certificates and public keys can be 273 // read from this slot without requiring a call to C_Login. 274 // askpw=only -- Only authenticate to the token when necessary. 275 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\""); 276 } 277 if (chaps_module_){ 278 // If this gets set, then we'll use the TPM for certs with 279 // private keys, otherwise we'll fall back to the software 280 // implementation. 281 tpm_slot_ = GetTPMSlot(); 282 283 return tpm_slot_ != NULL; 284 } 285 return false; 286 } 287 288 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) { 289 if (!tpm_token_enabled_for_nss_) { 290 LOG(ERROR) << "GetTPMTokenInfo called before TPM Token is ready."; 291 return; 292 } 293 if (token_name) 294 *token_name = tpm_token_name_; 295 if (user_pin) 296 *user_pin = tpm_user_pin_; 297 } 298 299 bool IsTPMTokenReady() { 300 return tpm_slot_ != NULL; 301 } 302 303 PK11SlotInfo* GetTPMSlot() { 304 std::string token_name; 305 GetTPMTokenInfo(&token_name, NULL); 306 return FindSlotWithTokenName(token_name); 307 } 308#endif // defined(OS_CHROMEOS) 309 310 311 bool OpenTestNSSDB() { 312 if (test_slot_) 313 return true; 314 if (!g_test_nss_db_dir.Get().CreateUniqueTempDir()) 315 return false; 316 test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), "Test DB"); 317 return !!test_slot_; 318 } 319 320 void CloseTestNSSDB() { 321 if (!test_slot_) 322 return; 323 SECStatus status = SECMOD_CloseUserDB(test_slot_); 324 if (status != SECSuccess) 325 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError(); 326 PK11_FreeSlot(test_slot_); 327 test_slot_ = NULL; 328 ignore_result(g_test_nss_db_dir.Get().Delete()); 329 } 330 331 PK11SlotInfo* GetPublicNSSKeySlot() { 332 if (test_slot_) 333 return PK11_ReferenceSlot(test_slot_); 334 if (software_slot_) 335 return PK11_ReferenceSlot(software_slot_); 336 return PK11_GetInternalKeySlot(); 337 } 338 339 PK11SlotInfo* GetPrivateNSSKeySlot() { 340 if (test_slot_) 341 return PK11_ReferenceSlot(test_slot_); 342 343#if defined(OS_CHROMEOS) 344 if (tpm_token_enabled_for_nss_) { 345 if (IsTPMTokenReady()) { 346 return PK11_ReferenceSlot(tpm_slot_); 347 } else { 348 // If we were supposed to get the hardware token, but were 349 // unable to, return NULL rather than fall back to sofware. 350 return NULL; 351 } 352 } 353#endif 354 // If we weren't supposed to enable the TPM for NSS, then return 355 // the software slot. 356 if (software_slot_) 357 return PK11_ReferenceSlot(software_slot_); 358 return PK11_GetInternalKeySlot(); 359 } 360 361#if defined(USE_NSS) 362 base::Lock* write_lock() { 363 return &write_lock_; 364 } 365#endif // defined(USE_NSS) 366 367 // This method is used to force NSS to be initialized without a DB. 368 // Call this method before NSSInitSingleton() is constructed. 369 static void ForceNoDBInit() { 370 force_nodb_init_ = true; 371 } 372 373 private: 374 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>; 375 376 NSSInitSingleton() 377 : tpm_token_enabled_for_nss_(false), 378 chaps_module_(NULL), 379 software_slot_(NULL), 380 test_slot_(NULL), 381 tpm_slot_(NULL), 382 root_(NULL), 383 chromeos_user_logged_in_(false) { 384 base::TimeTicks start_time = base::TimeTicks::Now(); 385 EnsureNSPRInit(); 386 387 // We *must* have NSS >= 3.12.3. See bug 26448. 388 COMPILE_ASSERT( 389 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) || 390 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) || 391 (NSS_VMAJOR > 3), 392 nss_version_check_failed); 393 // Also check the run-time NSS version. 394 // NSS_VersionCheck is a >= check, not strict equality. 395 if (!NSS_VersionCheck("3.12.3")) { 396 // It turns out many people have misconfigured NSS setups, where 397 // their run-time NSPR doesn't match the one their NSS was compiled 398 // against. So rather than aborting, complain loudly. 399 LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed. " 400 "We depend on NSS >= 3.12.3, and this error is not fatal " 401 "only because many people have busted NSS setups (for " 402 "example, using the wrong version of NSPR). " 403 "Please upgrade to the latest NSS and NSPR, and if you " 404 "still get this error, contact your distribution " 405 "maintainer."; 406 } 407 408 SECStatus status = SECFailure; 409 bool nodb_init = force_nodb_init_; 410 411#if !defined(USE_NSS) 412 // Use the system certificate store, so initialize NSS without database. 413 nodb_init = true; 414#endif 415 416 if (nodb_init) { 417 status = NSS_NoDB_Init(NULL); 418 if (status != SECSuccess) { 419 CrashOnNSSInitFailure(); 420 return; 421 } 422#if defined(OS_IOS) 423 root_ = InitDefaultRootCerts(); 424#endif // defined(OS_IOS) 425 } else { 426#if defined(USE_NSS) 427 base::FilePath database_dir = GetInitialConfigDirectory(); 428 if (!database_dir.empty()) { 429 // This duplicates the work which should have been done in 430 // EarlySetupForNSSInit. However, this function is idempotent so 431 // there's no harm done. 432 UseLocalCacheOfNSSDatabaseIfNFS(database_dir); 433 434 // Initialize with a persistent database (likely, ~/.pki/nssdb). 435 // Use "sql:" which can be shared by multiple processes safely. 436 std::string nss_config_dir = 437 base::StringPrintf("sql:%s", database_dir.value().c_str()); 438#if defined(OS_CHROMEOS) 439 status = NSS_Init(nss_config_dir.c_str()); 440#else 441 status = NSS_InitReadWrite(nss_config_dir.c_str()); 442#endif 443 if (status != SECSuccess) { 444 LOG(ERROR) << "Error initializing NSS with a persistent " 445 "database (" << nss_config_dir 446 << "): " << GetNSSErrorMessage(); 447 } 448 } 449 if (status != SECSuccess) { 450 VLOG(1) << "Initializing NSS without a persistent database."; 451 status = NSS_NoDB_Init(NULL); 452 if (status != SECSuccess) { 453 CrashOnNSSInitFailure(); 454 return; 455 } 456 } 457 458 PK11_SetPasswordFunc(PKCS11PasswordFunc); 459 460 // If we haven't initialized the password for the NSS databases, 461 // initialize an empty-string password so that we don't need to 462 // log in. 463 PK11SlotInfo* slot = PK11_GetInternalKeySlot(); 464 if (slot) { 465 // PK11_InitPin may write to the keyDB, but no other thread can use NSS 466 // yet, so we don't need to lock. 467 if (PK11_NeedUserInit(slot)) 468 PK11_InitPin(slot, NULL, NULL); 469 PK11_FreeSlot(slot); 470 } 471 472 root_ = InitDefaultRootCerts(); 473#endif // defined(USE_NSS) 474 } 475 476 // Disable MD5 certificate signatures. (They are disabled by default in 477 // NSS 3.14.) 478 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE); 479 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, 480 0, NSS_USE_ALG_IN_CERT_SIGNATURE); 481 482 // The UMA bit is conditionally set for this histogram in 483 // chrome/common/startup_metric_utils.cc . 484 HISTOGRAM_CUSTOM_TIMES("Startup.SlowStartupNSSInit", 485 base::TimeTicks::Now() - start_time, 486 base::TimeDelta::FromMilliseconds(10), 487 base::TimeDelta::FromHours(1), 488 50); 489 } 490 491 // NOTE(willchan): We don't actually execute this code since we leak NSS to 492 // prevent non-joinable threads from using NSS after it's already been shut 493 // down. 494 ~NSSInitSingleton() { 495 if (tpm_slot_) { 496 PK11_FreeSlot(tpm_slot_); 497 tpm_slot_ = NULL; 498 } 499 if (software_slot_) { 500 SECMOD_CloseUserDB(software_slot_); 501 PK11_FreeSlot(software_slot_); 502 software_slot_ = NULL; 503 } 504 CloseTestNSSDB(); 505 if (root_) { 506 SECMOD_UnloadUserModule(root_); 507 SECMOD_DestroyModule(root_); 508 root_ = NULL; 509 } 510 if (chaps_module_) { 511 SECMOD_UnloadUserModule(chaps_module_); 512 SECMOD_DestroyModule(chaps_module_); 513 chaps_module_ = NULL; 514 } 515 516 SECStatus status = NSS_Shutdown(); 517 if (status != SECSuccess) { 518 // We VLOG(1) because this failure is relatively harmless (leaking, but 519 // we're shutting down anyway). 520 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609"; 521 } 522 } 523 524#if defined(USE_NSS) || defined(OS_IOS) 525 // Load nss's built-in root certs. 526 SECMODModule* InitDefaultRootCerts() { 527 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL); 528 if (root) 529 return root; 530 531 // Aw, snap. Can't find/load root cert shared library. 532 // This will make it hard to talk to anybody via https. 533 NOTREACHED(); 534 return NULL; 535 } 536 537 // Load the given module for this NSS session. 538 SECMODModule* LoadModule(const char* name, 539 const char* library_path, 540 const char* params) { 541 std::string modparams = base::StringPrintf( 542 "name=\"%s\" library=\"%s\" %s", 543 name, library_path, params ? params : ""); 544 545 // Shouldn't need to const_cast here, but SECMOD doesn't properly 546 // declare input string arguments as const. Bug 547 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed 548 // on NSS codebase to address this. 549 SECMODModule* module = SECMOD_LoadUserModule( 550 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE); 551 if (!module) { 552 LOG(ERROR) << "Error loading " << name << " module into NSS: " 553 << GetNSSErrorMessage(); 554 return NULL; 555 } 556 return module; 557 } 558#endif 559 560 static PK11SlotInfo* OpenUserDB(const base::FilePath& path, 561 const char* description) { 562 const std::string modspec = 563 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'", 564 path.value().c_str(), description); 565 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str()); 566 if (db_slot) { 567 if (PK11_NeedUserInit(db_slot)) 568 PK11_InitPin(db_slot, NULL, NULL); 569 } 570 else { 571 LOG(ERROR) << "Error opening persistent database (" << modspec 572 << "): " << GetNSSErrorMessage(); 573 } 574 return db_slot; 575 } 576 577 // If this is set to true NSS is forced to be initialized without a DB. 578 static bool force_nodb_init_; 579 580 bool tpm_token_enabled_for_nss_; 581 std::string tpm_token_name_; 582 std::string tpm_user_pin_; 583 SECMODModule* chaps_module_; 584 PK11SlotInfo* software_slot_; 585 PK11SlotInfo* test_slot_; 586 PK11SlotInfo* tpm_slot_; 587 SECMODModule* root_; 588 bool chromeos_user_logged_in_; 589#if defined(USE_NSS) 590 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011 591 // is fixed, we will no longer need the lock. 592 base::Lock write_lock_; 593#endif // defined(USE_NSS) 594}; 595 596// static 597bool NSSInitSingleton::force_nodb_init_ = false; 598 599base::LazyInstance<NSSInitSingleton>::Leaky 600 g_nss_singleton = LAZY_INSTANCE_INITIALIZER; 601} // namespace 602 603#if defined(USE_NSS) 604void EarlySetupForNSSInit() { 605 base::FilePath database_dir = GetInitialConfigDirectory(); 606 if (!database_dir.empty()) 607 UseLocalCacheOfNSSDatabaseIfNFS(database_dir); 608} 609#endif 610 611void EnsureNSPRInit() { 612 g_nspr_singleton.Get(); 613} 614 615void InitNSSSafely() { 616 // We might fork, but we haven't loaded any security modules. 617 DisableNSSForkCheck(); 618 // If we're sandboxed, we shouldn't be able to open user security modules, 619 // but it's more correct to tell NSS to not even try. 620 // Loading user security modules would have security implications. 621 ForceNSSNoDBInit(); 622 // Initialize NSS. 623 EnsureNSSInit(); 624} 625 626void EnsureNSSInit() { 627 // Initializing SSL causes us to do blocking IO. 628 // Temporarily allow it until we fix 629 // http://code.google.com/p/chromium/issues/detail?id=59847 630 base::ThreadRestrictions::ScopedAllowIO allow_io; 631 g_nss_singleton.Get(); 632} 633 634void ForceNSSNoDBInit() { 635 NSSInitSingleton::ForceNoDBInit(); 636} 637 638void DisableNSSForkCheck() { 639 scoped_ptr<base::Environment> env(base::Environment::Create()); 640 env->SetVar("NSS_STRICT_NOFORK", "DISABLED"); 641} 642 643void LoadNSSLibraries() { 644 // Some NSS libraries are linked dynamically so load them here. 645#if defined(USE_NSS) 646 // Try to search for multiple directories to load the libraries. 647 std::vector<base::FilePath> paths; 648 649 // Use relative path to Search PATH for the library files. 650 paths.push_back(base::FilePath()); 651 652 // For Debian derivatives NSS libraries are located here. 653 paths.push_back(base::FilePath("/usr/lib/nss")); 654 655 // Ubuntu 11.10 (Oneiric) and Debian Wheezy place the libraries here. 656#if defined(ARCH_CPU_X86_64) 657 paths.push_back(base::FilePath("/usr/lib/x86_64-linux-gnu/nss")); 658#elif defined(ARCH_CPU_X86) 659 paths.push_back(base::FilePath("/usr/lib/i386-linux-gnu/nss")); 660#elif defined(ARCH_CPU_ARMEL) 661 paths.push_back(base::FilePath("/usr/lib/arm-linux-gnueabi/nss")); 662#elif defined(ARCH_CPU_MIPSEL) 663 paths.push_back(base::FilePath("/usr/lib/mipsel-linux-gnu/nss")); 664#endif 665 666 // A list of library files to load. 667 std::vector<std::string> libs; 668 libs.push_back("libsoftokn3.so"); 669 libs.push_back("libfreebl3.so"); 670 671 // For each combination of library file and path, check for existence and 672 // then load. 673 size_t loaded = 0; 674 for (size_t i = 0; i < libs.size(); ++i) { 675 for (size_t j = 0; j < paths.size(); ++j) { 676 base::FilePath path = paths[j].Append(libs[i]); 677 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL); 678 if (lib) { 679 ++loaded; 680 break; 681 } 682 } 683 } 684 685 if (loaded == libs.size()) { 686 VLOG(3) << "NSS libraries loaded."; 687 } else { 688 LOG(ERROR) << "Failed to load NSS libraries."; 689 } 690#endif 691} 692 693bool CheckNSSVersion(const char* version) { 694 return !!NSS_VersionCheck(version); 695} 696 697#if defined(USE_NSS) 698ScopedTestNSSDB::ScopedTestNSSDB() 699 : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) { 700} 701 702ScopedTestNSSDB::~ScopedTestNSSDB() { 703 // Don't close when NSS is < 3.15.1, because it would require an additional 704 // sleep for 1 second after closing the database, due to 705 // http://bugzil.la/875601. 706 if (NSS_VersionCheck("3.15.1")) { 707 g_nss_singleton.Get().CloseTestNSSDB(); 708 } 709} 710 711base::Lock* GetNSSWriteLock() { 712 return g_nss_singleton.Get().write_lock(); 713} 714 715AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) { 716 // May be NULL if the lock is not needed in our version of NSS. 717 if (lock_) 718 lock_->Acquire(); 719} 720 721AutoNSSWriteLock::~AutoNSSWriteLock() { 722 if (lock_) { 723 lock_->AssertAcquired(); 724 lock_->Release(); 725 } 726} 727 728AutoSECMODListReadLock::AutoSECMODListReadLock() 729 : lock_(SECMOD_GetDefaultModuleListLock()) { 730 SECMOD_GetReadLock(lock_); 731 } 732 733AutoSECMODListReadLock::~AutoSECMODListReadLock() { 734 SECMOD_ReleaseReadLock(lock_); 735} 736 737#endif // defined(USE_NSS) 738 739#if defined(OS_CHROMEOS) 740void OpenPersistentNSSDB() { 741 g_nss_singleton.Get().OpenPersistentNSSDB(); 742} 743 744void EnableTPMTokenForNSS() { 745 g_nss_singleton.Get().EnableTPMTokenForNSS(); 746} 747 748void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) { 749 g_nss_singleton.Get().GetTPMTokenInfo(token_name, user_pin); 750} 751 752bool IsTPMTokenReady() { 753 return g_nss_singleton.Get().IsTPMTokenReady(); 754} 755 756bool InitializeTPMToken(const std::string& token_name, 757 const std::string& user_pin) { 758 return g_nss_singleton.Get().InitializeTPMToken(token_name, user_pin); 759} 760#endif // defined(OS_CHROMEOS) 761 762base::Time PRTimeToBaseTime(PRTime prtime) { 763 return base::Time::FromInternalValue( 764 prtime + base::Time::UnixEpoch().ToInternalValue()); 765} 766 767PRTime BaseTimeToPRTime(base::Time time) { 768 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue(); 769} 770 771PK11SlotInfo* GetPublicNSSKeySlot() { 772 return g_nss_singleton.Get().GetPublicNSSKeySlot(); 773} 774 775PK11SlotInfo* GetPrivateNSSKeySlot() { 776 return g_nss_singleton.Get().GetPrivateNSSKeySlot(); 777} 778 779} // namespace crypto 780