x509_openssl.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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_openssl.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. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  76. * signed by the private key <b>rsa_sign</b>. The commonName of the
  77. * certificate will be <b>cname</b>; the commonName of the issuer will be
  78. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
  79. * seconds, starting from some time in the past.
  80. *
  81. * Return a certificate on success, NULL on failure.
  82. */
  83. MOCK_IMPL(X509 *,
  84. tor_tls_create_certificate,(crypto_pk_t *rsa,
  85. crypto_pk_t *rsa_sign,
  86. const char *cname,
  87. const char *cname_sign,
  88. unsigned int cert_lifetime))
  89. {
  90. /* OpenSSL generates self-signed certificates with random 64-bit serial
  91. * numbers, so let's do that too. */
  92. #define SERIAL_NUMBER_SIZE 8
  93. time_t start_time, end_time;
  94. BIGNUM *serial_number = NULL;
  95. unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
  96. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  97. X509 *x509 = NULL;
  98. X509_NAME *name = NULL, *name_issuer=NULL;
  99. tor_tls_init();
  100. time_t now = time(NULL);
  101. tor_tls_pick_certificate_lifetime(now, cert_lifetime,
  102. &start_time, &end_time);
  103. tor_assert(rsa);
  104. tor_assert(cname);
  105. tor_assert(rsa_sign);
  106. tor_assert(cname_sign);
  107. if (!(sign_pkey = crypto_pk_get_openssl_evp_pkey_(rsa_sign,1)))
  108. goto error;
  109. if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,0)))
  110. goto error;
  111. if (!(x509 = X509_new()))
  112. goto error;
  113. if (!(X509_set_version(x509, 2)))
  114. goto error;
  115. { /* our serial number is 8 random bytes. */
  116. crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
  117. if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
  118. goto error;
  119. if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
  120. goto error;
  121. }
  122. if (!(name = tor_x509_name_new(cname)))
  123. goto error;
  124. if (!(X509_set_subject_name(x509, name)))
  125. goto error;
  126. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  127. goto error;
  128. if (!(X509_set_issuer_name(x509, name_issuer)))
  129. goto error;
  130. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  131. goto error;
  132. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  133. goto error;
  134. if (!X509_set_pubkey(x509, pkey))
  135. goto error;
  136. if (!X509_sign(x509, sign_pkey, EVP_sha256()))
  137. goto error;
  138. goto done;
  139. error:
  140. if (x509) {
  141. X509_free(x509);
  142. x509 = NULL;
  143. }
  144. done:
  145. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  146. if (sign_pkey)
  147. EVP_PKEY_free(sign_pkey);
  148. if (pkey)
  149. EVP_PKEY_free(pkey);
  150. if (serial_number)
  151. BN_clear_free(serial_number);
  152. if (name)
  153. X509_NAME_free(name);
  154. if (name_issuer)
  155. X509_NAME_free(name_issuer);
  156. return x509;
  157. #undef SERIAL_NUMBER_SIZE
  158. }
  159. /** Free all storage held in <b>cert</b> */
  160. void
  161. tor_x509_cert_free_(tor_x509_cert_t *cert)
  162. {
  163. if (! cert)
  164. return;
  165. if (cert->cert)
  166. X509_free(cert->cert);
  167. tor_free(cert->encoded);
  168. memwipe(cert, 0x03, sizeof(*cert));
  169. /* LCOV_EXCL_BR_START since cert will never be NULL here */
  170. tor_free(cert);
  171. /* LCOV_EXCL_BR_STOP */
  172. }
  173. /**
  174. * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
  175. *
  176. * Steals a reference to x509_cert.
  177. */
  178. MOCK_IMPL(tor_x509_cert_t *,
  179. tor_x509_cert_new,(X509 *x509_cert))
  180. {
  181. tor_x509_cert_t *cert;
  182. EVP_PKEY *pkey;
  183. RSA *rsa;
  184. int length;
  185. unsigned char *buf = NULL;
  186. if (!x509_cert)
  187. return NULL;
  188. length = i2d_X509(x509_cert, &buf);
  189. cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
  190. if (length <= 0 || buf == NULL) {
  191. goto err;
  192. }
  193. cert->encoded_len = (size_t) length;
  194. cert->encoded = tor_malloc(length);
  195. memcpy(cert->encoded, buf, length);
  196. OPENSSL_free(buf);
  197. cert->cert = x509_cert;
  198. crypto_common_digests(&cert->cert_digests,
  199. (char*)cert->encoded, cert->encoded_len);
  200. if ((pkey = X509_get_pubkey(x509_cert)) &&
  201. (rsa = EVP_PKEY_get1_RSA(pkey))) {
  202. crypto_pk_t *pk = crypto_new_pk_from_openssl_rsa_(rsa);
  203. if (crypto_pk_get_common_digests(pk, &cert->pkey_digests) < 0) {
  204. crypto_pk_free(pk);
  205. EVP_PKEY_free(pkey);
  206. goto err;
  207. }
  208. cert->pkey_digests_set = 1;
  209. crypto_pk_free(pk);
  210. EVP_PKEY_free(pkey);
  211. }
  212. return cert;
  213. err:
  214. /* LCOV_EXCL_START for the same reason as the exclusion above */
  215. tor_free(cert);
  216. log_err(LD_CRYPTO, "Couldn't wrap encoded X509 certificate.");
  217. X509_free(x509_cert);
  218. return NULL;
  219. /* LCOV_EXCL_STOP */
  220. }
  221. /** Return a new copy of <b>cert</b>. */
  222. tor_x509_cert_t *
  223. tor_x509_cert_dup(const tor_x509_cert_t *cert)
  224. {
  225. tor_assert(cert);
  226. X509 *x509 = cert->cert;
  227. return tor_x509_cert_new(X509_dup(x509));
  228. }
  229. /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
  230. * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
  231. * success and NULL on failure. */
  232. tor_x509_cert_t *
  233. tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
  234. {
  235. X509 *x509;
  236. const unsigned char *cp = (const unsigned char *)certificate;
  237. tor_x509_cert_t *newcert;
  238. tor_assert(certificate);
  239. check_no_tls_errors();
  240. if (certificate_len > INT_MAX)
  241. goto err;
  242. x509 = d2i_X509(NULL, &cp, (int)certificate_len);
  243. if (!x509)
  244. goto err; /* Couldn't decode */
  245. if (cp - certificate != (int)certificate_len) {
  246. X509_free(x509);
  247. goto err; /* Didn't use all the bytes */
  248. }
  249. newcert = tor_x509_cert_new(x509);
  250. if (!newcert) {
  251. goto err;
  252. }
  253. if (newcert->encoded_len != certificate_len ||
  254. fast_memneq(newcert->encoded, certificate, certificate_len)) {
  255. /* Cert wasn't in DER */
  256. tor_x509_cert_free(newcert);
  257. goto err;
  258. }
  259. return newcert;
  260. err:
  261. tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
  262. return NULL;
  263. }
  264. /**
  265. * Return a newly allocated copy of the public key that a certificate
  266. * certifies. Watch out! This returns NULL if the cert's key is not RSA.
  267. */
  268. crypto_pk_t *
  269. tor_tls_cert_get_key(tor_x509_cert_t *cert)
  270. {
  271. crypto_pk_t *result = NULL;
  272. EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
  273. RSA *rsa;
  274. if (!pkey)
  275. return NULL;
  276. rsa = EVP_PKEY_get1_RSA(pkey);
  277. if (!rsa) {
  278. EVP_PKEY_free(pkey);
  279. return NULL;
  280. }
  281. result = crypto_new_pk_from_openssl_rsa_(rsa);
  282. EVP_PKEY_free(pkey);
  283. return result;
  284. }
  285. /** Check whether <b>cert</b> is well-formed, currently live, and correctly
  286. * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
  287. * make sure that it has an RSA key with 1024 bits; otherwise, just check that
  288. * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
  289. * we couldn't check it. */
  290. int
  291. tor_tls_cert_is_valid(int severity,
  292. const tor_x509_cert_t *cert,
  293. const tor_x509_cert_t *signing_cert,
  294. time_t now,
  295. int check_rsa_1024)
  296. {
  297. check_no_tls_errors();
  298. EVP_PKEY *cert_key;
  299. int r, key_ok = 0;
  300. if (!signing_cert || !cert)
  301. goto bad;
  302. EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
  303. if (!signing_key)
  304. goto bad;
  305. r = X509_verify(cert->cert, signing_key);
  306. EVP_PKEY_free(signing_key);
  307. if (r <= 0)
  308. goto bad;
  309. /* okay, the signature checked out right. Now let's check the check the
  310. * lifetime. */
  311. if (tor_x509_check_cert_lifetime_internal(severity, cert->cert, now,
  312. 48*60*60, 30*24*60*60) < 0)
  313. goto bad;
  314. cert_key = X509_get_pubkey(cert->cert);
  315. if (check_rsa_1024 && cert_key) {
  316. RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
  317. #ifdef OPENSSL_1_1_API
  318. if (rsa && RSA_bits(rsa) == 1024)
  319. #else
  320. if (rsa && BN_num_bits(rsa->n) == 1024)
  321. #endif
  322. key_ok = 1;
  323. if (rsa)
  324. RSA_free(rsa);
  325. } else if (cert_key) {
  326. int min_bits = 1024;
  327. #ifdef EVP_PKEY_EC
  328. if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
  329. min_bits = 128;
  330. #endif
  331. if (EVP_PKEY_bits(cert_key) >= min_bits)
  332. key_ok = 1;
  333. }
  334. EVP_PKEY_free(cert_key);
  335. if (!key_ok)
  336. goto bad;
  337. /* XXXX compare DNs or anything? */
  338. return 1;
  339. bad:
  340. tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
  341. return 0;
  342. }
  343. /** Warn that a certificate lifetime extends through a certain range. */
  344. static void
  345. log_cert_lifetime(int severity, const X509 *cert, const char *problem,
  346. time_t now)
  347. {
  348. BIO *bio = NULL;
  349. BUF_MEM *buf;
  350. char *s1=NULL, *s2=NULL;
  351. char mytime[33];
  352. struct tm tm;
  353. size_t n;
  354. if (problem)
  355. tor_log(severity, LD_GENERAL,
  356. "Certificate %s. Either their clock is set wrong, or your clock "
  357. "is wrong.",
  358. problem);
  359. if (!(bio = BIO_new(BIO_s_mem()))) {
  360. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  361. }
  362. if (!(ASN1_TIME_print(bio, X509_get_notBefore_const(cert)))) {
  363. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  364. goto end;
  365. }
  366. BIO_get_mem_ptr(bio, &buf);
  367. s1 = tor_strndup(buf->data, buf->length);
  368. (void)BIO_reset(bio);
  369. if (!(ASN1_TIME_print(bio, X509_get_notAfter_const(cert)))) {
  370. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  371. goto end;
  372. }
  373. BIO_get_mem_ptr(bio, &buf);
  374. s2 = tor_strndup(buf->data, buf->length);
  375. n = strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
  376. if (n > 0) {
  377. tor_log(severity, LD_GENERAL,
  378. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  379. s1,s2,mytime);
  380. } else {
  381. tor_log(severity, LD_GENERAL,
  382. "(certificate lifetime runs from %s through %s. "
  383. "Couldn't get your time.)",
  384. s1, s2);
  385. }
  386. end:
  387. /* Not expected to get invoked */
  388. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  389. if (bio)
  390. BIO_free(bio);
  391. tor_free(s1);
  392. tor_free(s2);
  393. }
  394. /** Helper: check whether <b>cert</b> is expired give or take
  395. * <b>past_tolerance</b> seconds, or not-yet-valid give or take
  396. * <b>future_tolerance</b> seconds. (Relative to the current time
  397. * <b>now</b>.) If it is live, return 0. If it is not live, log a message
  398. * and return -1. */
  399. int
  400. tor_x509_check_cert_lifetime_internal(int severity, const X509 *cert,
  401. time_t now,
  402. int past_tolerance, int future_tolerance)
  403. {
  404. time_t t;
  405. t = now + future_tolerance;
  406. if (X509_cmp_time(X509_get_notBefore_const(cert), &t) > 0) {
  407. log_cert_lifetime(severity, cert, "not yet valid", now);
  408. return -1;
  409. }
  410. t = now - past_tolerance;
  411. if (X509_cmp_time(X509_get_notAfter_const(cert), &t) < 0) {
  412. log_cert_lifetime(severity, cert, "already expired", now);
  413. return -1;
  414. }
  415. return 0;
  416. }
  417. #ifdef TOR_UNIT_TESTS
  418. /* Testing only: return a new x509 cert with the same contents as <b>inp</b>,
  419. but with the expiration time <b>new_expiration_time</b>, signed with
  420. <b>signing_key</b>. */
  421. STATIC tor_x509_cert_t *
  422. tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
  423. time_t new_expiration_time,
  424. crypto_pk_t *signing_key)
  425. {
  426. X509 *newc = X509_dup(inp->cert);
  427. X509_time_adj(X509_get_notAfter(newc), 0, &new_expiration_time);
  428. EVP_PKEY *pk = crypto_pk_get_openssl_evp_pkey_(signing_key, 1);
  429. tor_assert(X509_sign(newc, pk, EVP_sha256()));
  430. EVP_PKEY_free(pk);
  431. return tor_x509_cert_new(newc);
  432. }
  433. #endif /* defined(TOR_UNIT_TESTS) */