crypto_dh.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto_dh.c
  8. * \brief Block of functions related with DH utilities and operations.
  9. **/
  10. #include "compat_openssl.h"
  11. #include "crypto_dh.h"
  12. #include "crypto_digest.h"
  13. #include "crypto_hkdf.h"
  14. #include "crypto_util.h"
  15. DISABLE_GCC_WARNING(redundant-decls)
  16. #include <openssl/dh.h>
  17. ENABLE_GCC_WARNING(redundant-decls)
  18. #include "torlog.h"
  19. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  20. * while we're waiting for the second.*/
  21. struct crypto_dh_t {
  22. DH *dh; /**< The openssl DH object */
  23. };
  24. static int tor_check_dh_key(int severity, const BIGNUM *bn);
  25. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  26. */
  27. DH *
  28. crypto_dh_get_dh_(crypto_dh_t *dh)
  29. {
  30. return dh->dh;
  31. }
  32. /** Our DH 'g' parameter */
  33. #define DH_GENERATOR 2
  34. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  35. static BIGNUM *dh_param_p = NULL;
  36. /** Shared P parameter for our TLS DH key exchanges. */
  37. static BIGNUM *dh_param_p_tls = NULL;
  38. /** Shared G parameter for our DH key exchanges. */
  39. static BIGNUM *dh_param_g = NULL;
  40. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  41. * computationally expensive (milliseconds), so should only be called when
  42. * the DH parameters change. Returns 0 on success, * -1 on failure.
  43. */
  44. static int
  45. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  46. {
  47. DH *dh = NULL;
  48. int ret = -1;
  49. /* Copy into a temporary DH object, just so that DH_check() can be called. */
  50. if (!(dh = DH_new()))
  51. goto out;
  52. #ifdef OPENSSL_1_1_API
  53. BIGNUM *dh_p, *dh_g;
  54. if (!(dh_p = BN_dup(p)))
  55. goto out;
  56. if (!(dh_g = BN_dup(g)))
  57. goto out;
  58. if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
  59. goto out;
  60. #else /* !(defined(OPENSSL_1_1_API)) */
  61. if (!(dh->p = BN_dup(p)))
  62. goto out;
  63. if (!(dh->g = BN_dup(g)))
  64. goto out;
  65. #endif /* defined(OPENSSL_1_1_API) */
  66. /* Perform the validation. */
  67. int codes = 0;
  68. if (!DH_check(dh, &codes))
  69. goto out;
  70. if (BN_is_word(g, DH_GENERATOR_2)) {
  71. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  72. *
  73. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  74. * IETF's primes are congruent to 23 when g = 2.
  75. */
  76. BN_ULONG residue = BN_mod_word(p, 24);
  77. if (residue == 11 || residue == 23)
  78. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  79. }
  80. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  81. goto out;
  82. /* Things are probably not evil. */
  83. ret = 0;
  84. out:
  85. if (dh)
  86. DH_free(dh);
  87. return ret;
  88. }
  89. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  90. * DH stuff.
  91. */
  92. static void
  93. crypto_set_dh_generator(void)
  94. {
  95. BIGNUM *generator;
  96. int r;
  97. if (dh_param_g)
  98. return;
  99. generator = BN_new();
  100. tor_assert(generator);
  101. r = BN_set_word(generator, DH_GENERATOR);
  102. tor_assert(r);
  103. dh_param_g = generator;
  104. }
  105. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  106. * modulus. */
  107. void
  108. crypto_set_tls_dh_prime(void)
  109. {
  110. BIGNUM *tls_prime = NULL;
  111. int r;
  112. /* If the space is occupied, free the previous TLS DH prime */
  113. if (BUG(dh_param_p_tls)) {
  114. /* LCOV_EXCL_START
  115. *
  116. * We shouldn't be calling this twice.
  117. */
  118. BN_clear_free(dh_param_p_tls);
  119. dh_param_p_tls = NULL;
  120. /* LCOV_EXCL_STOP */
  121. }
  122. tls_prime = BN_new();
  123. tor_assert(tls_prime);
  124. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  125. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  126. * prime.
  127. */
  128. r = BN_hex2bn(&tls_prime,
  129. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  130. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  131. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  132. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  133. "B0E7393E0F24218EB3");
  134. tor_assert(r);
  135. tor_assert(tls_prime);
  136. dh_param_p_tls = tls_prime;
  137. crypto_set_dh_generator();
  138. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  139. }
  140. /** Initialize dh_param_p and dh_param_g if they are not already
  141. * set. */
  142. static void
  143. init_dh_param(void)
  144. {
  145. BIGNUM *circuit_dh_prime;
  146. int r;
  147. if (BUG(dh_param_p && dh_param_g))
  148. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  149. circuit_dh_prime = BN_new();
  150. tor_assert(circuit_dh_prime);
  151. /* This is from rfc2409, section 6.2. It's a safe prime, and
  152. supposedly it equals:
  153. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  154. */
  155. r = BN_hex2bn(&circuit_dh_prime,
  156. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  157. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  158. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  159. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  160. "49286651ECE65381FFFFFFFFFFFFFFFF");
  161. tor_assert(r);
  162. /* Set the new values as the global DH parameters. */
  163. dh_param_p = circuit_dh_prime;
  164. crypto_set_dh_generator();
  165. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  166. if (!dh_param_p_tls) {
  167. crypto_set_tls_dh_prime();
  168. }
  169. }
  170. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  171. * handshake. Since we exponentiate by this value, choosing a smaller one
  172. * lets our handhake go faster.
  173. */
  174. #define DH_PRIVATE_KEY_BITS 320
  175. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  176. * failure.
  177. */
  178. crypto_dh_t *
  179. crypto_dh_new(int dh_type)
  180. {
  181. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  182. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  183. dh_type == DH_TYPE_REND);
  184. if (!dh_param_p)
  185. init_dh_param();
  186. if (!(res->dh = DH_new()))
  187. goto err;
  188. #ifdef OPENSSL_1_1_API
  189. BIGNUM *dh_p = NULL, *dh_g = NULL;
  190. if (dh_type == DH_TYPE_TLS) {
  191. dh_p = BN_dup(dh_param_p_tls);
  192. } else {
  193. dh_p = BN_dup(dh_param_p);
  194. }
  195. if (!dh_p)
  196. goto err;
  197. dh_g = BN_dup(dh_param_g);
  198. if (!dh_g) {
  199. BN_free(dh_p);
  200. goto err;
  201. }
  202. if (!DH_set0_pqg(res->dh, dh_p, NULL, dh_g)) {
  203. goto err;
  204. }
  205. if (!DH_set_length(res->dh, DH_PRIVATE_KEY_BITS))
  206. goto err;
  207. #else /* !(defined(OPENSSL_1_1_API)) */
  208. if (dh_type == DH_TYPE_TLS) {
  209. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  210. goto err;
  211. } else {
  212. if (!(res->dh->p = BN_dup(dh_param_p)))
  213. goto err;
  214. }
  215. if (!(res->dh->g = BN_dup(dh_param_g)))
  216. goto err;
  217. res->dh->length = DH_PRIVATE_KEY_BITS;
  218. #endif /* defined(OPENSSL_1_1_API) */
  219. return res;
  220. /* LCOV_EXCL_START
  221. * This error condition is only reached when an allocation fails */
  222. err:
  223. crypto_log_errors(LOG_WARN, "creating DH object");
  224. if (res->dh) DH_free(res->dh); /* frees p and g too */
  225. tor_free(res);
  226. return NULL;
  227. /* LCOV_EXCL_STOP */
  228. }
  229. /** Return a copy of <b>dh</b>, sharing its internal state. */
  230. crypto_dh_t *
  231. crypto_dh_dup(const crypto_dh_t *dh)
  232. {
  233. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  234. tor_assert(dh);
  235. tor_assert(dh->dh);
  236. dh_new->dh = dh->dh;
  237. DH_up_ref(dh->dh);
  238. return dh_new;
  239. }
  240. /** Return the length of the DH key in <b>dh</b>, in bytes.
  241. */
  242. int
  243. crypto_dh_get_bytes(crypto_dh_t *dh)
  244. {
  245. tor_assert(dh);
  246. return DH_size(dh->dh);
  247. }
  248. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  249. * success, -1 on failure.
  250. */
  251. int
  252. crypto_dh_generate_public(crypto_dh_t *dh)
  253. {
  254. #ifndef OPENSSL_1_1_API
  255. again:
  256. #endif
  257. if (!DH_generate_key(dh->dh)) {
  258. /* LCOV_EXCL_START
  259. * To test this we would need some way to tell openssl to break DH. */
  260. crypto_log_errors(LOG_WARN, "generating DH key");
  261. return -1;
  262. /* LCOV_EXCL_STOP */
  263. }
  264. #ifdef OPENSSL_1_1_API
  265. /* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
  266. * recreating the DH object. I have no idea what sort of aliasing madness
  267. * can occur here, so do the check, and just bail on failure.
  268. */
  269. const BIGNUM *pub_key, *priv_key;
  270. DH_get0_key(dh->dh, &pub_key, &priv_key);
  271. if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
  272. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  273. "the-universe chances really do happen. Treating as a failure.");
  274. return -1;
  275. }
  276. #else /* !(defined(OPENSSL_1_1_API)) */
  277. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  278. /* LCOV_EXCL_START
  279. * If this happens, then openssl's DH implementation is busted. */
  280. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  281. "the-universe chances really do happen. Trying again.");
  282. /* Free and clear the keys, so OpenSSL will actually try again. */
  283. BN_clear_free(dh->dh->pub_key);
  284. BN_clear_free(dh->dh->priv_key);
  285. dh->dh->pub_key = dh->dh->priv_key = NULL;
  286. goto again;
  287. /* LCOV_EXCL_STOP */
  288. }
  289. #endif /* defined(OPENSSL_1_1_API) */
  290. return 0;
  291. }
  292. /** Generate g^x as necessary, and write the g^x for the key exchange
  293. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  294. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  295. */
  296. int
  297. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  298. {
  299. int bytes;
  300. tor_assert(dh);
  301. const BIGNUM *dh_pub;
  302. #ifdef OPENSSL_1_1_API
  303. const BIGNUM *dh_priv;
  304. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  305. #else
  306. dh_pub = dh->dh->pub_key;
  307. #endif /* defined(OPENSSL_1_1_API) */
  308. if (!dh_pub) {
  309. if (crypto_dh_generate_public(dh)<0)
  310. return -1;
  311. else {
  312. #ifdef OPENSSL_1_1_API
  313. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  314. #else
  315. dh_pub = dh->dh->pub_key;
  316. #endif
  317. }
  318. }
  319. tor_assert(dh_pub);
  320. bytes = BN_num_bytes(dh_pub);
  321. tor_assert(bytes >= 0);
  322. if (pubkey_len < (size_t)bytes) {
  323. log_warn(LD_CRYPTO,
  324. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  325. (int) pubkey_len, bytes);
  326. return -1;
  327. }
  328. memset(pubkey, 0, pubkey_len);
  329. BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  330. return 0;
  331. }
  332. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  333. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  334. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  335. */
  336. static int
  337. tor_check_dh_key(int severity, const BIGNUM *bn)
  338. {
  339. BIGNUM *x;
  340. char *s;
  341. tor_assert(bn);
  342. x = BN_new();
  343. tor_assert(x);
  344. if (BUG(!dh_param_p))
  345. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  346. BN_set_word(x, 1);
  347. if (BN_cmp(bn,x)<=0) {
  348. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  349. goto err;
  350. }
  351. BN_copy(x,dh_param_p);
  352. BN_sub_word(x, 1);
  353. if (BN_cmp(bn,x)>=0) {
  354. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  355. goto err;
  356. }
  357. BN_clear_free(x);
  358. return 0;
  359. err:
  360. BN_clear_free(x);
  361. s = BN_bn2hex(bn);
  362. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  363. OPENSSL_free(s);
  364. return -1;
  365. }
  366. /** Given a DH key exchange object, and our peer's value of g^y (as a
  367. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  368. * <b>secret_bytes_out</b> bytes of shared key material and write them
  369. * to <b>secret_out</b>. Return the number of bytes generated on success,
  370. * or -1 on failure.
  371. *
  372. * (We generate key material by computing
  373. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  374. * where || is concatenation.)
  375. */
  376. ssize_t
  377. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  378. const char *pubkey, size_t pubkey_len,
  379. char *secret_out, size_t secret_bytes_out)
  380. {
  381. char *secret_tmp = NULL;
  382. BIGNUM *pubkey_bn = NULL;
  383. size_t secret_len=0, secret_tmp_len=0;
  384. int result=0;
  385. tor_assert(dh);
  386. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  387. tor_assert(pubkey_len < INT_MAX);
  388. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  389. (int)pubkey_len, NULL)))
  390. goto error;
  391. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  392. /* Check for invalid public keys. */
  393. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  394. goto error;
  395. }
  396. secret_tmp_len = crypto_dh_get_bytes(dh);
  397. secret_tmp = tor_malloc(secret_tmp_len);
  398. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  399. if (result < 0) {
  400. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  401. goto error;
  402. }
  403. secret_len = result;
  404. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  405. (uint8_t*)secret_out, secret_bytes_out)<0)
  406. goto error;
  407. secret_len = secret_bytes_out;
  408. goto done;
  409. error:
  410. result = -1;
  411. done:
  412. crypto_log_errors(LOG_WARN, "completing DH handshake");
  413. if (pubkey_bn)
  414. BN_clear_free(pubkey_bn);
  415. if (secret_tmp) {
  416. memwipe(secret_tmp, 0, secret_tmp_len);
  417. tor_free(secret_tmp);
  418. }
  419. if (result < 0)
  420. return result;
  421. else
  422. return secret_len;
  423. }
  424. /** Free a DH key exchange object.
  425. */
  426. void
  427. crypto_dh_free_(crypto_dh_t *dh)
  428. {
  429. if (!dh)
  430. return;
  431. tor_assert(dh->dh);
  432. DH_free(dh->dh);
  433. tor_free(dh);
  434. }
  435. void
  436. crypto_dh_free_all(void)
  437. {
  438. if (dh_param_p)
  439. BN_clear_free(dh_param_p);
  440. if (dh_param_p_tls)
  441. BN_clear_free(dh_param_p_tls);
  442. if (dh_param_g)
  443. BN_clear_free(dh_param_g);
  444. dh_param_p = dh_param_p_tls = dh_param_g = NULL;
  445. }