blob: e484abe069a2fec83a06c789a9f3c8b29ed0b4d2 [file] [log] [blame]
[email protected]3b63f8f42011-03-28 01:54:151// Copyright (c) 2011 The Chromium Authors. All rights reserved.
[email protected]bc1e07c72008-09-16 14:32:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]4b559b4d2011-04-14 17:37:145#include "crypto/nss_util.h"
6#include "crypto/nss_util_internal.h"
[email protected]bc1e07c72008-09-16 14:32:447
[email protected]bc1e07c72008-09-16 14:32:448#include <nss.h>
[email protected]c72f16a2009-03-19 16:02:319#include <plarena.h>
[email protected]6e7e8062009-04-13 17:35:0910#include <prerror.h>
[email protected]c72f16a2009-03-19 16:02:3111#include <prinit.h>
[email protected]1b1a264a2010-01-14 22:36:3512#include <prtime.h>
[email protected]4b559b4d2011-04-14 17:37:1413#include <pk11pub.h>
[email protected]ea224582008-12-07 20:25:4614#include <secmod.h>
[email protected]b43c97c2008-10-22 19:50:5815
[email protected]a8b58f42010-07-14 20:21:3516#if defined(OS_LINUX)
[email protected]1f59edcb2010-11-04 00:32:2517#include <linux/nfs_fs.h>
[email protected]a8b58f42010-07-14 20:21:3518#include <sys/vfs.h>
19#endif
20
[email protected]f6a67b42011-03-17 23:49:2121#include <vector>
22
[email protected]ed450f32011-03-16 01:26:4923#include "base/environment.h"
[email protected]f6a67b42011-03-17 23:49:2124#include "base/file_path.h"
[email protected]ea224582008-12-07 20:25:4625#include "base/file_util.h"
[email protected]f615bda32010-11-21 01:04:5626#include "base/lazy_instance.h"
[email protected]c1444fe2008-09-17 09:42:5127#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1528#include "base/memory/scoped_ptr.h"
[email protected]f6a67b42011-03-17 23:49:2129#include "base/native_library.h"
[email protected]f1633932010-08-17 23:05:2830#include "base/stringprintf.h"
[email protected]34b99632011-01-01 01:01:0631#include "base/threading/thread_restrictions.h"
[email protected]4b559b4d2011-04-14 17:37:1432#include "crypto/scoped_nss_types.h"
[email protected]bc1e07c72008-09-16 14:32:4433
[email protected]a8b58f42010-07-14 20:21:3534// USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not
35// defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
36// use NSS for crypto or certificate verification, and we don't use the NSS
37// certificate and key databases.
[email protected]69138472010-06-25 22:44:4838#if defined(USE_NSS)
[email protected]20305ec2011-01-21 04:55:5239#include "base/synchronization/lock.h"
[email protected]4b559b4d2011-04-14 17:37:1440#include "crypto/crypto_module_blocking_password_delegate.h"
[email protected]a8b58f42010-07-14 20:21:3541#endif // defined(USE_NSS)
[email protected]abd4aba2010-01-27 19:36:2242
[email protected]4b559b4d2011-04-14 17:37:1443namespace crypto {
[email protected]f1633932010-08-17 23:05:2844
[email protected]bc1e07c72008-09-16 14:32:4445namespace {
46
[email protected]6a89ef22011-04-07 17:34:2147#if defined(OS_CHROMEOS)
48const char kNSSDatabaseName[] = "Real NSS database";
49
50// Constants for loading opencryptoki.
51const char kOpencryptokiModuleName[] = "opencryptoki";
52const char kOpencryptokiPath[] = "/usr/lib/opencryptoki/libopencryptoki.so";
53
[email protected]6a89ef22011-04-07 17:34:2154// Fake certificate authority database used for testing.
55static const FilePath::CharType kReadOnlyCertDB[] =
56 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
57#endif // defined(OS_CHROMEOS)
58
59std::string GetNSSErrorMessage() {
60 std::string result;
61 if (PR_GetErrorTextLength()) {
62 scoped_array<char> error_text(new char[PR_GetErrorTextLength() + 1]);
63 PRInt32 copied = PR_GetErrorText(error_text.get());
64 result = std::string(error_text.get(), copied);
65 } else {
66 result = StringPrintf("NSS error code: %d", PR_GetError());
67 }
68 return result;
69}
70
[email protected]a8b58f42010-07-14 20:21:3571#if defined(USE_NSS)
72FilePath GetDefaultConfigDirectory() {
73 FilePath dir = file_util::GetHomeDir();
74 if (dir.empty()) {
75 LOG(ERROR) << "Failed to get home directory.";
76 return dir;
[email protected]86913342009-05-25 02:14:3477 }
[email protected]86913342009-05-25 02:14:3478 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
79 if (!file_util::CreateDirectory(dir)) {
[email protected]948a707b2011-06-07 22:51:4480 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
[email protected]a8b58f42010-07-14 20:21:3581 dir.clear();
[email protected]86913342009-05-25 02:14:3482 }
[email protected]a8b58f42010-07-14 20:21:3583 return dir;
[email protected]86913342009-05-25 02:14:3484}
85
[email protected]dcce6cf2010-04-29 17:50:0686// On non-chromeos platforms, return the default config directory.
87// On chromeos, return a read-only directory with fake root CA certs for testing
88// (which will not exist on non-testing images). These root CA certs are used
89// by the local Google Accounts server mock we use when testing our login code.
90// If this directory is not present, NSS_Init() will fail. It is up to the
91// caller to failover to NSS_NoDB_Init() at that point.
[email protected]a8b58f42010-07-14 20:21:3592FilePath GetInitialConfigDirectory() {
[email protected]dcce6cf2010-04-29 17:50:0693#if defined(OS_CHROMEOS)
[email protected]a8b58f42010-07-14 20:21:3594 return FilePath(kReadOnlyCertDB);
[email protected]dcce6cf2010-04-29 17:50:0695#else
96 return GetDefaultConfigDirectory();
97#endif // defined(OS_CHROMEOS)
98}
99
[email protected]88b9db72011-01-13 01:48:43100// This callback for NSS forwards all requests to a caller-specified
[email protected]3f1f8412011-01-19 03:01:23101// CryptoModuleBlockingPasswordDelegate object.
102char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
[email protected]6a89ef22011-04-07 17:34:21103#if defined(OS_CHROMEOS)
104 // If we get asked for a password for the TPM, then return the
[email protected]c64b9142011-04-19 18:49:54105 // well known password we use, as long as the TPM slot has been
106 // initialized.
107 if (crypto::IsTPMTokenReady()) {
108 std::string token_name;
109 std::string user_pin;
110 crypto::GetTPMTokenInfo(&token_name, &user_pin);
111 if (PK11_GetTokenName(slot) == token_name)
112 return PORT_Strdup(user_pin.c_str());
113 }
[email protected]6a89ef22011-04-07 17:34:21114#endif
[email protected]4b559b4d2011-04-14 17:37:14115 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
116 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
[email protected]88b9db72011-01-13 01:48:43117 if (delegate) {
118 bool cancelled = false;
119 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
120 retry != PR_FALSE,
121 &cancelled);
122 if (cancelled)
123 return NULL;
124 char* result = PORT_Strdup(password.c_str());
125 password.replace(0, password.size(), password.size(), 0);
126 return result;
127 }
128 DLOG(ERROR) << "PK11 password requested with NULL arg";
129 return NULL;
130}
131
[email protected]a8b58f42010-07-14 20:21:35132// NSS creates a local cache of the sqlite database if it detects that the
133// filesystem the database is on is much slower than the local disk. The
134// detection doesn't work with the latest versions of sqlite, such as 3.6.22
135// (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
136// the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
137// detection when database_dir is on NFS. See http://crbug.com/48585.
138//
139// TODO(wtc): port this function to other USE_NSS platforms. It is defined
140// only for OS_LINUX simply because the statfs structure is OS-specific.
[email protected]ac3d5972011-01-13 20:33:45141//
142// Because this function sets an environment variable it must be run before we
143// go multi-threaded.
[email protected]a8b58f42010-07-14 20:21:35144void UseLocalCacheOfNSSDatabaseIfNFS(const FilePath& database_dir) {
145#if defined(OS_LINUX)
146 struct statfs buf;
147 if (statfs(database_dir.value().c_str(), &buf) == 0) {
148 if (buf.f_type == NFS_SUPER_MAGIC) {
[email protected]4b559b4d2011-04-14 17:37:14149 scoped_ptr<base::Environment> env(base::Environment::Create());
[email protected]a8b58f42010-07-14 20:21:35150 const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
[email protected]9432ade2010-08-04 23:43:20151 if (!env->HasVar(use_cache_env_var))
[email protected]c87bcf002010-08-06 01:03:37152 env->SetVar(use_cache_env_var, "yes");
[email protected]a8b58f42010-07-14 20:21:35153 }
154 }
155#endif // defined(OS_LINUX)
156}
157
[email protected]6a89ef22011-04-07 17:34:21158PK11SlotInfo* FindSlotWithTokenName(const std::string& token_name) {
159 AutoSECMODListReadLock auto_lock;
160 SECMODModuleList* head = SECMOD_GetDefaultModuleList();
161 for (SECMODModuleList* item = head; item != NULL; item = item->next) {
162 int slot_count = item->module->loaded ? item->module->slotCount : 0;
163 for (int i = 0; i < slot_count; i++) {
164 PK11SlotInfo* slot = item->module->slots[i];
165 if (PK11_GetTokenName(slot) == token_name)
166 return PK11_ReferenceSlot(slot);
167 }
168 }
[email protected]ea224582008-12-07 20:25:46169 return NULL;
170}
[email protected]6a89ef22011-04-07 17:34:21171
[email protected]a8b58f42010-07-14 20:21:35172#endif // defined(USE_NSS)
[email protected]ea224582008-12-07 20:25:46173
[email protected]730fb132009-09-02 22:50:25174// A singleton to initialize/deinitialize NSPR.
175// Separate from the NSS singleton because we initialize NSPR on the UI thread.
[email protected]f615bda32010-11-21 01:04:56176// Now that we're leaking the singleton, we could merge back with the NSS
177// singleton.
[email protected]730fb132009-09-02 22:50:25178class NSPRInitSingleton {
[email protected]f615bda32010-11-21 01:04:56179 private:
[email protected]4b559b4d2011-04-14 17:37:14180 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
[email protected]f615bda32010-11-21 01:04:56181
[email protected]730fb132009-09-02 22:50:25182 NSPRInitSingleton() {
183 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
184 }
185
[email protected]f615bda32010-11-21 01:04:56186 // 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.
[email protected]730fb132009-09-02 22:50:25189 ~NSPRInitSingleton() {
[email protected]829296f2010-01-27 02:58:03190 PL_ArenaFinish();
[email protected]730fb132009-09-02 22:50:25191 PRStatus prstatus = PR_Cleanup();
192 if (prstatus != PR_SUCCESS) {
193 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
194 }
195 }
196};
197
[email protected]4b559b4d2011-04-14 17:37:14198base::LazyInstance<NSPRInitSingleton,
199 base::LeakyLazyInstanceTraits<NSPRInitSingleton> >
200 g_nspr_singleton(base::LINKER_INITIALIZED);
[email protected]f615bda32010-11-21 01:04:56201
[email protected]bc1e07c72008-09-16 14:32:44202class NSSInitSingleton {
203 public:
[email protected]f615bda32010-11-21 01:04:56204#if defined(OS_CHROMEOS)
205 void OpenPersistentNSSDB() {
206 if (!chromeos_user_logged_in_) {
[email protected]61f93212011-01-24 14:37:08207 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
[email protected]6a89ef22011-04-07 17:34:21208 // Temporarily allow it until we fix http://crbug.com/70119
[email protected]4b559b4d2011-04-14 17:37:14209 base::ThreadRestrictions::ScopedAllowIO allow_io;
[email protected]f615bda32010-11-21 01:04:56210 chromeos_user_logged_in_ = true;
[email protected]6a89ef22011-04-07 17:34:21211
212 // This creates another DB slot in NSS that is read/write, unlike
213 // the fake root CA cert DB and the "default" crypto key
214 // provider, which are still read-only (because we initialized
215 // NSS before we had a cryptohome mounted).
216 software_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
[email protected]74beead2011-04-12 20:40:12217 kNSSDatabaseName);
[email protected]f615bda32010-11-21 01:04:56218 }
219 }
[email protected]6a89ef22011-04-07 17:34:21220
[email protected]c64b9142011-04-19 18:49:54221 void EnableTPMTokenForNSS(TPMTokenInfoDelegate* info_delegate) {
222 CHECK(info_delegate);
223 tpm_token_info_delegate_.reset(info_delegate);
224 // Try to load once to avoid jank later. Ignore the return value,
225 // because if it fails we will try again later.
226 EnsureTPMTokenReady();
[email protected]6a89ef22011-04-07 17:34:21227 }
228
[email protected]c64b9142011-04-19 18:49:54229 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
230 tpm_token_info_delegate_->GetTokenInfo(token_name, user_pin);
[email protected]6a89ef22011-04-07 17:34:21231 }
232
[email protected]c64b9142011-04-19 18:49:54233 bool IsTPMTokenReady() {
234 return tpm_slot_ != NULL;
[email protected]74beead2011-04-12 20:40:12235 }
236
[email protected]6a89ef22011-04-07 17:34:21237 PK11SlotInfo* GetTPMSlot() {
[email protected]c64b9142011-04-19 18:49:54238 std::string token_name;
239 GetTPMTokenInfo(&token_name, NULL);
240 return FindSlotWithTokenName(token_name);
[email protected]6a89ef22011-04-07 17:34:21241 }
[email protected]f615bda32010-11-21 01:04:56242#endif // defined(OS_CHROMEOS)
243
[email protected]6a89ef22011-04-07 17:34:21244
[email protected]f615bda32010-11-21 01:04:56245 bool OpenTestNSSDB(const FilePath& path, const char* description) {
[email protected]6a89ef22011-04-07 17:34:21246 test_slot_ = OpenUserDB(path, description);
247 return !!test_slot_;
[email protected]f615bda32010-11-21 01:04:56248 }
249
250 void CloseTestNSSDB() {
[email protected]6a89ef22011-04-07 17:34:21251 if (test_slot_) {
252 SECStatus status = SECMOD_CloseUserDB(test_slot_);
[email protected]f615bda32010-11-21 01:04:56253 if (status != SECSuccess)
254 LOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
[email protected]6a89ef22011-04-07 17:34:21255 PK11_FreeSlot(test_slot_);
256 test_slot_ = NULL;
[email protected]f615bda32010-11-21 01:04:56257 }
258 }
259
[email protected]6a89ef22011-04-07 17:34:21260 PK11SlotInfo* GetPublicNSSKeySlot() {
261 if (test_slot_)
262 return PK11_ReferenceSlot(test_slot_);
263 if (software_slot_)
264 return PK11_ReferenceSlot(software_slot_);
265 return PK11_GetInternalKeySlot();
266 }
267
268 PK11SlotInfo* GetPrivateNSSKeySlot() {
269 if (test_slot_)
270 return PK11_ReferenceSlot(test_slot_);
[email protected]c64b9142011-04-19 18:49:54271
272#if defined(OS_CHROMEOS)
273 // Make sure that if EnableTPMTokenForNSS has been called that we
274 // have successfully loaded opencryptoki.
275 if (tpm_token_info_delegate_.get() != NULL) {
276 if (EnsureTPMTokenReady()) {
277 return PK11_ReferenceSlot(tpm_slot_);
278 } else {
279 // If we were supposed to get the hardware token, but were
280 // unable to, return NULL rather than fall back to sofware.
281 return NULL;
282 }
283 }
284#endif
285 // If we weren't supposed to enable the TPM for NSS, then return
286 // the software slot.
[email protected]6a89ef22011-04-07 17:34:21287 if (software_slot_)
288 return PK11_ReferenceSlot(software_slot_);
[email protected]f615bda32010-11-21 01:04:56289 return PK11_GetInternalKeySlot();
290 }
291
292#if defined(USE_NSS)
[email protected]4b559b4d2011-04-14 17:37:14293 base::Lock* write_lock() {
[email protected]f615bda32010-11-21 01:04:56294 return &write_lock_;
295 }
296#endif // defined(USE_NSS)
297
[email protected]ed450f32011-03-16 01:26:49298 // This method is used to force NSS to be initialized without a DB.
299 // Call this method before NSSInitSingleton() is constructed.
300 static void ForceNoDBInit() {
301 force_nodb_init_ = true;
302 }
303
[email protected]f615bda32010-11-21 01:04:56304 private:
[email protected]4b559b4d2011-04-14 17:37:14305 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
[email protected]f615bda32010-11-21 01:04:56306
[email protected]dcce6cf2010-04-29 17:50:06307 NSSInitSingleton()
[email protected]6a89ef22011-04-07 17:34:21308 : opencryptoki_module_(NULL),
309 software_slot_(NULL),
310 test_slot_(NULL),
311 tpm_slot_(NULL),
[email protected]dcce6cf2010-04-29 17:50:06312 root_(NULL),
313 chromeos_user_logged_in_(false) {
[email protected]f615bda32010-11-21 01:04:56314 EnsureNSPRInit();
[email protected]730fb132009-09-02 22:50:25315
[email protected]dc36c9c2010-01-20 20:45:00316 // We *must* have NSS >= 3.12.3. See bug 26448.
317 COMPILE_ASSERT(
318 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
319 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
320 (NSS_VMAJOR > 3),
321 nss_version_check_failed);
322 // Also check the run-time NSS version.
323 // NSS_VersionCheck is a >= check, not strict equality.
[email protected]1b8082d2010-02-19 12:21:48324 if (!NSS_VersionCheck("3.12.3")) {
325 // It turns out many people have misconfigured NSS setups, where
326 // their run-time NSPR doesn't match the one their NSS was compiled
327 // against. So rather than aborting, complain loudly.
328 LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed. "
329 "We depend on NSS >= 3.12.3, and this error is not fatal "
330 "only because many people have busted NSS setups (for "
331 "example, using the wrong version of NSPR). "
332 "Please upgrade to the latest NSS and NSPR, and if you "
333 "still get this error, contact your distribution "
334 "maintainer.";
335 }
[email protected]dc36c9c2010-01-20 20:45:00336
[email protected]897f5202009-09-08 17:40:27337 SECStatus status = SECFailure;
[email protected]ed450f32011-03-16 01:26:49338 bool nodb_init = force_nodb_init_;
339
[email protected]a8b58f42010-07-14 20:21:35340#if !defined(USE_NSS)
[email protected]abd4aba2010-01-27 19:36:22341 // Use the system certificate store, so initialize NSS without database.
[email protected]ed450f32011-03-16 01:26:49342 nodb_init = true;
[email protected]dcce6cf2010-04-29 17:50:06343#endif
[email protected]ed450f32011-03-16 01:26:49344
345 if (nodb_init) {
[email protected]897f5202009-09-08 17:40:27346 status = NSS_NoDB_Init(NULL);
347 if (status != SECSuccess) {
348 LOG(ERROR) << "Error initializing NSS without a persistent "
[email protected]6a89ef22011-04-07 17:34:21349 "database: " << GetNSSErrorMessage();
[email protected]897f5202009-09-08 17:40:27350 }
[email protected]ed450f32011-03-16 01:26:49351 } else {
352#if defined(USE_NSS)
353 FilePath database_dir = GetInitialConfigDirectory();
354 if (!database_dir.empty()) {
355 // This duplicates the work which should have been done in
356 // EarlySetupForNSSInit. However, this function is idempotent so
357 // there's no harm done.
358 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
359
360 // Initialize with a persistent database (likely, ~/.pki/nssdb).
361 // Use "sql:" which can be shared by multiple processes safely.
362 std::string nss_config_dir =
363 StringPrintf("sql:%s", database_dir.value().c_str());
364#if defined(OS_CHROMEOS)
365 status = NSS_Init(nss_config_dir.c_str());
366#else
367 status = NSS_InitReadWrite(nss_config_dir.c_str());
368#endif
369 if (status != SECSuccess) {
370 LOG(ERROR) << "Error initializing NSS with a persistent "
371 "database (" << nss_config_dir
[email protected]6a89ef22011-04-07 17:34:21372 << "): " << GetNSSErrorMessage();
[email protected]ed450f32011-03-16 01:26:49373 }
374 }
375 if (status != SECSuccess) {
[email protected]6a89ef22011-04-07 17:34:21376 VLOG(1) << "Initializing NSS without a persistent database.";
[email protected]ed450f32011-03-16 01:26:49377 status = NSS_NoDB_Init(NULL);
378 if (status != SECSuccess) {
379 LOG(ERROR) << "Error initializing NSS without a persistent "
[email protected]6a89ef22011-04-07 17:34:21380 "database: " << GetNSSErrorMessage();
[email protected]ed450f32011-03-16 01:26:49381 return;
382 }
383 }
384
385 PK11_SetPasswordFunc(PKCS11PasswordFunc);
386
387 // If we haven't initialized the password for the NSS databases,
388 // initialize an empty-string password so that we don't need to
389 // log in.
390 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
391 if (slot) {
392 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
393 // yet, so we don't need to lock.
394 if (PK11_NeedUserInit(slot))
395 PK11_InitPin(slot, NULL, NULL);
396 PK11_FreeSlot(slot);
397 }
398
399 root_ = InitDefaultRootCerts();
400#endif // defined(USE_NSS)
[email protected]6e7e8062009-04-13 17:35:09401 }
[email protected]bc1e07c72008-09-16 14:32:44402 }
403
[email protected]f615bda32010-11-21 01:04:56404 // NOTE(willchan): We don't actually execute this code since we leak NSS to
405 // prevent non-joinable threads from using NSS after it's already been shut
406 // down.
[email protected]bc1e07c72008-09-16 14:32:44407 ~NSSInitSingleton() {
[email protected]6a89ef22011-04-07 17:34:21408 if (tpm_slot_) {
409 PK11_FreeSlot(tpm_slot_);
410 tpm_slot_ = NULL;
411 }
412 if (software_slot_) {
413 SECMOD_CloseUserDB(software_slot_);
414 PK11_FreeSlot(software_slot_);
415 software_slot_ = NULL;
[email protected]dcce6cf2010-04-29 17:50:06416 }
[email protected]bb6390382010-08-12 19:49:40417 CloseTestNSSDB();
[email protected]ea224582008-12-07 20:25:46418 if (root_) {
419 SECMOD_UnloadUserModule(root_);
420 SECMOD_DestroyModule(root_);
421 root_ = NULL;
422 }
[email protected]6a89ef22011-04-07 17:34:21423 if (opencryptoki_module_) {
424 SECMOD_UnloadUserModule(opencryptoki_module_);
425 SECMOD_DestroyModule(opencryptoki_module_);
426 opencryptoki_module_ = NULL;
427 }
[email protected]ea224582008-12-07 20:25:46428
[email protected]c1444fe2008-09-17 09:42:51429 SECStatus status = NSS_Shutdown();
[email protected]f8adef52009-08-04 17:52:06430 if (status != SECSuccess) {
[email protected]b026e35d2010-10-19 02:31:03431 // We VLOG(1) because this failure is relatively harmless (leaking, but
432 // we're shutting down anyway).
[email protected]6a89ef22011-04-07 17:34:21433 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
[email protected]f8adef52009-08-04 17:52:06434 }
[email protected]bc1e07c72008-09-16 14:32:44435 }
[email protected]c72f16a2009-03-19 16:02:31436
[email protected]6a89ef22011-04-07 17:34:21437#if defined(USE_NSS)
438 // Load nss's built-in root certs.
439 SECMODModule* InitDefaultRootCerts() {
440 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
441 if (root)
442 return root;
443
444 // Aw, snap. Can't find/load root cert shared library.
445 // This will make it hard to talk to anybody via https.
446 NOTREACHED();
447 return NULL;
448 }
449
450 // Load the given module for this NSS session.
451 SECMODModule* LoadModule(const char* name,
452 const char* library_path,
453 const char* params) {
454 std::string modparams = StringPrintf(
455 "name=\"%s\" library=\"%s\" %s",
456 name, library_path, params ? params : "");
457
458 // Shouldn't need to const_cast here, but SECMOD doesn't properly
459 // declare input string arguments as const. Bug
460 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
461 // on NSS codebase to address this.
462 SECMODModule* module = SECMOD_LoadUserModule(
463 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
464 if (!module) {
465 LOG(ERROR) << "Error loading " << name << " module into NSS: "
466 << GetNSSErrorMessage();
467 return NULL;
468 }
469 return module;
470 }
471#endif
472
[email protected]bb6390382010-08-12 19:49:40473 static PK11SlotInfo* OpenUserDB(const FilePath& path,
474 const char* description) {
475 const std::string modspec =
476 StringPrintf("configDir='sql:%s' tokenDescription='%s'",
477 path.value().c_str(), description);
478 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
479 if (db_slot) {
480 if (PK11_NeedUserInit(db_slot))
481 PK11_InitPin(db_slot, NULL, NULL);
482 }
483 else {
484 LOG(ERROR) << "Error opening persistent database (" << modspec
[email protected]6a89ef22011-04-07 17:34:21485 << "): " << GetNSSErrorMessage();
[email protected]bb6390382010-08-12 19:49:40486 }
487 return db_slot;
488 }
489
[email protected]c64b9142011-04-19 18:49:54490#if defined(OS_CHROMEOS)
491 // This is called whenever we want to make sure opencryptoki is
492 // properly loaded, because it can fail shortly after the initial
493 // login while the PINs are being initialized, and we want to retry
494 // if this happens.
495 bool EnsureTPMTokenReady() {
496 // If EnableTPMTokenForNSS hasn't been called, or if everything is
497 // already initialized, then this call succeeds.
498 if (tpm_token_info_delegate_.get() == NULL ||
499 (opencryptoki_module_ && tpm_slot_)) {
500 return true;
501 }
502
503 if (tpm_token_info_delegate_->IsTokenReady()) {
504 // This tries to load the opencryptoki module so NSS can talk to
505 // the hardware TPM.
506 if (!opencryptoki_module_) {
507 opencryptoki_module_ = LoadModule(
508 kOpencryptokiModuleName,
509 kOpencryptokiPath,
510 // trustOrder=100 -- means it'll select this as the most
511 // trusted slot for the mechanisms it provides.
512 // slotParams=... -- selects RSA as the only mechanism, and only
513 // asks for the password when necessary (instead of every
514 // time, or after a timeout).
515 "trustOrder=100 slotParams=(1={slotFlags=[RSA] askpw=only})");
516 }
517 if (opencryptoki_module_) {
518 // If this gets set, then we'll use the TPM for certs with
519 // private keys, otherwise we'll fall back to the software
520 // implementation.
521 tpm_slot_ = GetTPMSlot();
522 return tpm_slot_ != NULL;
523 }
524 }
525 return false;
526 }
527#endif
528
[email protected]ed450f32011-03-16 01:26:49529 // If this is set to true NSS is forced to be initialized without a DB.
530 static bool force_nodb_init_;
531
[email protected]c64b9142011-04-19 18:49:54532#if defined(OS_CHROMEOS)
533 scoped_ptr<TPMTokenInfoDelegate> tpm_token_info_delegate_;
534#endif
535
[email protected]6a89ef22011-04-07 17:34:21536 SECMODModule* opencryptoki_module_;
537 PK11SlotInfo* software_slot_;
538 PK11SlotInfo* test_slot_;
539 PK11SlotInfo* tpm_slot_;
540 SECMODModule* root_;
[email protected]dcce6cf2010-04-29 17:50:06541 bool chromeos_user_logged_in_;
[email protected]69138472010-06-25 22:44:48542#if defined(USE_NSS)
[email protected]f615bda32010-11-21 01:04:56543 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
544 // is fixed, we will no longer need the lock.
[email protected]4b559b4d2011-04-14 17:37:14545 base::Lock write_lock_;
[email protected]a8b58f42010-07-14 20:21:35546#endif // defined(USE_NSS)
[email protected]bc1e07c72008-09-16 14:32:44547};
548
[email protected]ed450f32011-03-16 01:26:49549// static
550bool NSSInitSingleton::force_nodb_init_ = false;
551
[email protected]4b559b4d2011-04-14 17:37:14552base::LazyInstance<NSSInitSingleton,
553 base::LeakyLazyInstanceTraits<NSSInitSingleton> >
554 g_nss_singleton(base::LINKER_INITIALIZED);
[email protected]f615bda32010-11-21 01:04:56555
[email protected]bc1e07c72008-09-16 14:32:44556} // namespace
557
[email protected]ac3d5972011-01-13 20:33:45558#if defined(USE_NSS)
559void EarlySetupForNSSInit() {
560 FilePath database_dir = GetInitialConfigDirectory();
561 if (!database_dir.empty())
562 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
563}
564#endif
565
[email protected]730fb132009-09-02 22:50:25566void EnsureNSPRInit() {
[email protected]f615bda32010-11-21 01:04:56567 g_nspr_singleton.Get();
[email protected]730fb132009-09-02 22:50:25568}
569
[email protected]bc1e07c72008-09-16 14:32:44570void EnsureNSSInit() {
[email protected]a8e4b5a82010-10-27 00:05:47571 // Initializing SSL causes us to do blocking IO.
572 // Temporarily allow it until we fix
573 // http://code.google.com/p/chromium/issues/detail?id=59847
[email protected]4b559b4d2011-04-14 17:37:14574 base::ThreadRestrictions::ScopedAllowIO allow_io;
[email protected]f615bda32010-11-21 01:04:56575 g_nss_singleton.Get();
[email protected]bc1e07c72008-09-16 14:32:44576}
577
[email protected]ed450f32011-03-16 01:26:49578void ForceNSSNoDBInit() {
579 NSSInitSingleton::ForceNoDBInit();
580}
581
582void DisableNSSForkCheck() {
[email protected]4b559b4d2011-04-14 17:37:14583 scoped_ptr<base::Environment> env(base::Environment::Create());
[email protected]ed450f32011-03-16 01:26:49584 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
585}
586
[email protected]f6a67b42011-03-17 23:49:21587void LoadNSSLibraries() {
588 // Some NSS libraries are linked dynamically so load them here.
589#if defined(USE_NSS)
590 // Try to search for multiple directories to load the libraries.
591 std::vector<FilePath> paths;
592
593 // Use relative path to Search PATH for the library files.
594 paths.push_back(FilePath());
595
596 // For Debian derivaties NSS libraries are located here.
597 paths.push_back(FilePath("/usr/lib/nss"));
598
599 // A list of library files to load.
600 std::vector<std::string> libs;
601 libs.push_back("libsoftokn3.so");
602 libs.push_back("libfreebl3.so");
603
604 // For each combination of library file and path, check for existence and
605 // then load.
606 size_t loaded = 0;
607 for (size_t i = 0; i < libs.size(); ++i) {
608 for (size_t j = 0; j < paths.size(); ++j) {
609 FilePath path = paths[j].Append(libs[i]);
[email protected]84479322011-04-18 22:06:22610 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
[email protected]9f9b4f22011-04-08 21:57:46611 if (lib) {
612 ++loaded;
613 break;
[email protected]f6a67b42011-03-17 23:49:21614 }
615 }
616 }
617
618 if (loaded == libs.size()) {
619 VLOG(3) << "NSS libraries loaded.";
620 } else {
621 LOG(WARNING) << "Failed to load NSS libraries.";
622 }
623#endif
624}
625
[email protected]f61c3972010-12-23 09:54:15626bool CheckNSSVersion(const char* version) {
627 return !!NSS_VersionCheck(version);
628}
629
[email protected]69138472010-06-25 22:44:48630#if defined(USE_NSS)
[email protected]bb6390382010-08-12 19:49:40631bool OpenTestNSSDB(const FilePath& path, const char* description) {
[email protected]f615bda32010-11-21 01:04:56632 return g_nss_singleton.Get().OpenTestNSSDB(path, description);
[email protected]bb6390382010-08-12 19:49:40633}
634
635void CloseTestNSSDB() {
[email protected]f615bda32010-11-21 01:04:56636 g_nss_singleton.Get().CloseTestNSSDB();
[email protected]bb6390382010-08-12 19:49:40637}
638
[email protected]4b559b4d2011-04-14 17:37:14639base::Lock* GetNSSWriteLock() {
[email protected]f615bda32010-11-21 01:04:56640 return g_nss_singleton.Get().write_lock();
[email protected]69138472010-06-25 22:44:48641}
642
643AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
644 // May be NULL if the lock is not needed in our version of NSS.
645 if (lock_)
646 lock_->Acquire();
647}
648
649AutoNSSWriteLock::~AutoNSSWriteLock() {
650 if (lock_) {
651 lock_->AssertAcquired();
652 lock_->Release();
653 }
654}
[email protected]dd24ffc2011-06-08 19:46:42655
656AutoSECMODListReadLock::AutoSECMODListReadLock()
657 : lock_(SECMOD_GetDefaultModuleListLock()) {
658 SECMOD_GetReadLock(lock_);
659 }
660
661AutoSECMODListReadLock::~AutoSECMODListReadLock() {
662 SECMOD_ReleaseReadLock(lock_);
663}
664
[email protected]69138472010-06-25 22:44:48665#endif // defined(USE_NSS)
666
[email protected]dcce6cf2010-04-29 17:50:06667#if defined(OS_CHROMEOS)
668void OpenPersistentNSSDB() {
[email protected]f615bda32010-11-21 01:04:56669 g_nss_singleton.Get().OpenPersistentNSSDB();
[email protected]dcce6cf2010-04-29 17:50:06670}
[email protected]6a89ef22011-04-07 17:34:21671
[email protected]c64b9142011-04-19 18:49:54672TPMTokenInfoDelegate::TPMTokenInfoDelegate() {}
673TPMTokenInfoDelegate::~TPMTokenInfoDelegate() {}
674
675void EnableTPMTokenForNSS(TPMTokenInfoDelegate* info_delegate) {
676 g_nss_singleton.Get().EnableTPMTokenForNSS(info_delegate);
[email protected]6a89ef22011-04-07 17:34:21677}
678
[email protected]c64b9142011-04-19 18:49:54679void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
680 g_nss_singleton.Get().GetTPMTokenInfo(token_name, user_pin);
[email protected]6a89ef22011-04-07 17:34:21681}
[email protected]74beead2011-04-12 20:40:12682
[email protected]c64b9142011-04-19 18:49:54683bool IsTPMTokenReady() {
684 return g_nss_singleton.Get().IsTPMTokenReady();
[email protected]74beead2011-04-12 20:40:12685}
[email protected]c64b9142011-04-19 18:49:54686
[email protected]6a89ef22011-04-07 17:34:21687#endif // defined(OS_CHROMEOS)
[email protected]dcce6cf2010-04-29 17:50:06688
[email protected]1b1a264a2010-01-14 22:36:35689// TODO(port): Implement this more simply. We can convert by subtracting an
690// offset (the difference between NSPR's and base::Time's epochs).
[email protected]4b559b4d2011-04-14 17:37:14691base::Time PRTimeToBaseTime(PRTime prtime) {
[email protected]1b1a264a2010-01-14 22:36:35692 PRExplodedTime prxtime;
693 PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);
694
[email protected]4b559b4d2011-04-14 17:37:14695 base::Time::Exploded exploded;
[email protected]1b1a264a2010-01-14 22:36:35696 exploded.year = prxtime.tm_year;
697 exploded.month = prxtime.tm_month + 1;
698 exploded.day_of_week = prxtime.tm_wday;
699 exploded.day_of_month = prxtime.tm_mday;
700 exploded.hour = prxtime.tm_hour;
701 exploded.minute = prxtime.tm_min;
702 exploded.second = prxtime.tm_sec;
703 exploded.millisecond = prxtime.tm_usec / 1000;
704
[email protected]4b559b4d2011-04-14 17:37:14705 return base::Time::FromUTCExploded(exploded);
[email protected]1b1a264a2010-01-14 22:36:35706}
707
[email protected]6a89ef22011-04-07 17:34:21708PK11SlotInfo* GetPublicNSSKeySlot() {
709 return g_nss_singleton.Get().GetPublicNSSKeySlot();
710}
711
712PK11SlotInfo* GetPrivateNSSKeySlot() {
713 return g_nss_singleton.Get().GetPrivateNSSKeySlot();
[email protected]dcce6cf2010-04-29 17:50:06714}
715
[email protected]4b559b4d2011-04-14 17:37:14716} // namespace crypto