x509.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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.c
  7. * \brief Wrapper functions to present a consistent interface to
  8. * X.509 functions from OpenSSL.
  9. **/
  10. #define TOR_X509_PRIVATE
  11. #include "lib/tls/x509.h"
  12. #include "lib/tls/tortls.h"
  13. #include "lib/crypt_ops/crypto_rand.h"
  14. #include "lib/crypt_ops/crypto_util.h"
  15. #include "lib/crypt_ops/compat_openssl.h"
  16. /* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
  17. * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
  18. DISABLE_GCC_WARNING(redundant-decls)
  19. #include <openssl/opensslv.h>
  20. #ifdef OPENSSL_NO_EC
  21. #error "We require OpenSSL with ECC support"
  22. #endif
  23. #include <openssl/err.h>
  24. #include <openssl/asn1.h>
  25. #include <openssl/bio.h>
  26. #include <openssl/bn.h>
  27. #include <openssl/rsa.h>
  28. ENABLE_GCC_WARNING(redundant-decls)
  29. #include "lib/log/log.h"
  30. #include "lib/log/util_bug.h"
  31. #include "lib/ctime/di_ops.h"
  32. #include "lib/encoding/time_fmt.h"
  33. #include <stdlib.h>
  34. #include <string.h>
  35. #ifdef OPENSSL_1_1_API
  36. #define X509_get_notBefore_const(cert) \
  37. X509_get0_notBefore(cert)
  38. #define X509_get_notAfter_const(cert) \
  39. X509_get0_notAfter(cert)
  40. #ifndef X509_get_notBefore
  41. #define X509_get_notBefore(cert) \
  42. X509_getm_notBefore(cert)
  43. #endif
  44. #ifndef X509_get_notAfter
  45. #define X509_get_notAfter(cert) \
  46. X509_getm_notAfter(cert)
  47. #endif
  48. #else /* ! OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
  49. #define X509_get_notBefore_const(cert) \
  50. ((const ASN1_TIME*) X509_get_notBefore((X509 *)cert))
  51. #define X509_get_notAfter_const(cert) \
  52. ((const ASN1_TIME*) X509_get_notAfter((X509 *)cert))
  53. #endif
  54. /** Return a newly allocated X509 name with commonName <b>cname</b>. */
  55. static X509_NAME *
  56. tor_x509_name_new(const char *cname)
  57. {
  58. int nid;
  59. X509_NAME *name;
  60. /* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
  61. if (!(name = X509_NAME_new()))
  62. return NULL;
  63. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  64. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  65. (unsigned char*)cname, -1, -1, 0)))
  66. goto error;
  67. /* LCOV_EXCL_BR_STOP */
  68. return name;
  69. /* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
  70. error:
  71. X509_NAME_free(name);
  72. return NULL;
  73. /* LCOV_EXCL_STOP */
  74. }
  75. /** Choose the start and end times for a certificate */
  76. void
  77. tor_tls_pick_certificate_lifetime(time_t now,
  78. unsigned int cert_lifetime,
  79. time_t *start_time_out,
  80. time_t *end_time_out)
  81. {
  82. time_t start_time, end_time;
  83. /* Make sure we're part-way through the certificate lifetime, rather
  84. * than having it start right now. Don't choose quite uniformly, since
  85. * then we might pick a time where we're about to expire. Lastly, be
  86. * sure to start on a day boundary. */
  87. /* Our certificate lifetime will be cert_lifetime no matter what, but if we
  88. * start cert_lifetime in the past, we'll have 0 real lifetime. instead we
  89. * start up to (cert_lifetime - min_real_lifetime - start_granularity) in
  90. * the past. */
  91. const time_t min_real_lifetime = 24*3600;
  92. const time_t start_granularity = 24*3600;
  93. time_t earliest_start_time;
  94. /* Don't actually start in the future! */
  95. if (cert_lifetime <= min_real_lifetime + start_granularity) {
  96. earliest_start_time = now - 1;
  97. } else {
  98. earliest_start_time = now + min_real_lifetime + start_granularity
  99. - cert_lifetime;
  100. }
  101. start_time = crypto_rand_time_range(earliest_start_time, now);
  102. /* Round the start time back to the start of a day. */
  103. start_time -= start_time % start_granularity;
  104. end_time = start_time + cert_lifetime;
  105. *start_time_out = start_time;
  106. *end_time_out = end_time;
  107. }
  108. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  109. * signed by the private key <b>rsa_sign</b>. The commonName of the
  110. * certificate will be <b>cname</b>; the commonName of the issuer will be
  111. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
  112. * seconds, starting from some time in the past.
  113. *
  114. * Return a certificate on success, NULL on failure.
  115. */
  116. MOCK_IMPL(X509 *,
  117. tor_tls_create_certificate,(crypto_pk_t *rsa,
  118. crypto_pk_t *rsa_sign,
  119. const char *cname,
  120. const char *cname_sign,
  121. unsigned int cert_lifetime))
  122. {
  123. /* OpenSSL generates self-signed certificates with random 64-bit serial
  124. * numbers, so let's do that too. */
  125. #define SERIAL_NUMBER_SIZE 8
  126. time_t start_time, end_time;
  127. BIGNUM *serial_number = NULL;
  128. unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
  129. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  130. X509 *x509 = NULL;
  131. X509_NAME *name = NULL, *name_issuer=NULL;
  132. tor_tls_init();
  133. time_t now = time(NULL);
  134. tor_tls_pick_certificate_lifetime(now, cert_lifetime,
  135. &start_time, &end_time);
  136. tor_assert(rsa);
  137. tor_assert(cname);
  138. tor_assert(rsa_sign);
  139. tor_assert(cname_sign);
  140. if (!(sign_pkey = crypto_pk_get_openssl_evp_pkey_(rsa_sign,1)))
  141. goto error;
  142. if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,0)))
  143. goto error;
  144. if (!(x509 = X509_new()))
  145. goto error;
  146. if (!(X509_set_version(x509, 2)))
  147. goto error;
  148. { /* our serial number is 8 random bytes. */
  149. crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
  150. if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
  151. goto error;
  152. if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
  153. goto error;
  154. }
  155. if (!(name = tor_x509_name_new(cname)))
  156. goto error;
  157. if (!(X509_set_subject_name(x509, name)))
  158. goto error;
  159. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  160. goto error;
  161. if (!(X509_set_issuer_name(x509, name_issuer)))
  162. goto error;
  163. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  164. goto error;
  165. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  166. goto error;
  167. if (!X509_set_pubkey(x509, pkey))
  168. goto error;
  169. if (!X509_sign(x509, sign_pkey, EVP_sha256()))
  170. goto error;
  171. goto done;
  172. error:
  173. if (x509) {
  174. X509_free(x509);
  175. x509 = NULL;
  176. }
  177. done:
  178. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  179. if (sign_pkey)
  180. EVP_PKEY_free(sign_pkey);
  181. if (pkey)
  182. EVP_PKEY_free(pkey);
  183. if (serial_number)
  184. BN_clear_free(serial_number);
  185. if (name)
  186. X509_NAME_free(name);
  187. if (name_issuer)
  188. X509_NAME_free(name_issuer);
  189. return x509;
  190. #undef SERIAL_NUMBER_SIZE
  191. }
  192. /** Free all storage held in <b>cert</b> */
  193. void
  194. tor_x509_cert_free_(tor_x509_cert_t *cert)
  195. {
  196. if (! cert)
  197. return;
  198. if (cert->cert)
  199. X509_free(cert->cert);
  200. tor_free(cert->encoded);
  201. memwipe(cert, 0x03, sizeof(*cert));
  202. /* LCOV_EXCL_BR_START since cert will never be NULL here */
  203. tor_free(cert);
  204. /* LCOV_EXCL_BR_STOP */
  205. }
  206. /**
  207. * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
  208. *
  209. * Steals a reference to x509_cert.
  210. */
  211. MOCK_IMPL(tor_x509_cert_t *,
  212. tor_x509_cert_new,(X509 *x509_cert))
  213. {
  214. tor_x509_cert_t *cert;
  215. EVP_PKEY *pkey;
  216. RSA *rsa;
  217. int length;
  218. unsigned char *buf = NULL;
  219. if (!x509_cert)
  220. return NULL;
  221. length = i2d_X509(x509_cert, &buf);
  222. cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
  223. if (length <= 0 || buf == NULL) {
  224. goto err;
  225. }
  226. cert->encoded_len = (size_t) length;
  227. cert->encoded = tor_malloc(length);
  228. memcpy(cert->encoded, buf, length);
  229. OPENSSL_free(buf);
  230. cert->cert = x509_cert;
  231. crypto_common_digests(&cert->cert_digests,
  232. (char*)cert->encoded, cert->encoded_len);
  233. if ((pkey = X509_get_pubkey(x509_cert)) &&
  234. (rsa = EVP_PKEY_get1_RSA(pkey))) {
  235. crypto_pk_t *pk = crypto_new_pk_from_openssl_rsa_(rsa);
  236. if (crypto_pk_get_common_digests(pk, &cert->pkey_digests) < 0) {
  237. crypto_pk_free(pk);
  238. EVP_PKEY_free(pkey);
  239. goto err;
  240. }
  241. cert->pkey_digests_set = 1;
  242. crypto_pk_free(pk);
  243. EVP_PKEY_free(pkey);
  244. }
  245. return cert;
  246. err:
  247. /* LCOV_EXCL_START for the same reason as the exclusion above */
  248. tor_free(cert);
  249. log_err(LD_CRYPTO, "Couldn't wrap encoded X509 certificate.");
  250. X509_free(x509_cert);
  251. return NULL;
  252. /* LCOV_EXCL_STOP */
  253. }
  254. /** Return a new copy of <b>cert</b>. */
  255. tor_x509_cert_t *
  256. tor_x509_cert_dup(const tor_x509_cert_t *cert)
  257. {
  258. tor_assert(cert);
  259. X509 *x509 = cert->cert;
  260. return tor_x509_cert_new(X509_dup(x509));
  261. }
  262. /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
  263. * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
  264. * success and NULL on failure. */
  265. tor_x509_cert_t *
  266. tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
  267. {
  268. X509 *x509;
  269. const unsigned char *cp = (const unsigned char *)certificate;
  270. tor_x509_cert_t *newcert;
  271. tor_assert(certificate);
  272. check_no_tls_errors();
  273. if (certificate_len > INT_MAX)
  274. goto err;
  275. x509 = d2i_X509(NULL, &cp, (int)certificate_len);
  276. if (!x509)
  277. goto err; /* Couldn't decode */
  278. if (cp - certificate != (int)certificate_len) {
  279. X509_free(x509);
  280. goto err; /* Didn't use all the bytes */
  281. }
  282. newcert = tor_x509_cert_new(x509);
  283. if (!newcert) {
  284. goto err;
  285. }
  286. if (newcert->encoded_len != certificate_len ||
  287. fast_memneq(newcert->encoded, certificate, certificate_len)) {
  288. /* Cert wasn't in DER */
  289. tor_x509_cert_free(newcert);
  290. goto err;
  291. }
  292. return newcert;
  293. err:
  294. tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
  295. return NULL;
  296. }
  297. /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
  298. * representation and length, respectively. */
  299. void
  300. tor_x509_cert_get_der(const tor_x509_cert_t *cert,
  301. const uint8_t **encoded_out, size_t *size_out)
  302. {
  303. tor_assert(cert);
  304. tor_assert(encoded_out);
  305. tor_assert(size_out);
  306. *encoded_out = cert->encoded;
  307. *size_out = cert->encoded_len;
  308. }
  309. /** Return the underlying implementation for <b>cert</b> */
  310. const tor_x509_cert_impl_t *
  311. tor_x509_cert_get_impl(const tor_x509_cert_t *cert)
  312. {
  313. tor_assert(cert);
  314. return cert->cert;
  315. }
  316. /** Return a set of digests for the public key in <b>cert</b>, or NULL if this
  317. * cert's public key is not one we know how to take the digest of. */
  318. const common_digests_t *
  319. tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
  320. {
  321. if (cert->pkey_digests_set)
  322. return &cert->pkey_digests;
  323. else
  324. return NULL;
  325. }
  326. /** Return a set of digests for the public key in <b>cert</b>. */
  327. const common_digests_t *
  328. tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
  329. {
  330. return &cert->cert_digests;
  331. }
  332. /**
  333. * Return a newly allocated copy of the public key that a certificate
  334. * certifies. Watch out! This returns NULL if the cert's key is not RSA.
  335. */
  336. crypto_pk_t *
  337. tor_tls_cert_get_key(tor_x509_cert_t *cert)
  338. {
  339. crypto_pk_t *result = NULL;
  340. EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
  341. RSA *rsa;
  342. if (!pkey)
  343. return NULL;
  344. rsa = EVP_PKEY_get1_RSA(pkey);
  345. if (!rsa) {
  346. EVP_PKEY_free(pkey);
  347. return NULL;
  348. }
  349. result = crypto_new_pk_from_openssl_rsa_(rsa);
  350. EVP_PKEY_free(pkey);
  351. return result;
  352. }
  353. /** Check whether <b>cert</b> is well-formed, currently live, and correctly
  354. * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
  355. * make sure that it has an RSA key with 1024 bits; otherwise, just check that
  356. * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
  357. * we couldn't check it. */
  358. int
  359. tor_tls_cert_is_valid(int severity,
  360. const tor_x509_cert_t *cert,
  361. const tor_x509_cert_t *signing_cert,
  362. time_t now,
  363. int check_rsa_1024)
  364. {
  365. check_no_tls_errors();
  366. EVP_PKEY *cert_key;
  367. int r, key_ok = 0;
  368. if (!signing_cert || !cert)
  369. goto bad;
  370. EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
  371. if (!signing_key)
  372. goto bad;
  373. r = X509_verify(cert->cert, signing_key);
  374. EVP_PKEY_free(signing_key);
  375. if (r <= 0)
  376. goto bad;
  377. /* okay, the signature checked out right. Now let's check the check the
  378. * lifetime. */
  379. if (tor_x509_check_cert_lifetime_internal(severity, cert->cert, now,
  380. 48*60*60, 30*24*60*60) < 0)
  381. goto bad;
  382. cert_key = X509_get_pubkey(cert->cert);
  383. if (check_rsa_1024 && cert_key) {
  384. RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
  385. #ifdef OPENSSL_1_1_API
  386. if (rsa && RSA_bits(rsa) == 1024)
  387. #else
  388. if (rsa && BN_num_bits(rsa->n) == 1024)
  389. #endif
  390. key_ok = 1;
  391. if (rsa)
  392. RSA_free(rsa);
  393. } else if (cert_key) {
  394. int min_bits = 1024;
  395. #ifdef EVP_PKEY_EC
  396. if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
  397. min_bits = 128;
  398. #endif
  399. if (EVP_PKEY_bits(cert_key) >= min_bits)
  400. key_ok = 1;
  401. }
  402. EVP_PKEY_free(cert_key);
  403. if (!key_ok)
  404. goto bad;
  405. /* XXXX compare DNs or anything? */
  406. return 1;
  407. bad:
  408. tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
  409. return 0;
  410. }
  411. /** Warn that a certificate lifetime extends through a certain range. */
  412. static void
  413. log_cert_lifetime(int severity, const X509 *cert, const char *problem,
  414. time_t now)
  415. {
  416. BIO *bio = NULL;
  417. BUF_MEM *buf;
  418. char *s1=NULL, *s2=NULL;
  419. char mytime[33];
  420. struct tm tm;
  421. size_t n;
  422. if (problem)
  423. tor_log(severity, LD_GENERAL,
  424. "Certificate %s. Either their clock is set wrong, or your clock "
  425. "is wrong.",
  426. problem);
  427. if (!(bio = BIO_new(BIO_s_mem()))) {
  428. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  429. }
  430. if (!(ASN1_TIME_print(bio, X509_get_notBefore_const(cert)))) {
  431. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  432. goto end;
  433. }
  434. BIO_get_mem_ptr(bio, &buf);
  435. s1 = tor_strndup(buf->data, buf->length);
  436. (void)BIO_reset(bio);
  437. if (!(ASN1_TIME_print(bio, X509_get_notAfter_const(cert)))) {
  438. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  439. goto end;
  440. }
  441. BIO_get_mem_ptr(bio, &buf);
  442. s2 = tor_strndup(buf->data, buf->length);
  443. n = strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
  444. if (n > 0) {
  445. tor_log(severity, LD_GENERAL,
  446. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  447. s1,s2,mytime);
  448. } else {
  449. tor_log(severity, LD_GENERAL,
  450. "(certificate lifetime runs from %s through %s. "
  451. "Couldn't get your time.)",
  452. s1, s2);
  453. }
  454. end:
  455. /* Not expected to get invoked */
  456. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  457. if (bio)
  458. BIO_free(bio);
  459. tor_free(s1);
  460. tor_free(s2);
  461. }
  462. /** Helper: check whether <b>cert</b> is expired give or take
  463. * <b>past_tolerance</b> seconds, or not-yet-valid give or take
  464. * <b>future_tolerance</b> seconds. (Relative to the current time
  465. * <b>now</b>.) If it is live, return 0. If it is not live, log a message
  466. * and return -1. */
  467. int
  468. tor_x509_check_cert_lifetime_internal(int severity, const X509 *cert,
  469. time_t now,
  470. int past_tolerance, int future_tolerance)
  471. {
  472. time_t t;
  473. t = now + future_tolerance;
  474. if (X509_cmp_time(X509_get_notBefore_const(cert), &t) > 0) {
  475. log_cert_lifetime(severity, cert, "not yet valid", now);
  476. return -1;
  477. }
  478. t = now - past_tolerance;
  479. if (X509_cmp_time(X509_get_notAfter_const(cert), &t) < 0) {
  480. log_cert_lifetime(severity, cert, "already expired", now);
  481. return -1;
  482. }
  483. return 0;
  484. }
  485. #ifdef TOR_UNIT_TESTS
  486. /* Testing only: return a new x509 cert with the same contents as <b>inp</b>,
  487. but with the expiration time <b>new_expiration_time</b>, signed with
  488. <b>signing_key</b>. */
  489. STATIC tor_x509_cert_t *
  490. tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
  491. time_t new_expiration_time,
  492. crypto_pk_t *signing_key)
  493. {
  494. X509 *newc = X509_dup(inp->cert);
  495. X509_time_adj(X509_get_notAfter(newc), 0, &new_expiration_time);
  496. EVP_PKEY *pk = crypto_pk_get_openssl_evp_pkey_(signing_key, 1);
  497. tor_assert(X509_sign(newc, pk, EVP_sha256()));
  498. EVP_PKEY_free(pk);
  499. return tor_x509_cert_new(newc);
  500. }
  501. #endif /* defined(TOR_UNIT_TESTS) */