x509_nss.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, 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. s = SEC_DerSignDataWithAlgorithmID(cert->arena,
  99. &signed_der,
  100. der.data, der.len,
  101. (SECKEYPrivateKey *)signing_key,//const
  102. &cert->signature);
  103. if (s != SECSuccess)
  104. goto err;
  105. /* Re-parse it, to make sure all the certificates we actually use
  106. * appear via being decoded. */
  107. result_cert = tor_x509_cert_decode_internal(signed_der.data, signed_der.len);
  108. #if 1
  109. {
  110. // Can we check the cert we just signed?
  111. tor_assert(result_cert);
  112. SECKEYPublicKey *issuer_pk = (SECKEYPublicKey *)
  113. crypto_pk_get_nss_pubkey(rsa_sign);
  114. SECStatus cert_ok = CERT_VerifySignedDataWithPublicKey(
  115. &result_cert->signatureWrap, issuer_pk, NULL);
  116. tor_assert(cert_ok == SECSuccess);
  117. }
  118. #endif
  119. err:
  120. if (subject_spki)
  121. SECKEY_DestroySubjectPublicKeyInfo(subject_spki);
  122. if (request)
  123. CERT_DestroyCertificateRequest(request);
  124. if (validity)
  125. CERT_DestroyValidity(validity);
  126. // unnecessary, since these are allocated in the cert's arena.
  127. //SECITEM_FreeItem(&der, PR_FALSE);
  128. //SECITEM_FreeItem(&signed_der, PR_FALSE);
  129. if (cert)
  130. CERT_DestroyCertificate(cert);
  131. return result_cert;
  132. }
  133. MOCK_IMPL(tor_x509_cert_impl_t *,
  134. tor_tls_create_certificate,(crypto_pk_t *rsa,
  135. crypto_pk_t *rsa_sign,
  136. const char *cname,
  137. const char *cname_sign,
  138. unsigned int cert_lifetime))
  139. {
  140. tor_assert(rsa);
  141. tor_assert(rsa_sign);
  142. tor_assert(cname);
  143. tor_assert(cname_sign);
  144. char *cname_rfc_1485 = NULL, *cname_sign_rfc_1485 = NULL;
  145. CERTName *subject_dn = NULL, *issuer_dn = NULL;
  146. time_t start_time;
  147. time_t end_time;
  148. CERTCertificate *result = NULL;
  149. tor_asprintf(&cname_rfc_1485, "CN=%s", cname);
  150. tor_asprintf(&cname_sign_rfc_1485, "CN=%s", cname_sign);
  151. subject_dn = CERT_AsciiToName(cname_rfc_1485);
  152. issuer_dn = CERT_AsciiToName(cname_sign_rfc_1485);
  153. if (!subject_dn || !issuer_dn)
  154. goto err;
  155. tor_tls_pick_certificate_lifetime(time(NULL), cert_lifetime,
  156. &start_time, &end_time);
  157. result = tor_tls_create_certificate_internal(rsa,
  158. rsa_sign,
  159. subject_dn,
  160. issuer_dn,
  161. start_time,
  162. end_time);
  163. err:
  164. tor_free(cname_rfc_1485);
  165. tor_free(cname_sign_rfc_1485);
  166. if (subject_dn)
  167. CERT_DestroyName(subject_dn);
  168. if (issuer_dn)
  169. CERT_DestroyName(issuer_dn);
  170. return result;
  171. }
  172. /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
  173. * representation and length, respectively. */
  174. void
  175. tor_x509_cert_get_der(const tor_x509_cert_t *cert,
  176. const uint8_t **encoded_out, size_t *size_out)
  177. {
  178. tor_assert(cert);
  179. tor_assert(cert->cert);
  180. tor_assert(encoded_out);
  181. tor_assert(size_out);
  182. const SECItem *item = &cert->cert->derCert;
  183. *encoded_out = item->data;
  184. *size_out = (size_t)item->len;
  185. }
  186. void
  187. tor_x509_cert_impl_free_(tor_x509_cert_impl_t *cert)
  188. {
  189. if (cert)
  190. CERT_DestroyCertificate(cert);
  191. }
  192. tor_x509_cert_t *
  193. tor_x509_cert_dup(const tor_x509_cert_t *cert)
  194. {
  195. tor_assert(cert);
  196. return tor_x509_cert_new(CERT_DupCertificate(cert->cert));
  197. }
  198. /**
  199. * As tor_x509_cert_decode, but return the NSS certificate type
  200. */
  201. static tor_x509_cert_impl_t *
  202. tor_x509_cert_decode_internal(const uint8_t *certificate,
  203. int certificate_len)
  204. {
  205. tor_assert(certificate);
  206. if (certificate_len > INT_MAX)
  207. return NULL;
  208. SECItem der = { .type = siBuffer,
  209. .data = (unsigned char *)certificate,
  210. .len = certificate_len };
  211. CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
  212. tor_assert(certdb);
  213. return CERT_NewTempCertificate(certdb,
  214. &der,
  215. NULL /* nickname */,
  216. PR_FALSE, /* isPerm */
  217. PR_TRUE /* CopyDER */);
  218. }
  219. tor_x509_cert_t *
  220. tor_x509_cert_decode(const uint8_t *certificate,
  221. size_t certificate_len)
  222. {
  223. CERTCertificate *cert = tor_x509_cert_decode_internal(certificate,
  224. (int)certificate_len);
  225. if (! cert) {
  226. crypto_nss_log_errors(LOG_INFO, "decoding certificate");
  227. return NULL;
  228. }
  229. tor_x509_cert_t *newcert = tor_x509_cert_new(cert);
  230. return newcert;
  231. }
  232. crypto_pk_t *
  233. tor_tls_cert_get_key(tor_x509_cert_t *cert)
  234. {
  235. tor_assert(cert);
  236. CERTSubjectPublicKeyInfo *spki = &cert->cert->subjectPublicKeyInfo;
  237. SECKEYPublicKey *pub = SECKEY_ExtractPublicKey(spki); // we own this pointer
  238. if (pub == NULL)
  239. return NULL;
  240. if (SECKEY_GetPublicKeyType(pub) != rsaKey) {
  241. SECKEY_DestroyPublicKey(pub);
  242. return NULL;
  243. }
  244. return crypto_pk_new_from_nss_pubkey(pub);
  245. }
  246. int
  247. tor_tls_cert_is_valid(int severity,
  248. const tor_x509_cert_t *cert,
  249. const tor_x509_cert_t *signing_cert,
  250. time_t now,
  251. int check_rsa_1024)
  252. {
  253. int result = 0;
  254. tor_assert(cert);
  255. tor_assert(signing_cert);
  256. SECKEYPublicKey *pk = CERT_ExtractPublicKey(signing_cert->cert);
  257. if (pk == NULL) {
  258. log_fn(severity, LD_CRYPTO,
  259. "Invalid certificate: could not extract issuer key");
  260. goto fail;
  261. }
  262. SECStatus s = CERT_VerifySignedDataWithPublicKey(&cert->cert->signatureWrap,
  263. pk, NULL);
  264. if (s != SECSuccess) {
  265. log_fn(severity, LD_CRYPTO,
  266. "Invalid certificate: could not validate signature.");
  267. goto fail;
  268. }
  269. if (tor_x509_check_cert_lifetime_internal(severity,
  270. cert->cert,
  271. now,
  272. TOR_X509_PAST_SLOP,
  273. TOR_X509_FUTURE_SLOP) < 0)
  274. goto fail;
  275. if (check_rsa_1024) {
  276. /* We require that this is a 1024-bit RSA key, for legacy reasons .:p */
  277. if (SECKEY_GetPublicKeyType(pk) != rsaKey ||
  278. SECKEY_PublicKeyStrengthInBits(pk) != 1024) {
  279. log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is not RSA1024.");
  280. goto fail;
  281. }
  282. } else {
  283. /* We require that this key is at least minimally strong. */
  284. unsigned min_bits = (SECKEY_GetPublicKeyType(pk) == ecKey) ? 128: 1024;
  285. if (SECKEY_PublicKeyStrengthInBits(pk) < min_bits) {
  286. log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is too weak.");
  287. goto fail;
  288. }
  289. }
  290. /* The certificate is valid. */
  291. result = 1;
  292. fail:
  293. if (pk)
  294. SECKEY_DestroyPublicKey(pk);
  295. return result;
  296. }
  297. static void
  298. log_cert_lifetime(int severity,
  299. const char *status,
  300. time_t now,
  301. PRTime notBefore,
  302. PRTime notAfter)
  303. {
  304. log_fn(severity, LD_GENERAL,
  305. "Certificate %s. Either their clock is set wrong, or your clock "
  306. "is incorrect.", status);
  307. char nowbuf[ISO_TIME_LEN+1];
  308. char nbbuf[ISO_TIME_LEN+1];
  309. char nabuf[ISO_TIME_LEN+1];
  310. format_iso_time(nowbuf, now);
  311. format_iso_time(nbbuf, notBefore / PRTIME_PER_SEC);
  312. format_iso_time(nabuf, notAfter / PRTIME_PER_SEC);
  313. log_fn(severity, LD_GENERAL,
  314. "(The certificate is valid from %s until %s. Your time is %s.)",
  315. nbbuf, nabuf, nowbuf);
  316. }
  317. int
  318. tor_x509_check_cert_lifetime_internal(int severity,
  319. const tor_x509_cert_impl_t *cert,
  320. time_t now,
  321. int past_tolerance,
  322. int future_tolerance)
  323. {
  324. tor_assert(cert);
  325. PRTime notBefore=0, notAfter=0;
  326. int64_t t;
  327. SECStatus r = CERT_GetCertTimes(cert, &notBefore, &notAfter);
  328. if (r != SECSuccess) {
  329. log_fn(severity, LD_CRYPTO,
  330. "Couldn't get validity times from certificate");
  331. return -1;
  332. }
  333. t = ((int64_t)now) + future_tolerance;
  334. t *= PRTIME_PER_SEC;
  335. if (notBefore > t) {
  336. log_cert_lifetime(severity, "not yet valid", now,
  337. notBefore, notAfter);
  338. return -1;
  339. }
  340. t = ((int64_t)now) - past_tolerance;
  341. t *= PRTIME_PER_SEC;
  342. if (notAfter < t) {
  343. log_cert_lifetime(severity, "already expired", now,
  344. notBefore, notAfter);
  345. return -1;
  346. }
  347. return 0;
  348. }
  349. #ifdef TOR_UNIT_TESTS
  350. tor_x509_cert_t *
  351. tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
  352. time_t new_expiration_time,
  353. crypto_pk_t *signing_key)
  354. {
  355. tor_assert(inp);
  356. tor_assert(signing_key);
  357. PRTime notBefore=0, notAfter=0;
  358. SECStatus r = CERT_GetCertTimes(inp->cert, &notBefore, &notAfter);
  359. if (r != SECSuccess)
  360. return NULL;
  361. time_t start_time = notBefore / PRTIME_PER_SEC;
  362. if (new_expiration_time < start_time) {
  363. /* This prevents an NSS error. */
  364. start_time = new_expiration_time - 10;
  365. }
  366. crypto_pk_t *subject_key = tor_tls_cert_get_key((tor_x509_cert_t *)inp);
  367. if (!subject_key)
  368. return NULL;
  369. CERTCertificate *newcert;
  370. newcert = tor_tls_create_certificate_internal(subject_key,
  371. signing_key,
  372. &inp->cert->subject,
  373. &inp->cert->issuer,
  374. start_time,
  375. new_expiration_time);
  376. crypto_pk_free(subject_key);
  377. return newcert ? tor_x509_cert_new(newcert) : NULL;
  378. }
  379. #endif