crypto_dh.c 13 KB

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