crypto_dh_openssl.c 12 KB

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