x509_nss.c 13 KB

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