x509_openssl.c 13 KB

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