nss_util.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // Copyright (c) 2012 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. #include "crypto/nss_util.h"
  5. #include <nss.h>
  6. #include <pk11pub.h>
  7. #include <plarena.h>
  8. #include <prerror.h>
  9. #include <prinit.h>
  10. #include <prtime.h>
  11. #include <secmod.h>
  12. #include <memory>
  13. #include <utility>
  14. #include "base/base_paths.h"
  15. #include "base/containers/flat_map.h"
  16. #include "base/debug/alias.h"
  17. #include "base/files/file_path.h"
  18. #include "base/files/file_util.h"
  19. #include "base/lazy_instance.h"
  20. #include "base/logging.h"
  21. #include "base/path_service.h"
  22. #include "base/strings/stringprintf.h"
  23. #include "base/threading/scoped_blocking_call.h"
  24. #include "base/threading/thread_restrictions.h"
  25. #include "build/build_config.h"
  26. #include "build/chromeos_buildflags.h"
  27. #include "crypto/nss_crypto_module_delegate.h"
  28. #include "crypto/nss_util_internal.h"
  29. namespace crypto {
  30. namespace {
  31. #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
  32. // Fake certificate authority database used for testing.
  33. static const base::FilePath::CharType kReadOnlyCertDB[] =
  34. FILE_PATH_LITERAL("/etc/fake_root_ca/nssdb");
  35. #else
  36. base::FilePath GetDefaultConfigDirectory() {
  37. base::FilePath dir;
  38. base::PathService::Get(base::DIR_HOME, &dir);
  39. if (dir.empty()) {
  40. LOG(ERROR) << "Failed to get home directory.";
  41. return dir;
  42. }
  43. dir = dir.AppendASCII(".pki").AppendASCII("nssdb");
  44. if (!base::CreateDirectory(dir)) {
  45. LOG(ERROR) << "Failed to create " << dir.value() << " directory.";
  46. dir.clear();
  47. }
  48. DVLOG(2) << "DefaultConfigDirectory: " << dir.value();
  49. return dir;
  50. }
  51. #endif // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
  52. // On non-Chrome OS platforms, return the default config directory. On Chrome OS
  53. // test images, return a read-only directory with fake root CA certs (which are
  54. // used by the local Google Accounts server mock we use when testing our login
  55. // code). On Chrome OS non-test images (where the read-only directory doesn't
  56. // exist), return an empty path.
  57. base::FilePath GetInitialConfigDirectory() {
  58. #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
  59. base::FilePath database_dir = base::FilePath(kReadOnlyCertDB);
  60. if (!base::PathExists(database_dir))
  61. database_dir.clear();
  62. return database_dir;
  63. #else
  64. return GetDefaultConfigDirectory();
  65. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  66. }
  67. // This callback for NSS forwards all requests to a caller-specified
  68. // CryptoModuleBlockingPasswordDelegate object.
  69. char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
  70. crypto::CryptoModuleBlockingPasswordDelegate* delegate =
  71. reinterpret_cast<crypto::CryptoModuleBlockingPasswordDelegate*>(arg);
  72. if (delegate) {
  73. bool cancelled = false;
  74. std::string password = delegate->RequestPassword(
  75. PK11_GetTokenName(slot), retry != PR_FALSE, &cancelled);
  76. if (cancelled)
  77. return nullptr;
  78. char* result = PORT_Strdup(password.c_str());
  79. password.replace(0, password.size(), password.size(), 0);
  80. return result;
  81. }
  82. DLOG(ERROR) << "PK11 password requested with nullptr arg";
  83. return nullptr;
  84. }
  85. // A singleton to initialize/deinitialize NSPR.
  86. // Separate from the NSS singleton because we initialize NSPR on the UI thread.
  87. // Now that we're leaking the singleton, we could merge back with the NSS
  88. // singleton.
  89. class NSPRInitSingleton {
  90. private:
  91. friend struct base::LazyInstanceTraitsBase<NSPRInitSingleton>;
  92. NSPRInitSingleton() { PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0); }
  93. // NOTE(willchan): We don't actually cleanup on destruction since we leak NSS
  94. // to prevent non-joinable threads from using NSS after it's already been
  95. // shut down.
  96. ~NSPRInitSingleton() = delete;
  97. };
  98. base::LazyInstance<NSPRInitSingleton>::Leaky g_nspr_singleton =
  99. LAZY_INSTANCE_INITIALIZER;
  100. // Force a crash with error info on NSS_NoDB_Init failure.
  101. void CrashOnNSSInitFailure() {
  102. int nss_error = PR_GetError();
  103. int os_error = PR_GetOSError();
  104. base::debug::Alias(&nss_error);
  105. base::debug::Alias(&os_error);
  106. LOG(ERROR) << "Error initializing NSS without a persistent database: "
  107. << GetNSSErrorMessage();
  108. LOG(FATAL) << "nss_error=" << nss_error << ", os_error=" << os_error;
  109. }
  110. class NSSInitSingleton {
  111. public:
  112. // NOTE(willchan): We don't actually cleanup on destruction since we leak NSS
  113. // to prevent non-joinable threads from using NSS after it's already been
  114. // shut down.
  115. ~NSSInitSingleton() = delete;
  116. ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
  117. const std::string& description) {
  118. base::AutoLock lock(slot_map_lock_);
  119. auto slot_map_iter = slot_map_.find(path);
  120. if (slot_map_iter != slot_map_.end()) {
  121. // PK11_ReferenceSlot returns a new PK11Slot instance which refers
  122. // to the same slot.
  123. return ScopedPK11Slot(PK11_ReferenceSlot(slot_map_iter->second.get()));
  124. }
  125. const std::string modspec =
  126. base::StringPrintf("configDir='sql:%s' tokenDescription='%s'",
  127. path.value().c_str(), description.c_str());
  128. // TODO(crbug.com/1163303): Presumably there's a race condition with
  129. // session_manager around creating/opening the software NSS database. The
  130. // retry loop is a temporary workaround that should at least reduce the
  131. // amount of failures until a proper fix is implemented.
  132. PK11SlotInfo* db_slot_info = nullptr;
  133. int attempts_counter = 0;
  134. for (; !db_slot_info && (attempts_counter < 10); ++attempts_counter) {
  135. db_slot_info = SECMOD_OpenUserDB(modspec.c_str());
  136. }
  137. if (db_slot_info && (attempts_counter > 1)) {
  138. LOG(ERROR) << "Opening persistent database failed "
  139. << attempts_counter - 1 << " times before succeeding";
  140. }
  141. if (db_slot_info) {
  142. if (PK11_NeedUserInit(db_slot_info))
  143. PK11_InitPin(db_slot_info, nullptr, nullptr);
  144. slot_map_[path] = ScopedPK11Slot(PK11_ReferenceSlot(db_slot_info));
  145. } else {
  146. LOG(ERROR) << "Error opening persistent database (" << modspec
  147. << "): " << GetNSSErrorMessage();
  148. #if BUILDFLAG(IS_CHROMEOS_ASH)
  149. DiagnosePublicSlotAndCrash(path);
  150. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  151. }
  152. return ScopedPK11Slot(db_slot_info);
  153. }
  154. SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
  155. if (!slot) {
  156. return SECFailure;
  157. }
  158. base::AutoLock lock(slot_map_lock_);
  159. CK_SLOT_ID slot_id = PK11_GetSlotID(slot);
  160. for (auto const& [stored_path, stored_slot] : slot_map_) {
  161. if (PK11_GetSlotID(stored_slot.get()) == slot_id) {
  162. slot_map_.erase(stored_path);
  163. return SECMOD_CloseUserDB(slot);
  164. }
  165. }
  166. return SECFailure;
  167. }
  168. private:
  169. friend struct base::LazyInstanceTraitsBase<NSSInitSingleton>;
  170. NSSInitSingleton() {
  171. // Initializing NSS causes us to do blocking IO.
  172. // Temporarily allow it until we fix
  173. // http://code.google.com/p/chromium/issues/detail?id=59847
  174. base::ThreadRestrictions::ScopedAllowIO allow_io;
  175. EnsureNSPRInit();
  176. // We *must* have NSS >= 3.26 at compile time.
  177. static_assert((NSS_VMAJOR == 3 && NSS_VMINOR >= 26) || (NSS_VMAJOR > 3),
  178. "nss version check failed");
  179. // Also check the run-time NSS version.
  180. // NSS_VersionCheck is a >= check, not strict equality.
  181. if (!NSS_VersionCheck("3.26")) {
  182. LOG(FATAL) << "NSS_VersionCheck(\"3.26\") failed. NSS >= 3.26 is "
  183. "required. Please upgrade to the latest NSS, and if you "
  184. "still get this error, contact your distribution "
  185. "maintainer.";
  186. }
  187. SECStatus status = SECFailure;
  188. base::FilePath database_dir = GetInitialConfigDirectory();
  189. if (!database_dir.empty()) {
  190. // Initialize with a persistent database (likely, ~/.pki/nssdb).
  191. // Use "sql:" which can be shared by multiple processes safely.
  192. std::string nss_config_dir =
  193. base::StringPrintf("sql:%s", database_dir.value().c_str());
  194. #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
  195. status = NSS_Init(nss_config_dir.c_str());
  196. #else
  197. status = NSS_InitReadWrite(nss_config_dir.c_str());
  198. #endif
  199. if (status != SECSuccess) {
  200. LOG(ERROR) << "Error initializing NSS with a persistent "
  201. "database ("
  202. << nss_config_dir << "): " << GetNSSErrorMessage();
  203. }
  204. }
  205. if (status != SECSuccess) {
  206. VLOG(1) << "Initializing NSS without a persistent database.";
  207. status = NSS_NoDB_Init(nullptr);
  208. if (status != SECSuccess) {
  209. CrashOnNSSInitFailure();
  210. return;
  211. }
  212. }
  213. PK11_SetPasswordFunc(PKCS11PasswordFunc);
  214. // If we haven't initialized the password for the NSS databases,
  215. // initialize an empty-string password so that we don't need to
  216. // log in.
  217. PK11SlotInfo* slot = PK11_GetInternalKeySlot();
  218. if (slot) {
  219. // PK11_InitPin may write to the keyDB, but no other thread can use NSS
  220. // yet, so we don't need to lock.
  221. if (PK11_NeedUserInit(slot))
  222. PK11_InitPin(slot, nullptr, nullptr);
  223. PK11_FreeSlot(slot);
  224. }
  225. // Load nss's built-in root certs.
  226. //
  227. // TODO(mattm): DCHECK this succeeded when crbug.com/310972 is fixed.
  228. // Failing to load root certs will it hard to talk to anybody via https.
  229. LoadNSSModule("Root Certs", "libnssckbi.so", nullptr);
  230. // Disable MD5 certificate signatures. (They are disabled by default in
  231. // NSS 3.14.)
  232. NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
  233. NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, 0,
  234. NSS_USE_ALG_IN_CERT_SIGNATURE);
  235. }
  236. // Stores opened software NSS databases.
  237. base::flat_map<base::FilePath, /*slot=*/ScopedPK11Slot> slot_map_
  238. GUARDED_BY(slot_map_lock_);
  239. // Ensures thread-safety for the methods that modify slot_map_.
  240. // Performance considerations:
  241. // Opening/closing a database is a rare operation in Chrome. Actually opening
  242. // a database is a blocking I/O operation. Chrome doesn't open a lot of
  243. // different databases in parallel. So, waiting for another thread to finish
  244. // opening a database and (almost certainly) reusing the result is comparable
  245. // to opening the same database twice in parallel (but the latter is not
  246. // supported by NSS).
  247. base::Lock slot_map_lock_;
  248. };
  249. base::LazyInstance<NSSInitSingleton>::Leaky g_nss_singleton =
  250. LAZY_INSTANCE_INITIALIZER;
  251. } // namespace
  252. ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
  253. const std::string& description) {
  254. return g_nss_singleton.Get().OpenSoftwareNSSDB(path, description);
  255. }
  256. SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
  257. return g_nss_singleton.Get().CloseSoftwareNSSDB(slot);
  258. }
  259. void EnsureNSPRInit() {
  260. g_nspr_singleton.Get();
  261. }
  262. void EnsureNSSInit() {
  263. g_nss_singleton.Get();
  264. }
  265. bool CheckNSSVersion(const char* version) {
  266. return !!NSS_VersionCheck(version);
  267. }
  268. AutoSECMODListReadLock::AutoSECMODListReadLock()
  269. : lock_(SECMOD_GetDefaultModuleListLock()) {
  270. SECMOD_GetReadLock(lock_);
  271. }
  272. AutoSECMODListReadLock::~AutoSECMODListReadLock() {
  273. SECMOD_ReleaseReadLock(lock_);
  274. }
  275. base::Time PRTimeToBaseTime(PRTime prtime) {
  276. return base::Time::FromInternalValue(
  277. prtime + base::Time::UnixEpoch().ToInternalValue());
  278. }
  279. PRTime BaseTimeToPRTime(base::Time time) {
  280. return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
  281. }
  282. SECMODModule* LoadNSSModule(const char* name,
  283. const char* library_path,
  284. const char* params) {
  285. std::string modparams =
  286. base::StringPrintf("name=\"%s\" library=\"%s\" %s", name, library_path,
  287. params ? params : "");
  288. // Shouldn't need to const_cast here, but SECMOD doesn't properly declare
  289. // input string arguments as const. Bug
  290. // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed on NSS
  291. // codebase to address this.
  292. SECMODModule* module = SECMOD_LoadUserModule(
  293. const_cast<char*>(modparams.c_str()), nullptr, PR_FALSE);
  294. if (!module) {
  295. LOG(ERROR) << "Error loading " << name
  296. << " module into NSS: " << GetNSSErrorMessage();
  297. return nullptr;
  298. }
  299. if (!module->loaded) {
  300. LOG(ERROR) << "After loading " << name
  301. << ", loaded==false: " << GetNSSErrorMessage();
  302. SECMOD_DestroyModule(module);
  303. return nullptr;
  304. }
  305. return module;
  306. }
  307. std::string GetNSSErrorMessage() {
  308. std::string result;
  309. if (PR_GetErrorTextLength()) {
  310. std::unique_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
  311. PRInt32 copied = PR_GetErrorText(error_text.get());
  312. result = std::string(error_text.get(), copied);
  313. } else {
  314. result = base::StringPrintf("NSS error code: %d", PR_GetError());
  315. }
  316. return result;
  317. }
  318. } // namespace crypto