nss_util.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. PK11SlotInfo* db_slot_info = SECMOD_OpenUserDB(modspec.c_str());
  129. if (db_slot_info) {
  130. if (PK11_NeedUserInit(db_slot_info))
  131. PK11_InitPin(db_slot_info, nullptr, nullptr);
  132. slot_map_[path] = ScopedPK11Slot(PK11_ReferenceSlot(db_slot_info));
  133. } else {
  134. LOG(ERROR) << "Error opening persistent database (" << modspec
  135. << "): " << GetNSSErrorMessage();
  136. #if BUILDFLAG(IS_CHROMEOS_ASH)
  137. DiagnosePublicSlotAndCrash(path);
  138. #endif // BUILDFLAG(IS_CHROMEOS_ASH)
  139. }
  140. return ScopedPK11Slot(db_slot_info);
  141. }
  142. SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
  143. if (!slot) {
  144. return SECFailure;
  145. }
  146. base::AutoLock lock(slot_map_lock_);
  147. CK_SLOT_ID slot_id = PK11_GetSlotID(slot);
  148. for (auto const& [stored_path, stored_slot] : slot_map_) {
  149. if (PK11_GetSlotID(stored_slot.get()) == slot_id) {
  150. slot_map_.erase(stored_path);
  151. return SECMOD_CloseUserDB(slot);
  152. }
  153. }
  154. return SECFailure;
  155. }
  156. private:
  157. friend struct base::LazyInstanceTraitsBase<NSSInitSingleton>;
  158. NSSInitSingleton() {
  159. // Initializing NSS causes us to do blocking IO.
  160. // Temporarily allow it until we fix
  161. // http://code.google.com/p/chromium/issues/detail?id=59847
  162. base::ThreadRestrictions::ScopedAllowIO allow_io;
  163. EnsureNSPRInit();
  164. // We *must* have NSS >= 3.26 at compile time.
  165. static_assert((NSS_VMAJOR == 3 && NSS_VMINOR >= 26) || (NSS_VMAJOR > 3),
  166. "nss version check failed");
  167. // Also check the run-time NSS version.
  168. // NSS_VersionCheck is a >= check, not strict equality.
  169. if (!NSS_VersionCheck("3.26")) {
  170. LOG(FATAL) << "NSS_VersionCheck(\"3.26\") failed. NSS >= 3.26 is "
  171. "required. Please upgrade to the latest NSS, and if you "
  172. "still get this error, contact your distribution "
  173. "maintainer.";
  174. }
  175. SECStatus status = SECFailure;
  176. base::FilePath database_dir = GetInitialConfigDirectory();
  177. if (!database_dir.empty()) {
  178. // Initialize with a persistent database (likely, ~/.pki/nssdb).
  179. // Use "sql:" which can be shared by multiple processes safely.
  180. std::string nss_config_dir =
  181. base::StringPrintf("sql:%s", database_dir.value().c_str());
  182. #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
  183. status = NSS_Init(nss_config_dir.c_str());
  184. #else
  185. status = NSS_InitReadWrite(nss_config_dir.c_str());
  186. #endif
  187. if (status != SECSuccess) {
  188. LOG(ERROR) << "Error initializing NSS with a persistent "
  189. "database ("
  190. << nss_config_dir << "): " << GetNSSErrorMessage();
  191. }
  192. }
  193. if (status != SECSuccess) {
  194. VLOG(1) << "Initializing NSS without a persistent database.";
  195. status = NSS_NoDB_Init(nullptr);
  196. if (status != SECSuccess) {
  197. CrashOnNSSInitFailure();
  198. return;
  199. }
  200. }
  201. PK11_SetPasswordFunc(PKCS11PasswordFunc);
  202. // If we haven't initialized the password for the NSS databases,
  203. // initialize an empty-string password so that we don't need to
  204. // log in.
  205. PK11SlotInfo* slot = PK11_GetInternalKeySlot();
  206. if (slot) {
  207. // PK11_InitPin may write to the keyDB, but no other thread can use NSS
  208. // yet, so we don't need to lock.
  209. if (PK11_NeedUserInit(slot))
  210. PK11_InitPin(slot, nullptr, nullptr);
  211. PK11_FreeSlot(slot);
  212. }
  213. // Load nss's built-in root certs.
  214. //
  215. // TODO(mattm): DCHECK this succeeded when crbug.com/310972 is fixed.
  216. // Failing to load root certs will it hard to talk to anybody via https.
  217. LoadNSSModule("Root Certs", "libnssckbi.so", nullptr);
  218. // Disable MD5 certificate signatures. (They are disabled by default in
  219. // NSS 3.14.)
  220. NSS_SetAlgorithmPolicy(SEC_OID_MD5, 0, NSS_USE_ALG_IN_CERT_SIGNATURE);
  221. NSS_SetAlgorithmPolicy(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION, 0,
  222. NSS_USE_ALG_IN_CERT_SIGNATURE);
  223. }
  224. // Stores opened software NSS databases.
  225. base::flat_map<base::FilePath, /*slot=*/ScopedPK11Slot> slot_map_
  226. GUARDED_BY(slot_map_lock_);
  227. // Ensures thread-safety for the methods that modify slot_map_.
  228. // Performance considerations:
  229. // Opening/closing a database is a rare operation in Chrome. Actually opening
  230. // a database is a blocking I/O operation. Chrome doesn't open a lot of
  231. // different databases in parallel. So, waiting for another thread to finish
  232. // opening a database and (almost certainly) reusing the result is comparable
  233. // to opening the same database twice in parallel (but the latter is not
  234. // supported by NSS).
  235. base::Lock slot_map_lock_;
  236. };
  237. base::LazyInstance<NSSInitSingleton>::Leaky g_nss_singleton =
  238. LAZY_INSTANCE_INITIALIZER;
  239. } // namespace
  240. ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
  241. const std::string& description) {
  242. return g_nss_singleton.Get().OpenSoftwareNSSDB(path, description);
  243. }
  244. SECStatus CloseSoftwareNSSDB(PK11SlotInfo* slot) {
  245. return g_nss_singleton.Get().CloseSoftwareNSSDB(slot);
  246. }
  247. void EnsureNSPRInit() {
  248. g_nspr_singleton.Get();
  249. }
  250. void EnsureNSSInit() {
  251. g_nss_singleton.Get();
  252. }
  253. bool CheckNSSVersion(const char* version) {
  254. return !!NSS_VersionCheck(version);
  255. }
  256. AutoSECMODListReadLock::AutoSECMODListReadLock()
  257. : lock_(SECMOD_GetDefaultModuleListLock()) {
  258. SECMOD_GetReadLock(lock_);
  259. }
  260. AutoSECMODListReadLock::~AutoSECMODListReadLock() {
  261. SECMOD_ReleaseReadLock(lock_);
  262. }
  263. base::Time PRTimeToBaseTime(PRTime prtime) {
  264. return base::Time::FromInternalValue(
  265. prtime + base::Time::UnixEpoch().ToInternalValue());
  266. }
  267. PRTime BaseTimeToPRTime(base::Time time) {
  268. return time.ToInternalValue() - base::Time::UnixEpoch().ToInternalValue();
  269. }
  270. SECMODModule* LoadNSSModule(const char* name,
  271. const char* library_path,
  272. const char* params) {
  273. std::string modparams =
  274. base::StringPrintf("name=\"%s\" library=\"%s\" %s", name, library_path,
  275. params ? params : "");
  276. // Shouldn't need to const_cast here, but SECMOD doesn't properly declare
  277. // input string arguments as const. Bug
  278. // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed on NSS
  279. // codebase to address this.
  280. SECMODModule* module = SECMOD_LoadUserModule(
  281. const_cast<char*>(modparams.c_str()), nullptr, PR_FALSE);
  282. if (!module) {
  283. LOG(ERROR) << "Error loading " << name
  284. << " module into NSS: " << GetNSSErrorMessage();
  285. return nullptr;
  286. }
  287. if (!module->loaded) {
  288. LOG(ERROR) << "After loading " << name
  289. << ", loaded==false: " << GetNSSErrorMessage();
  290. SECMOD_DestroyModule(module);
  291. return nullptr;
  292. }
  293. return module;
  294. }
  295. std::string GetNSSErrorMessage() {
  296. std::string result;
  297. if (PR_GetErrorTextLength()) {
  298. std::unique_ptr<char[]> error_text(new char[PR_GetErrorTextLength() + 1]);
  299. PRInt32 copied = PR_GetErrorText(error_text.get());
  300. result = std::string(error_text.get(), copied);
  301. } else {
  302. result = base::StringPrintf("NSS error code: %d", PR_GetError());
  303. }
  304. return result;
  305. }
  306. } // namespace crypto