Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(433)

Side by Side Diff: base/nss_util.cc

Issue 6667020: This change loads opencryptoki and uses the TPM for keygen tags. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: adding missing args in unit tests Created 9 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « base/nss_util.h ('k') | base/nss_util_internal.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/nss_util.h" 5 #include "base/nss_util.h"
6 #include "base/nss_util_internal.h" 6 #include "base/nss_util_internal.h"
7 7
8 #include <nss.h> 8 #include <nss.h>
9 #include <plarena.h> 9 #include <plarena.h>
10 #include <prerror.h> 10 #include <prerror.h>
11 #include <prinit.h> 11 #include <prinit.h>
12 #include <prtime.h> 12 #include <prtime.h>
13 #include <pk11pub.h> 13 #include <pk11pub.h>
14 #include <secmod.h> 14 #include <secmod.h>
15 15
16 #if defined(OS_LINUX) 16 #if defined(OS_LINUX)
17 #include <linux/nfs_fs.h> 17 #include <linux/nfs_fs.h>
18 #include <sys/vfs.h> 18 #include <sys/vfs.h>
19 #endif 19 #endif
20 20
21 #include <vector> 21 #include <vector>
22 22
23 #include "base/crypto/scoped_nss_types.h"
23 #include "base/environment.h" 24 #include "base/environment.h"
24 #include "base/file_path.h" 25 #include "base/file_path.h"
25 #include "base/file_util.h" 26 #include "base/file_util.h"
26 #include "base/lazy_instance.h" 27 #include "base/lazy_instance.h"
27 #include "base/logging.h" 28 #include "base/logging.h"
28 #include "base/memory/scoped_ptr.h" 29 #include "base/memory/scoped_ptr.h"
29 #include "base/native_library.h" 30 #include "base/native_library.h"
30 #include "base/stringprintf.h" 31 #include "base/stringprintf.h"
31 #include "base/threading/thread_restrictions.h" 32 #include "base/threading/thread_restrictions.h"
32 33
33 // USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not 34 // USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not
34 // defined, such as on Mac and Windows, we use NSS for SSL only -- we don't 35 // defined, such as on Mac and Windows, we use NSS for SSL only -- we don't
35 // use NSS for crypto or certificate verification, and we don't use the NSS 36 // use NSS for crypto or certificate verification, and we don't use the NSS
36 // certificate and key databases. 37 // certificate and key databases.
37 #if defined(USE_NSS) 38 #if defined(USE_NSS)
38 #include "base/crypto/crypto_module_blocking_password_delegate.h" 39 #include "base/crypto/crypto_module_blocking_password_delegate.h"
39 #include "base/synchronization/lock.h" 40 #include "base/synchronization/lock.h"
40 #endif // defined(USE_NSS) 41 #endif // defined(USE_NSS)
41 42
42 namespace base { 43 namespace base {
43 44
44 namespace { 45 namespace {
45 46
47 #if defined(OS_CHROMEOS)
48 static const char kNSSDatabaseName[] = "Real NSS database";
49
50 // TODO(gspencer): Get these values from cryptohomed's dbus API when
51 // we ask if it has initialized the TPM yet. These should not be
52 // hard-coded here.
53 static const char kTPMTokenName[] = "Initialized by CrOS";
54 static const char kTPMUserPIN[] = "111111";
55 static const char kTPMSecurityOfficerPIN[] = "000000";
56
57 // Fake certificate authority database used for testing.
58 static const FilePath::CharType kReadOnlyCertDB[] =
59 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
60 #endif // defined(OS_CHROMEOS)
61
62 std::string GetNSSErrorMessage() {
63 std::string result;
64 if (PR_GetErrorTextLength()) {
65 scoped_array<char> error_text(new char[PR_GetErrorTextLength() + 1]);
66 PRInt32 copied = PR_GetErrorText(error_text.get());
67 result = std::string(error_text.get(), copied);
68 } else {
69 result = StringPrintf("NSS error code: %d", PR_GetError());
70 }
71 return result;
72 }
73
46 #if defined(USE_NSS) 74 #if defined(USE_NSS)
47 FilePath GetDefaultConfigDirectory() { 75 FilePath GetDefaultConfigDirectory() {
48 FilePath dir = file_util::GetHomeDir(); 76 FilePath dir = file_util::GetHomeDir();
49 if (dir.empty()) { 77 if (dir.empty()) {
50 LOG(ERROR) << "Failed to get home directory."; 78 LOG(ERROR) << "Failed to get home directory.";
51 return dir; 79 return dir;
52 } 80 }
53 dir = dir.AppendASCII(".pki").AppendASCII("nssdb"); 81 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
54 if (!file_util::CreateDirectory(dir)) { 82 if (!file_util::CreateDirectory(dir)) {
55 LOG(ERROR) << "Failed to create ~/.pki/nssdb directory."; 83 LOG(ERROR) << "Failed to create ~/.pki/nssdb directory.";
56 dir.clear(); 84 dir.clear();
57 } 85 }
58 return dir; 86 return dir;
59 } 87 }
60 88
61 // On non-chromeos platforms, return the default config directory. 89 // On non-chromeos platforms, return the default config directory.
62 // On chromeos, return a read-only directory with fake root CA certs for testing 90 // On chromeos, return a read-only directory with fake root CA certs for testing
63 // (which will not exist on non-testing images). These root CA certs are used 91 // (which will not exist on non-testing images). These root CA certs are used
64 // by the local Google Accounts server mock we use when testing our login code. 92 // by the local Google Accounts server mock we use when testing our login code.
65 // If this directory is not present, NSS_Init() will fail. It is up to the 93 // If this directory is not present, NSS_Init() will fail. It is up to the
66 // caller to failover to NSS_NoDB_Init() at that point. 94 // caller to failover to NSS_NoDB_Init() at that point.
67 FilePath GetInitialConfigDirectory() { 95 FilePath GetInitialConfigDirectory() {
68 #if defined(OS_CHROMEOS) 96 #if defined(OS_CHROMEOS)
69 static const FilePath::CharType kReadOnlyCertDB[] =
70 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
71 return FilePath(kReadOnlyCertDB); 97 return FilePath(kReadOnlyCertDB);
72 #else 98 #else
73 return GetDefaultConfigDirectory(); 99 return GetDefaultConfigDirectory();
74 #endif // defined(OS_CHROMEOS) 100 #endif // defined(OS_CHROMEOS)
75 } 101 }
76 102
77 // This callback for NSS forwards all requests to a caller-specified 103 // This callback for NSS forwards all requests to a caller-specified
78 // CryptoModuleBlockingPasswordDelegate object. 104 // CryptoModuleBlockingPasswordDelegate object.
79 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) { 105 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
106 #if defined(OS_CHROMEOS)
107 // If we get asked for a password for the TPM, then return the
108 // static password we use.
109 if (PK11_GetTokenName(slot) == base::GetTPMTokenName())
110 return PORT_Strdup(kTPMUserPIN);
111 #endif
80 base::CryptoModuleBlockingPasswordDelegate* delegate = 112 base::CryptoModuleBlockingPasswordDelegate* delegate =
81 reinterpret_cast<base::CryptoModuleBlockingPasswordDelegate*>(arg); 113 reinterpret_cast<base::CryptoModuleBlockingPasswordDelegate*>(arg);
82 if (delegate) { 114 if (delegate) {
83 bool cancelled = false; 115 bool cancelled = false;
84 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot), 116 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
85 retry != PR_FALSE, 117 retry != PR_FALSE,
86 &cancelled); 118 &cancelled);
87 if (cancelled) 119 if (cancelled)
88 return NULL; 120 return NULL;
89 char* result = PORT_Strdup(password.c_str()); 121 char* result = PORT_Strdup(password.c_str());
(...skipping 23 matching lines...) Expand all
113 if (buf.f_type == NFS_SUPER_MAGIC) { 145 if (buf.f_type == NFS_SUPER_MAGIC) {
114 scoped_ptr<Environment> env(Environment::Create()); 146 scoped_ptr<Environment> env(Environment::Create());
115 const char* use_cache_env_var = "NSS_SDB_USE_CACHE"; 147 const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
116 if (!env->HasVar(use_cache_env_var)) 148 if (!env->HasVar(use_cache_env_var))
117 env->SetVar(use_cache_env_var, "yes"); 149 env->SetVar(use_cache_env_var, "yes");
118 } 150 }
119 } 151 }
120 #endif // defined(OS_LINUX) 152 #endif // defined(OS_LINUX)
121 } 153 }
122 154
123 // Load nss's built-in root certs. 155 // A helper class that acquires the SECMOD list read lock while the
124 SECMODModule *InitDefaultRootCerts() { 156 // AutoSECMODListReadLock is in scope.
125 const char* kModulePath = "libnssckbi.so"; 157 class AutoSECMODListReadLock {
126 char modparams[1024]; 158 public:
127 snprintf(modparams, sizeof(modparams), 159 AutoSECMODListReadLock()
128 "name=\"Root Certs\" library=\"%s\"", kModulePath); 160 : lock_(SECMOD_GetDefaultModuleListLock()) {
129 SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE); 161 SECMOD_GetReadLock(lock_);
130 if (root) 162 }
131 return root;
132 163
133 // Aw, snap. Can't find/load root cert shared library. 164 ~AutoSECMODListReadLock() {
134 // This will make it hard to talk to anybody via https. 165 SECMOD_ReleaseReadLock(lock_);
135 NOTREACHED(); 166 }
167
168 private:
169 SECMODListLock* lock_;
170 DISALLOW_COPY_AND_ASSIGN(AutoSECMODListReadLock);
171 };
172
173 PK11SlotInfo* FindSlotWithTokenName(const std::string& token_name) {
174 AutoSECMODListReadLock auto_lock;
175 SECMODModuleList* head = SECMOD_GetDefaultModuleList();
176 for (SECMODModuleList* item = head; item != NULL; item = item->next) {
177 int slot_count = item->module->loaded ? item->module->slotCount : 0;
178 for (int i = 0; i < slot_count; i++) {
179 PK11SlotInfo* slot = item->module->slots[i];
180 if (PK11_GetTokenName(slot) == token_name)
181 return PK11_ReferenceSlot(slot);
182 }
183 }
136 return NULL; 184 return NULL;
137 } 185 }
186
138 #endif // defined(USE_NSS) 187 #endif // defined(USE_NSS)
139 188
140 // A singleton to initialize/deinitialize NSPR. 189 // A singleton to initialize/deinitialize NSPR.
141 // Separate from the NSS singleton because we initialize NSPR on the UI thread. 190 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
142 // Now that we're leaking the singleton, we could merge back with the NSS 191 // Now that we're leaking the singleton, we could merge back with the NSS
143 // singleton. 192 // singleton.
144 class NSPRInitSingleton { 193 class NSPRInitSingleton {
145 private: 194 private:
146 friend struct DefaultLazyInstanceTraits<NSPRInitSingleton>; 195 friend struct DefaultLazyInstanceTraits<NSPRInitSingleton>;
147 196
(...skipping 12 matching lines...) Expand all
160 } 209 }
161 } 210 }
162 }; 211 };
163 212
164 LazyInstance<NSPRInitSingleton, LeakyLazyInstanceTraits<NSPRInitSingleton> > 213 LazyInstance<NSPRInitSingleton, LeakyLazyInstanceTraits<NSPRInitSingleton> >
165 g_nspr_singleton(LINKER_INITIALIZED); 214 g_nspr_singleton(LINKER_INITIALIZED);
166 215
167 class NSSInitSingleton { 216 class NSSInitSingleton {
168 public: 217 public:
169 #if defined(OS_CHROMEOS) 218 #if defined(OS_CHROMEOS)
170 void OpenPersistentNSSDB() { 219 void OpenPersistentNSSDB(bool load_opencryptoki) {
171 if (!chromeos_user_logged_in_) { 220 if (!chromeos_user_logged_in_) {
172 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread. 221 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
173 // Temporarily allow it until we fix http://crbug.com.70119 222 // Temporarily allow it until we fix http://crbug.com/70119
174 ThreadRestrictions::ScopedAllowIO allow_io; 223 ThreadRestrictions::ScopedAllowIO allow_io;
175 chromeos_user_logged_in_ = true; 224 chromeos_user_logged_in_ = true;
176 real_db_slot_ = OpenUserDB(GetDefaultConfigDirectory(), 225
177 "Real NSS database"); 226 // This creates a third DB slot in NSS that is read/write, unlike
227 // the fake root CA cert DB and the "default" crypto key
228 // provider, which are still read-only (because we initialized
229 // NSS before we had a cryptohome mounted).
230 real_db_slot_ = OpenUserDB(GetDefaultConfigDirectory(), kNSSDatabaseName);
231 }
232 if (!opencryptoki_module_ && load_opencryptoki) {
233 // This loads the opencryptoki module so we can talk to the
234 // hardware TPM.
235 opencryptoki_module_ = LoadModule(
236 "opencryptoki",
237 "/usr/lib/opencryptoki/libopencryptoki.so",
stevenjb 2011/04/05 23:57:25 nit: Maybe define this as a constant at the top of
238 // trustOrder=100 -- means it'll select this as the most
239 // trusted slot for the mechanisms it provides.
240 // slotParams=... -- selects RSA as only mechanism, and only
241 // asks for the password when necessary (instead of every
242 // time, or after a timeout).
243 "trustOrder=100 slotParams=(1={slotFlags=[RSA] askpw=only})");
244 if (opencryptoki_module_) {
245 // We shouldn't need to initialize the TPM PIN here because
246 // it'll be taken care of by cryptohomed, but we have to make
247 // sure that it is initialized.
248
249 // TODO(gspencer): replace this with a dbus call to check and
250 // see that cryptohomed has initialized the PINs already.
stevenjb 2011/04/05 23:57:25 We probably want the DBUS calls in a function, so
251 EnsureTPMInit();
252 }
178 } 253 }
179 } 254 }
255
256 std::string GetTPMTokenName() {
257 // TODO(gspencer): This should come from the dbus interchange with
258 // cryptohomed instead of being hard-coded.
259 return std::string(kTPMTokenName);
stevenjb 2011/04/05 23:57:25 This should be provided to the callback passed to
260 }
261
262 PK11SlotInfo* GetTPMSlot() {
263 return FindSlotWithTokenName(GetTPMTokenName());
264 }
180 #endif // defined(OS_CHROMEOS) 265 #endif // defined(OS_CHROMEOS)
181 266
267
182 bool OpenTestNSSDB(const FilePath& path, const char* description) { 268 bool OpenTestNSSDB(const FilePath& path, const char* description) {
183 test_db_slot_ = OpenUserDB(path, description); 269 test_db_slot_ = OpenUserDB(path, description);
184 return !!test_db_slot_; 270 return !!test_db_slot_;
185 } 271 }
186 272
187 void CloseTestNSSDB() { 273 void CloseTestNSSDB() {
188 if (test_db_slot_) { 274 if (test_db_slot_) {
189 SECStatus status = SECMOD_CloseUserDB(test_db_slot_); 275 SECStatus status = SECMOD_CloseUserDB(test_db_slot_);
190 if (status != SECSuccess) 276 if (status != SECSuccess)
191 LOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError(); 277 LOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
192 PK11_FreeSlot(test_db_slot_); 278 PK11_FreeSlot(test_db_slot_);
193 test_db_slot_ = NULL; 279 test_db_slot_ = NULL;
194 } 280 }
195 } 281 }
196 282
197 PK11SlotInfo* GetDefaultKeySlot() { 283 PK11SlotInfo* GetDefaultNSSKeySlot() {
198 if (test_db_slot_) 284 if (test_db_slot_)
199 return PK11_ReferenceSlot(test_db_slot_); 285 return PK11_ReferenceSlot(test_db_slot_);
200 if (real_db_slot_) 286 if (real_db_slot_)
201 return PK11_ReferenceSlot(real_db_slot_); 287 return PK11_ReferenceSlot(real_db_slot_);
202 return PK11_GetInternalKeySlot(); 288 return PK11_GetInternalKeySlot();
203 } 289 }
204 290
205 #if defined(USE_NSS) 291 #if defined(USE_NSS)
206 Lock* write_lock() { 292 Lock* write_lock() {
207 return &write_lock_; 293 return &write_lock_;
208 } 294 }
209 #endif // defined(USE_NSS) 295 #endif // defined(USE_NSS)
210 296
211 // This method is used to force NSS to be initialized without a DB. 297 // This method is used to force NSS to be initialized without a DB.
212 // Call this method before NSSInitSingleton() is constructed. 298 // Call this method before NSSInitSingleton() is constructed.
213 static void ForceNoDBInit() { 299 static void ForceNoDBInit() {
214 force_nodb_init_ = true; 300 force_nodb_init_ = true;
215 } 301 }
216 302
217 private: 303 private:
218 friend struct DefaultLazyInstanceTraits<NSSInitSingleton>; 304 friend struct DefaultLazyInstanceTraits<NSSInitSingleton>;
219 305
220 NSSInitSingleton() 306 NSSInitSingleton()
221 : real_db_slot_(NULL), 307 : real_db_slot_(NULL),
222 test_db_slot_(NULL), 308 test_db_slot_(NULL),
223 root_(NULL), 309 root_(NULL),
310 opencryptoki_module_(NULL),
224 chromeos_user_logged_in_(false) { 311 chromeos_user_logged_in_(false) {
225 EnsureNSPRInit(); 312 EnsureNSPRInit();
226 313
227 // We *must* have NSS >= 3.12.3. See bug 26448. 314 // We *must* have NSS >= 3.12.3. See bug 26448.
228 COMPILE_ASSERT( 315 COMPILE_ASSERT(
229 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) || 316 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
230 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) || 317 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
231 (NSS_VMAJOR > 3), 318 (NSS_VMAJOR > 3),
232 nss_version_check_failed); 319 nss_version_check_failed);
233 // Also check the run-time NSS version. 320 // Also check the run-time NSS version.
(...skipping 16 matching lines...) Expand all
250 337
251 #if !defined(USE_NSS) 338 #if !defined(USE_NSS)
252 // Use the system certificate store, so initialize NSS without database. 339 // Use the system certificate store, so initialize NSS without database.
253 nodb_init = true; 340 nodb_init = true;
254 #endif 341 #endif
255 342
256 if (nodb_init) { 343 if (nodb_init) {
257 status = NSS_NoDB_Init(NULL); 344 status = NSS_NoDB_Init(NULL);
258 if (status != SECSuccess) { 345 if (status != SECSuccess) {
259 LOG(ERROR) << "Error initializing NSS without a persistent " 346 LOG(ERROR) << "Error initializing NSS without a persistent "
260 "database: NSS error code " << PR_GetError(); 347 "database: " << GetNSSErrorMessage();
261 } 348 }
262 } else { 349 } else {
263 #if defined(USE_NSS) 350 #if defined(USE_NSS)
264 FilePath database_dir = GetInitialConfigDirectory(); 351 FilePath database_dir = GetInitialConfigDirectory();
265 if (!database_dir.empty()) { 352 if (!database_dir.empty()) {
266 // This duplicates the work which should have been done in 353 // This duplicates the work which should have been done in
267 // EarlySetupForNSSInit. However, this function is idempotent so 354 // EarlySetupForNSSInit. However, this function is idempotent so
268 // there's no harm done. 355 // there's no harm done.
269 UseLocalCacheOfNSSDatabaseIfNFS(database_dir); 356 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
270 357
271 // Initialize with a persistent database (likely, ~/.pki/nssdb). 358 // Initialize with a persistent database (likely, ~/.pki/nssdb).
272 // Use "sql:" which can be shared by multiple processes safely. 359 // Use "sql:" which can be shared by multiple processes safely.
273 std::string nss_config_dir = 360 std::string nss_config_dir =
274 StringPrintf("sql:%s", database_dir.value().c_str()); 361 StringPrintf("sql:%s", database_dir.value().c_str());
275 #if defined(OS_CHROMEOS) 362 #if defined(OS_CHROMEOS)
276 status = NSS_Init(nss_config_dir.c_str()); 363 status = NSS_Init(nss_config_dir.c_str());
277 #else 364 #else
278 status = NSS_InitReadWrite(nss_config_dir.c_str()); 365 status = NSS_InitReadWrite(nss_config_dir.c_str());
279 #endif 366 #endif
280 if (status != SECSuccess) { 367 if (status != SECSuccess) {
281 LOG(ERROR) << "Error initializing NSS with a persistent " 368 LOG(ERROR) << "Error initializing NSS with a persistent "
282 "database (" << nss_config_dir 369 "database (" << nss_config_dir
283 << "): NSS error code " << PR_GetError(); 370 << "): " << GetNSSErrorMessage();
284 } 371 }
285 } 372 }
286 if (status != SECSuccess) { 373 if (status != SECSuccess) {
287 LOG(WARNING) << "Initialize NSS without a persistent database " 374 VLOG(1) << "Initializing NSS without a persistent database.";
288 "(~/.pki/nssdb).";
289 status = NSS_NoDB_Init(NULL); 375 status = NSS_NoDB_Init(NULL);
290 if (status != SECSuccess) { 376 if (status != SECSuccess) {
291 LOG(ERROR) << "Error initializing NSS without a persistent " 377 LOG(ERROR) << "Error initializing NSS without a persistent "
292 "database: NSS error code " << PR_GetError(); 378 "database: " << GetNSSErrorMessage();
293 return; 379 return;
294 } 380 }
295 } 381 }
296 382
297 PK11_SetPasswordFunc(PKCS11PasswordFunc); 383 PK11_SetPasswordFunc(PKCS11PasswordFunc);
298 384
299 // If we haven't initialized the password for the NSS databases, 385 // If we haven't initialized the password for the NSS databases,
300 // initialize an empty-string password so that we don't need to 386 // initialize an empty-string password so that we don't need to
301 // log in. 387 // log in.
302 PK11SlotInfo* slot = PK11_GetInternalKeySlot(); 388 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
(...skipping 18 matching lines...) Expand all
321 SECMOD_CloseUserDB(real_db_slot_); 407 SECMOD_CloseUserDB(real_db_slot_);
322 PK11_FreeSlot(real_db_slot_); 408 PK11_FreeSlot(real_db_slot_);
323 real_db_slot_ = NULL; 409 real_db_slot_ = NULL;
324 } 410 }
325 CloseTestNSSDB(); 411 CloseTestNSSDB();
326 if (root_) { 412 if (root_) {
327 SECMOD_UnloadUserModule(root_); 413 SECMOD_UnloadUserModule(root_);
328 SECMOD_DestroyModule(root_); 414 SECMOD_DestroyModule(root_);
329 root_ = NULL; 415 root_ = NULL;
330 } 416 }
417 if (opencryptoki_module_) {
418 SECMOD_UnloadUserModule(opencryptoki_module_);
419 SECMOD_DestroyModule(opencryptoki_module_);
420 opencryptoki_module_ = NULL;
421 }
331 422
332 SECStatus status = NSS_Shutdown(); 423 SECStatus status = NSS_Shutdown();
333 if (status != SECSuccess) { 424 if (status != SECSuccess) {
334 // We VLOG(1) because this failure is relatively harmless (leaking, but 425 // We VLOG(1) because this failure is relatively harmless (leaking, but
335 // we're shutting down anyway). 426 // we're shutting down anyway).
336 VLOG(1) << "NSS_Shutdown failed; see " 427 VLOG(1) << "NSS_Shutdown failed; see http://crbug.com/4609";
337 "http://code.google.com/p/chromium/issues/detail?id=4609";
338 } 428 }
339 } 429 }
340 430
431 #if defined(USE_NSS)
432 // Load nss's built-in root certs.
433 SECMODModule* InitDefaultRootCerts() {
434 SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
435 if (root)
436 return root;
437
438 // Aw, snap. Can't find/load root cert shared library.
439 // This will make it hard to talk to anybody via https.
440 NOTREACHED();
441 return NULL;
442 }
443
444 // Load the given module for this NSS session.
445 SECMODModule* LoadModule(const char* name,
446 const char* library_path,
447 const char* params) {
448 std::string modparams = StringPrintf(
449 "name=\"%s\" library=\"%s\" %s",
450 name, library_path, params ? params : "");
451
452 // Shouldn't need to const_cast here, but SECMOD doesn't properly
453 // declare input string arguments as const. Bug
454 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
455 // on NSS codebase to address this.
456 SECMODModule* module = SECMOD_LoadUserModule(
457 const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
458 if (!module) {
459 LOG(ERROR) << "Error loading " << name << " module into NSS: "
460 << GetNSSErrorMessage();
461 return NULL;
462 }
463 return module;
464 }
465 #endif
466
467 #if defined(OS_CHROMEOS)
468 void EnsureTPMInit() {
469 base::ScopedPK11Slot tpm_slot(GetTPMSlot());
470 if (tpm_slot.get()) {
471 // TODO(gspencer): Remove this in favor of the dbus API for
472 // cryptohomed when that is available.
473 if (PK11_NeedUserInit(tpm_slot.get())) {
474 PK11_InitPin(tpm_slot.get(),
475 kTPMSecurityOfficerPIN,
476 kTPMUserPIN);
477 }
478 }
479 }
480 #endif
481
341 static PK11SlotInfo* OpenUserDB(const FilePath& path, 482 static PK11SlotInfo* OpenUserDB(const FilePath& path,
342 const char* description) { 483 const char* description) {
343 const std::string modspec = 484 const std::string modspec =
344 StringPrintf("configDir='sql:%s' tokenDescription='%s'", 485 StringPrintf("configDir='sql:%s' tokenDescription='%s'",
345 path.value().c_str(), description); 486 path.value().c_str(), description);
346 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str()); 487 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
347 if (db_slot) { 488 if (db_slot) {
348 if (PK11_NeedUserInit(db_slot)) 489 if (PK11_NeedUserInit(db_slot))
349 PK11_InitPin(db_slot, NULL, NULL); 490 PK11_InitPin(db_slot, NULL, NULL);
350 } 491 }
351 else { 492 else {
352 LOG(ERROR) << "Error opening persistent database (" << modspec 493 LOG(ERROR) << "Error opening persistent database (" << modspec
353 << "): NSS error code " << PR_GetError(); 494 << "): " << GetNSSErrorMessage();
354 } 495 }
355 return db_slot; 496 return db_slot;
356 } 497 }
357 498
358 // If this is set to true NSS is forced to be initialized without a DB. 499 // If this is set to true NSS is forced to be initialized without a DB.
359 static bool force_nodb_init_; 500 static bool force_nodb_init_;
360 501
361 PK11SlotInfo* real_db_slot_; // Overrides internal key slot if non-NULL. 502 PK11SlotInfo* real_db_slot_; // Overrides internal key slot if non-NULL.
362 PK11SlotInfo* test_db_slot_; // Overrides internal key slot and real_db_slot_ 503 PK11SlotInfo* test_db_slot_; // Overrides internal key slot and real_db_slot_
363 SECMODModule *root_; 504 SECMODModule* root_;
505 SECMODModule* opencryptoki_module_;
364 bool chromeos_user_logged_in_; 506 bool chromeos_user_logged_in_;
365 #if defined(USE_NSS) 507 #if defined(USE_NSS)
366 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011 508 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
367 // is fixed, we will no longer need the lock. 509 // is fixed, we will no longer need the lock.
368 Lock write_lock_; 510 Lock write_lock_;
369 #endif // defined(USE_NSS) 511 #endif // defined(USE_NSS)
370 }; 512 };
371 513
372 // static 514 // static
373 bool NSSInitSingleton::force_nodb_init_ = false; 515 bool NSSInitSingleton::force_nodb_init_ = false;
(...skipping 98 matching lines...) Expand 10 before | Expand all | Expand 10 after
472 614
473 AutoNSSWriteLock::~AutoNSSWriteLock() { 615 AutoNSSWriteLock::~AutoNSSWriteLock() {
474 if (lock_) { 616 if (lock_) {
475 lock_->AssertAcquired(); 617 lock_->AssertAcquired();
476 lock_->Release(); 618 lock_->Release();
477 } 619 }
478 } 620 }
479 #endif // defined(USE_NSS) 621 #endif // defined(USE_NSS)
480 622
481 #if defined(OS_CHROMEOS) 623 #if defined(OS_CHROMEOS)
482 void OpenPersistentNSSDB() { 624 void OpenPersistentNSSDB(bool load_opencryptoki) {
483 g_nss_singleton.Get().OpenPersistentNSSDB(); 625 g_nss_singleton.Get().OpenPersistentNSSDB(load_opencryptoki);
484 } 626 }
485 #endif 627
628 std::string GetTPMTokenName() {
629 return g_nss_singleton.Get().GetTPMTokenName();
630 }
631 #endif // defined(OS_CHROMEOS)
486 632
487 // TODO(port): Implement this more simply. We can convert by subtracting an 633 // TODO(port): Implement this more simply. We can convert by subtracting an
488 // offset (the difference between NSPR's and base::Time's epochs). 634 // offset (the difference between NSPR's and base::Time's epochs).
489 Time PRTimeToBaseTime(PRTime prtime) { 635 Time PRTimeToBaseTime(PRTime prtime) {
490 PRExplodedTime prxtime; 636 PRExplodedTime prxtime;
491 PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime); 637 PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);
492 638
493 Time::Exploded exploded; 639 Time::Exploded exploded;
494 exploded.year = prxtime.tm_year; 640 exploded.year = prxtime.tm_year;
495 exploded.month = prxtime.tm_month + 1; 641 exploded.month = prxtime.tm_month + 1;
496 exploded.day_of_week = prxtime.tm_wday; 642 exploded.day_of_week = prxtime.tm_wday;
497 exploded.day_of_month = prxtime.tm_mday; 643 exploded.day_of_month = prxtime.tm_mday;
498 exploded.hour = prxtime.tm_hour; 644 exploded.hour = prxtime.tm_hour;
499 exploded.minute = prxtime.tm_min; 645 exploded.minute = prxtime.tm_min;
500 exploded.second = prxtime.tm_sec; 646 exploded.second = prxtime.tm_sec;
501 exploded.millisecond = prxtime.tm_usec / 1000; 647 exploded.millisecond = prxtime.tm_usec / 1000;
502 648
503 return Time::FromUTCExploded(exploded); 649 return Time::FromUTCExploded(exploded);
504 } 650 }
505 651
506 PK11SlotInfo* GetDefaultNSSKeySlot() { 652 PK11SlotInfo* GetDefaultNSSKeySlot() {
507 return g_nss_singleton.Get().GetDefaultKeySlot(); 653 return g_nss_singleton.Get().GetDefaultNSSKeySlot();
654 }
655
656 PK11SlotInfo* GetPreferredKeySlot() {
657 #if defined(OS_CHROMEOS)
658 return g_nss_singleton.Get().GetTPMSlot();
659 #else
660 return GetDefaultNSSKeySlot();
661 #endif
508 } 662 }
509 663
510 } // namespace base 664 } // namespace base
OLDNEW
« no previous file with comments | « base/nss_util.h ('k') | base/nss_util_internal.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698