1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "crypto/nss_util.h"
18 #include "base/base_paths.h"
19 #include "base/containers/flat_map.h"
20 #include "base/debug/alias.h"
21 #include "base/files/file_path.h"
22 #include "base/files/file_util.h"
23 #include "base/lazy_instance.h"
24 #include "base/logging.h"
25 #include "base/path_service.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/threading/scoped_blocking_call.h"
28 #include "base/threading/thread_restrictions.h"
29 #include "build/build_config.h"
30 #include "build/chromeos_buildflags.h"
31 #include "crypto/nss_crypto_module_delegate.h"
32 #include "crypto/nss_util_internal.h"
38 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
40 // Fake certificate authority database used for testing.
41 static const base::FilePath::CharType kReadOnlyCertDB[] =
42 FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
46 base::FilePath GetDefaultConfigDirectory() {
48 base::PathService::Get(base::DIR_HOME, &dir);
50 LOG(ERROR) << "Failed to get home directory.";
53 dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
54 if (!base::CreateDirectory(dir)) {
55 LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
58 DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
62 #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
64 // On non-Chrome OS platforms, return the default config directory. On Chrome OS
65 // test images, return a read-only directory with fake root CA certs (which are
66 // used by the local Google Accounts server mock we use when testing our login
67 // code). On Chrome OS non-test images (where the read-only directory doesn't
68 // exist), return an empty path.
69 base::FilePath GetInitialConfigDirectory() {
70 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
71 base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
72 if (!base::PathExists(database_dir))
76 return GetDefaultConfigDirectory();
77 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
80 // This callback for NSS forwards all requests to a caller-specified
81 // CryptoModuleBlockingPasswordDelegate object.
82 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
83 crypto::CryptoModuleBlockingPasswordDelegate* delegate =
84 reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
86 bool cancelled = false;
87 std::string password = delegate->RequestPassword(
88 PK11_GetTokenName(slot), retry != PR_FALSE, &cancelled);
91 char* result = PORT_Strdup(password.c_str());
92 password.replace(0, password.size(), password.size(), 0);
95 DLOG(ERROR) << "PK11 password requested with nullptr arg";
99 // A singleton to initialize/deinitialize NSPR.
100 // Separate from the NSS singleton because we initialize NSPR on the UI thread.
101 // Now that we're leaking the singleton, we could merge back with the NSS
103 class NSPRInitSingleton {
105 friend struct base::LazyInstanceTraitsBase<NSPRInitSingleton>;
107 NSPRInitSingleton() { PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); }
109 // NOTE(willchan): We don't actually cleanup on destruction since we leak NSS
110 // to prevent non-joinable threads from using NSS after it's already been
112 ~NSPRInitSingleton() = delete;
115 base::LazyInstance<NSPRInitSingleton>::Leaky g_nspr_singleton =
116 LAZY_INSTANCE_INITIALIZER;
118 // Force a crash with error info on NSS_NoDB_Init failure.
119 void CrashOnNSSInitFailure() {
120 int nss_error = PR_GetError();
121 int os_error = PR_GetOSError();
122 base::debug::Alias(&nss_error);
123 base::debug::Alias(&os_error);
124 LOG(ERROR) << "Error initializing NSS without a persistent database: "
125 << GetNSSErrorMessage();
126 LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
129 class NSSInitSingleton {
131 // NOTE(willchan): We don't actually cleanup on destruction since we leak NSS
132 // to prevent non-joinable threads from using NSS after it's already been
134 ~NSSInitSingleton() = delete;
136 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
137 const std::string& description) {
138 base::AutoLock lock(slot_map_lock_);
140 auto slot_map_iter = slot_map_.find(path);
141 if (slot_map_iter != slot_map_.end()) {
142 // PK11_ReferenceSlot returns a new PK11Slot instance which refers
144 return ScopedPK11Slot(PK11_ReferenceSlot(slot_map_iter->second.get()));
147 const std::string modspec =
148 base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
149 path.value().c_str(), description.c_str());
151 // TODO(crbug.com/1163303): Presumably there's a race condition with
152 // session_manager around creating/opening the software NSS database. The
153 // retry loop is a temporary workaround that should at least reduce the
154 // amount of failures until a proper fix is implemented.
155 PK11SlotInfo* db_slot_info = nullptr;
156 int attempts_counter = 0;
157 for (; !db_slot_info && (attempts_counter < 10); ++attempts_counter) {
158 db_slot_info = SECMOD_OpenUserDB(modspec.c_str());
160 if (db_slot_info && (attempts_counter > 1)) {
161 LOG(ERROR) << "Opening persistent database failed "
162 << attempts_counter - 1 << " times before succeeding";
166 if (PK11_NeedUserInit(db_slot_info))
167 PK11_InitPin(db_slot_info, nullptr, nullptr);
168 slot_map_[path] = ScopedPK11Slot(PK11_ReferenceSlot(db_slot_info));
170 LOG(ERROR) << "Error opening persistent database (" << modspec
171 << "): " << GetNSSErrorMessage();
172 #if BUILDFLAG(IS_CHROMEOS_ASH)
173 DiagnosePublicSlotAndCrash(path);
174 #endif // BUILDFLAG(IS_CHROMEOS_ASH)
177 return ScopedPK11Slot(db_slot_info);
180 SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
185 base::AutoLock lock(slot_map_lock_);
186 CK_SLOT_ID slot_id = PK11_GetSlotID(slot);
187 for (auto const& [stored_path, stored_slot] : slot_map_) {
188 if (PK11_GetSlotID(stored_slot.get()) == slot_id) {
189 slot_map_.erase(stored_path);
190 return SECMOD_CloseUserDB(slot);
197 friend struct base::LazyInstanceTraitsBase<NSSInitSingleton>;
200 // Initializing NSS causes us to do blocking IO.
201 // Temporarily allow it until we fix
202 // http://code.google.com/p/chromium/issues/detail?id=59847
203 ScopedAllowBlockingForNSS allow_blocking;
206 #if BUILDFLAG(IS_TIZEN)
207 LOG(INFO) << " Tizen 8.0 platform NSS library version is 3.34 and open "
208 "source expects 3.35 or higher";
210 // We *must* have NSS >= 3.35 at compile time.
211 static_assert((NSS_VMAJOR == 3 && NSS_VMINOR >= 35) || (NSS_VMAJOR > 3),
212 "nss version check failed");
213 // Also check the run-time NSS version.
214 // NSS_VersionCheck is a >= check, not strict equality.
215 if (!NSS_VersionCheck("3.35")) {
216 LOG(FATAL) << "NSS_VersionCheck(\"3.35\") failed. NSS >= 3.35 is "
217 "required. Please upgrade to the latest NSS, and if you "
218 "still get this error, contact your distribution "
223 SECStatus status = SECFailure;
224 base::FilePath database_dir = GetInitialConfigDirectory();
225 // In MSAN, all loaded libraries needs to be instrumented. But the user
226 // config may reference an uninstrumented module, so load NSS without cert
227 // DBs instead. Tests should ideally be run under
228 // testing/run_with_dummy_home.py to eliminate dependencies on user
229 // configuration, but the bots are not currently configured to do so. This
230 // workaround may be removed if/when the bots use run_with_dummy_home.py.
231 #if !defined(MEMORY_SANITIZER)
232 if (!database_dir.empty()) {
233 // Initialize with a persistent database (likely, ~/.pki/nssdb).
234 // Use "sql:" which can be shared by multiple processes safely.
235 std::string nss_config_dir =
236 base::StringPrintf("sql:%s", database_dir.value().c_str());
237 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
238 status = NSS_Init(nss_config_dir.c_str());
240 status = NSS_InitReadWrite(nss_config_dir.c_str());
242 if (status != SECSuccess) {
243 LOG(ERROR) << "Error initializing NSS with a persistent "
245 << nss_config_dir << "): " << GetNSSErrorMessage();
248 #endif // !defined(MEMORY_SANITIZER)
249 if (status != SECSuccess) {
250 VLOG(1) << "Initializing NSS without a persistent database.";
251 status = NSS_NoDB_Init(nullptr);
252 if (status != SECSuccess) {
253 CrashOnNSSInitFailure();
258 PK11_SetPasswordFunc(PKCS11PasswordFunc);
260 // If we haven't initialized the password for the NSS databases,
261 // initialize an empty-string password so that we don't need to
263 PK11SlotInfo* slot = PK11_GetInternalKeySlot();
265 // PK11_InitPin may write to the keyDB, but no other thread can use NSS
266 // yet, so we don't need to lock.
267 if (PK11_NeedUserInit(slot))
268 PK11_InitPin(slot, nullptr, nullptr);
272 // Load nss's built-in root certs.
274 // TODO(mattm): DCHECK this succeeded when crbug.com/310972 is fixed.
275 // Failing to load root certs will it hard to talk to anybody via https.
276 LoadNSSModule("Root Certs", "libnssckbi.so", nullptr);
278 // Disable MD5 certificate signatures. (They are disabled by default in
280 NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
281 NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, 0,
282 NSS_USE_ALG_IN_CERT_SIGNATURE);
285 // Stores opened software NSS databases.
286 base::flat_map<base::FilePath, /*slot=*/ScopedPK11Slot> slot_map_
287 GUARDED_BY(slot_map_lock_);
288 // Ensures thread-safety for the methods that modify slot_map_.
289 // Performance considerations:
290 // Opening/closing a database is a rare operation in Chrome. Actually opening
291 // a database is a blocking I/O operation. Chrome doesn't open a lot of
292 // different databases in parallel. So, waiting for another thread to finish
293 // opening a database and (almost certainly) reusing the result is comparable
294 // to opening the same database twice in parallel (but the latter is not
295 // supported by NSS).
296 base::Lock slot_map_lock_;
299 base::LazyInstance<NSSInitSingleton>::Leaky g_nss_singleton =
300 LAZY_INSTANCE_INITIALIZER;
303 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
304 const std::string& description) {
305 return g_nss_singleton.Get().OpenSoftwareNSSDB(path, description);
308 SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
309 return g_nss_singleton.Get().CloseSoftwareNSSDB(slot);
312 void EnsureNSPRInit() {
313 g_nspr_singleton.Get();
316 void EnsureNSSInit() {
317 g_nss_singleton.Get();
320 bool CheckNSSVersion(const char* version) {
321 return !!NSS_VersionCheck(version);
324 AutoSECMODListReadLock::AutoSECMODListReadLock()
325 : lock_(SECMOD_GetDefaultModuleListLock()) {
326 SECMOD_GetReadLock(lock_);
329 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
330 SECMOD_ReleaseReadLock(lock_);
333 base::Time PRTimeToBaseTime(PRTime prtime) {
334 return base::Time::FromInternalValue(
335 prtime + base::Time::UnixEpoch().ToInternalValue());
338 PRTime BaseTimeToPRTime(base::Time time) {
339 return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
342 SECMODModule* LoadNSSModule(const char* name,
343 const char* library_path,
344 const char* params) {
345 std::string modparams =
346 base::StringPrintf("name=\"%s\" library=\"%s\" %s", name, library_path,
347 params ? params : "");
349 // Shouldn't need to const_cast here, but SECMOD doesn't properly declare
350 // input string arguments as const. Bug
351 // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed on NSS
352 // codebase to address this.
353 SECMODModule* module = SECMOD_LoadUserModule(
354 const_cast<char*>(modparams.c_str()), nullptr, PR_FALSE);
356 LOG(ERROR) << "Error loading " << name
357 << " module into NSS: " << GetNSSErrorMessage();
360 if (!module->loaded) {
361 LOG(ERROR) << "After loading " << name
362 << ", loaded==false: " << GetNSSErrorMessage();
363 SECMOD_DestroyModule(module);
369 std::string GetNSSErrorMessage() {
371 if (PR_GetErrorTextLength()) {
372 std::unique_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
373 PRInt32 copied = PR_GetErrorText(error_text.get());
374 result = std::string(error_text.get(), copied);
376 result = base::StringPrintf("NSS error code: %d", PR_GetError());
381 } // namespace crypto