blob: dac0e223501ddcd367588682234d1f5f568a7b56 [file] [log] [blame]
[email protected]9fc44162012-01-23 22:56:411// Copyright (c) 2012 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]ea1a3f62012-11-16 20:34:239#include <pk11pub.h>
[email protected]c72f16a2009-03-19 16:02:3110#include <plarena.h>
[email protected]6e7e8062009-04-13 17:35:0911#include <prerror.h>
[email protected]c72f16a2009-03-19 16:02:3112#include <prinit.h>
[email protected]1b1a264a2010-01-14 22:36:3513#include <prtime.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>
[email protected]d816516f2011-10-25 19:11:5919#elif defined(OS_OPENBSD)
20#include <sys/mount.h>
21#include <sys/param.h>
[email protected]a8b58f42010-07-14 20:21:3522#endif
23
[email protected]f6a67b42011-03-17 23:49:2124#include <vector>
25
[email protected]716fb112012-11-15 05:41:2526#include "base/debug/alias.h"
[email protected]ed450f32011-03-16 01:26:4927#include "base/environment.h"
[email protected]f6a67b42011-03-17 23:49:2128#include "base/file_path.h"
[email protected]ea224582008-12-07 20:25:4629#include "base/file_util.h"
[email protected]ea1a3f62012-11-16 20:34:2330#include "base/files/scoped_temp_dir.h"
[email protected]f615bda32010-11-21 01:04:5631#include "base/lazy_instance.h"
[email protected]c1444fe2008-09-17 09:42:5132#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1533#include "base/memory/scoped_ptr.h"
[email protected]f6a67b42011-03-17 23:49:2134#include "base/native_library.h"
[email protected]f1633932010-08-17 23:05:2835#include "base/stringprintf.h"
[email protected]34b99632011-01-01 01:01:0636#include "base/threading/thread_restrictions.h"
[email protected]26661c22011-10-07 01:33:5837#include "build/build_config.h"
[email protected]bc1e07c72008-09-16 14:32:4438
[email protected]6e3d9a92011-09-07 04:01:0339#if defined(OS_CHROMEOS)
40#include "crypto/symmetric_key.h"
41#endif
42
[email protected]a8b58f42010-07-14 20:21:3543// USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not
44// defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
45// use NSS for crypto or certificate verification, and we don't use the NSS
46// certificate and key databases.
[email protected]69138472010-06-25 22:44:4847#if defined(USE_NSS)
[email protected]20305ec2011-01-21 04:55:5248#include "base/synchronization/lock.h"
[email protected]4b559b4d2011-04-14 17:37:1449#include "crypto/crypto_module_blocking_password_delegate.h"
[email protected]a8b58f42010-07-14 20:21:3550#endif // defined(USE_NSS)
[email protected]abd4aba2010-01-27 19:36:2251
[email protected]4b559b4d2011-04-14 17:37:1452namespace crypto {
[email protected]f1633932010-08-17 23:05:2853
[email protected]bc1e07c72008-09-16 14:32:4454namespace {
55
[email protected]6a89ef22011-04-07 17:34:2156#if defined(OS_CHROMEOS)
57const char kNSSDatabaseName[] = "Real NSS database";
58
[email protected]84e47722011-11-17 05:12:0259// Constants for loading the Chrome OS TPM-backed PKCS #11 library.
60const char kChapsModuleName[] = "Chaps";
61const char kChapsPath[] = "libchaps.so";
[email protected]6a89ef22011-04-07 17:34:2162
[email protected]6a89ef22011-04-07 17:34:2163// Fake certificate authority database used for testing.
64static const FilePath::CharType kReadOnlyCertDB[] =
65 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
66#endif // defined(OS_CHROMEOS)
67
68std::string GetNSSErrorMessage() {
69 std::string result;
70 if (PR_GetErrorTextLength()) {
71 scoped_array<char> error_text(new char[PR_GetErrorTextLength() + 1]);
72 PRInt32 copied = PR_GetErrorText(error_text.get());
73 result = std::string(error_text.get(), copied);
74 } else {
75 result = StringPrintf("NSS error code: %d", PR_GetError());
76 }
77 return result;
78}
79
[email protected]a8b58f42010-07-14 20:21:3580#if defined(USE_NSS)
81FilePath GetDefaultConfigDirectory() {
82 FilePath dir = file_util::GetHomeDir();
83 if (dir.empty()) {
84 LOG(ERROR) << "Failed to get home directory.";
85 return dir;
[email protected]86913342009-05-25 02:14:3486 }
[email protected]86913342009-05-25 02:14:3487 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
88 if (!file_util::CreateDirectory(dir)) {
[email protected]948a707b2011-06-07 22:51:4489 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
[email protected]a8b58f42010-07-14 20:21:3590 dir.clear();
[email protected]86913342009-05-25 02:14:3491 }
[email protected]a8b58f42010-07-14 20:21:3592 return dir;
[email protected]86913342009-05-25 02:14:3493}
94
[email protected]6e3d9a92011-09-07 04:01:0395#if defined(OS_CHROMEOS)
96// Supplemental user key id.
97unsigned char kSupplementalUserKeyId[] = {
98 0xCC, 0x13, 0x19, 0xDE, 0x75, 0x5E, 0xFE, 0xFA,
99 0x5E, 0x71, 0xD4, 0xA6, 0xFB, 0x00, 0x00, 0xCC
100};
101#endif // defined(OS_CHROMEOS)
102
103
[email protected]dcce6cf2010-04-29 17:50:06104// On non-chromeos platforms, return the default config directory.
105// On chromeos, return a read-only directory with fake root CA certs for testing
106// (which will not exist on non-testing images). These root CA certs are used
107// by the local Google Accounts server mock we use when testing our login code.
108// If this directory is not present, NSS_Init() will fail. It is up to the
109// caller to failover to NSS_NoDB_Init() at that point.
[email protected]a8b58f42010-07-14 20:21:35110FilePath GetInitialConfigDirectory() {
[email protected]dcce6cf2010-04-29 17:50:06111#if defined(OS_CHROMEOS)
[email protected]a8b58f42010-07-14 20:21:35112 return FilePath(kReadOnlyCertDB);
[email protected]dcce6cf2010-04-29 17:50:06113#else
114 return GetDefaultConfigDirectory();
115#endif // defined(OS_CHROMEOS)
116}
117
[email protected]88b9db72011-01-13 01:48:43118// This callback for NSS forwards all requests to a caller-specified
[email protected]3f1f8412011-01-19 03:01:23119// CryptoModuleBlockingPasswordDelegate object.
120char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
[email protected]6a89ef22011-04-07 17:34:21121#if defined(OS_CHROMEOS)
122 // If we get asked for a password for the TPM, then return the
[email protected]c64b9142011-04-19 18:49:54123 // well known password we use, as long as the TPM slot has been
124 // initialized.
125 if (crypto::IsTPMTokenReady()) {
126 std::string token_name;
127 std::string user_pin;
128 crypto::GetTPMTokenInfo(&token_name, &user_pin);
129 if (PK11_GetTokenName(slot) == token_name)
130 return PORT_Strdup(user_pin.c_str());
131 }
[email protected]6a89ef22011-04-07 17:34:21132#endif
[email protected]4b559b4d2011-04-14 17:37:14133 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
134 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
[email protected]88b9db72011-01-13 01:48:43135 if (delegate) {
136 bool cancelled = false;
137 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
138 retry != PR_FALSE,
139 &cancelled);
140 if (cancelled)
141 return NULL;
142 char* result = PORT_Strdup(password.c_str());
143 password.replace(0, password.size(), password.size(), 0);
144 return result;
145 }
146 DLOG(ERROR) << "PK11 password requested with NULL arg";
147 return NULL;
148}
149
[email protected]a8b58f42010-07-14 20:21:35150// NSS creates a local cache of the sqlite database if it detects that the
151// filesystem the database is on is much slower than the local disk. The
152// detection doesn't work with the latest versions of sqlite, such as 3.6.22
153// (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
154// the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
155// detection when database_dir is on NFS. See http://crbug.com/48585.
156//
157// TODO(wtc): port this function to other USE_NSS platforms. It is defined
[email protected]d816516f2011-10-25 19:11:59158// only for OS_LINUX and OS_OPENBSD simply because the statfs structure
159// is OS-specific.
[email protected]ac3d5972011-01-13 20:33:45160//
161// Because this function sets an environment variable it must be run before we
162// go multi-threaded.
[email protected]a8b58f42010-07-14 20:21:35163void UseLocalCacheOfNSSDatabaseIfNFS(const FilePath& database_dir) {
[email protected]d816516f2011-10-25 19:11:59164#if defined(OS_LINUX) || defined(OS_OPENBSD)
[email protected]a8b58f42010-07-14 20:21:35165 struct statfs buf;
166 if (statfs(database_dir.value().c_str(), &buf) == 0) {
[email protected]d816516f2011-10-25 19:11:59167#if defined(OS_LINUX)
[email protected]a8b58f42010-07-14 20:21:35168 if (buf.f_type == NFS_SUPER_MAGIC) {
[email protected]d816516f2011-10-25 19:11:59169#elif defined(OS_OPENBSD)
170 if (strcmp(buf.f_fstypename, MOUNT_NFS) == 0) {
171#endif
[email protected]4b559b4d2011-04-14 17:37:14172 scoped_ptr<base::Environment> env(base::Environment::Create());
[email protected]a8b58f42010-07-14 20:21:35173 const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
[email protected]9432ade2010-08-04 23:43:20174 if (!env->HasVar(use_cache_env_var))
[email protected]c87bcf002010-08-06 01:03:37175 env->SetVar(use_cache_env_var, "yes");
[email protected]a8b58f42010-07-14 20:21:35176 }
177 }
[email protected]d816516f2011-10-25 19:11:59178#endif // defined(OS_LINUX) || defined(OS_OPENBSD)
[email protected]a8b58f42010-07-14 20:21:35179}
180
[email protected]6a89ef22011-04-07 17:34:21181PK11SlotInfo* FindSlotWithTokenName(const std::string& token_name) {
182 AutoSECMODListReadLock auto_lock;
183 SECMODModuleList* head = SECMOD_GetDefaultModuleList();
184 for (SECMODModuleList* item = head; item != NULL; item = item->next) {
185 int slot_count = item->module->loaded ? item->module->slotCount : 0;
186 for (int i = 0; i < slot_count; i++) {
187 PK11SlotInfo* slot = item->module->slots[i];
188 if (PK11_GetTokenName(slot) == token_name)
189 return PK11_ReferenceSlot(slot);
190 }
191 }
[email protected]ea224582008-12-07 20:25:46192 return NULL;
193}
[email protected]6a89ef22011-04-07 17:34:21194
[email protected]a8b58f42010-07-14 20:21:35195#endif // defined(USE_NSS)
[email protected]ea224582008-12-07 20:25:46196
[email protected]730fb132009-09-02 22:50:25197// A singleton to initialize/deinitialize NSPR.
198// Separate from the NSS singleton because we initialize NSPR on the UI thread.
[email protected]f615bda32010-11-21 01:04:56199// Now that we're leaking the singleton, we could merge back with the NSS
200// singleton.
[email protected]730fb132009-09-02 22:50:25201class NSPRInitSingleton {
[email protected]f615bda32010-11-21 01:04:56202 private:
[email protected]4b559b4d2011-04-14 17:37:14203 friend struct base::DefaultLazyInstanceTraits<NSPRInitSingleton>;
[email protected]f615bda32010-11-21 01:04:56204
[email protected]730fb132009-09-02 22:50:25205 NSPRInitSingleton() {
206 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
207 }
208
[email protected]f615bda32010-11-21 01:04:56209 // NOTE(willchan): We don't actually execute this code since we leak NSS to
210 // prevent non-joinable threads from using NSS after it's already been shut
211 // down.
[email protected]730fb132009-09-02 22:50:25212 ~NSPRInitSingleton() {
[email protected]829296f2010-01-27 02:58:03213 PL_ArenaFinish();
[email protected]730fb132009-09-02 22:50:25214 PRStatus prstatus = PR_Cleanup();
[email protected]450b4ad72012-05-17 10:04:17215 if (prstatus != PR_SUCCESS)
[email protected]730fb132009-09-02 22:50:25216 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
[email protected]730fb132009-09-02 22:50:25217 }
218};
219
[email protected]9fc44162012-01-23 22:56:41220base::LazyInstance<NSPRInitSingleton>::Leaky
[email protected]6de0fd1d2011-11-15 13:31:49221 g_nspr_singleton = LAZY_INSTANCE_INITIALIZER;
[email protected]f615bda32010-11-21 01:04:56222
[email protected]02746292012-01-25 04:37:51223// This is a LazyInstance so that it will be deleted automatically when the
224// unittest exits. NSSInitSingleton is a LeakySingleton, so it would not be
225// deleted if it were a regular member.
[email protected]ea1a3f62012-11-16 20:34:23226base::LazyInstance<base::ScopedTempDir> g_test_nss_db_dir =
227 LAZY_INSTANCE_INITIALIZER;
[email protected]02746292012-01-25 04:37:51228
[email protected]716fb112012-11-15 05:41:25229// Force a crash to debug http://crbug.com/153281.
230void CrashWithErrors(int nss_error, int os_error) {
231 base::debug::Alias(&nss_error);
232 base::debug::Alias(&os_error);
[email protected]2b12459a2012-11-16 03:45:32233 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
[email protected]716fb112012-11-15 05:41:25234}
235
[email protected]bc1e07c72008-09-16 14:32:44236class NSSInitSingleton {
237 public:
[email protected]f615bda32010-11-21 01:04:56238#if defined(OS_CHROMEOS)
239 void OpenPersistentNSSDB() {
240 if (!chromeos_user_logged_in_) {
[email protected]61f93212011-01-24 14:37:08241 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
[email protected]6a89ef22011-04-07 17:34:21242 // Temporarily allow it until we fix http://crbug.com/70119
[email protected]4b559b4d2011-04-14 17:37:14243 base::ThreadRestrictions::ScopedAllowIO allow_io;
[email protected]f615bda32010-11-21 01:04:56244 chromeos_user_logged_in_ = true;
[email protected]6a89ef22011-04-07 17:34:21245
246 // This creates another DB slot in NSS that is read/write, unlike
247 // the fake root CA cert DB and the "default" crypto key
248 // provider, which are still read-only (because we initialized
249 // NSS before we had a cryptohome mounted).
250 software_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
[email protected]74beead2011-04-12 20:40:12251 kNSSDatabaseName);
[email protected]f615bda32010-11-21 01:04:56252 }
253 }
[email protected]6a89ef22011-04-07 17:34:21254
[email protected]450b4ad72012-05-17 10:04:17255 void EnableTPMTokenForNSS() {
256 tpm_token_enabled_for_nss_ = true;
[email protected]6a89ef22011-04-07 17:34:21257 }
258
[email protected]450b4ad72012-05-17 10:04:17259 bool InitializeTPMToken(const std::string& token_name,
260 const std::string& user_pin) {
261 // If EnableTPMTokenForNSS hasn't been called, return false.
262 if (!tpm_token_enabled_for_nss_)
263 return false;
[email protected]14172c82012-02-28 10:34:21264
[email protected]450b4ad72012-05-17 10:04:17265 // If everything is already initialized, then return true.
266 if (chaps_module_ && tpm_slot_)
267 return true;
268
269 tpm_token_name_ = token_name;
270 tpm_user_pin_ = user_pin;
271
272 // This tries to load the Chaps module so NSS can talk to the hardware
273 // TPM.
274 if (!chaps_module_) {
275 chaps_module_ = LoadModule(
276 kChapsModuleName,
277 kChapsPath,
278 // For more details on these parameters, see:
279 // https://developer.mozilla.org/en/PKCS11_Module_Specs
280 // slotFlags=[PublicCerts] -- Certificates and public keys can be
281 // read from this slot without requiring a call to C_Login.
282 // askpw=only -- Only authenticate to the token when necessary.
283 "NSS=\"slotParams=(0={slotFlags=[PublicCerts] askpw=only})\"");
[email protected]14172c82012-02-28 10:34:21284 }
[email protected]450b4ad72012-05-17 10:04:17285 if (chaps_module_){
286 // If this gets set, then we'll use the TPM for certs with
287 // private keys, otherwise we'll fall back to the software
288 // implementation.
289 tpm_slot_ = GetTPMSlot();
290
291 return tpm_slot_ != NULL;
292 }
293 return false;
[email protected]c175cdb2011-06-28 20:41:55294 }
295
[email protected]c64b9142011-04-19 18:49:54296 void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
[email protected]450b4ad72012-05-17 10:04:17297 if (!tpm_token_enabled_for_nss_) {
[email protected]7be616d42011-07-08 21:43:41298 LOG(ERROR) << "GetTPMTokenInfo called before TPM Token is ready.";
299 return;
300 }
[email protected]450b4ad72012-05-17 10:04:17301 if (token_name)
302 *token_name = tpm_token_name_;
303 if (user_pin)
304 *user_pin = tpm_user_pin_;
[email protected]6a89ef22011-04-07 17:34:21305 }
306
[email protected]c64b9142011-04-19 18:49:54307 bool IsTPMTokenReady() {
308 return tpm_slot_ != NULL;
[email protected]74beead2011-04-12 20:40:12309 }
310
[email protected]6a89ef22011-04-07 17:34:21311 PK11SlotInfo* GetTPMSlot() {
[email protected]c64b9142011-04-19 18:49:54312 std::string token_name;
313 GetTPMTokenInfo(&token_name, NULL);
314 return FindSlotWithTokenName(token_name);
[email protected]6a89ef22011-04-07 17:34:21315 }
[email protected]c175cdb2011-06-28 20:41:55316
[email protected]6e3d9a92011-09-07 04:01:03317 SymmetricKey* GetSupplementalUserKey() {
318 DCHECK(chromeos_user_logged_in_);
319
320 PK11SlotInfo* slot = NULL;
321 PK11SymKey* key = NULL;
322 SECItem keyID;
323 CK_MECHANISM_TYPE type = CKM_AES_ECB;
324
325 slot = GetPublicNSSKeySlot();
326 if (!slot)
327 goto done;
328
329 if (PK11_Authenticate(slot, PR_TRUE, NULL) != SECSuccess)
330 goto done;
331
332 keyID.type = siBuffer;
333 keyID.data = kSupplementalUserKeyId;
334 keyID.len = static_cast<int>(sizeof(kSupplementalUserKeyId));
335
336 // Find/generate AES key.
337 key = PK11_FindFixedKey(slot, type, &keyID, NULL);
338 if (!key) {
339 const int kKeySizeInBytes = 32;
340 key = PK11_TokenKeyGen(slot, type, NULL,
341 kKeySizeInBytes,
342 &keyID, PR_TRUE, NULL);
343 }
344
345 done:
346 if (slot)
347 PK11_FreeSlot(slot);
348
349 return key ? SymmetricKey::CreateFromKey(key) : NULL;
350 }
[email protected]f615bda32010-11-21 01:04:56351#endif // defined(OS_CHROMEOS)
352
[email protected]6a89ef22011-04-07 17:34:21353
[email protected]02746292012-01-25 04:37:51354 bool OpenTestNSSDB() {
355 if (test_slot_)
356 return true;
357 if (!g_test_nss_db_dir.Get().CreateUniqueTempDir())
358 return false;
359 test_slot_ = OpenUserDB(g_test_nss_db_dir.Get().path(), "Test DB");
[email protected]6a89ef22011-04-07 17:34:21360 return !!test_slot_;
[email protected]f615bda32010-11-21 01:04:56361 }
362
363 void CloseTestNSSDB() {
[email protected]6a89ef22011-04-07 17:34:21364 if (test_slot_) {
365 SECStatus status = SECMOD_CloseUserDB(test_slot_);
[email protected]f615bda32010-11-21 01:04:56366 if (status != SECSuccess)
[email protected]54df7392011-11-03 21:57:09367 PLOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
[email protected]6a89ef22011-04-07 17:34:21368 PK11_FreeSlot(test_slot_);
369 test_slot_ = NULL;
[email protected]02746292012-01-25 04:37:51370 ignore_result(g_test_nss_db_dir.Get().Delete());
[email protected]f615bda32010-11-21 01:04:56371 }
372 }
373
[email protected]6a89ef22011-04-07 17:34:21374 PK11SlotInfo* GetPublicNSSKeySlot() {
375 if (test_slot_)
376 return PK11_ReferenceSlot(test_slot_);
377 if (software_slot_)
378 return PK11_ReferenceSlot(software_slot_);
379 return PK11_GetInternalKeySlot();
380 }
381
382 PK11SlotInfo* GetPrivateNSSKeySlot() {
383 if (test_slot_)
384 return PK11_ReferenceSlot(test_slot_);
[email protected]c64b9142011-04-19 18:49:54385
386#if defined(OS_CHROMEOS)
[email protected]450b4ad72012-05-17 10:04:17387 if (tpm_token_enabled_for_nss_) {
[email protected]20ba9d82012-02-15 04:17:00388 if (IsTPMTokenReady()) {
[email protected]c64b9142011-04-19 18:49:54389 return PK11_ReferenceSlot(tpm_slot_);
390 } else {
391 // If we were supposed to get the hardware token, but were
392 // unable to, return NULL rather than fall back to sofware.
393 return NULL;
394 }
395 }
396#endif
397 // If we weren't supposed to enable the TPM for NSS, then return
398 // the software slot.
[email protected]6a89ef22011-04-07 17:34:21399 if (software_slot_)
400 return PK11_ReferenceSlot(software_slot_);
[email protected]f615bda32010-11-21 01:04:56401 return PK11_GetInternalKeySlot();
402 }
403
404#if defined(USE_NSS)
[email protected]4b559b4d2011-04-14 17:37:14405 base::Lock* write_lock() {
[email protected]f615bda32010-11-21 01:04:56406 return &write_lock_;
407 }
408#endif // defined(USE_NSS)
409
[email protected]ed450f32011-03-16 01:26:49410 // This method is used to force NSS to be initialized without a DB.
411 // Call this method before NSSInitSingleton() is constructed.
412 static void ForceNoDBInit() {
413 force_nodb_init_ = true;
414 }
415
[email protected]f615bda32010-11-21 01:04:56416 private:
[email protected]4b559b4d2011-04-14 17:37:14417 friend struct base::DefaultLazyInstanceTraits<NSSInitSingleton>;
[email protected]f615bda32010-11-21 01:04:56418
[email protected]dcce6cf2010-04-29 17:50:06419 NSSInitSingleton()
[email protected]450b4ad72012-05-17 10:04:17420 : tpm_token_enabled_for_nss_(false),
421 chaps_module_(NULL),
[email protected]6a89ef22011-04-07 17:34:21422 software_slot_(NULL),
423 test_slot_(NULL),
424 tpm_slot_(NULL),
[email protected]dcce6cf2010-04-29 17:50:06425 root_(NULL),
[email protected]450b4ad72012-05-17 10:04:17426 chromeos_user_logged_in_(false) {
[email protected]f615bda32010-11-21 01:04:56427 EnsureNSPRInit();
[email protected]730fb132009-09-02 22:50:25428
[email protected]dc36c9c2010-01-20 20:45:00429 // We *must* have NSS >= 3.12.3. See bug 26448.
430 COMPILE_ASSERT(
431 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
432 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
433 (NSS_VMAJOR > 3),
434 nss_version_check_failed);
435 // Also check the run-time NSS version.
436 // NSS_VersionCheck is a >= check, not strict equality.
[email protected]1b8082d2010-02-19 12:21:48437 if (!NSS_VersionCheck("3.12.3")) {
438 // It turns out many people have misconfigured NSS setups, where
439 // their run-time NSPR doesn't match the one their NSS was compiled
440 // against. So rather than aborting, complain loudly.
441 LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed. "
442 "We depend on NSS >= 3.12.3, and this error is not fatal "
443 "only because many people have busted NSS setups (for "
444 "example, using the wrong version of NSPR). "
445 "Please upgrade to the latest NSS and NSPR, and if you "
446 "still get this error, contact your distribution "
447 "maintainer.";
448 }
[email protected]dc36c9c2010-01-20 20:45:00449
[email protected]897f5202009-09-08 17:40:27450 SECStatus status = SECFailure;
[email protected]ed450f32011-03-16 01:26:49451 bool nodb_init = force_nodb_init_;
452
[email protected]a8b58f42010-07-14 20:21:35453#if !defined(USE_NSS)
[email protected]abd4aba2010-01-27 19:36:22454 // Use the system certificate store, so initialize NSS without database.
[email protected]ed450f32011-03-16 01:26:49455 nodb_init = true;
[email protected]dcce6cf2010-04-29 17:50:06456#endif
[email protected]ed450f32011-03-16 01:26:49457
458 if (nodb_init) {
[email protected]897f5202009-09-08 17:40:27459 status = NSS_NoDB_Init(NULL);
460 if (status != SECSuccess) {
[email protected]716fb112012-11-15 05:41:25461 // Force a crash with error info to debug http://crbug.com/153281.
462 int nss_error = PR_GetError();
463 int os_error = PR_GetOSError();
[email protected]897f5202009-09-08 17:40:27464 LOG(ERROR) << "Error initializing NSS without a persistent "
[email protected]6a89ef22011-04-07 17:34:21465 "database: " << GetNSSErrorMessage();
[email protected]716fb112012-11-15 05:41:25466 CrashWithErrors(nss_error, os_error);
467 return;
[email protected]897f5202009-09-08 17:40:27468 }
[email protected]a88f87e2012-08-14 19:46:28469#if defined(OS_IOS)
470 root_ = InitDefaultRootCerts();
471#endif // defined(OS_IOS)
[email protected]ed450f32011-03-16 01:26:49472 } else {
473#if defined(USE_NSS)
474 FilePath database_dir = GetInitialConfigDirectory();
475 if (!database_dir.empty()) {
476 // This duplicates the work which should have been done in
477 // EarlySetupForNSSInit. However, this function is idempotent so
478 // there's no harm done.
479 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
480
481 // Initialize with a persistent database (likely, ~/.pki/nssdb).
482 // Use "sql:" which can be shared by multiple processes safely.
483 std::string nss_config_dir =
484 StringPrintf("sql:%s", database_dir.value().c_str());
485#if defined(OS_CHROMEOS)
486 status = NSS_Init(nss_config_dir.c_str());
487#else
488 status = NSS_InitReadWrite(nss_config_dir.c_str());
489#endif
490 if (status != SECSuccess) {
491 LOG(ERROR) << "Error initializing NSS with a persistent "
492 "database (" << nss_config_dir
[email protected]6a89ef22011-04-07 17:34:21493 << "): " << GetNSSErrorMessage();
[email protected]ed450f32011-03-16 01:26:49494 }
495 }
496 if (status != SECSuccess) {
[email protected]6a89ef22011-04-07 17:34:21497 VLOG(1) << "Initializing NSS without a persistent database.";
[email protected]ed450f32011-03-16 01:26:49498 status = NSS_NoDB_Init(NULL);
499 if (status != SECSuccess) {
500 LOG(ERROR) << "Error initializing NSS without a persistent "
[email protected]6a89ef22011-04-07 17:34:21501 "database: " << GetNSSErrorMessage();
[email protected]ed450f32011-03-16 01:26:49502 return;
503 }
504 }
505
506 PK11_SetPasswordFunc(PKCS11PasswordFunc);
507
508 // If we haven't initialized the password for the NSS databases,
509 // initialize an empty-string password so that we don't need to
510 // log in.
511 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
512 if (slot) {
513 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
514 // yet, so we don't need to lock.
515 if (PK11_NeedUserInit(slot))
516 PK11_InitPin(slot, NULL, NULL);
517 PK11_FreeSlot(slot);
518 }
519
520 root_ = InitDefaultRootCerts();
[email protected]e83b2552012-10-19 23:57:45521
522 // MD5 certificate signatures are disabled by default in NSS 3.14.
523 // Enable MD5 certificate signatures until we figure out how to deal
524 // with the weak certificate signature unit tests.
525 NSS_SetAlgorithmPolicy(SEC_OID_MD5, NSS_USE_ALG_IN_CERT_SIGNATURE, 0);
[email protected]ed450f32011-03-16 01:26:49526#endif // defined(USE_NSS)
[email protected]6e7e8062009-04-13 17:35:09527 }
[email protected]bc1e07c72008-09-16 14:32:44528 }
529
[email protected]f615bda32010-11-21 01:04:56530 // NOTE(willchan): We don't actually execute this code since we leak NSS to
531 // prevent non-joinable threads from using NSS after it's already been shut
532 // down.
[email protected]bc1e07c72008-09-16 14:32:44533 ~NSSInitSingleton() {
[email protected]6a89ef22011-04-07 17:34:21534 if (tpm_slot_) {
535 PK11_FreeSlot(tpm_slot_);
536 tpm_slot_ = NULL;
537 }
538 if (software_slot_) {
539 SECMOD_CloseUserDB(software_slot_);
540 PK11_FreeSlot(software_slot_);
541 software_slot_ = NULL;
[email protected]dcce6cf2010-04-29 17:50:06542 }
[email protected]bb6390382010-08-12 19:49:40543 CloseTestNSSDB();
[email protected]ea224582008-12-07 20:25:46544 if (root_) {
545 SECMOD_UnloadUserModule(root_);
546 SECMOD_DestroyModule(root_);
547 root_ = NULL;
548 }
[email protected]84e47722011-11-17 05:12:02549 if (chaps_module_) {
550 SECMOD_UnloadUserModule(chaps_module_);
551 SECMOD_DestroyModule(chaps_module_);
552 chaps_module_ = NULL;
[email protected]6a89ef22011-04-07 17:34:21553 }
[email protected]ea224582008-12-07 20:25:46554
[email protected]c1444fe2008-09-17 09:42:51555 SECStatus status = NSS_Shutdown();
[email protected]f8adef52009-08-04 17:52:06556 if (status != SECSuccess) {
[email protected]b026e35d2010-10-19 02:31:03557 // We VLOG(1) because this failure is relatively harmless (leaking, but
558 // we're shutting down anyway).
[email protected]6a89ef22011-04-07 17:34:21559 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
[email protected]f8adef52009-08-04 17:52:06560 }
[email protected]bc1e07c72008-09-16 14:32:44561 }
[email protected]c72f16a2009-03-19 16:02:31562
[email protected]a88f87e2012-08-14 19:46:28563#if defined(USE_NSS) || defined(OS_IOS)
[email protected]6a89ef22011-04-07 17:34:21564 // Load nss's built-in root certs.
565 SECMODModule* InitDefaultRootCerts() {
566 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
567 if (root)
568 return root;
569
570 // Aw, snap. Can't find/load root cert shared library.
571 // This will make it hard to talk to anybody via https.
572 NOTREACHED();
573 return NULL;
574 }
575
576 // Load the given module for this NSS session.
577 SECMODModule* LoadModule(const char* name,
578 const char* library_path,
579 const char* params) {
580 std::string modparams = StringPrintf(
581 "name=\"%s\" library=\"%s\" %s",
582 name, library_path, params ? params : "");
583
584 // Shouldn't need to const_cast here, but SECMOD doesn't properly
585 // declare input string arguments as const. Bug
586 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
587 // on NSS codebase to address this.
588 SECMODModule* module = SECMOD_LoadUserModule(
589 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
590 if (!module) {
591 LOG(ERROR) << "Error loading " << name << " module into NSS: "
592 << GetNSSErrorMessage();
593 return NULL;
594 }
595 return module;
596 }
597#endif
598
[email protected]bb6390382010-08-12 19:49:40599 static PK11SlotInfo* OpenUserDB(const FilePath& path,
600 const char* description) {
601 const std::string modspec =
602 StringPrintf("configDir='sql:%s' tokenDescription='%s'",
603 path.value().c_str(), description);
604 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
605 if (db_slot) {
606 if (PK11_NeedUserInit(db_slot))
607 PK11_InitPin(db_slot, NULL, NULL);
608 }
609 else {
610 LOG(ERROR) << "Error opening persistent database (" << modspec
[email protected]6a89ef22011-04-07 17:34:21611 << "): " << GetNSSErrorMessage();
[email protected]bb6390382010-08-12 19:49:40612 }
613 return db_slot;
614 }
615
[email protected]ed450f32011-03-16 01:26:49616 // If this is set to true NSS is forced to be initialized without a DB.
617 static bool force_nodb_init_;
618
[email protected]450b4ad72012-05-17 10:04:17619 bool tpm_token_enabled_for_nss_;
620 std::string tpm_token_name_;
621 std::string tpm_user_pin_;
[email protected]84e47722011-11-17 05:12:02622 SECMODModule* chaps_module_;
[email protected]6a89ef22011-04-07 17:34:21623 PK11SlotInfo* software_slot_;
624 PK11SlotInfo* test_slot_;
625 PK11SlotInfo* tpm_slot_;
626 SECMODModule* root_;
[email protected]dcce6cf2010-04-29 17:50:06627 bool chromeos_user_logged_in_;
[email protected]69138472010-06-25 22:44:48628#if defined(USE_NSS)
[email protected]f615bda32010-11-21 01:04:56629 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
630 // is fixed, we will no longer need the lock.
[email protected]4b559b4d2011-04-14 17:37:14631 base::Lock write_lock_;
[email protected]a8b58f42010-07-14 20:21:35632#endif // defined(USE_NSS)
[email protected]bc1e07c72008-09-16 14:32:44633};
634
[email protected]ed450f32011-03-16 01:26:49635// static
636bool NSSInitSingleton::force_nodb_init_ = false;
637
[email protected]9fc44162012-01-23 22:56:41638base::LazyInstance<NSSInitSingleton>::Leaky
[email protected]6de0fd1d2011-11-15 13:31:49639 g_nss_singleton = LAZY_INSTANCE_INITIALIZER;
[email protected]bc1e07c72008-09-16 14:32:44640} // namespace
641
[email protected]ac3d5972011-01-13 20:33:45642#if defined(USE_NSS)
643void EarlySetupForNSSInit() {
644 FilePath database_dir = GetInitialConfigDirectory();
645 if (!database_dir.empty())
646 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
647}
648#endif
649
[email protected]730fb132009-09-02 22:50:25650void EnsureNSPRInit() {
[email protected]f615bda32010-11-21 01:04:56651 g_nspr_singleton.Get();
[email protected]730fb132009-09-02 22:50:25652}
653
[email protected]bc1e07c72008-09-16 14:32:44654void EnsureNSSInit() {
[email protected]a8e4b5a82010-10-27 00:05:47655 // Initializing SSL causes us to do blocking IO.
656 // Temporarily allow it until we fix
657 // http://code.google.com/p/chromium/issues/detail?id=59847
[email protected]4b559b4d2011-04-14 17:37:14658 base::ThreadRestrictions::ScopedAllowIO allow_io;
[email protected]f615bda32010-11-21 01:04:56659 g_nss_singleton.Get();
[email protected]bc1e07c72008-09-16 14:32:44660}
661
[email protected]ed450f32011-03-16 01:26:49662void ForceNSSNoDBInit() {
663 NSSInitSingleton::ForceNoDBInit();
664}
665
666void DisableNSSForkCheck() {
[email protected]4b559b4d2011-04-14 17:37:14667 scoped_ptr<base::Environment> env(base::Environment::Create());
[email protected]ed450f32011-03-16 01:26:49668 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
669}
670
[email protected]f6a67b42011-03-17 23:49:21671void LoadNSSLibraries() {
672 // Some NSS libraries are linked dynamically so load them here.
673#if defined(USE_NSS)
674 // Try to search for multiple directories to load the libraries.
675 std::vector<FilePath> paths;
676
677 // Use relative path to Search PATH for the library files.
678 paths.push_back(FilePath());
679
[email protected]26661c22011-10-07 01:33:58680 // For Debian derivatives NSS libraries are located here.
[email protected]f6a67b42011-03-17 23:49:21681 paths.push_back(FilePath("/usr/lib/nss"));
682
[email protected]26661c22011-10-07 01:33:58683 // Ubuntu 11.10 (Oneiric) places the libraries here.
684#if defined(ARCH_CPU_X86_64)
685 paths.push_back(FilePath("/usr/lib/x86_64-linux-gnu/nss"));
686#elif defined(ARCH_CPU_X86)
687 paths.push_back(FilePath("/usr/lib/i386-linux-gnu/nss"));
688#elif defined(ARCH_CPU_ARMEL)
689 paths.push_back(FilePath("/usr/lib/arm-linux-gnueabi/nss"));
690#endif
691
[email protected]f6a67b42011-03-17 23:49:21692 // A list of library files to load.
693 std::vector<std::string> libs;
694 libs.push_back("libsoftokn3.so");
695 libs.push_back("libfreebl3.so");
696
697 // For each combination of library file and path, check for existence and
698 // then load.
699 size_t loaded = 0;
700 for (size_t i = 0; i < libs.size(); ++i) {
701 for (size_t j = 0; j < paths.size(); ++j) {
702 FilePath path = paths[j].Append(libs[i]);
[email protected]84479322011-04-18 22:06:22703 base::NativeLibrary lib = base::LoadNativeLibrary(path, NULL);
[email protected]9f9b4f22011-04-08 21:57:46704 if (lib) {
705 ++loaded;
706 break;
[email protected]f6a67b42011-03-17 23:49:21707 }
708 }
709 }
710
711 if (loaded == libs.size()) {
712 VLOG(3) << "NSS libraries loaded.";
713 } else {
[email protected]26661c22011-10-07 01:33:58714 LOG(ERROR) << "Failed to load NSS libraries.";
[email protected]f6a67b42011-03-17 23:49:21715 }
716#endif
717}
718
[email protected]f61c3972010-12-23 09:54:15719bool CheckNSSVersion(const char* version) {
720 return !!NSS_VersionCheck(version);
721}
722
[email protected]69138472010-06-25 22:44:48723#if defined(USE_NSS)
[email protected]7025e932012-10-18 07:02:54724ScopedTestNSSDB::ScopedTestNSSDB()
725 : is_open_(g_nss_singleton.Get().OpenTestNSSDB()) {
726}
727
728ScopedTestNSSDB::~ScopedTestNSSDB() {
729 // TODO(mattm): Close the dababase once NSS 3.14 is required,
730 // which fixes https://bugzilla.mozilla.org/show_bug.cgi?id=588269
731 // Resource leaks are suppressed. http://crbug.com/156433 .
[email protected]bb6390382010-08-12 19:49:40732}
733
[email protected]4b559b4d2011-04-14 17:37:14734base::Lock* GetNSSWriteLock() {
[email protected]f615bda32010-11-21 01:04:56735 return g_nss_singleton.Get().write_lock();
[email protected]69138472010-06-25 22:44:48736}
737
738AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
739 // May be NULL if the lock is not needed in our version of NSS.
740 if (lock_)
741 lock_->Acquire();
742}
743
744AutoNSSWriteLock::~AutoNSSWriteLock() {
745 if (lock_) {
746 lock_->AssertAcquired();
747 lock_->Release();
748 }
749}
[email protected]dd24ffc2011-06-08 19:46:42750
751AutoSECMODListReadLock::AutoSECMODListReadLock()
752 : lock_(SECMOD_GetDefaultModuleListLock()) {
753 SECMOD_GetReadLock(lock_);
754 }
755
756AutoSECMODListReadLock::~AutoSECMODListReadLock() {
757 SECMOD_ReleaseReadLock(lock_);
758}
759
[email protected]69138472010-06-25 22:44:48760#endif // defined(USE_NSS)
761
[email protected]dcce6cf2010-04-29 17:50:06762#if defined(OS_CHROMEOS)
763void OpenPersistentNSSDB() {
[email protected]f615bda32010-11-21 01:04:56764 g_nss_singleton.Get().OpenPersistentNSSDB();
[email protected]dcce6cf2010-04-29 17:50:06765}
[email protected]6a89ef22011-04-07 17:34:21766
[email protected]450b4ad72012-05-17 10:04:17767void EnableTPMTokenForNSS() {
768 g_nss_singleton.Get().EnableTPMTokenForNSS();
[email protected]6a89ef22011-04-07 17:34:21769}
770
[email protected]c64b9142011-04-19 18:49:54771void GetTPMTokenInfo(std::string* token_name, std::string* user_pin) {
772 g_nss_singleton.Get().GetTPMTokenInfo(token_name, user_pin);
[email protected]6a89ef22011-04-07 17:34:21773}
[email protected]74beead2011-04-12 20:40:12774
[email protected]c64b9142011-04-19 18:49:54775bool IsTPMTokenReady() {
776 return g_nss_singleton.Get().IsTPMTokenReady();
[email protected]74beead2011-04-12 20:40:12777}
[email protected]c64b9142011-04-19 18:49:54778
[email protected]450b4ad72012-05-17 10:04:17779bool InitializeTPMToken(const std::string& token_name,
780 const std::string& user_pin) {
781 return g_nss_singleton.Get().InitializeTPMToken(token_name, user_pin);
[email protected]c175cdb2011-06-28 20:41:55782}
783
[email protected]6e3d9a92011-09-07 04:01:03784SymmetricKey* GetSupplementalUserKey() {
785 return g_nss_singleton.Get().GetSupplementalUserKey();
786}
[email protected]6a89ef22011-04-07 17:34:21787#endif // defined(OS_CHROMEOS)
[email protected]dcce6cf2010-04-29 17:50:06788
[email protected]4b559b4d2011-04-14 17:37:14789base::Time PRTimeToBaseTime(PRTime prtime) {
[email protected]ca929ed32011-12-15 20:37:28790 return base::Time::FromInternalValue(
791 prtime + base::Time::UnixEpoch().ToInternalValue());
792}
[email protected]1b1a264a2010-01-14 22:36:35793
[email protected]ca929ed32011-12-15 20:37:28794PRTime BaseTimeToPRTime(base::Time time) {
795 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
[email protected]1b1a264a2010-01-14 22:36:35796}
797
[email protected]6a89ef22011-04-07 17:34:21798PK11SlotInfo* GetPublicNSSKeySlot() {
799 return g_nss_singleton.Get().GetPublicNSSKeySlot();
800}
801
802PK11SlotInfo* GetPrivateNSSKeySlot() {
803 return g_nss_singleton.Get().GetPrivateNSSKeySlot();
[email protected]dcce6cf2010-04-29 17:50:06804}
805
[email protected]4b559b4d2011-04-14 17:37:14806} // namespace crypto