x509_nss.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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_impl_t *
  193. tor_x509_cert_impl_dup_(tor_x509_cert_impl_t *cert)
  194. {
  195. if (cert)
  196. return CERT_DupCertificate(cert);
  197. else
  198. return NULL;
  199. }
  200. /**
  201. * As tor_x509_cert_decode, but return the NSS certificate type
  202. */
  203. static tor_x509_cert_impl_t *
  204. tor_x509_cert_decode_internal(const uint8_t *certificate,
  205. int certificate_len)
  206. {
  207. tor_assert(certificate);
  208. if (certificate_len > INT_MAX)
  209. return NULL;
  210. SECItem der = { .type = siBuffer,
  211. .data = (unsigned char *)certificate,
  212. .len = certificate_len };
  213. CERTCertDBHandle *certdb = CERT_GetDefaultCertDB();
  214. tor_assert(certdb);
  215. return CERT_NewTempCertificate(certdb,
  216. &der,
  217. NULL /* nickname */,
  218. PR_FALSE, /* isPerm */
  219. PR_TRUE /* CopyDER */);
  220. }
  221. tor_x509_cert_t *
  222. tor_x509_cert_decode(const uint8_t *certificate,
  223. size_t certificate_len)
  224. {
  225. CERTCertificate *cert = tor_x509_cert_decode_internal(certificate,
  226. (int)certificate_len);
  227. if (! cert) {
  228. crypto_nss_log_errors(LOG_INFO, "decoding certificate");
  229. return NULL;
  230. }
  231. tor_x509_cert_t *newcert = tor_x509_cert_new(cert);
  232. return newcert;
  233. }
  234. crypto_pk_t *
  235. tor_tls_cert_get_key(tor_x509_cert_t *cert)
  236. {
  237. tor_assert(cert);
  238. CERTSubjectPublicKeyInfo *spki = &cert->cert->subjectPublicKeyInfo;
  239. SECKEYPublicKey *pub = SECKEY_ExtractPublicKey(spki); // we own this pointer
  240. if (pub == NULL)
  241. return NULL;
  242. if (SECKEY_GetPublicKeyType(pub) != rsaKey) {
  243. SECKEY_DestroyPublicKey(pub);
  244. return NULL;
  245. }
  246. return crypto_pk_new_from_nss_pubkey(pub);
  247. }
  248. int
  249. tor_tls_cert_is_valid(int severity,
  250. const tor_x509_cert_t *cert,
  251. const tor_x509_cert_t *signing_cert,
  252. time_t now,
  253. int check_rsa_1024)
  254. {
  255. int result = 0;
  256. tor_assert(cert);
  257. tor_assert(signing_cert);
  258. SECKEYPublicKey *pk = CERT_ExtractPublicKey(signing_cert->cert);
  259. if (pk == NULL) {
  260. log_fn(severity, LD_CRYPTO,
  261. "Invalid certificate: could not extract issuer key");
  262. goto fail;
  263. }
  264. SECStatus s = CERT_VerifySignedDataWithPublicKey(&cert->cert->signatureWrap,
  265. pk, NULL);
  266. if (s != SECSuccess) {
  267. log_fn(severity, LD_CRYPTO,
  268. "Invalid certificate: could not validate signature.");
  269. goto fail;
  270. }
  271. if (tor_x509_check_cert_lifetime_internal(severity,
  272. cert->cert,
  273. now,
  274. TOR_X509_PAST_SLOP,
  275. TOR_X509_FUTURE_SLOP) < 0)
  276. goto fail;
  277. if (check_rsa_1024) {
  278. /* We require that this is a 1024-bit RSA key, for legacy reasons .:p */
  279. if (SECKEY_GetPublicKeyType(pk) != rsaKey ||
  280. SECKEY_PublicKeyStrengthInBits(pk) != 1024) {
  281. log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is not RSA1024.");
  282. goto fail;
  283. }
  284. } else {
  285. /* We require that this key is at least minimally strong. */
  286. unsigned min_bits = (SECKEY_GetPublicKeyType(pk) == ecKey) ? 128: 1024;
  287. if (SECKEY_PublicKeyStrengthInBits(pk) < min_bits) {
  288. log_fn(severity, LD_CRYPTO, "Invalid certificate: Key is too weak.");
  289. goto fail;
  290. }
  291. }
  292. /* The certificate is valid. */
  293. result = 1;
  294. fail:
  295. if (pk)
  296. SECKEY_DestroyPublicKey(pk);
  297. return result;
  298. }
  299. static void
  300. log_cert_lifetime(int severity,
  301. const char *status,
  302. time_t now,
  303. PRTime notBefore,
  304. PRTime notAfter)
  305. {
  306. log_fn(severity, LD_GENERAL,
  307. "Certificate %s. Either their clock is set wrong, or your clock "
  308. "is incorrect.", status);
  309. char nowbuf[ISO_TIME_LEN+1];
  310. char nbbuf[ISO_TIME_LEN+1];
  311. char nabuf[ISO_TIME_LEN+1];
  312. format_iso_time(nowbuf, now);
  313. format_iso_time(nbbuf, notBefore / PRTIME_PER_SEC);
  314. format_iso_time(nabuf, notAfter / PRTIME_PER_SEC);
  315. log_fn(severity, LD_GENERAL,
  316. "(The certificate is valid from %s until %s. Your time is %s.)",
  317. nbbuf, nabuf, nowbuf);
  318. }
  319. int
  320. tor_x509_check_cert_lifetime_internal(int severity,
  321. const tor_x509_cert_impl_t *cert,
  322. time_t now,
  323. int past_tolerance,
  324. int future_tolerance)
  325. {
  326. tor_assert(cert);
  327. PRTime notBefore=0, notAfter=0;
  328. int64_t t;
  329. SECStatus r = CERT_GetCertTimes(cert, &notBefore, &notAfter);
  330. if (r != SECSuccess) {
  331. log_fn(severity, LD_CRYPTO,
  332. "Couldn't get validity times from certificate");
  333. return -1;
  334. }
  335. t = ((int64_t)now) + future_tolerance;
  336. t *= PRTIME_PER_SEC;
  337. if (notBefore > t) {
  338. log_cert_lifetime(severity, "not yet valid", now,
  339. notBefore, notAfter);
  340. return -1;
  341. }
  342. t = ((int64_t)now) - past_tolerance;
  343. t *= PRTIME_PER_SEC;
  344. if (notAfter < t) {
  345. log_cert_lifetime(severity, "already expired", now,
  346. notBefore, notAfter);
  347. return -1;
  348. }
  349. return 0;
  350. }
  351. #ifdef TOR_UNIT_TESTS
  352. tor_x509_cert_t *
  353. tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
  354. time_t new_expiration_time,
  355. crypto_pk_t *signing_key)
  356. {
  357. tor_assert(inp);
  358. tor_assert(signing_key);
  359. PRTime notBefore=0, notAfter=0;
  360. SECStatus r = CERT_GetCertTimes(inp->cert, &notBefore, &notAfter);
  361. if (r != SECSuccess)
  362. return NULL;
  363. time_t start_time = notBefore / PRTIME_PER_SEC;
  364. if (new_expiration_time < start_time) {
  365. /* This prevents an NSS error. */
  366. start_time = new_expiration_time - 10;
  367. }
  368. crypto_pk_t *subject_key = tor_tls_cert_get_key((tor_x509_cert_t *)inp);
  369. if (!subject_key)
  370. return NULL;
  371. CERTCertificate *newcert;
  372. newcert = tor_tls_create_certificate_internal(subject_key,
  373. signing_key,
  374. &inp->cert->subject,
  375. &inp->cert->issuer,
  376. start_time,
  377. new_expiration_time);
  378. crypto_pk_free(subject_key);
  379. return newcert ? tor_x509_cert_new(newcert) : NULL;
  380. }
  381. #endif