• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "crypto/nss_util.h"
6 
7 #include <nss.h>
8 #include <pk11pub.h>
9 #include <plarena.h>
10 #include <prerror.h>
11 #include <prinit.h>
12 #include <prtime.h>
13 #include <secmod.h>
14 
15 #include <memory>
16 #include <utility>
17 
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"
33 
34 namespace crypto {
35 
36 namespace {
37 
38 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
39 
40 // Fake certificate authority database used for testing.
41 static const base::FilePath::CharType kReadOnlyCertDB[] =
42     FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
43 
44 #else
45 
46 base::FilePath GetDefaultConfigDirectory() {
47   base::FilePath dir;
48   base::PathService::Get(base::DIR_HOME, &dir);
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 (!base::CreateDirectory(dir)) {
55     LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
56     dir.clear();
57   }
58   DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
59   return dir;
60 }
61 
62 #endif  // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
63 
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.
GetInitialConfigDirectory()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))
73     database_dir.clear();
74   return database_dir;
75 #else
76   return GetDefaultConfigDirectory();
77 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
78 }
79 
80 // This callback for NSS forwards all requests to a caller-specified
81 // CryptoModuleBlockingPasswordDelegate object.
PKCS11PasswordFunc(PK11SlotInfo * slot,PRBool retry,void * arg)82 char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
83   crypto::CryptoModuleBlockingPasswordDelegate* delegate =
84       reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
85   if (delegate) {
86     bool cancelled = false;
87     std::string password = delegate->RequestPassword(
88         PK11_GetTokenName(slot), retry != PR_FALSE, &cancelled);
89     if (cancelled)
90       return nullptr;
91     char* result = PORT_Strdup(password.c_str());
92     password.replace(0, password.size(), password.size(), 0);
93     return result;
94   }
95   DLOG(ERROR) << "PK11 password requested with nullptr arg";
96   return nullptr;
97 }
98 
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
102 // singleton.
103 class NSPRInitSingleton {
104  private:
105   friend struct base::LazyInstanceTraitsBase<NSPRInitSingleton>;
106 
NSPRInitSingleton()107   NSPRInitSingleton() { PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); }
108 
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
111   // shut down.
112   ~NSPRInitSingleton() = delete;
113 };
114 
115 base::LazyInstance<NSPRInitSingleton>::Leaky g_nspr_singleton =
116     LAZY_INSTANCE_INITIALIZER;
117 
118 // Force a crash with error info on NSS_NoDB_Init failure.
CrashOnNSSInitFailure()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;
127 }
128 
129 class NSSInitSingleton {
130  public:
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
133   // shut down.
134   ~NSSInitSingleton() = delete;
135 
OpenSoftwareNSSDB(const base::FilePath & path,const std::string & description)136   ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
137                                    const std::string& description) {
138     base::AutoLock lock(slot_map_lock_);
139 
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
143       // to the same slot.
144       return ScopedPK11Slot(PK11_ReferenceSlot(slot_map_iter->second.get()));
145     }
146 
147     const std::string modspec =
148         base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
149                            path.value().c_str(), description.c_str());
150 
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());
159     }
160     if (db_slot_info && (attempts_counter > 1)) {
161       LOG(ERROR) << "Opening persistent database failed "
162                  << attempts_counter - 1 << " times before succeeding";
163     }
164 
165     if (db_slot_info) {
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));
169     } else {
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)
175     }
176 
177     return ScopedPK11Slot(db_slot_info);
178   }
179 
CloseSoftwareNSSDB(PK11SlotInfo * slot)180   SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
181     if (!slot) {
182       return SECFailure;
183     }
184 
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);
191       }
192     }
193     return SECFailure;
194   }
195 
196  private:
197   friend struct base::LazyInstanceTraitsBase<NSSInitSingleton>;
198 
NSSInitSingleton()199   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;
204 
205     EnsureNSPRInit();
206 
207     // We *must* have NSS >= 3.35 at compile time.
208     static_assert((NSS_VMAJOR == 3 && NSS_VMINOR >= 35) || (NSS_VMAJOR > 3),
209                   "nss version check failed");
210     // Also check the run-time NSS version.
211     // NSS_VersionCheck is a >= check, not strict equality.
212     if (!NSS_VersionCheck("3.35")) {
213       LOG(FATAL) << "NSS_VersionCheck(\"3.35\") failed. NSS >= 3.35 is "
214                     "required. Please upgrade to the latest NSS, and if you "
215                     "still get this error, contact your distribution "
216                     "maintainer.";
217     }
218 
219     SECStatus status = SECFailure;
220     base::FilePath database_dir = GetInitialConfigDirectory();
221     // In MSAN, all loaded libraries needs to be instrumented. But the user
222     // config may reference an uninstrumented module, so load NSS without cert
223     // DBs instead. Tests should ideally be run under
224     // testing/run_with_dummy_home.py to eliminate dependencies on user
225     // configuration, but the bots are not currently configured to do so. This
226     // workaround may be removed if/when the bots use run_with_dummy_home.py.
227 #if !defined(MEMORY_SANITIZER)
228     if (!database_dir.empty()) {
229       // Initialize with a persistent database (likely, ~/.pki/nssdb).
230       // Use "sql:" which can be shared by multiple processes safely.
231       std::string nss_config_dir =
232           base::StringPrintf("sql:%s", database_dir.value().c_str());
233 #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
234       status = NSS_Init(nss_config_dir.c_str());
235 #else
236       status = NSS_InitReadWrite(nss_config_dir.c_str());
237 #endif
238       if (status != SECSuccess) {
239         LOG(ERROR) << "Error initializing NSS with a persistent "
240                       "database ("
241                    << nss_config_dir << "): " << GetNSSErrorMessage();
242       }
243     }
244 #endif  // !defined(MEMORY_SANITIZER)
245     if (status != SECSuccess) {
246       VLOG(1) << "Initializing NSS without a persistent database.";
247       status = NSS_NoDB_Init(nullptr);
248       if (status != SECSuccess) {
249         CrashOnNSSInitFailure();
250         return;
251       }
252     }
253 
254     PK11_SetPasswordFunc(PKCS11PasswordFunc);
255 
256     // If we haven't initialized the password for the NSS databases,
257     // initialize an empty-string password so that we don't need to
258     // log in.
259     PK11SlotInfo* slot = PK11_GetInternalKeySlot();
260     if (slot) {
261       // PK11_InitPin may write to the keyDB, but no other thread can use NSS
262       // yet, so we don't need to lock.
263       if (PK11_NeedUserInit(slot))
264         PK11_InitPin(slot, nullptr, nullptr);
265       PK11_FreeSlot(slot);
266     }
267 
268     // Load nss's built-in root certs.
269     //
270     // TODO(mattm): DCHECK this succeeded when crbug.com/310972 is fixed.
271     // Failing to load root certs will it hard to talk to anybody via https.
272     LoadNSSModule("Root Certs", "libnssckbi.so", nullptr);
273 
274     // Disable MD5 certificate signatures. (They are disabled by default in
275     // NSS 3.14.)
276     NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
277     NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, 0,
278                            NSS_USE_ALG_IN_CERT_SIGNATURE);
279   }
280 
281   // Stores opened software NSS databases.
282   base::flat_map<base::FilePath, /*slot=*/ScopedPK11Slot> slot_map_
283       GUARDED_BY(slot_map_lock_);
284   // Ensures thread-safety for the methods that modify slot_map_.
285   // Performance considerations:
286   // Opening/closing a database is a rare operation in Chrome. Actually opening
287   // a database is a blocking I/O operation. Chrome doesn't open a lot of
288   // different databases in parallel. So, waiting for another thread to finish
289   // opening a database and (almost certainly) reusing the result is comparable
290   // to opening the same database twice in parallel (but the latter is not
291   // supported by NSS).
292   base::Lock slot_map_lock_;
293 };
294 
295 base::LazyInstance<NSSInitSingleton>::Leaky g_nss_singleton =
296     LAZY_INSTANCE_INITIALIZER;
297 }  // namespace
298 
OpenSoftwareNSSDB(const base::FilePath & path,const std::string & description)299 ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
300                                  const std::string& description) {
301   return g_nss_singleton.Get().OpenSoftwareNSSDB(path, description);
302 }
303 
CloseSoftwareNSSDB(PK11SlotInfo * slot)304 SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
305   return g_nss_singleton.Get().CloseSoftwareNSSDB(slot);
306 }
307 
EnsureNSPRInit()308 void EnsureNSPRInit() {
309   g_nspr_singleton.Get();
310 }
311 
EnsureNSSInit()312 void EnsureNSSInit() {
313   g_nss_singleton.Get();
314 }
315 
CheckNSSVersion(const char * version)316 bool CheckNSSVersion(const char* version) {
317   return !!NSS_VersionCheck(version);
318 }
319 
AutoSECMODListReadLock()320 AutoSECMODListReadLock::AutoSECMODListReadLock()
321     : lock_(SECMOD_GetDefaultModuleListLock()) {
322   SECMOD_GetReadLock(lock_);
323 }
324 
~AutoSECMODListReadLock()325 AutoSECMODListReadLock::~AutoSECMODListReadLock() {
326   SECMOD_ReleaseReadLock(lock_);
327 }
328 
PRTimeToBaseTime(PRTime prtime)329 base::Time PRTimeToBaseTime(PRTime prtime) {
330   return base::Time::FromInternalValue(
331       prtime + base::Time::UnixEpoch().ToInternalValue());
332 }
333 
BaseTimeToPRTime(base::Time time)334 PRTime BaseTimeToPRTime(base::Time time) {
335   return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
336 }
337 
LoadNSSModule(const char * name,const char * library_path,const char * params)338 SECMODModule* LoadNSSModule(const char* name,
339                             const char* library_path,
340                             const char* params) {
341   std::string modparams =
342       base::StringPrintf("name=\"%s\" library=\"%s\" %s", name, library_path,
343                          params ? params : "");
344 
345   // Shouldn't need to const_cast here, but SECMOD doesn't properly declare
346   // input string arguments as const.  Bug
347   // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed on NSS
348   // codebase to address this.
349   SECMODModule* module = SECMOD_LoadUserModule(
350       const_cast<char*>(modparams.c_str()), nullptr, PR_FALSE);
351   if (!module) {
352     LOG(ERROR) << "Error loading " << name
353                << " module into NSS: " << GetNSSErrorMessage();
354     return nullptr;
355   }
356   if (!module->loaded) {
357     LOG(ERROR) << "After loading " << name
358                << ", loaded==false: " << GetNSSErrorMessage();
359     SECMOD_DestroyModule(module);
360     return nullptr;
361   }
362   return module;
363 }
364 
GetNSSErrorMessage()365 std::string GetNSSErrorMessage() {
366   std::string result;
367   if (PR_GetErrorTextLength()) {
368     std::unique_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
369     PRInt32 copied = PR_GetErrorText(error_text.get());
370     result = std::string(error_text.get(), copied);
371   } else {
372     result = base::StringPrintf("NSS error code: %d", PR_GetError());
373   }
374   return result;
375 }
376 
377 }  // namespace crypto
378