crypto_dh_openssl.c 12 KB

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