crypto.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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-2017, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto.c
  8. * \brief Wrapper functions to present a consistent interface to
  9. * public-key and symmetric cryptography operations from OpenSSL and
  10. * other places.
  11. **/
  12. #include "orconfig.h"
  13. #ifdef _WIN32
  14. #include <winsock2.h>
  15. #include <windows.h>
  16. #include <wincrypt.h>
  17. /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
  18. * use either definition. */
  19. #undef OCSP_RESPONSE
  20. #endif /* defined(_WIN32) */
  21. #define CRYPTO_PRIVATE
  22. #include "compat_openssl.h"
  23. #include "crypto.h"
  24. #include "crypto_curve25519.h"
  25. #include "crypto_digest.h"
  26. #include "crypto_ed25519.h"
  27. #include "crypto_format.h"
  28. #include "crypto_rand.h"
  29. #include "crypto_rsa.h"
  30. #include "crypto_util.h"
  31. DISABLE_GCC_WARNING(redundant-decls)
  32. #include <openssl/err.h>
  33. #include <openssl/evp.h>
  34. #include <openssl/engine.h>
  35. #include <openssl/bn.h>
  36. #include <openssl/dh.h>
  37. #include <openssl/conf.h>
  38. #include <openssl/hmac.h>
  39. #include <openssl/ssl.h>
  40. ENABLE_GCC_WARNING(redundant-decls)
  41. #if __GNUC__ && GCC_VERSION >= 402
  42. #if GCC_VERSION >= 406
  43. #pragma GCC diagnostic pop
  44. #else
  45. #pragma GCC diagnostic warning "-Wredundant-decls"
  46. #endif
  47. #endif /* __GNUC__ && GCC_VERSION >= 402 */
  48. #ifdef HAVE_CTYPE_H
  49. #include <ctype.h>
  50. #endif
  51. #ifdef HAVE_UNISTD_H
  52. #include <unistd.h>
  53. #endif
  54. #include "torlog.h"
  55. #include "torint.h"
  56. #include "aes.h"
  57. #include "util.h"
  58. #include "container.h"
  59. #include "compat.h"
  60. #include "sandbox.h"
  61. #include "util_format.h"
  62. #include "keccak-tiny/keccak-tiny.h"
  63. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  64. * while we're waiting for the second.*/
  65. struct crypto_dh_t {
  66. DH *dh; /**< The openssl DH object */
  67. };
  68. static int tor_check_dh_key(int severity, const BIGNUM *bn);
  69. /** Boolean: has OpenSSL's crypto been initialized? */
  70. static int crypto_early_initialized_ = 0;
  71. /** Boolean: has OpenSSL's crypto been initialized? */
  72. static int crypto_global_initialized_ = 0;
  73. #ifndef DISABLE_ENGINES
  74. /** Log any OpenSSL engines we're using at NOTICE. */
  75. static void
  76. log_engine(const char *fn, ENGINE *e)
  77. {
  78. if (e) {
  79. const char *name, *id;
  80. name = ENGINE_get_name(e);
  81. id = ENGINE_get_id(e);
  82. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  83. fn, name?name:"?", id?id:"?");
  84. } else {
  85. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  86. }
  87. }
  88. #endif /* !defined(DISABLE_ENGINES) */
  89. #ifndef DISABLE_ENGINES
  90. /** Try to load an engine in a shared library via fully qualified path.
  91. */
  92. static ENGINE *
  93. try_load_engine(const char *path, const char *engine)
  94. {
  95. ENGINE *e = ENGINE_by_id("dynamic");
  96. if (e) {
  97. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  98. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  99. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  100. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  101. ENGINE_free(e);
  102. e = NULL;
  103. }
  104. }
  105. return e;
  106. }
  107. #endif /* !defined(DISABLE_ENGINES) */
  108. static int have_seeded_siphash = 0;
  109. /** Set up the siphash key if we haven't already done so. */
  110. int
  111. crypto_init_siphash_key(void)
  112. {
  113. struct sipkey key;
  114. if (have_seeded_siphash)
  115. return 0;
  116. crypto_rand((char*) &key, sizeof(key));
  117. siphash_set_global_key(&key);
  118. have_seeded_siphash = 1;
  119. return 0;
  120. }
  121. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  122. */
  123. int
  124. crypto_early_init(void)
  125. {
  126. if (!crypto_early_initialized_) {
  127. crypto_early_initialized_ = 1;
  128. #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)
  129. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS |
  130. OPENSSL_INIT_LOAD_CRYPTO_STRINGS |
  131. OPENSSL_INIT_ADD_ALL_CIPHERS |
  132. OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
  133. #else
  134. ERR_load_crypto_strings();
  135. OpenSSL_add_all_algorithms();
  136. #endif
  137. setup_openssl_threading();
  138. unsigned long version_num = OpenSSL_version_num();
  139. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  140. if (version_num == OPENSSL_VERSION_NUMBER &&
  141. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  142. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  143. "(%lx: %s).", version_num, version_str);
  144. } else {
  145. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  146. "version we're running with. If you get weird crashes, that "
  147. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  148. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  149. version_num, version_str);
  150. }
  151. crypto_force_rand_ssleay();
  152. if (crypto_seed_rng() < 0)
  153. return -1;
  154. if (crypto_init_siphash_key() < 0)
  155. return -1;
  156. curve25519_init();
  157. ed25519_init();
  158. }
  159. return 0;
  160. }
  161. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  162. */
  163. int
  164. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  165. {
  166. if (!crypto_global_initialized_) {
  167. if (crypto_early_init() < 0)
  168. return -1;
  169. crypto_global_initialized_ = 1;
  170. if (useAccel > 0) {
  171. #ifdef DISABLE_ENGINES
  172. (void)accelName;
  173. (void)accelDir;
  174. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  175. #else
  176. ENGINE *e = NULL;
  177. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  178. ENGINE_load_builtin_engines();
  179. ENGINE_register_all_complete();
  180. if (accelName) {
  181. if (accelDir) {
  182. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  183. " via path \"%s\".", accelName, accelDir);
  184. e = try_load_engine(accelName, accelDir);
  185. } else {
  186. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  187. " acceleration support.", accelName);
  188. e = ENGINE_by_id(accelName);
  189. }
  190. if (!e) {
  191. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  192. accelName);
  193. } else {
  194. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  195. accelName);
  196. }
  197. }
  198. if (e) {
  199. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  200. " setting default ciphers.");
  201. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  202. }
  203. /* Log, if available, the intersection of the set of algorithms
  204. used by Tor and the set of algorithms available in the engine */
  205. log_engine("RSA", ENGINE_get_default_RSA());
  206. log_engine("DH", ENGINE_get_default_DH());
  207. #ifdef OPENSSL_1_1_API
  208. log_engine("EC", ENGINE_get_default_EC());
  209. #else
  210. log_engine("ECDH", ENGINE_get_default_ECDH());
  211. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  212. #endif /* defined(OPENSSL_1_1_API) */
  213. log_engine("RAND", ENGINE_get_default_RAND());
  214. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  215. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  216. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  217. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  218. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  219. #ifdef NID_aes_128_ctr
  220. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  221. #endif
  222. #ifdef NID_aes_128_gcm
  223. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  224. #endif
  225. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  226. #ifdef NID_aes_256_gcm
  227. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  228. #endif
  229. #endif /* defined(DISABLE_ENGINES) */
  230. } else {
  231. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  232. }
  233. if (crypto_force_rand_ssleay()) {
  234. if (crypto_seed_rng() < 0)
  235. return -1;
  236. }
  237. evaluate_evp_for_aes(-1);
  238. evaluate_ctr_for_aes();
  239. }
  240. return 0;
  241. }
  242. /** Free crypto resources held by this thread. */
  243. void
  244. crypto_thread_cleanup(void)
  245. {
  246. #ifndef NEW_THREAD_API
  247. ERR_remove_thread_state(NULL);
  248. #endif
  249. }
  250. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  251. */
  252. DH *
  253. crypto_dh_get_dh_(crypto_dh_t *dh)
  254. {
  255. return dh->dh;
  256. }
  257. /** Allocate and return a new symmetric cipher using the provided key and iv.
  258. * The key is <b>bits</b> bits long; the IV is CIPHER_IV_LEN bytes. Both
  259. * must be provided. Key length must be 128, 192, or 256 */
  260. crypto_cipher_t *
  261. crypto_cipher_new_with_iv_and_bits(const uint8_t *key,
  262. const uint8_t *iv,
  263. int bits)
  264. {
  265. tor_assert(key);
  266. tor_assert(iv);
  267. return aes_new_cipher((const uint8_t*)key, (const uint8_t*)iv, bits);
  268. }
  269. /** Allocate and return a new symmetric cipher using the provided key and iv.
  270. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. Both
  271. * must be provided.
  272. */
  273. crypto_cipher_t *
  274. crypto_cipher_new_with_iv(const char *key, const char *iv)
  275. {
  276. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)iv,
  277. 128);
  278. }
  279. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  280. * zero bytes and key length <b>bits</b>. Key length must be 128, 192, or
  281. * 256. */
  282. crypto_cipher_t *
  283. crypto_cipher_new_with_bits(const char *key, int bits)
  284. {
  285. char zeroiv[CIPHER_IV_LEN];
  286. memset(zeroiv, 0, sizeof(zeroiv));
  287. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)zeroiv,
  288. bits);
  289. }
  290. /** Return a new crypto_cipher_t with the provided <b>key</b> (of
  291. * CIPHER_KEY_LEN bytes) and an IV of all zero bytes. */
  292. crypto_cipher_t *
  293. crypto_cipher_new(const char *key)
  294. {
  295. return crypto_cipher_new_with_bits(key, 128);
  296. }
  297. /** Free a symmetric cipher.
  298. */
  299. void
  300. crypto_cipher_free_(crypto_cipher_t *env)
  301. {
  302. if (!env)
  303. return;
  304. aes_cipher_free(env);
  305. }
  306. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  307. * every four characters. */
  308. void
  309. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  310. {
  311. int n = 0;
  312. char *end = out+outlen;
  313. tor_assert(outlen < SIZE_T_CEILING);
  314. while (*in && out<end) {
  315. *out++ = *in++;
  316. if (++n == 4 && *in && out<end) {
  317. n = 0;
  318. *out++ = ' ';
  319. }
  320. }
  321. tor_assert(out<end);
  322. *out = '\0';
  323. }
  324. /* symmetric crypto */
  325. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  326. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  327. * Does not check for failure.
  328. */
  329. int
  330. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  331. const char *from, size_t fromlen)
  332. {
  333. tor_assert(env);
  334. tor_assert(env);
  335. tor_assert(from);
  336. tor_assert(fromlen);
  337. tor_assert(to);
  338. tor_assert(fromlen < SIZE_T_CEILING);
  339. memcpy(to, from, fromlen);
  340. aes_crypt_inplace(env, to, fromlen);
  341. return 0;
  342. }
  343. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  344. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  345. * Does not check for failure.
  346. */
  347. int
  348. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  349. const char *from, size_t fromlen)
  350. {
  351. tor_assert(env);
  352. tor_assert(from);
  353. tor_assert(to);
  354. tor_assert(fromlen < SIZE_T_CEILING);
  355. memcpy(to, from, fromlen);
  356. aes_crypt_inplace(env, to, fromlen);
  357. return 0;
  358. }
  359. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  360. * on success. Does not check for failure.
  361. */
  362. void
  363. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  364. {
  365. tor_assert(len < SIZE_T_CEILING);
  366. aes_crypt_inplace(env, buf, len);
  367. }
  368. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  369. * <b>key</b> to the buffer in <b>to</b> of length
  370. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  371. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  372. * number of bytes written, on failure, return -1.
  373. */
  374. int
  375. crypto_cipher_encrypt_with_iv(const char *key,
  376. char *to, size_t tolen,
  377. const char *from, size_t fromlen)
  378. {
  379. crypto_cipher_t *cipher;
  380. tor_assert(from);
  381. tor_assert(to);
  382. tor_assert(fromlen < INT_MAX);
  383. if (fromlen < 1)
  384. return -1;
  385. if (tolen < fromlen + CIPHER_IV_LEN)
  386. return -1;
  387. char iv[CIPHER_IV_LEN];
  388. crypto_rand(iv, sizeof(iv));
  389. cipher = crypto_cipher_new_with_iv(key, iv);
  390. memcpy(to, iv, CIPHER_IV_LEN);
  391. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  392. crypto_cipher_free(cipher);
  393. memwipe(iv, 0, sizeof(iv));
  394. return (int)(fromlen + CIPHER_IV_LEN);
  395. }
  396. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  397. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  398. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  399. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  400. * number of bytes written, on failure, return -1.
  401. */
  402. int
  403. crypto_cipher_decrypt_with_iv(const char *key,
  404. char *to, size_t tolen,
  405. const char *from, size_t fromlen)
  406. {
  407. crypto_cipher_t *cipher;
  408. tor_assert(key);
  409. tor_assert(from);
  410. tor_assert(to);
  411. tor_assert(fromlen < INT_MAX);
  412. if (fromlen <= CIPHER_IV_LEN)
  413. return -1;
  414. if (tolen < fromlen - CIPHER_IV_LEN)
  415. return -1;
  416. cipher = crypto_cipher_new_with_iv(key, from);
  417. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  418. crypto_cipher_free(cipher);
  419. return (int)(fromlen - CIPHER_IV_LEN);
  420. }
  421. /* DH */
  422. /** Our DH 'g' parameter */
  423. #define DH_GENERATOR 2
  424. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  425. static BIGNUM *dh_param_p = NULL;
  426. /** Shared P parameter for our TLS DH key exchanges. */
  427. static BIGNUM *dh_param_p_tls = NULL;
  428. /** Shared G parameter for our DH key exchanges. */
  429. static BIGNUM *dh_param_g = NULL;
  430. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  431. * computationally expensive (milliseconds), so should only be called when
  432. * the DH parameters change. Returns 0 on success, * -1 on failure.
  433. */
  434. static int
  435. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  436. {
  437. DH *dh = NULL;
  438. int ret = -1;
  439. /* Copy into a temporary DH object, just so that DH_check() can be called. */
  440. if (!(dh = DH_new()))
  441. goto out;
  442. #ifdef OPENSSL_1_1_API
  443. BIGNUM *dh_p, *dh_g;
  444. if (!(dh_p = BN_dup(p)))
  445. goto out;
  446. if (!(dh_g = BN_dup(g)))
  447. goto out;
  448. if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
  449. goto out;
  450. #else /* !(defined(OPENSSL_1_1_API)) */
  451. if (!(dh->p = BN_dup(p)))
  452. goto out;
  453. if (!(dh->g = BN_dup(g)))
  454. goto out;
  455. #endif /* defined(OPENSSL_1_1_API) */
  456. /* Perform the validation. */
  457. int codes = 0;
  458. if (!DH_check(dh, &codes))
  459. goto out;
  460. if (BN_is_word(g, DH_GENERATOR_2)) {
  461. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  462. *
  463. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  464. * IETF's primes are congruent to 23 when g = 2.
  465. */
  466. BN_ULONG residue = BN_mod_word(p, 24);
  467. if (residue == 11 || residue == 23)
  468. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  469. }
  470. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  471. goto out;
  472. /* Things are probably not evil. */
  473. ret = 0;
  474. out:
  475. if (dh)
  476. DH_free(dh);
  477. return ret;
  478. }
  479. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  480. * DH stuff.
  481. */
  482. static void
  483. crypto_set_dh_generator(void)
  484. {
  485. BIGNUM *generator;
  486. int r;
  487. if (dh_param_g)
  488. return;
  489. generator = BN_new();
  490. tor_assert(generator);
  491. r = BN_set_word(generator, DH_GENERATOR);
  492. tor_assert(r);
  493. dh_param_g = generator;
  494. }
  495. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  496. * modulus. */
  497. void
  498. crypto_set_tls_dh_prime(void)
  499. {
  500. BIGNUM *tls_prime = NULL;
  501. int r;
  502. /* If the space is occupied, free the previous TLS DH prime */
  503. if (BUG(dh_param_p_tls)) {
  504. /* LCOV_EXCL_START
  505. *
  506. * We shouldn't be calling this twice.
  507. */
  508. BN_clear_free(dh_param_p_tls);
  509. dh_param_p_tls = NULL;
  510. /* LCOV_EXCL_STOP */
  511. }
  512. tls_prime = BN_new();
  513. tor_assert(tls_prime);
  514. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  515. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  516. * prime.
  517. */
  518. r = BN_hex2bn(&tls_prime,
  519. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  520. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  521. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  522. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  523. "B0E7393E0F24218EB3");
  524. tor_assert(r);
  525. tor_assert(tls_prime);
  526. dh_param_p_tls = tls_prime;
  527. crypto_set_dh_generator();
  528. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  529. }
  530. /** Initialize dh_param_p and dh_param_g if they are not already
  531. * set. */
  532. static void
  533. init_dh_param(void)
  534. {
  535. BIGNUM *circuit_dh_prime;
  536. int r;
  537. if (BUG(dh_param_p && dh_param_g))
  538. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  539. circuit_dh_prime = BN_new();
  540. tor_assert(circuit_dh_prime);
  541. /* This is from rfc2409, section 6.2. It's a safe prime, and
  542. supposedly it equals:
  543. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  544. */
  545. r = BN_hex2bn(&circuit_dh_prime,
  546. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  547. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  548. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  549. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  550. "49286651ECE65381FFFFFFFFFFFFFFFF");
  551. tor_assert(r);
  552. /* Set the new values as the global DH parameters. */
  553. dh_param_p = circuit_dh_prime;
  554. crypto_set_dh_generator();
  555. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  556. if (!dh_param_p_tls) {
  557. crypto_set_tls_dh_prime();
  558. }
  559. }
  560. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  561. * handshake. Since we exponentiate by this value, choosing a smaller one
  562. * lets our handhake go faster.
  563. */
  564. #define DH_PRIVATE_KEY_BITS 320
  565. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  566. * failure.
  567. */
  568. crypto_dh_t *
  569. crypto_dh_new(int dh_type)
  570. {
  571. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  572. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  573. dh_type == DH_TYPE_REND);
  574. if (!dh_param_p)
  575. init_dh_param();
  576. if (!(res->dh = DH_new()))
  577. goto err;
  578. #ifdef OPENSSL_1_1_API
  579. BIGNUM *dh_p = NULL, *dh_g = NULL;
  580. if (dh_type == DH_TYPE_TLS) {
  581. dh_p = BN_dup(dh_param_p_tls);
  582. } else {
  583. dh_p = BN_dup(dh_param_p);
  584. }
  585. if (!dh_p)
  586. goto err;
  587. dh_g = BN_dup(dh_param_g);
  588. if (!dh_g) {
  589. BN_free(dh_p);
  590. goto err;
  591. }
  592. if (!DH_set0_pqg(res->dh, dh_p, NULL, dh_g)) {
  593. goto err;
  594. }
  595. if (!DH_set_length(res->dh, DH_PRIVATE_KEY_BITS))
  596. goto err;
  597. #else /* !(defined(OPENSSL_1_1_API)) */
  598. if (dh_type == DH_TYPE_TLS) {
  599. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  600. goto err;
  601. } else {
  602. if (!(res->dh->p = BN_dup(dh_param_p)))
  603. goto err;
  604. }
  605. if (!(res->dh->g = BN_dup(dh_param_g)))
  606. goto err;
  607. res->dh->length = DH_PRIVATE_KEY_BITS;
  608. #endif /* defined(OPENSSL_1_1_API) */
  609. return res;
  610. /* LCOV_EXCL_START
  611. * This error condition is only reached when an allocation fails */
  612. err:
  613. crypto_log_errors(LOG_WARN, "creating DH object");
  614. if (res->dh) DH_free(res->dh); /* frees p and g too */
  615. tor_free(res);
  616. return NULL;
  617. /* LCOV_EXCL_STOP */
  618. }
  619. /** Return a copy of <b>dh</b>, sharing its internal state. */
  620. crypto_dh_t *
  621. crypto_dh_dup(const crypto_dh_t *dh)
  622. {
  623. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  624. tor_assert(dh);
  625. tor_assert(dh->dh);
  626. dh_new->dh = dh->dh;
  627. DH_up_ref(dh->dh);
  628. return dh_new;
  629. }
  630. /** Return the length of the DH key in <b>dh</b>, in bytes.
  631. */
  632. int
  633. crypto_dh_get_bytes(crypto_dh_t *dh)
  634. {
  635. tor_assert(dh);
  636. return DH_size(dh->dh);
  637. }
  638. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  639. * success, -1 on failure.
  640. */
  641. int
  642. crypto_dh_generate_public(crypto_dh_t *dh)
  643. {
  644. #ifndef OPENSSL_1_1_API
  645. again:
  646. #endif
  647. if (!DH_generate_key(dh->dh)) {
  648. /* LCOV_EXCL_START
  649. * To test this we would need some way to tell openssl to break DH. */
  650. crypto_log_errors(LOG_WARN, "generating DH key");
  651. return -1;
  652. /* LCOV_EXCL_STOP */
  653. }
  654. #ifdef OPENSSL_1_1_API
  655. /* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
  656. * recreating the DH object. I have no idea what sort of aliasing madness
  657. * can occur here, so do the check, and just bail on failure.
  658. */
  659. const BIGNUM *pub_key, *priv_key;
  660. DH_get0_key(dh->dh, &pub_key, &priv_key);
  661. if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
  662. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  663. "the-universe chances really do happen. Treating as a failure.");
  664. return -1;
  665. }
  666. #else /* !(defined(OPENSSL_1_1_API)) */
  667. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  668. /* LCOV_EXCL_START
  669. * If this happens, then openssl's DH implementation is busted. */
  670. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  671. "the-universe chances really do happen. Trying again.");
  672. /* Free and clear the keys, so OpenSSL will actually try again. */
  673. BN_clear_free(dh->dh->pub_key);
  674. BN_clear_free(dh->dh->priv_key);
  675. dh->dh->pub_key = dh->dh->priv_key = NULL;
  676. goto again;
  677. /* LCOV_EXCL_STOP */
  678. }
  679. #endif /* defined(OPENSSL_1_1_API) */
  680. return 0;
  681. }
  682. /** Generate g^x as necessary, and write the g^x for the key exchange
  683. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  684. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  685. */
  686. int
  687. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  688. {
  689. int bytes;
  690. tor_assert(dh);
  691. const BIGNUM *dh_pub;
  692. #ifdef OPENSSL_1_1_API
  693. const BIGNUM *dh_priv;
  694. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  695. #else
  696. dh_pub = dh->dh->pub_key;
  697. #endif /* defined(OPENSSL_1_1_API) */
  698. if (!dh_pub) {
  699. if (crypto_dh_generate_public(dh)<0)
  700. return -1;
  701. else {
  702. #ifdef OPENSSL_1_1_API
  703. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  704. #else
  705. dh_pub = dh->dh->pub_key;
  706. #endif
  707. }
  708. }
  709. tor_assert(dh_pub);
  710. bytes = BN_num_bytes(dh_pub);
  711. tor_assert(bytes >= 0);
  712. if (pubkey_len < (size_t)bytes) {
  713. log_warn(LD_CRYPTO,
  714. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  715. (int) pubkey_len, bytes);
  716. return -1;
  717. }
  718. memset(pubkey, 0, pubkey_len);
  719. BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  720. return 0;
  721. }
  722. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  723. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  724. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  725. */
  726. static int
  727. tor_check_dh_key(int severity, const BIGNUM *bn)
  728. {
  729. BIGNUM *x;
  730. char *s;
  731. tor_assert(bn);
  732. x = BN_new();
  733. tor_assert(x);
  734. if (BUG(!dh_param_p))
  735. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  736. BN_set_word(x, 1);
  737. if (BN_cmp(bn,x)<=0) {
  738. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  739. goto err;
  740. }
  741. BN_copy(x,dh_param_p);
  742. BN_sub_word(x, 1);
  743. if (BN_cmp(bn,x)>=0) {
  744. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  745. goto err;
  746. }
  747. BN_clear_free(x);
  748. return 0;
  749. err:
  750. BN_clear_free(x);
  751. s = BN_bn2hex(bn);
  752. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  753. OPENSSL_free(s);
  754. return -1;
  755. }
  756. /** Given a DH key exchange object, and our peer's value of g^y (as a
  757. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  758. * <b>secret_bytes_out</b> bytes of shared key material and write them
  759. * to <b>secret_out</b>. Return the number of bytes generated on success,
  760. * or -1 on failure.
  761. *
  762. * (We generate key material by computing
  763. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  764. * where || is concatenation.)
  765. */
  766. ssize_t
  767. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  768. const char *pubkey, size_t pubkey_len,
  769. char *secret_out, size_t secret_bytes_out)
  770. {
  771. char *secret_tmp = NULL;
  772. BIGNUM *pubkey_bn = NULL;
  773. size_t secret_len=0, secret_tmp_len=0;
  774. int result=0;
  775. tor_assert(dh);
  776. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  777. tor_assert(pubkey_len < INT_MAX);
  778. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  779. (int)pubkey_len, NULL)))
  780. goto error;
  781. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  782. /* Check for invalid public keys. */
  783. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  784. goto error;
  785. }
  786. secret_tmp_len = crypto_dh_get_bytes(dh);
  787. secret_tmp = tor_malloc(secret_tmp_len);
  788. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  789. if (result < 0) {
  790. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  791. goto error;
  792. }
  793. secret_len = result;
  794. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  795. (uint8_t*)secret_out, secret_bytes_out)<0)
  796. goto error;
  797. secret_len = secret_bytes_out;
  798. goto done;
  799. error:
  800. result = -1;
  801. done:
  802. crypto_log_errors(LOG_WARN, "completing DH handshake");
  803. if (pubkey_bn)
  804. BN_clear_free(pubkey_bn);
  805. if (secret_tmp) {
  806. memwipe(secret_tmp, 0, secret_tmp_len);
  807. tor_free(secret_tmp);
  808. }
  809. if (result < 0)
  810. return result;
  811. else
  812. return secret_len;
  813. }
  814. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  815. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  816. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  817. * H(K | [00]) | H(K | [01]) | ....
  818. *
  819. * This is the key expansion algorithm used in the "TAP" circuit extension
  820. * mechanism; it shouldn't be used for new protocols.
  821. *
  822. * Return 0 on success, -1 on failure.
  823. */
  824. int
  825. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  826. uint8_t *key_out, size_t key_out_len)
  827. {
  828. int i, r = -1;
  829. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  830. uint8_t digest[DIGEST_LEN];
  831. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  832. tor_assert(key_out_len <= DIGEST_LEN*256);
  833. memcpy(tmp, key_in, key_in_len);
  834. for (cp = key_out, i=0; cp < key_out+key_out_len;
  835. ++i, cp += DIGEST_LEN) {
  836. tmp[key_in_len] = i;
  837. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1) < 0)
  838. goto exit;
  839. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  840. }
  841. r = 0;
  842. exit:
  843. memwipe(tmp, 0, key_in_len+1);
  844. tor_free(tmp);
  845. memwipe(digest, 0, sizeof(digest));
  846. return r;
  847. }
  848. /** Expand some secret key material according to RFC5869, using SHA256 as the
  849. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  850. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  851. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  852. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  853. * bytes to <b>key_out</b> and return 0. Assert on failure.
  854. */
  855. int
  856. crypto_expand_key_material_rfc5869_sha256(
  857. const uint8_t *key_in, size_t key_in_len,
  858. const uint8_t *salt_in, size_t salt_in_len,
  859. const uint8_t *info_in, size_t info_in_len,
  860. uint8_t *key_out, size_t key_out_len)
  861. {
  862. uint8_t prk[DIGEST256_LEN];
  863. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  864. uint8_t mac[DIGEST256_LEN];
  865. int i;
  866. uint8_t *outp;
  867. size_t tmp_len;
  868. crypto_hmac_sha256((char*)prk,
  869. (const char*)salt_in, salt_in_len,
  870. (const char*)key_in, key_in_len);
  871. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  872. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  873. tor_assert(info_in_len <= 128);
  874. memset(tmp, 0, sizeof(tmp));
  875. outp = key_out;
  876. i = 1;
  877. while (key_out_len) {
  878. size_t n;
  879. if (i > 1) {
  880. memcpy(tmp, mac, DIGEST256_LEN);
  881. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  882. tmp[DIGEST256_LEN+info_in_len] = i;
  883. tmp_len = DIGEST256_LEN + info_in_len + 1;
  884. } else {
  885. memcpy(tmp, info_in, info_in_len);
  886. tmp[info_in_len] = i;
  887. tmp_len = info_in_len + 1;
  888. }
  889. crypto_hmac_sha256((char*)mac,
  890. (const char*)prk, DIGEST256_LEN,
  891. (const char*)tmp, tmp_len);
  892. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  893. memcpy(outp, mac, n);
  894. key_out_len -= n;
  895. outp += n;
  896. ++i;
  897. }
  898. memwipe(tmp, 0, sizeof(tmp));
  899. memwipe(mac, 0, sizeof(mac));
  900. return 0;
  901. }
  902. /** Free a DH key exchange object.
  903. */
  904. void
  905. crypto_dh_free_(crypto_dh_t *dh)
  906. {
  907. if (!dh)
  908. return;
  909. tor_assert(dh->dh);
  910. DH_free(dh->dh);
  911. tor_free(dh);
  912. }
  913. /** @{ */
  914. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  915. * failure.
  916. */
  917. int
  918. crypto_global_cleanup(void)
  919. {
  920. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
  921. EVP_cleanup();
  922. #endif
  923. #ifndef NEW_THREAD_API
  924. ERR_remove_thread_state(NULL);
  925. #endif
  926. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
  927. ERR_free_strings();
  928. #endif
  929. if (dh_param_p)
  930. BN_clear_free(dh_param_p);
  931. if (dh_param_p_tls)
  932. BN_clear_free(dh_param_p_tls);
  933. if (dh_param_g)
  934. BN_clear_free(dh_param_g);
  935. dh_param_p = dh_param_p_tls = dh_param_g = NULL;
  936. #ifndef DISABLE_ENGINES
  937. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
  938. ENGINE_cleanup();
  939. #endif
  940. #endif
  941. CONF_modules_unload(1);
  942. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
  943. CRYPTO_cleanup_all_ex_data();
  944. #endif
  945. crypto_openssl_free_all();
  946. crypto_early_initialized_ = 0;
  947. crypto_global_initialized_ = 0;
  948. have_seeded_siphash = 0;
  949. siphash_unset_global_key();
  950. return 0;
  951. }
  952. /** @} */
  953. #ifdef USE_DMALLOC
  954. /** Tell the crypto library to use Tor's allocation functions rather than
  955. * calling libc's allocation functions directly. Return 0 on success, -1
  956. * on failure. */
  957. int
  958. crypto_use_tor_alloc_functions(void)
  959. {
  960. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  961. return r ? 0 : -1;
  962. }
  963. #endif /* defined(USE_DMALLOC) */