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

Side by Side Diff: base/nss_util.cc

Issue 6805019: Move crypto files out of base, to a top level directory. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: 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
OLDNEW
(Empty)
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
3 // found in the LICENSE file.
4
5 #include "base/nss_util.h"
6 #include "base/nss_util_internal.h"
7
8 #include <nss.h>
9 #include <plarena.h>
10 #include <prerror.h>
11 #include <prinit.h>
12 #include <prtime.h>
13 #include <pk11pub.h>
14 #include <secmod.h>
15
16 #if defined(OS_LINUX)
17 #include <linux/nfs_fs.h>
18 #include <sys/vfs.h>
19 #endif
20
21 #include <vector>
22
23 #include "base/environment.h"
24 #include "base/file_path.h"
25 #include "base/file_util.h"
26 #include "base/lazy_instance.h"
27 #include "base/logging.h"
28 #include "base/memory/scoped_ptr.h"
29 #include "base/native_library.h"
30 #include "base/stringprintf.h"
31 #include "base/threading/thread_restrictions.h"
32
33 // 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 // use NSS for crypto or certificate verification, and we don't use the NSS
36 // certificate and key databases.
37 #if defined(USE_NSS)
38 #include "base/crypto/crypto_module_blocking_password_delegate.h"
39 #include "base/synchronization/lock.h"
40 #endif // defined(USE_NSS)
41
42 namespace base {
43
44 namespace {
45
46 #if defined(USE_NSS)
47 FilePath GetDefaultConfigDirectory() {
48 FilePath dir = file_util::GetHomeDir();
49 if (dir.empty()) {
50 LOG(ERROR) << "Failed to get home directory.";
51 return dir;
52 }
53 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
54 if (!file_util::CreateDirectory(dir)) {
55 LOG(ERROR) << "Failed to create ~/.pki/nssdb directory.";
56 dir.clear();
57 }
58 return dir;
59 }
60
61 // On non-chromeos platforms, return the default config directory.
62 // 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
64 // 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
66 // caller to failover to NSS_NoDB_Init() at that point.
67 FilePath GetInitialConfigDirectory() {
68 #if defined(OS_CHROMEOS)
69 static const FilePath::CharType kReadOnlyCertDB[] =
70 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
71 return FilePath(kReadOnlyCertDB);
72 #else
73 return GetDefaultConfigDirectory();
74 #endif // defined(OS_CHROMEOS)
75 }
76
77 // This callback for NSS forwards all requests to a caller-specified
78 // CryptoModuleBlockingPasswordDelegate object.
79 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
80 base::CryptoModuleBlockingPasswordDelegate* delegate =
81 reinterpret_cast<base::CryptoModuleBlockingPasswordDelegate*>(arg);
82 if (delegate) {
83 bool cancelled = false;
84 std::string password = delegate->RequestPassword(PK11_GetTokenName(slot),
85 retry != PR_FALSE,
86 &cancelled);
87 if (cancelled)
88 return NULL;
89 char* result = PORT_Strdup(password.c_str());
90 password.replace(0, password.size(), password.size(), 0);
91 return result;
92 }
93 DLOG(ERROR) << "PK11 password requested with NULL arg";
94 return NULL;
95 }
96
97 // NSS creates a local cache of the sqlite database if it detects that the
98 // filesystem the database is on is much slower than the local disk. The
99 // detection doesn't work with the latest versions of sqlite, such as 3.6.22
100 // (NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=578561). So we set
101 // the NSS environment variable NSS_SDB_USE_CACHE to "yes" to override NSS's
102 // detection when database_dir is on NFS. See http://crbug.com/48585.
103 //
104 // TODO(wtc): port this function to other USE_NSS platforms. It is defined
105 // only for OS_LINUX simply because the statfs structure is OS-specific.
106 //
107 // Because this function sets an environment variable it must be run before we
108 // go multi-threaded.
109 void UseLocalCacheOfNSSDatabaseIfNFS(const FilePath& database_dir) {
110 #if defined(OS_LINUX)
111 struct statfs buf;
112 if (statfs(database_dir.value().c_str(), &buf) == 0) {
113 if (buf.f_type == NFS_SUPER_MAGIC) {
114 scoped_ptr<Environment> env(Environment::Create());
115 const char* use_cache_env_var = "NSS_SDB_USE_CACHE";
116 if (!env->HasVar(use_cache_env_var))
117 env->SetVar(use_cache_env_var, "yes");
118 }
119 }
120 #endif // defined(OS_LINUX)
121 }
122
123 // Load nss's built-in root certs.
124 SECMODModule *InitDefaultRootCerts() {
125 const char* kModulePath = "libnssckbi.so";
126 char modparams[1024];
127 snprintf(modparams, sizeof(modparams),
128 "name=\"Root Certs\" library=\"%s\"", kModulePath);
129 SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE);
130 if (root)
131 return root;
132
133 // Aw, snap. Can't find/load root cert shared library.
134 // This will make it hard to talk to anybody via https.
135 NOTREACHED();
136 return NULL;
137 }
138 #endif // defined(USE_NSS)
139
140 // A singleton to initialize/deinitialize NSPR.
141 // 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
143 // singleton.
144 class NSPRInitSingleton {
145 private:
146 friend struct DefaultLazyInstanceTraits<NSPRInitSingleton>;
147
148 NSPRInitSingleton() {
149 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
150 }
151
152 // NOTE(willchan): We don't actually execute this code since we leak NSS to
153 // prevent non-joinable threads from using NSS after it's already been shut
154 // down.
155 ~NSPRInitSingleton() {
156 PL_ArenaFinish();
157 PRStatus prstatus = PR_Cleanup();
158 if (prstatus != PR_SUCCESS) {
159 LOG(ERROR) << "PR_Cleanup failed; was NSPR initialized on wrong thread?";
160 }
161 }
162 };
163
164 LazyInstance<NSPRInitSingleton, LeakyLazyInstanceTraits<NSPRInitSingleton> >
165 g_nspr_singleton(LINKER_INITIALIZED);
166
167 class NSSInitSingleton {
168 public:
169 #if defined(OS_CHROMEOS)
170 void OpenPersistentNSSDB() {
171 if (!chromeos_user_logged_in_) {
172 // GetDefaultConfigDirectory causes us to do blocking IO on UI thread.
173 // Temporarily allow it until we fix http://crbug.com.70119
174 ThreadRestrictions::ScopedAllowIO allow_io;
175 chromeos_user_logged_in_ = true;
176 real_db_slot_ = OpenUserDB(GetDefaultConfigDirectory(),
177 "Real NSS database");
178 }
179 }
180 #endif // defined(OS_CHROMEOS)
181
182 bool OpenTestNSSDB(const FilePath& path, const char* description) {
183 test_db_slot_ = OpenUserDB(path, description);
184 return !!test_db_slot_;
185 }
186
187 void CloseTestNSSDB() {
188 if (test_db_slot_) {
189 SECStatus status = SECMOD_CloseUserDB(test_db_slot_);
190 if (status != SECSuccess)
191 LOG(ERROR) << "SECMOD_CloseUserDB failed: " << PORT_GetError();
192 PK11_FreeSlot(test_db_slot_);
193 test_db_slot_ = NULL;
194 }
195 }
196
197 PK11SlotInfo* GetDefaultKeySlot() {
198 if (test_db_slot_)
199 return PK11_ReferenceSlot(test_db_slot_);
200 if (real_db_slot_)
201 return PK11_ReferenceSlot(real_db_slot_);
202 return PK11_GetInternalKeySlot();
203 }
204
205 #if defined(USE_NSS)
206 Lock* write_lock() {
207 return &write_lock_;
208 }
209 #endif // defined(USE_NSS)
210
211 // This method is used to force NSS to be initialized without a DB.
212 // Call this method before NSSInitSingleton() is constructed.
213 static void ForceNoDBInit() {
214 force_nodb_init_ = true;
215 }
216
217 private:
218 friend struct DefaultLazyInstanceTraits<NSSInitSingleton>;
219
220 NSSInitSingleton()
221 : real_db_slot_(NULL),
222 test_db_slot_(NULL),
223 root_(NULL),
224 chromeos_user_logged_in_(false) {
225 EnsureNSPRInit();
226
227 // We *must* have NSS >= 3.12.3. See bug 26448.
228 COMPILE_ASSERT(
229 (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||
230 (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||
231 (NSS_VMAJOR > 3),
232 nss_version_check_failed);
233 // Also check the run-time NSS version.
234 // NSS_VersionCheck is a >= check, not strict equality.
235 if (!NSS_VersionCheck("3.12.3")) {
236 // It turns out many people have misconfigured NSS setups, where
237 // their run-time NSPR doesn't match the one their NSS was compiled
238 // against. So rather than aborting, complain loudly.
239 LOG(ERROR) << "NSS_VersionCheck(\"3.12.3\") failed. "
240 "We depend on NSS >= 3.12.3, and this error is not fatal "
241 "only because many people have busted NSS setups (for "
242 "example, using the wrong version of NSPR). "
243 "Please upgrade to the latest NSS and NSPR, and if you "
244 "still get this error, contact your distribution "
245 "maintainer.";
246 }
247
248 SECStatus status = SECFailure;
249 bool nodb_init = force_nodb_init_;
250
251 #if !defined(USE_NSS)
252 // Use the system certificate store, so initialize NSS without database.
253 nodb_init = true;
254 #endif
255
256 if (nodb_init) {
257 status = NSS_NoDB_Init(NULL);
258 if (status != SECSuccess) {
259 LOG(ERROR) << "Error initializing NSS without a persistent "
260 "database: NSS error code " << PR_GetError();
261 }
262 } else {
263 #if defined(USE_NSS)
264 FilePath database_dir = GetInitialConfigDirectory();
265 if (!database_dir.empty()) {
266 // This duplicates the work which should have been done in
267 // EarlySetupForNSSInit. However, this function is idempotent so
268 // there's no harm done.
269 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
270
271 // Initialize with a persistent database (likely, ~/.pki/nssdb).
272 // Use "sql:" which can be shared by multiple processes safely.
273 std::string nss_config_dir =
274 StringPrintf("sql:%s", database_dir.value().c_str());
275 #if defined(OS_CHROMEOS)
276 status = NSS_Init(nss_config_dir.c_str());
277 #else
278 status = NSS_InitReadWrite(nss_config_dir.c_str());
279 #endif
280 if (status != SECSuccess) {
281 LOG(ERROR) << "Error initializing NSS with a persistent "
282 "database (" << nss_config_dir
283 << "): NSS error code " << PR_GetError();
284 }
285 }
286 if (status != SECSuccess) {
287 LOG(WARNING) << "Initialize NSS without a persistent database "
288 "(~/.pki/nssdb).";
289 status = NSS_NoDB_Init(NULL);
290 if (status != SECSuccess) {
291 LOG(ERROR) << "Error initializing NSS without a persistent "
292 "database: NSS error code " << PR_GetError();
293 return;
294 }
295 }
296
297 PK11_SetPasswordFunc(PKCS11PasswordFunc);
298
299 // If we haven't initialized the password for the NSS databases,
300 // initialize an empty-string password so that we don't need to
301 // log in.
302 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
303 if (slot) {
304 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
305 // yet, so we don't need to lock.
306 if (PK11_NeedUserInit(slot))
307 PK11_InitPin(slot, NULL, NULL);
308 PK11_FreeSlot(slot);
309 }
310
311 root_ = InitDefaultRootCerts();
312 #endif // defined(USE_NSS)
313 }
314 }
315
316 // NOTE(willchan): We don't actually execute this code since we leak NSS to
317 // prevent non-joinable threads from using NSS after it's already been shut
318 // down.
319 ~NSSInitSingleton() {
320 if (real_db_slot_) {
321 SECMOD_CloseUserDB(real_db_slot_);
322 PK11_FreeSlot(real_db_slot_);
323 real_db_slot_ = NULL;
324 }
325 CloseTestNSSDB();
326 if (root_) {
327 SECMOD_UnloadUserModule(root_);
328 SECMOD_DestroyModule(root_);
329 root_ = NULL;
330 }
331
332 SECStatus status = NSS_Shutdown();
333 if (status != SECSuccess) {
334 // We VLOG(1) because this failure is relatively harmless (leaking, but
335 // we're shutting down anyway).
336 VLOG(1) << "NSS_Shutdown failed; see "
337 "http://code.google.com/p/chromium/issues/detail?id=4609";
338 }
339 }
340
341 static PK11SlotInfo* OpenUserDB(const FilePath& path,
342 const char* description) {
343 const std::string modspec =
344 StringPrintf("configDir='sql:%s' tokenDescription='%s'",
345 path.value().c_str(), description);
346 PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
347 if (db_slot) {
348 if (PK11_NeedUserInit(db_slot))
349 PK11_InitPin(db_slot, NULL, NULL);
350 }
351 else {
352 LOG(ERROR) << "Error opening persistent database (" << modspec
353 << "): NSS error code " << PR_GetError();
354 }
355 return db_slot;
356 }
357
358 // If this is set to true NSS is forced to be initialized without a DB.
359 static bool force_nodb_init_;
360
361 PK11SlotInfo* real_db_slot_; // Overrides internal key slot if non-NULL.
362 PK11SlotInfo* test_db_slot_; // Overrides internal key slot and real_db_slot_
363 SECMODModule *root_;
364 bool chromeos_user_logged_in_;
365 #if defined(USE_NSS)
366 // TODO(davidben): When https://bugzilla.mozilla.org/show_bug.cgi?id=564011
367 // is fixed, we will no longer need the lock.
368 Lock write_lock_;
369 #endif // defined(USE_NSS)
370 };
371
372 // static
373 bool NSSInitSingleton::force_nodb_init_ = false;
374
375 LazyInstance<NSSInitSingleton, LeakyLazyInstanceTraits<NSSInitSingleton> >
376 g_nss_singleton(LINKER_INITIALIZED);
377
378 } // namespace
379
380 #if defined(USE_NSS)
381 void EarlySetupForNSSInit() {
382 FilePath database_dir = GetInitialConfigDirectory();
383 if (!database_dir.empty())
384 UseLocalCacheOfNSSDatabaseIfNFS(database_dir);
385 }
386 #endif
387
388 void EnsureNSPRInit() {
389 g_nspr_singleton.Get();
390 }
391
392 void EnsureNSSInit() {
393 // Initializing SSL causes us to do blocking IO.
394 // Temporarily allow it until we fix
395 // http://code.google.com/p/chromium/issues/detail?id=59847
396 ThreadRestrictions::ScopedAllowIO allow_io;
397 g_nss_singleton.Get();
398 }
399
400 void ForceNSSNoDBInit() {
401 NSSInitSingleton::ForceNoDBInit();
402 }
403
404 void DisableNSSForkCheck() {
405 scoped_ptr<Environment> env(Environment::Create());
406 env->SetVar("NSS_STRICT_NOFORK", "DISABLED");
407 }
408
409 void LoadNSSLibraries() {
410 // Some NSS libraries are linked dynamically so load them here.
411 #if defined(USE_NSS)
412 // Try to search for multiple directories to load the libraries.
413 std::vector<FilePath> paths;
414
415 // Use relative path to Search PATH for the library files.
416 paths.push_back(FilePath());
417
418 // For Debian derivaties NSS libraries are located here.
419 paths.push_back(FilePath("/usr/lib/nss"));
420
421 // A list of library files to load.
422 std::vector<std::string> libs;
423 libs.push_back("libsoftokn3.so");
424 libs.push_back("libfreebl3.so");
425
426 // For each combination of library file and path, check for existence and
427 // then load.
428 size_t loaded = 0;
429 for (size_t i = 0; i < libs.size(); ++i) {
430 for (size_t j = 0; j < paths.size(); ++j) {
431 FilePath path = paths[j].Append(libs[i]);
432 if (file_util::PathExists(path)) {
433 NativeLibrary lib = base::LoadNativeLibrary(path);
434 if (lib) {
435 ++loaded;
436 break;
437 }
438 }
439 }
440 }
441
442 if (loaded == libs.size()) {
443 VLOG(3) << "NSS libraries loaded.";
444 } else {
445 LOG(WARNING) << "Failed to load NSS libraries.";
446 }
447 #endif
448 }
449
450 bool CheckNSSVersion(const char* version) {
451 return !!NSS_VersionCheck(version);
452 }
453
454 #if defined(USE_NSS)
455 bool OpenTestNSSDB(const FilePath& path, const char* description) {
456 return g_nss_singleton.Get().OpenTestNSSDB(path, description);
457 }
458
459 void CloseTestNSSDB() {
460 g_nss_singleton.Get().CloseTestNSSDB();
461 }
462
463 Lock* GetNSSWriteLock() {
464 return g_nss_singleton.Get().write_lock();
465 }
466
467 AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
468 // May be NULL if the lock is not needed in our version of NSS.
469 if (lock_)
470 lock_->Acquire();
471 }
472
473 AutoNSSWriteLock::~AutoNSSWriteLock() {
474 if (lock_) {
475 lock_->AssertAcquired();
476 lock_->Release();
477 }
478 }
479 #endif // defined(USE_NSS)
480
481 #if defined(OS_CHROMEOS)
482 void OpenPersistentNSSDB() {
483 g_nss_singleton.Get().OpenPersistentNSSDB();
484 }
485 #endif
486
487 // TODO(port): Implement this more simply. We can convert by subtracting an
488 // offset (the difference between NSPR's and base::Time's epochs).
489 Time PRTimeToBaseTime(PRTime prtime) {
490 PRExplodedTime prxtime;
491 PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);
492
493 Time::Exploded exploded;
494 exploded.year = prxtime.tm_year;
495 exploded.month = prxtime.tm_month + 1;
496 exploded.day_of_week = prxtime.tm_wday;
497 exploded.day_of_month = prxtime.tm_mday;
498 exploded.hour = prxtime.tm_hour;
499 exploded.minute = prxtime.tm_min;
500 exploded.second = prxtime.tm_sec;
501 exploded.millisecond = prxtime.tm_usec / 1000;
502
503 return Time::FromUTCExploded(exploded);
504 }
505
506 PK11SlotInfo* GetDefaultNSSKeySlot() {
507 return g_nss_singleton.Get().GetDefaultKeySlot();
508 }
509
510 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698