x509_openssl.c 13 KB

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