crypto.c 30 KB

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