crypto.c 30 KB

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