crypto_dh.c 13 KB

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