x509_nss.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file x509_nss.c
  7. * \brief Wrapper functions to present a consistent interface to
  8. * X.509 functions from NSS.
  9. **/
  10. #define TOR_X509_PRIVATE
  11. #include "lib/tls/x509.h"
  12. #include "lib/tls/x509_internal.h"
  13. #include "lib/tls/tortls.h"
  14. #include "lib/crypt_ops/crypto_rand.h"
  15. #include "lib/crypt_ops/crypto_util.h"
  16. #include "lib/crypt_ops/crypto_nss_mgt.h"
  17. #include "lib/log/util_bug.h"
  18. #include "lib/encoding/time_fmt.h"
  19. #include "lib/string/printf.h"
  20. #include <pk11pub.h>
  21. #include <cryptohi.h>
  22. #include <cert.h>
  23. #include <keyhi.h>
  24. #include <time.h>
  25. /* Units of PRTime per second.
  26. *
  27. * (PRTime is based in microseconds since the Unix
  28. * epoch.) */
  29. #define PRTIME_PER_SEC (1000*1000)
  30. static tor_x509_cert_impl_t *tor_x509_cert_decode_internal(
  31. const uint8_t *certificate, int certificate_len);
  32. static tor_x509_cert_impl_t *
  33. tor_tls_create_certificate_internal(crypto_pk_t *rsa,
  34. crypto_pk_t *rsa_sign,
  35. CERTName *subject_dn,
  36. CERTName *issuer_dn,
  37. time_t start_time,
  38. time_t end_time)
  39. {
  40. if (! crypto_pk_key_is_private(rsa_sign)) {
  41. return NULL;
  42. }
  43. const SECKEYPublicKey *subject_key = crypto_pk_get_nss_pubkey(rsa);
  44. const SECKEYPrivateKey *signing_key = crypto_pk_get_nss_privkey(rsa_sign);
  45. SECStatus s;
  46. CERTSubjectPublicKeyInfo *subject_spki = NULL;
  47. CERTCertificateRequest *request = NULL;
  48. CERTValidity *validity = NULL;
  49. CERTCertificate *cert = NULL;
  50. SECItem der = { .data = NULL, .len = 0 };
  51. SECItem signed_der = { .data = NULL, .len = 0 };
  52. CERTCertificate *result_cert = NULL;
  53. validity = CERT_CreateValidity(((PRTime)start_time) * PRTIME_PER_SEC,
  54. ((PRTime)end_time) * PRTIME_PER_SEC);
  55. if (BUG(! validity)) {
  56. /* LCOV_EXCL_START */
  57. crypto_nss_log_errors(LOG_WARN, "creating a validity object");
  58. goto err;
  59. /* LCOV_EXCL_STOP */
  60. }
  61. unsigned long serial_number;
  62. crypto_rand((char*)&serial_number, sizeof(serial_number));
  63. subject_spki = SECKEY_CreateSubjectPublicKeyInfo(subject_key);
  64. if (!subject_spki)
  65. goto err;
  66. /* Make a CSR ... */
  67. // XXX do we need to set any attributes?
  68. request = CERT_CreateCertificateRequest(subject_dn,
  69. subject_spki,
  70. NULL /* attributes */);
  71. if (!request)
  72. goto err;
  73. /* Put it into a certificate ... */
  74. cert = CERT_CreateCertificate(serial_number,
  75. issuer_dn,
  76. validity,
  77. request);
  78. if (!cert)
  79. goto err;
  80. /* version 3 cert */
  81. *cert->version.data = 2; /* 2 means version 3. */
  82. cert->version.len = 1;
  83. // XXX do we need to set anything else on the cert?
  84. /* Sign it. */
  85. KeyType privkey_type = SECKEY_GetPrivateKeyType(signing_key);
  86. SECOidTag oid_tag = SEC_GetSignatureAlgorithmOidTag(privkey_type,
  87. SEC_OID_SHA256);
  88. if (oid_tag == SEC_OID_UNKNOWN)
  89. goto err;
  90. s = SECOID_SetAlgorithmID(cert->arena, &cert->signature, oid_tag, NULL);
  91. if (s != SECSuccess)
  92. goto err;
  93. void *tmp;
  94. tmp = SEC_ASN1EncodeItem(cert->arena, &der, cert,
  95. SEC_ASN1_GET(CERT_CertificateTemplate));
  96. if (!tmp)
  97. goto err;
  98. #if 0
  99. s = SEC_DerSignDataWithAlgorithmID(cert->arena,
  100. &signed_der,
  101. der.data, der.len,
  102. (SECKEYPrivateKey *)signing_key,//const
  103. &cert->signature);
  104. #else
  105. s = SEC_DerSignData(cert->arena,
  106. &signed_der,
  107. der.data, der.len,
  108. (SECKEYPrivateKey *)signing_key,//const
  109. SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION);
  110. #endif
  111. if (s != SECSuccess)
  112. goto err;
  113. /* Re-parse it, to make sure all the certificates we actually use
  114. * appear via being decoded. */
  115. result_cert = tor_x509_cert_decode_internal(signed_der.data, signed_der.len);
  116. #if 1
  117. {
  118. // Can we check the cert we just signed?
  119. tor_assert(result_cert);
  120. SECKEYPublicKey *issuer_pk = (SECKEYPublicKey *)
  121. crypto_pk_get_nss_pubkey(rsa_sign);
  122. SECStatus cert_ok = CERT_VerifySignedDataWithPublicKey(
  123. &result_cert->signatureWrap, issuer_pk, NULL);
  124. tor_assert(cert_ok == SECSuccess);
  125. }
  126. #endif
  127. err:
  128. if (subject_spki)
  129. SECKEY_DestroySubjectPublicKeyInfo(subject_spki);
  130. if (request)
  131. CERT_DestroyCertificateRequest(request);
  132. if (validity)
  133. CERT_DestroyValidity(validity);
  134. // unnecessary, since these are allocated in the cert's arena.
  135. //SECITEM_FreeItem(&der, PR_FALSE);
  136. //SECITEM_FreeItem(&signed_der, PR_FALSE);
  137. if (cert)
  138. CERT_DestroyCertificate(cert);
  139. return result_cert;
  140. }
  141. MOCK_IMPL(tor_x509_cert_impl_t *,
  142. tor_tls_create_certificate,(crypto_pk_t *rsa,
  143. crypto_pk_t *rsa_sign,
  144. const char *cname,
  145. const char *cname_sign,
  146. unsigned int cert_lifetime))
  147. {
  148. tor_assert(rsa);
  149. tor_assert(rsa_sign);
  150. tor_assert(cname);
  151. tor_assert(cname_sign);
  152. char *cname_rfc_1485 = NULL, *cname_sign_rfc_1485 = NULL;
  153. CERTName *subject_dn = NULL, *issuer_dn = NULL;
  154. time_t start_time;
  155. time_t end_time;
  156. CERTCertificate *result = NULL;
  157. tor_asprintf(&cname_rfc_1485, "CN=%s", cname);
  158. tor_asprintf(&cname_sign_rfc_1485, "CN=%s", cname_sign);
  159. subject_dn = CERT_AsciiToName(cname_rfc_1485);
  160. issuer_dn = CERT_AsciiToName(cname_sign_rfc_1485);
  161. if (!subject_dn || !issuer_dn)
  162. goto err;
  163. tor_tls_pick_certificate_lifetime(time(NULL), cert_lifetime,
  164. &start_time, &end_time);
  165. result = tor_tls_create_certificate_internal(rsa,
  166. rsa_sign,
  167. subject_dn,
  168. issuer_dn,
  169. start_time,
  170. end_time);
  171. err:
  172. tor_free(cname_rfc_1485);
  173. tor_free(cname_sign_rfc_1485);
  174. if (subject_dn)
  175. CERT_DestroyName(subject_dn);
  176. if (issuer_dn)
  177. CERT_DestroyName(issuer_dn);
  178. return result;
  179. }
  180. /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
  181. * representation and length, respectively. */
  182. void
  183. tor_x509_cert_get_der(const tor_x509_cert_t *cert,
  184. const uint8_t **encoded_out, size_t *size_out)
  185. {
  186. tor_assert(cert);
  187. tor_assert(cert->cert);
  188. tor_assert(encoded_out);
  189. tor_assert(size_out);
  190. const SECItem *item = &cert->cert->derCert;
  191. *encoded_out = item->data;
  192. *size_out = (size_t)item->len;
  193. }
  194. void
  195. tor_x509_cert_impl_free_(tor_x509_cert_impl_t *cert)
  196. {
  197. if (cert)
  198. CERT_DestroyCertificate(cert);
  199. }
  200. tor_x509_cert_impl_t *
  201. tor_x509_cert_impl_dup_(tor_x509_cert_impl_t *cert)
  202. {
  203. if (cert)
  204. return CERT_DupCertificate(cert);
  205. else
  206. return NULL;
  207. }
  208. /**
  209. * As tor_x509_cert_decode, but return the NSS certificate type
  210. */
  211. static tor_x509_cert_impl_t *
  212. tor_x509_cert_decode_internal(const uint8_t *certificate,
  213. int certificate_len)
  214. {
  215. tor_assert(certificate);
  216. if (certificate_len > INT_MAX)
  217. return NULL;
  218. SECItem der = { .type = siBuffer,
  219. .data = (unsigned char *)certificate,
  220. .len = certificate_len };
  221. CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
  222. tor_assert(certdb);
  223. return CERT_NewTempCertificate(certdb,
  224. &der,
  225. NULL /* nickname */,
  226. PR_FALSE, /* isPerm */
  227. PR_TRUE /* CopyDER */);
  228. }
  229. tor_x509_cert_t *
  230. tor_x509_cert_decode(const uint8_t *certificate,
  231. size_t certificate_len)
  232. {
  233. CERTCertificate *cert = tor_x509_cert_decode_internal(certificate,
  234. (int)certificate_len);
  235. if (! cert) {
  236. crypto_nss_log_errors(LOG_INFO, "decoding certificate");
  237. return NULL;
  238. }
  239. tor_x509_cert_t *newcert = tor_x509_cert_new(cert);
  240. return newcert;
  241. }
  242. crypto_pk_t *
  243. tor_tls_cert_get_key(tor_x509_cert_t *cert)
  244. {
  245. tor_assert(cert);
  246. CERTSubjectPublicKeyInfo *spki = &cert->cert->subjectPublicKeyInfo;
  247. SECKEYPublicKey *pub = SECKEY_ExtractPublicKey(spki); // we own this pointer
  248. if (pub == NULL)
  249. return NULL;
  250. if (SECKEY_GetPublicKeyType(pub) != rsaKey) {
  251. SECKEY_DestroyPublicKey(pub);
  252. return NULL;
  253. }
  254. return crypto_pk_new_from_nss_pubkey(pub);
  255. }
  256. int
  257. tor_tls_cert_is_valid(int severity,
  258. const tor_x509_cert_t *cert,
  259. const tor_x509_cert_t *signing_cert,
  260. time_t now,
  261. int check_rsa_1024)
  262. {
  263. int result = 0;
  264. tor_assert(cert);
  265. tor_assert(signing_cert);
  266. SECKEYPublicKey *pk = CERT_ExtractPublicKey(signing_cert->cert);
  267. if (pk == NULL) {
  268. log_fn(severity, LD_CRYPTO,
  269. "Invalid certificate: could not extract issuer key");
  270. goto fail;
  271. }
  272. SECStatus s = CERT_VerifySignedDataWithPublicKey(&cert->cert->signatureWrap,
  273. pk, NULL);
  274. if (s != SECSuccess) {
  275. log_fn(severity, LD_CRYPTO,
  276. "Invalid certificate: could not validate signature.");
  277. goto fail;
  278. }
  279. if (tor_x509_check_cert_lifetime_internal(severity,
  280. cert->cert,
  281. now,
  282. TOR_X509_PAST_SLOP,
  283. TOR_X509_FUTURE_SLOP) < 0)
  284. goto fail;
  285. if (check_rsa_1024) {
  286. /* We require that this is a 1024-bit RSA key, for legacy reasons .:p */
  287. if (SECKEY_GetPublicKeyType(pk) != rsaKey ||
  288. SECKEY_PublicKeyStrengthInBits(pk) != 1024) {
  289. log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is not RSA1024.");
  290. goto fail;
  291. }
  292. } else {
  293. /* We require that this key is at least minimally strong. */
  294. unsigned min_bits = (SECKEY_GetPublicKeyType(pk) == ecKey) ? 128: 1024;
  295. if (SECKEY_PublicKeyStrengthInBits(pk) < min_bits) {
  296. log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is too weak.");
  297. goto fail;
  298. }
  299. }
  300. /* The certificate is valid. */
  301. result = 1;
  302. fail:
  303. if (pk)
  304. SECKEY_DestroyPublicKey(pk);
  305. return result;
  306. }
  307. static void
  308. log_cert_lifetime(int severity,
  309. const char *status,
  310. time_t now,
  311. PRTime notBefore,
  312. PRTime notAfter)
  313. {
  314. log_fn(severity, LD_GENERAL,
  315. "Certificate %s. Either their clock is set wrong, or your clock "
  316. "is incorrect.", status);
  317. char nowbuf[ISO_TIME_LEN+1];
  318. char nbbuf[ISO_TIME_LEN+1];
  319. char nabuf[ISO_TIME_LEN+1];
  320. format_iso_time(nowbuf, now);
  321. format_iso_time(nbbuf, notBefore / PRTIME_PER_SEC);
  322. format_iso_time(nabuf, notAfter / PRTIME_PER_SEC);
  323. log_fn(severity, LD_GENERAL,
  324. "(The certificate is valid from %s until %s. Your time is %s.)",
  325. nbbuf, nabuf, nowbuf);
  326. }
  327. int
  328. tor_x509_check_cert_lifetime_internal(int severity,
  329. const tor_x509_cert_impl_t *cert,
  330. time_t now,
  331. int past_tolerance,
  332. int future_tolerance)
  333. {
  334. tor_assert(cert);
  335. PRTime notBefore=0, notAfter=0;
  336. int64_t t;
  337. SECStatus r = CERT_GetCertTimes(cert, &notBefore, &notAfter);
  338. if (r != SECSuccess) {
  339. log_fn(severity, LD_CRYPTO,
  340. "Couldn't get validity times from certificate");
  341. return -1;
  342. }
  343. t = ((int64_t)now) + future_tolerance;
  344. t *= PRTIME_PER_SEC;
  345. if (notBefore > t) {
  346. log_cert_lifetime(severity, "not yet valid", now,
  347. notBefore, notAfter);
  348. return -1;
  349. }
  350. t = ((int64_t)now) - past_tolerance;
  351. t *= PRTIME_PER_SEC;
  352. if (notAfter < t) {
  353. log_cert_lifetime(severity, "already expired", now,
  354. notBefore, notAfter);
  355. return -1;
  356. }
  357. return 0;
  358. }
  359. #ifdef TOR_UNIT_TESTS
  360. tor_x509_cert_t *
  361. tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
  362. time_t new_expiration_time,
  363. crypto_pk_t *signing_key)
  364. {
  365. tor_assert(inp);
  366. tor_assert(signing_key);
  367. PRTime notBefore=0, notAfter=0;
  368. SECStatus r = CERT_GetCertTimes(inp->cert, &notBefore, &notAfter);
  369. if (r != SECSuccess)
  370. return NULL;
  371. time_t start_time = notBefore / PRTIME_PER_SEC;
  372. if (new_expiration_time < start_time) {
  373. /* This prevents an NSS error. */
  374. start_time = new_expiration_time - 10;
  375. }
  376. crypto_pk_t *subject_key = tor_tls_cert_get_key((tor_x509_cert_t *)inp);
  377. if (!subject_key)
  378. return NULL;
  379. CERTCertificate *newcert;
  380. newcert = tor_tls_create_certificate_internal(subject_key,
  381. signing_key,
  382. &inp->cert->subject,
  383. &inp->cert->issuer,
  384. start_time,
  385. new_expiration_time);
  386. crypto_pk_free(subject_key);
  387. return newcert ? tor_x509_cert_new(newcert) : NULL;
  388. }
  389. #endif