x509.c 15 KB

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