crypto.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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 "crypto.h"
  23. #include "compat_openssl.h"
  24. #include "crypto_curve25519.h"
  25. #include "crypto_ed25519.h"
  26. #include "crypto_format.h"
  27. #include "crypto_rand.h"
  28. #include "crypto_rsa.h"
  29. #include "crypto_digest.h"
  30. #include "crypto_util.h"
  31. DISABLE_GCC_WARNING(redundant-decls)
  32. #include <openssl/err.h>
  33. #include <openssl/rsa.h>
  34. #include <openssl/pem.h>
  35. #include <openssl/evp.h>
  36. #include <openssl/engine.h>
  37. #include <openssl/bn.h>
  38. #include <openssl/dh.h>
  39. #include <openssl/conf.h>
  40. #include <openssl/hmac.h>
  41. ENABLE_GCC_WARNING(redundant-decls)
  42. #if __GNUC__ && GCC_VERSION >= 402
  43. #if GCC_VERSION >= 406
  44. #pragma GCC diagnostic pop
  45. #else
  46. #pragma GCC diagnostic warning "-Wredundant-decls"
  47. #endif
  48. #endif /* __GNUC__ && GCC_VERSION >= 402 */
  49. #ifdef HAVE_CTYPE_H
  50. #include <ctype.h>
  51. #endif
  52. #ifdef HAVE_UNISTD_H
  53. #include <unistd.h>
  54. #endif
  55. #ifdef HAVE_SYS_SYSCALL_H
  56. #include <sys/syscall.h>
  57. #endif
  58. #ifdef HAVE_SYS_RANDOM_H
  59. #include <sys/random.h>
  60. #endif
  61. #include "torlog.h"
  62. #include "torint.h"
  63. #include "aes.h"
  64. #include "util.h"
  65. #include "container.h"
  66. #include "compat.h"
  67. #include "sandbox.h"
  68. #include "util_format.h"
  69. #include "keccak-tiny/keccak-tiny.h"
  70. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  71. * while we're waiting for the second.*/
  72. struct crypto_dh_t {
  73. DH *dh; /**< The openssl DH object */
  74. };
  75. static int tor_check_dh_key(int severity, const BIGNUM *bn);
  76. /** Boolean: has OpenSSL's crypto been initialized? */
  77. static int crypto_early_initialized_ = 0;
  78. /** Boolean: has OpenSSL's crypto been initialized? */
  79. static int crypto_global_initialized_ = 0;
  80. /** Log all pending crypto errors at level <b>severity</b>. Use
  81. * <b>doing</b> to describe our current activities.
  82. */
  83. static void
  84. crypto_log_errors(int severity, const char *doing)
  85. {
  86. unsigned long err;
  87. const char *msg, *lib, *func;
  88. while ((err = ERR_get_error()) != 0) {
  89. msg = (const char*)ERR_reason_error_string(err);
  90. lib = (const char*)ERR_lib_error_string(err);
  91. func = (const char*)ERR_func_error_string(err);
  92. if (!msg) msg = "(null)";
  93. if (!lib) lib = "(null)";
  94. if (!func) func = "(null)";
  95. if (BUG(!doing)) doing = "(null)";
  96. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  97. doing, msg, lib, func);
  98. }
  99. }
  100. #ifndef DISABLE_ENGINES
  101. /** Log any OpenSSL engines we're using at NOTICE. */
  102. static void
  103. log_engine(const char *fn, ENGINE *e)
  104. {
  105. if (e) {
  106. const char *name, *id;
  107. name = ENGINE_get_name(e);
  108. id = ENGINE_get_id(e);
  109. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  110. fn, name?name:"?", id?id:"?");
  111. } else {
  112. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  113. }
  114. }
  115. #endif /* !defined(DISABLE_ENGINES) */
  116. #ifndef DISABLE_ENGINES
  117. /** Try to load an engine in a shared library via fully qualified path.
  118. */
  119. static ENGINE *
  120. try_load_engine(const char *path, const char *engine)
  121. {
  122. ENGINE *e = ENGINE_by_id("dynamic");
  123. if (e) {
  124. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  125. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  126. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  127. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  128. ENGINE_free(e);
  129. e = NULL;
  130. }
  131. }
  132. return e;
  133. }
  134. #endif /* !defined(DISABLE_ENGINES) */
  135. static int have_seeded_siphash = 0;
  136. /** Set up the siphash key if we haven't already done so. */
  137. int
  138. crypto_init_siphash_key(void)
  139. {
  140. struct sipkey key;
  141. if (have_seeded_siphash)
  142. return 0;
  143. crypto_rand((char*) &key, sizeof(key));
  144. siphash_set_global_key(&key);
  145. have_seeded_siphash = 1;
  146. return 0;
  147. }
  148. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  149. */
  150. int
  151. crypto_early_init(void)
  152. {
  153. if (!crypto_early_initialized_) {
  154. crypto_early_initialized_ = 1;
  155. ERR_load_crypto_strings();
  156. OpenSSL_add_all_algorithms();
  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. EVP_cleanup();
  941. #ifndef NEW_THREAD_API
  942. ERR_remove_thread_state(NULL);
  943. #endif
  944. ERR_free_strings();
  945. if (dh_param_p)
  946. BN_clear_free(dh_param_p);
  947. if (dh_param_p_tls)
  948. BN_clear_free(dh_param_p_tls);
  949. if (dh_param_g)
  950. BN_clear_free(dh_param_g);
  951. dh_param_p = dh_param_p_tls = dh_param_g = NULL;
  952. #ifndef DISABLE_ENGINES
  953. ENGINE_cleanup();
  954. #endif
  955. CONF_modules_unload(1);
  956. CRYPTO_cleanup_all_ex_data();
  957. crypto_openssl_free_all();
  958. crypto_early_initialized_ = 0;
  959. crypto_global_initialized_ = 0;
  960. have_seeded_siphash = 0;
  961. siphash_unset_global_key();
  962. return 0;
  963. }
  964. /** @} */
  965. #ifdef USE_DMALLOC
  966. /** Tell the crypto library to use Tor's allocation functions rather than
  967. * calling libc's allocation functions directly. Return 0 on success, -1
  968. * on failure. */
  969. int
  970. crypto_use_tor_alloc_functions(void)
  971. {
  972. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  973. return r ? 0 : -1;
  974. }
  975. #endif /* defined(USE_DMALLOC) */