x509_util_nss.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2015 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 "net/cert/x509_util_nss.h"
  5. #include <cert.h> // Must be included before certdb.h
  6. #include <certdb.h>
  7. #include <cryptohi.h>
  8. #include <nss.h>
  9. #include <pk11pub.h>
  10. #include <prerror.h>
  11. #include <secder.h>
  12. #include <sechash.h>
  13. #include <secmod.h>
  14. #include <secport.h>
  15. #include <string.h>
  16. #include "base/logging.h"
  17. #include "base/strings/stringprintf.h"
  18. #include "crypto/nss_util.h"
  19. #include "crypto/scoped_nss_types.h"
  20. #include "third_party/boringssl/src/include/openssl/pool.h"
  21. namespace net::x509_util {
  22. namespace {
  23. // Microsoft User Principal Name: 1.3.6.1.4.1.311.20.2.3
  24. const uint8_t kUpnOid[] = {0x2b, 0x6, 0x1, 0x4, 0x1,
  25. 0x82, 0x37, 0x14, 0x2, 0x3};
  26. std::string DecodeAVAValue(CERTAVA* ava) {
  27. SECItem* decode_item = CERT_DecodeAVAValue(&ava->value);
  28. if (!decode_item)
  29. return std::string();
  30. std::string value(reinterpret_cast<char*>(decode_item->data),
  31. decode_item->len);
  32. SECITEM_FreeItem(decode_item, PR_TRUE);
  33. return value;
  34. }
  35. // Generates a unique nickname for |slot|, returning |nickname| if it is
  36. // already unique.
  37. //
  38. // Note: The nickname returned will NOT include the token name, thus the
  39. // token name must be prepended if calling an NSS function that expects
  40. // <token>:<nickname>.
  41. // TODO(gspencer): Internationalize this: it's wrong to hard-code English.
  42. std::string GetUniqueNicknameForSlot(const std::string& nickname,
  43. const SECItem* subject,
  44. PK11SlotInfo* slot) {
  45. int index = 2;
  46. std::string new_name = nickname;
  47. std::string temp_nickname = new_name;
  48. std::string token_name;
  49. if (!slot)
  50. return new_name;
  51. if (!PK11_IsInternalKeySlot(slot)) {
  52. token_name.assign(PK11_GetTokenName(slot));
  53. token_name.append(":");
  54. temp_nickname = token_name + new_name;
  55. }
  56. while (SEC_CertNicknameConflict(temp_nickname.c_str(),
  57. const_cast<SECItem*>(subject),
  58. CERT_GetDefaultCertDB())) {
  59. base::SStringPrintf(&new_name, "%s #%d", nickname.c_str(), index++);
  60. temp_nickname = token_name + new_name;
  61. }
  62. return new_name;
  63. }
  64. // The default nickname of the certificate, based on the certificate type
  65. // passed in.
  66. std::string GetDefaultNickname(CERTCertificate* nss_cert, CertType type) {
  67. std::string result;
  68. if (type == USER_CERT && nss_cert->slot) {
  69. // Find the private key for this certificate and see if it has a
  70. // nickname. If there is a private key, and it has a nickname, then
  71. // return that nickname.
  72. SECKEYPrivateKey* private_key = PK11_FindPrivateKeyFromCert(
  73. nss_cert->slot, nss_cert, nullptr /*wincx*/);
  74. if (private_key) {
  75. char* private_key_nickname = PK11_GetPrivateKeyNickname(private_key);
  76. if (private_key_nickname) {
  77. result = private_key_nickname;
  78. PORT_Free(private_key_nickname);
  79. SECKEY_DestroyPrivateKey(private_key);
  80. return result;
  81. }
  82. SECKEY_DestroyPrivateKey(private_key);
  83. }
  84. }
  85. switch (type) {
  86. case CA_CERT: {
  87. char* nickname = CERT_MakeCANickname(nss_cert);
  88. result = nickname;
  89. PORT_Free(nickname);
  90. break;
  91. }
  92. case USER_CERT: {
  93. std::string subject_name = GetCERTNameDisplayName(&nss_cert->subject);
  94. if (subject_name.empty()) {
  95. const char* email = CERT_GetFirstEmailAddress(nss_cert);
  96. if (email)
  97. subject_name = email;
  98. }
  99. // TODO(gspencer): Internationalize this. It's wrong to assume English
  100. // here.
  101. result =
  102. base::StringPrintf("%s's %s ID", subject_name.c_str(),
  103. GetCERTNameDisplayName(&nss_cert->issuer).c_str());
  104. break;
  105. }
  106. case SERVER_CERT: {
  107. result = GetCERTNameDisplayName(&nss_cert->subject);
  108. break;
  109. }
  110. case OTHER_CERT:
  111. default:
  112. break;
  113. }
  114. return result;
  115. }
  116. } // namespace
  117. bool IsSameCertificate(CERTCertificate* a, CERTCertificate* b) {
  118. DCHECK(a && b);
  119. if (a == b)
  120. return true;
  121. return a->derCert.len == b->derCert.len &&
  122. memcmp(a->derCert.data, b->derCert.data, a->derCert.len) == 0;
  123. }
  124. bool IsSameCertificate(CERTCertificate* a, const X509Certificate* b) {
  125. return a->derCert.len == CRYPTO_BUFFER_len(b->cert_buffer()) &&
  126. memcmp(a->derCert.data, CRYPTO_BUFFER_data(b->cert_buffer()),
  127. a->derCert.len) == 0;
  128. }
  129. bool IsSameCertificate(const X509Certificate* a, CERTCertificate* b) {
  130. return IsSameCertificate(b, a);
  131. }
  132. ScopedCERTCertificate CreateCERTCertificateFromBytes(const uint8_t* data,
  133. size_t length) {
  134. crypto::EnsureNSSInit();
  135. if (!NSS_IsInitialized())
  136. return nullptr;
  137. SECItem der_cert;
  138. der_cert.data = const_cast<uint8_t*>(data);
  139. der_cert.len = base::checked_cast<unsigned>(length);
  140. der_cert.type = siDERCertBuffer;
  141. // Parse into a certificate structure.
  142. return ScopedCERTCertificate(CERT_NewTempCertificate(
  143. CERT_GetDefaultCertDB(), &der_cert, nullptr /* nickname */,
  144. PR_FALSE /* is_perm */, PR_TRUE /* copyDER */));
  145. }
  146. ScopedCERTCertificate CreateCERTCertificateFromX509Certificate(
  147. const X509Certificate* cert) {
  148. return CreateCERTCertificateFromBytes(CRYPTO_BUFFER_data(cert->cert_buffer()),
  149. CRYPTO_BUFFER_len(cert->cert_buffer()));
  150. }
  151. ScopedCERTCertificateList CreateCERTCertificateListFromX509Certificate(
  152. const X509Certificate* cert) {
  153. return x509_util::CreateCERTCertificateListFromX509Certificate(
  154. cert, InvalidIntermediateBehavior::kFail);
  155. }
  156. ScopedCERTCertificateList CreateCERTCertificateListFromX509Certificate(
  157. const X509Certificate* cert,
  158. InvalidIntermediateBehavior invalid_intermediate_behavior) {
  159. ScopedCERTCertificateList nss_chain;
  160. nss_chain.reserve(1 + cert->intermediate_buffers().size());
  161. ScopedCERTCertificate nss_cert =
  162. CreateCERTCertificateFromX509Certificate(cert);
  163. if (!nss_cert)
  164. return {};
  165. nss_chain.push_back(std::move(nss_cert));
  166. for (const auto& intermediate : cert->intermediate_buffers()) {
  167. ScopedCERTCertificate nss_intermediate =
  168. CreateCERTCertificateFromBytes(CRYPTO_BUFFER_data(intermediate.get()),
  169. CRYPTO_BUFFER_len(intermediate.get()));
  170. if (!nss_intermediate) {
  171. if (invalid_intermediate_behavior == InvalidIntermediateBehavior::kFail)
  172. return {};
  173. LOG(WARNING) << "error parsing intermediate";
  174. continue;
  175. }
  176. nss_chain.push_back(std::move(nss_intermediate));
  177. }
  178. return nss_chain;
  179. }
  180. ScopedCERTCertificateList CreateCERTCertificateListFromBytes(const char* data,
  181. size_t length,
  182. int format) {
  183. CertificateList certs = X509Certificate::CreateCertificateListFromBytes(
  184. base::as_bytes(base::make_span(data, length)), format);
  185. ScopedCERTCertificateList nss_chain;
  186. nss_chain.reserve(certs.size());
  187. for (const scoped_refptr<X509Certificate>& cert : certs) {
  188. ScopedCERTCertificate nss_cert =
  189. CreateCERTCertificateFromX509Certificate(cert.get());
  190. if (!nss_cert)
  191. return {};
  192. nss_chain.push_back(std::move(nss_cert));
  193. }
  194. return nss_chain;
  195. }
  196. ScopedCERTCertificate DupCERTCertificate(CERTCertificate* cert) {
  197. return ScopedCERTCertificate(CERT_DupCertificate(cert));
  198. }
  199. ScopedCERTCertificateList DupCERTCertificateList(
  200. const ScopedCERTCertificateList& certs) {
  201. ScopedCERTCertificateList result;
  202. result.reserve(certs.size());
  203. for (const ScopedCERTCertificate& cert : certs)
  204. result.push_back(DupCERTCertificate(cert.get()));
  205. return result;
  206. }
  207. scoped_refptr<X509Certificate> CreateX509CertificateFromCERTCertificate(
  208. CERTCertificate* nss_cert,
  209. const std::vector<CERTCertificate*>& nss_chain) {
  210. return CreateX509CertificateFromCERTCertificate(nss_cert, nss_chain, {});
  211. }
  212. scoped_refptr<X509Certificate> CreateX509CertificateFromCERTCertificate(
  213. CERTCertificate* nss_cert,
  214. const std::vector<CERTCertificate*>& nss_chain,
  215. X509Certificate::UnsafeCreateOptions options) {
  216. if (!nss_cert || !nss_cert->derCert.len)
  217. return nullptr;
  218. bssl::UniquePtr<CRYPTO_BUFFER> cert_handle(
  219. X509Certificate::CreateCertBufferFromBytes(
  220. base::make_span(nss_cert->derCert.data, nss_cert->derCert.len)));
  221. if (!cert_handle)
  222. return nullptr;
  223. std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates;
  224. intermediates.reserve(nss_chain.size());
  225. for (const CERTCertificate* nss_intermediate : nss_chain) {
  226. if (!nss_intermediate || !nss_intermediate->derCert.len)
  227. return nullptr;
  228. bssl::UniquePtr<CRYPTO_BUFFER> intermediate_cert_handle(
  229. X509Certificate::CreateCertBufferFromBytes(base::make_span(
  230. nss_intermediate->derCert.data, nss_intermediate->derCert.len)));
  231. if (!intermediate_cert_handle)
  232. return nullptr;
  233. intermediates.push_back(std::move(intermediate_cert_handle));
  234. }
  235. scoped_refptr<X509Certificate> result(
  236. X509Certificate::CreateFromBufferUnsafeOptions(
  237. std::move(cert_handle), std::move(intermediates), options));
  238. return result;
  239. }
  240. scoped_refptr<X509Certificate> CreateX509CertificateFromCERTCertificate(
  241. CERTCertificate* cert) {
  242. return CreateX509CertificateFromCERTCertificate(
  243. cert, std::vector<CERTCertificate*>());
  244. }
  245. CertificateList CreateX509CertificateListFromCERTCertificates(
  246. const ScopedCERTCertificateList& certs) {
  247. CertificateList result;
  248. result.reserve(certs.size());
  249. for (const ScopedCERTCertificate& cert : certs) {
  250. scoped_refptr<X509Certificate> x509_cert(
  251. CreateX509CertificateFromCERTCertificate(cert.get()));
  252. if (!x509_cert)
  253. return {};
  254. result.push_back(std::move(x509_cert));
  255. }
  256. return result;
  257. }
  258. bool GetDEREncoded(CERTCertificate* cert, std::string* der_encoded) {
  259. if (!cert || !cert->derCert.len)
  260. return false;
  261. der_encoded->assign(reinterpret_cast<char*>(cert->derCert.data),
  262. cert->derCert.len);
  263. return true;
  264. }
  265. bool GetPEMEncoded(CERTCertificate* cert, std::string* pem_encoded) {
  266. if (!cert || !cert->derCert.len)
  267. return false;
  268. std::string der(reinterpret_cast<char*>(cert->derCert.data),
  269. cert->derCert.len);
  270. return X509Certificate::GetPEMEncodedFromDER(der, pem_encoded);
  271. }
  272. void GetRFC822SubjectAltNames(CERTCertificate* cert_handle,
  273. std::vector<std::string>* names) {
  274. crypto::ScopedSECItem alt_name(SECITEM_AllocItem(nullptr, nullptr, 0));
  275. DCHECK(alt_name.get());
  276. names->clear();
  277. SECStatus rv = CERT_FindCertExtension(
  278. cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get());
  279. if (rv != SECSuccess)
  280. return;
  281. crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
  282. DCHECK(arena.get());
  283. CERTGeneralName* alt_name_list;
  284. alt_name_list = CERT_DecodeAltNameExtension(arena.get(), alt_name.get());
  285. CERTGeneralName* name = alt_name_list;
  286. while (name) {
  287. if (name->type == certRFC822Name) {
  288. names->push_back(
  289. std::string(reinterpret_cast<char*>(name->name.other.data),
  290. name->name.other.len));
  291. }
  292. name = CERT_GetNextGeneralName(name);
  293. if (name == alt_name_list)
  294. break;
  295. }
  296. }
  297. void GetUPNSubjectAltNames(CERTCertificate* cert_handle,
  298. std::vector<std::string>* names) {
  299. crypto::ScopedSECItem alt_name(SECITEM_AllocItem(nullptr, nullptr, 0));
  300. DCHECK(alt_name.get());
  301. names->clear();
  302. SECStatus rv = CERT_FindCertExtension(
  303. cert_handle, SEC_OID_X509_SUBJECT_ALT_NAME, alt_name.get());
  304. if (rv != SECSuccess)
  305. return;
  306. crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
  307. DCHECK(arena.get());
  308. CERTGeneralName* alt_name_list;
  309. alt_name_list = CERT_DecodeAltNameExtension(arena.get(), alt_name.get());
  310. CERTGeneralName* name = alt_name_list;
  311. while (name) {
  312. if (name->type == certOtherName) {
  313. OtherName* on = &name->name.OthName;
  314. if (on->oid.len == sizeof(kUpnOid) &&
  315. memcmp(on->oid.data, kUpnOid, sizeof(kUpnOid)) == 0) {
  316. SECItem decoded;
  317. if (SEC_QuickDERDecodeItem(arena.get(), &decoded,
  318. SEC_ASN1_GET(SEC_UTF8StringTemplate),
  319. &name->name.OthName.name) == SECSuccess) {
  320. names->push_back(
  321. std::string(reinterpret_cast<char*>(decoded.data), decoded.len));
  322. }
  323. }
  324. }
  325. name = CERT_GetNextGeneralName(name);
  326. if (name == alt_name_list)
  327. break;
  328. }
  329. }
  330. std::string GetDefaultUniqueNickname(CERTCertificate* nss_cert,
  331. CertType type,
  332. PK11SlotInfo* slot) {
  333. return GetUniqueNicknameForSlot(GetDefaultNickname(nss_cert, type),
  334. &nss_cert->derSubject, slot);
  335. }
  336. std::string GetCERTNameDisplayName(CERTName* name) {
  337. // Search for attributes in the Name, in this order: CN, O and OU.
  338. CERTAVA* ou_ava = nullptr;
  339. CERTAVA* o_ava = nullptr;
  340. CERTRDN** rdns = name->rdns;
  341. for (size_t rdn = 0; rdns[rdn]; ++rdn) {
  342. CERTAVA** avas = rdns[rdn]->avas;
  343. for (size_t pair = 0; avas[pair] != nullptr; ++pair) {
  344. SECOidTag tag = CERT_GetAVATag(avas[pair]);
  345. if (tag == SEC_OID_AVA_COMMON_NAME) {
  346. // If CN is found, return immediately.
  347. return DecodeAVAValue(avas[pair]);
  348. }
  349. // If O or OU is found, save the first one of each so that it can be
  350. // returned later if no CN attribute is found.
  351. if (tag == SEC_OID_AVA_ORGANIZATION_NAME && !o_ava)
  352. o_ava = avas[pair];
  353. if (tag == SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME && !ou_ava)
  354. ou_ava = avas[pair];
  355. }
  356. }
  357. if (o_ava)
  358. return DecodeAVAValue(o_ava);
  359. if (ou_ava)
  360. return DecodeAVAValue(ou_ava);
  361. return std::string();
  362. }
  363. bool GetValidityTimes(CERTCertificate* cert,
  364. base::Time* not_before,
  365. base::Time* not_after) {
  366. PRTime pr_not_before, pr_not_after;
  367. if (CERT_GetCertTimes(cert, &pr_not_before, &pr_not_after) == SECSuccess) {
  368. if (not_before)
  369. *not_before = crypto::PRTimeToBaseTime(pr_not_before);
  370. if (not_after)
  371. *not_after = crypto::PRTimeToBaseTime(pr_not_after);
  372. return true;
  373. }
  374. return false;
  375. }
  376. SHA256HashValue CalculateFingerprint256(CERTCertificate* cert) {
  377. SHA256HashValue sha256;
  378. memset(sha256.data, 0, sizeof(sha256.data));
  379. DCHECK(cert->derCert.data);
  380. DCHECK_NE(0U, cert->derCert.len);
  381. SECStatus rv = HASH_HashBuf(HASH_AlgSHA256, sha256.data, cert->derCert.data,
  382. cert->derCert.len);
  383. DCHECK_EQ(SECSuccess, rv);
  384. return sha256;
  385. }
  386. } // namespace net::x509_util