crypto.c 31 KB

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