crypto.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  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_rsa.h"
  28. DISABLE_GCC_WARNING(redundant-decls)
  29. #include <openssl/err.h>
  30. #include <openssl/rsa.h>
  31. #include <openssl/pem.h>
  32. #include <openssl/evp.h>
  33. #include <openssl/engine.h>
  34. #include <openssl/rand.h>
  35. #include <openssl/bn.h>
  36. #include <openssl/dh.h>
  37. #include <openssl/conf.h>
  38. #include <openssl/hmac.h>
  39. ENABLE_GCC_WARNING(redundant-decls)
  40. #if __GNUC__ && GCC_VERSION >= 402
  41. #if GCC_VERSION >= 406
  42. #pragma GCC diagnostic pop
  43. #else
  44. #pragma GCC diagnostic warning "-Wredundant-decls"
  45. #endif
  46. #endif /* __GNUC__ && GCC_VERSION >= 402 */
  47. #ifdef HAVE_CTYPE_H
  48. #include <ctype.h>
  49. #endif
  50. #ifdef HAVE_UNISTD_H
  51. #include <unistd.h>
  52. #endif
  53. #ifdef HAVE_FCNTL_H
  54. #include <fcntl.h>
  55. #endif
  56. #ifdef HAVE_SYS_FCNTL_H
  57. #include <sys/fcntl.h>
  58. #endif
  59. #ifdef HAVE_SYS_SYSCALL_H
  60. #include <sys/syscall.h>
  61. #endif
  62. #ifdef HAVE_SYS_RANDOM_H
  63. #include <sys/random.h>
  64. #endif
  65. #include "torlog.h"
  66. #include "torint.h"
  67. #include "aes.h"
  68. #include "util.h"
  69. #include "container.h"
  70. #include "compat.h"
  71. #include "sandbox.h"
  72. #include "util_format.h"
  73. #include "keccak-tiny/keccak-tiny.h"
  74. /** Longest recognized */
  75. #define MAX_DNS_LABEL_SIZE 63
  76. /** Largest strong entropy request */
  77. #define MAX_STRONGEST_RAND_SIZE 256
  78. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  79. * while we're waiting for the second.*/
  80. struct crypto_dh_t {
  81. DH *dh; /**< The openssl DH object */
  82. };
  83. static int tor_check_dh_key(int severity, const BIGNUM *bn);
  84. /** Boolean: has OpenSSL's crypto been initialized? */
  85. static int crypto_early_initialized_ = 0;
  86. /** Boolean: has OpenSSL's crypto been initialized? */
  87. static int crypto_global_initialized_ = 0;
  88. /** Log all pending crypto errors at level <b>severity</b>. Use
  89. * <b>doing</b> to describe our current activities.
  90. */
  91. static void
  92. crypto_log_errors(int severity, const char *doing)
  93. {
  94. unsigned long err;
  95. const char *msg, *lib, *func;
  96. while ((err = ERR_get_error()) != 0) {
  97. msg = (const char*)ERR_reason_error_string(err);
  98. lib = (const char*)ERR_lib_error_string(err);
  99. func = (const char*)ERR_func_error_string(err);
  100. if (!msg) msg = "(null)";
  101. if (!lib) lib = "(null)";
  102. if (!func) func = "(null)";
  103. if (BUG(!doing)) doing = "(null)";
  104. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  105. doing, msg, lib, func);
  106. }
  107. }
  108. #ifndef DISABLE_ENGINES
  109. /** Log any OpenSSL engines we're using at NOTICE. */
  110. static void
  111. log_engine(const char *fn, ENGINE *e)
  112. {
  113. if (e) {
  114. const char *name, *id;
  115. name = ENGINE_get_name(e);
  116. id = ENGINE_get_id(e);
  117. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  118. fn, name?name:"?", id?id:"?");
  119. } else {
  120. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  121. }
  122. }
  123. #endif /* !defined(DISABLE_ENGINES) */
  124. #ifndef DISABLE_ENGINES
  125. /** Try to load an engine in a shared library via fully qualified path.
  126. */
  127. static ENGINE *
  128. try_load_engine(const char *path, const char *engine)
  129. {
  130. ENGINE *e = ENGINE_by_id("dynamic");
  131. if (e) {
  132. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  133. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  134. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  135. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  136. ENGINE_free(e);
  137. e = NULL;
  138. }
  139. }
  140. return e;
  141. }
  142. #endif /* !defined(DISABLE_ENGINES) */
  143. /** Make sure that openssl is using its default PRNG. Return 1 if we had to
  144. * adjust it; 0 otherwise. */
  145. STATIC int
  146. crypto_force_rand_ssleay(void)
  147. {
  148. RAND_METHOD *default_method;
  149. default_method = RAND_OpenSSL();
  150. if (RAND_get_rand_method() != default_method) {
  151. log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
  152. "a replacement the OpenSSL RNG. Resetting it to the default "
  153. "implementation.");
  154. RAND_set_rand_method(default_method);
  155. return 1;
  156. }
  157. return 0;
  158. }
  159. static int have_seeded_siphash = 0;
  160. /** Set up the siphash key if we haven't already done so. */
  161. int
  162. crypto_init_siphash_key(void)
  163. {
  164. struct sipkey key;
  165. if (have_seeded_siphash)
  166. return 0;
  167. crypto_rand((char*) &key, sizeof(key));
  168. siphash_set_global_key(&key);
  169. have_seeded_siphash = 1;
  170. return 0;
  171. }
  172. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  173. */
  174. int
  175. crypto_early_init(void)
  176. {
  177. if (!crypto_early_initialized_) {
  178. crypto_early_initialized_ = 1;
  179. ERR_load_crypto_strings();
  180. OpenSSL_add_all_algorithms();
  181. setup_openssl_threading();
  182. unsigned long version_num = OpenSSL_version_num();
  183. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  184. if (version_num == OPENSSL_VERSION_NUMBER &&
  185. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  186. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  187. "(%lx: %s).", version_num, version_str);
  188. } else {
  189. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  190. "version we're running with. If you get weird crashes, that "
  191. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  192. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  193. version_num, version_str);
  194. }
  195. crypto_force_rand_ssleay();
  196. if (crypto_seed_rng() < 0)
  197. return -1;
  198. if (crypto_init_siphash_key() < 0)
  199. return -1;
  200. curve25519_init();
  201. ed25519_init();
  202. }
  203. return 0;
  204. }
  205. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  206. */
  207. int
  208. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  209. {
  210. if (!crypto_global_initialized_) {
  211. if (crypto_early_init() < 0)
  212. return -1;
  213. crypto_global_initialized_ = 1;
  214. if (useAccel > 0) {
  215. #ifdef DISABLE_ENGINES
  216. (void)accelName;
  217. (void)accelDir;
  218. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  219. #else
  220. ENGINE *e = NULL;
  221. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  222. ENGINE_load_builtin_engines();
  223. ENGINE_register_all_complete();
  224. if (accelName) {
  225. if (accelDir) {
  226. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  227. " via path \"%s\".", accelName, accelDir);
  228. e = try_load_engine(accelName, accelDir);
  229. } else {
  230. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  231. " acceleration support.", accelName);
  232. e = ENGINE_by_id(accelName);
  233. }
  234. if (!e) {
  235. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  236. accelName);
  237. } else {
  238. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  239. accelName);
  240. }
  241. }
  242. if (e) {
  243. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  244. " setting default ciphers.");
  245. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  246. }
  247. /* Log, if available, the intersection of the set of algorithms
  248. used by Tor and the set of algorithms available in the engine */
  249. log_engine("RSA", ENGINE_get_default_RSA());
  250. log_engine("DH", ENGINE_get_default_DH());
  251. #ifdef OPENSSL_1_1_API
  252. log_engine("EC", ENGINE_get_default_EC());
  253. #else
  254. log_engine("ECDH", ENGINE_get_default_ECDH());
  255. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  256. #endif /* defined(OPENSSL_1_1_API) */
  257. log_engine("RAND", ENGINE_get_default_RAND());
  258. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  259. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  260. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  261. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  262. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  263. #ifdef NID_aes_128_ctr
  264. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  265. #endif
  266. #ifdef NID_aes_128_gcm
  267. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  268. #endif
  269. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  270. #ifdef NID_aes_256_gcm
  271. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  272. #endif
  273. #endif /* defined(DISABLE_ENGINES) */
  274. } else {
  275. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  276. }
  277. if (crypto_force_rand_ssleay()) {
  278. if (crypto_seed_rng() < 0)
  279. return -1;
  280. }
  281. evaluate_evp_for_aes(-1);
  282. evaluate_ctr_for_aes();
  283. }
  284. return 0;
  285. }
  286. /** Free crypto resources held by this thread. */
  287. void
  288. crypto_thread_cleanup(void)
  289. {
  290. #ifndef NEW_THREAD_API
  291. ERR_remove_thread_state(NULL);
  292. #endif
  293. }
  294. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  295. */
  296. DH *
  297. crypto_dh_get_dh_(crypto_dh_t *dh)
  298. {
  299. return dh->dh;
  300. }
  301. /** Allocate and return a new symmetric cipher using the provided key and iv.
  302. * The key is <b>bits</b> bits long; the IV is CIPHER_IV_LEN bytes. Both
  303. * must be provided. Key length must be 128, 192, or 256 */
  304. crypto_cipher_t *
  305. crypto_cipher_new_with_iv_and_bits(const uint8_t *key,
  306. const uint8_t *iv,
  307. int bits)
  308. {
  309. tor_assert(key);
  310. tor_assert(iv);
  311. return aes_new_cipher((const uint8_t*)key, (const uint8_t*)iv, bits);
  312. }
  313. /** Allocate and return a new symmetric cipher using the provided key and iv.
  314. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. Both
  315. * must be provided.
  316. */
  317. crypto_cipher_t *
  318. crypto_cipher_new_with_iv(const char *key, const char *iv)
  319. {
  320. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)iv,
  321. 128);
  322. }
  323. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  324. * zero bytes and key length <b>bits</b>. Key length must be 128, 192, or
  325. * 256. */
  326. crypto_cipher_t *
  327. crypto_cipher_new_with_bits(const char *key, int bits)
  328. {
  329. char zeroiv[CIPHER_IV_LEN];
  330. memset(zeroiv, 0, sizeof(zeroiv));
  331. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)zeroiv,
  332. bits);
  333. }
  334. /** Return a new crypto_cipher_t with the provided <b>key</b> (of
  335. * CIPHER_KEY_LEN bytes) and an IV of all zero bytes. */
  336. crypto_cipher_t *
  337. crypto_cipher_new(const char *key)
  338. {
  339. return crypto_cipher_new_with_bits(key, 128);
  340. }
  341. /** Free a symmetric cipher.
  342. */
  343. void
  344. crypto_cipher_free_(crypto_cipher_t *env)
  345. {
  346. if (!env)
  347. return;
  348. aes_cipher_free(env);
  349. }
  350. /* public key crypto */
  351. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  352. * bytes of data from <b>from</b>, with padding type 'padding',
  353. * storing the results on <b>to</b>.
  354. *
  355. * Returns the number of bytes written on success, -1 on failure.
  356. *
  357. * The encrypted data consists of:
  358. * - The source data, padded and encrypted with the public key, if the
  359. * padded source data is no longer than the public key, and <b>force</b>
  360. * is false, OR
  361. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  362. * padded and encrypted with the public key; followed by the rest of
  363. * the source data encrypted in AES-CTR mode with the symmetric key.
  364. *
  365. * NOTE that this format does not authenticate the symmetrically encrypted
  366. * part of the data, and SHOULD NOT BE USED for new protocols.
  367. */
  368. int
  369. crypto_pk_obsolete_public_hybrid_encrypt(crypto_pk_t *env,
  370. char *to, size_t tolen,
  371. const char *from,
  372. size_t fromlen,
  373. int padding, int force)
  374. {
  375. int overhead, outlen, r;
  376. size_t pkeylen, symlen;
  377. crypto_cipher_t *cipher = NULL;
  378. char *buf = NULL;
  379. tor_assert(env);
  380. tor_assert(from);
  381. tor_assert(to);
  382. tor_assert(fromlen < SIZE_T_CEILING);
  383. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  384. pkeylen = crypto_pk_keysize(env);
  385. if (!force && fromlen+overhead <= pkeylen) {
  386. /* It all fits in a single encrypt. */
  387. return crypto_pk_public_encrypt(env,to,
  388. tolen,
  389. from,fromlen,padding);
  390. }
  391. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  392. tor_assert(tolen >= pkeylen);
  393. char key[CIPHER_KEY_LEN];
  394. crypto_rand(key, sizeof(key)); /* generate a new key. */
  395. cipher = crypto_cipher_new(key);
  396. buf = tor_malloc(pkeylen+1);
  397. memcpy(buf, key, CIPHER_KEY_LEN);
  398. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  399. /* Length of symmetrically encrypted data. */
  400. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  401. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  402. if (outlen!=(int)pkeylen) {
  403. goto err;
  404. }
  405. r = crypto_cipher_encrypt(cipher, to+outlen,
  406. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  407. if (r<0) goto err;
  408. memwipe(buf, 0, pkeylen);
  409. memwipe(key, 0, sizeof(key));
  410. tor_free(buf);
  411. crypto_cipher_free(cipher);
  412. tor_assert(outlen+symlen < INT_MAX);
  413. return (int)(outlen + symlen);
  414. err:
  415. memwipe(buf, 0, pkeylen);
  416. memwipe(key, 0, sizeof(key));
  417. tor_free(buf);
  418. crypto_cipher_free(cipher);
  419. return -1;
  420. }
  421. /** Invert crypto_pk_obsolete_public_hybrid_encrypt. Returns the number of
  422. * bytes written on success, -1 on failure.
  423. *
  424. * NOTE that this format does not authenticate the symmetrically encrypted
  425. * part of the data, and SHOULD NOT BE USED for new protocols.
  426. */
  427. int
  428. crypto_pk_obsolete_private_hybrid_decrypt(crypto_pk_t *env,
  429. char *to,
  430. size_t tolen,
  431. const char *from,
  432. size_t fromlen,
  433. int padding, int warnOnFailure)
  434. {
  435. int outlen, r;
  436. size_t pkeylen;
  437. crypto_cipher_t *cipher = NULL;
  438. char *buf = NULL;
  439. tor_assert(fromlen < SIZE_T_CEILING);
  440. pkeylen = crypto_pk_keysize(env);
  441. if (fromlen <= pkeylen) {
  442. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  443. warnOnFailure);
  444. }
  445. buf = tor_malloc(pkeylen);
  446. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  447. warnOnFailure);
  448. if (outlen<0) {
  449. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  450. "Error decrypting public-key data");
  451. goto err;
  452. }
  453. if (outlen < CIPHER_KEY_LEN) {
  454. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  455. "No room for a symmetric key");
  456. goto err;
  457. }
  458. cipher = crypto_cipher_new(buf);
  459. if (!cipher) {
  460. goto err;
  461. }
  462. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  463. outlen -= CIPHER_KEY_LEN;
  464. tor_assert(tolen - outlen >= fromlen - pkeylen);
  465. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  466. if (r<0)
  467. goto err;
  468. memwipe(buf,0,pkeylen);
  469. tor_free(buf);
  470. crypto_cipher_free(cipher);
  471. tor_assert(outlen + fromlen < INT_MAX);
  472. return (int)(outlen + (fromlen-pkeylen));
  473. err:
  474. memwipe(buf,0,pkeylen);
  475. tor_free(buf);
  476. crypto_cipher_free(cipher);
  477. return -1;
  478. }
  479. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  480. * every four characters. */
  481. void
  482. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  483. {
  484. int n = 0;
  485. char *end = out+outlen;
  486. tor_assert(outlen < SIZE_T_CEILING);
  487. while (*in && out<end) {
  488. *out++ = *in++;
  489. if (++n == 4 && *in && out<end) {
  490. n = 0;
  491. *out++ = ' ';
  492. }
  493. }
  494. tor_assert(out<end);
  495. *out = '\0';
  496. }
  497. /* symmetric crypto */
  498. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  499. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  500. * Does not check for failure.
  501. */
  502. int
  503. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  504. const char *from, size_t fromlen)
  505. {
  506. tor_assert(env);
  507. tor_assert(env);
  508. tor_assert(from);
  509. tor_assert(fromlen);
  510. tor_assert(to);
  511. tor_assert(fromlen < SIZE_T_CEILING);
  512. memcpy(to, from, fromlen);
  513. aes_crypt_inplace(env, to, fromlen);
  514. return 0;
  515. }
  516. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  517. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  518. * Does not check for failure.
  519. */
  520. int
  521. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  522. const char *from, size_t fromlen)
  523. {
  524. tor_assert(env);
  525. tor_assert(from);
  526. tor_assert(to);
  527. tor_assert(fromlen < SIZE_T_CEILING);
  528. memcpy(to, from, fromlen);
  529. aes_crypt_inplace(env, to, fromlen);
  530. return 0;
  531. }
  532. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  533. * on success. Does not check for failure.
  534. */
  535. void
  536. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  537. {
  538. tor_assert(len < SIZE_T_CEILING);
  539. aes_crypt_inplace(env, buf, len);
  540. }
  541. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  542. * <b>key</b> to the buffer in <b>to</b> of length
  543. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  544. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  545. * number of bytes written, on failure, return -1.
  546. */
  547. int
  548. crypto_cipher_encrypt_with_iv(const char *key,
  549. char *to, size_t tolen,
  550. const char *from, size_t fromlen)
  551. {
  552. crypto_cipher_t *cipher;
  553. tor_assert(from);
  554. tor_assert(to);
  555. tor_assert(fromlen < INT_MAX);
  556. if (fromlen < 1)
  557. return -1;
  558. if (tolen < fromlen + CIPHER_IV_LEN)
  559. return -1;
  560. char iv[CIPHER_IV_LEN];
  561. crypto_rand(iv, sizeof(iv));
  562. cipher = crypto_cipher_new_with_iv(key, iv);
  563. memcpy(to, iv, CIPHER_IV_LEN);
  564. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  565. crypto_cipher_free(cipher);
  566. memwipe(iv, 0, sizeof(iv));
  567. return (int)(fromlen + CIPHER_IV_LEN);
  568. }
  569. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  570. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  571. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  572. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  573. * number of bytes written, on failure, return -1.
  574. */
  575. int
  576. crypto_cipher_decrypt_with_iv(const char *key,
  577. char *to, size_t tolen,
  578. const char *from, size_t fromlen)
  579. {
  580. crypto_cipher_t *cipher;
  581. tor_assert(key);
  582. tor_assert(from);
  583. tor_assert(to);
  584. tor_assert(fromlen < INT_MAX);
  585. if (fromlen <= CIPHER_IV_LEN)
  586. return -1;
  587. if (tolen < fromlen - CIPHER_IV_LEN)
  588. return -1;
  589. cipher = crypto_cipher_new_with_iv(key, from);
  590. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  591. crypto_cipher_free(cipher);
  592. return (int)(fromlen - CIPHER_IV_LEN);
  593. }
  594. /* DH */
  595. /** Our DH 'g' parameter */
  596. #define DH_GENERATOR 2
  597. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  598. static BIGNUM *dh_param_p = NULL;
  599. /** Shared P parameter for our TLS DH key exchanges. */
  600. static BIGNUM *dh_param_p_tls = NULL;
  601. /** Shared G parameter for our DH key exchanges. */
  602. static BIGNUM *dh_param_g = NULL;
  603. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  604. * computationally expensive (milliseconds), so should only be called when
  605. * the DH parameters change. Returns 0 on success, * -1 on failure.
  606. */
  607. static int
  608. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  609. {
  610. DH *dh = NULL;
  611. int ret = -1;
  612. /* Copy into a temporary DH object, just so that DH_check() can be called. */
  613. if (!(dh = DH_new()))
  614. goto out;
  615. #ifdef OPENSSL_1_1_API
  616. BIGNUM *dh_p, *dh_g;
  617. if (!(dh_p = BN_dup(p)))
  618. goto out;
  619. if (!(dh_g = BN_dup(g)))
  620. goto out;
  621. if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
  622. goto out;
  623. #else /* !(defined(OPENSSL_1_1_API)) */
  624. if (!(dh->p = BN_dup(p)))
  625. goto out;
  626. if (!(dh->g = BN_dup(g)))
  627. goto out;
  628. #endif /* defined(OPENSSL_1_1_API) */
  629. /* Perform the validation. */
  630. int codes = 0;
  631. if (!DH_check(dh, &codes))
  632. goto out;
  633. if (BN_is_word(g, DH_GENERATOR_2)) {
  634. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  635. *
  636. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  637. * IETF's primes are congruent to 23 when g = 2.
  638. */
  639. BN_ULONG residue = BN_mod_word(p, 24);
  640. if (residue == 11 || residue == 23)
  641. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  642. }
  643. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  644. goto out;
  645. /* Things are probably not evil. */
  646. ret = 0;
  647. out:
  648. if (dh)
  649. DH_free(dh);
  650. return ret;
  651. }
  652. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  653. * DH stuff.
  654. */
  655. static void
  656. crypto_set_dh_generator(void)
  657. {
  658. BIGNUM *generator;
  659. int r;
  660. if (dh_param_g)
  661. return;
  662. generator = BN_new();
  663. tor_assert(generator);
  664. r = BN_set_word(generator, DH_GENERATOR);
  665. tor_assert(r);
  666. dh_param_g = generator;
  667. }
  668. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  669. * modulus. */
  670. void
  671. crypto_set_tls_dh_prime(void)
  672. {
  673. BIGNUM *tls_prime = NULL;
  674. int r;
  675. /* If the space is occupied, free the previous TLS DH prime */
  676. if (BUG(dh_param_p_tls)) {
  677. /* LCOV_EXCL_START
  678. *
  679. * We shouldn't be calling this twice.
  680. */
  681. BN_clear_free(dh_param_p_tls);
  682. dh_param_p_tls = NULL;
  683. /* LCOV_EXCL_STOP */
  684. }
  685. tls_prime = BN_new();
  686. tor_assert(tls_prime);
  687. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  688. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  689. * prime.
  690. */
  691. r = BN_hex2bn(&tls_prime,
  692. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  693. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  694. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  695. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  696. "B0E7393E0F24218EB3");
  697. tor_assert(r);
  698. tor_assert(tls_prime);
  699. dh_param_p_tls = tls_prime;
  700. crypto_set_dh_generator();
  701. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  702. }
  703. /** Initialize dh_param_p and dh_param_g if they are not already
  704. * set. */
  705. static void
  706. init_dh_param(void)
  707. {
  708. BIGNUM *circuit_dh_prime;
  709. int r;
  710. if (BUG(dh_param_p && dh_param_g))
  711. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  712. circuit_dh_prime = BN_new();
  713. tor_assert(circuit_dh_prime);
  714. /* This is from rfc2409, section 6.2. It's a safe prime, and
  715. supposedly it equals:
  716. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  717. */
  718. r = BN_hex2bn(&circuit_dh_prime,
  719. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  720. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  721. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  722. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  723. "49286651ECE65381FFFFFFFFFFFFFFFF");
  724. tor_assert(r);
  725. /* Set the new values as the global DH parameters. */
  726. dh_param_p = circuit_dh_prime;
  727. crypto_set_dh_generator();
  728. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  729. if (!dh_param_p_tls) {
  730. crypto_set_tls_dh_prime();
  731. }
  732. }
  733. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  734. * handshake. Since we exponentiate by this value, choosing a smaller one
  735. * lets our handhake go faster.
  736. */
  737. #define DH_PRIVATE_KEY_BITS 320
  738. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  739. * failure.
  740. */
  741. crypto_dh_t *
  742. crypto_dh_new(int dh_type)
  743. {
  744. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  745. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  746. dh_type == DH_TYPE_REND);
  747. if (!dh_param_p)
  748. init_dh_param();
  749. if (!(res->dh = DH_new()))
  750. goto err;
  751. #ifdef OPENSSL_1_1_API
  752. BIGNUM *dh_p = NULL, *dh_g = NULL;
  753. if (dh_type == DH_TYPE_TLS) {
  754. dh_p = BN_dup(dh_param_p_tls);
  755. } else {
  756. dh_p = BN_dup(dh_param_p);
  757. }
  758. if (!dh_p)
  759. goto err;
  760. dh_g = BN_dup(dh_param_g);
  761. if (!dh_g) {
  762. BN_free(dh_p);
  763. goto err;
  764. }
  765. if (!DH_set0_pqg(res->dh, dh_p, NULL, dh_g)) {
  766. goto err;
  767. }
  768. if (!DH_set_length(res->dh, DH_PRIVATE_KEY_BITS))
  769. goto err;
  770. #else /* !(defined(OPENSSL_1_1_API)) */
  771. if (dh_type == DH_TYPE_TLS) {
  772. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  773. goto err;
  774. } else {
  775. if (!(res->dh->p = BN_dup(dh_param_p)))
  776. goto err;
  777. }
  778. if (!(res->dh->g = BN_dup(dh_param_g)))
  779. goto err;
  780. res->dh->length = DH_PRIVATE_KEY_BITS;
  781. #endif /* defined(OPENSSL_1_1_API) */
  782. return res;
  783. /* LCOV_EXCL_START
  784. * This error condition is only reached when an allocation fails */
  785. err:
  786. crypto_log_errors(LOG_WARN, "creating DH object");
  787. if (res->dh) DH_free(res->dh); /* frees p and g too */
  788. tor_free(res);
  789. return NULL;
  790. /* LCOV_EXCL_STOP */
  791. }
  792. /** Return a copy of <b>dh</b>, sharing its internal state. */
  793. crypto_dh_t *
  794. crypto_dh_dup(const crypto_dh_t *dh)
  795. {
  796. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  797. tor_assert(dh);
  798. tor_assert(dh->dh);
  799. dh_new->dh = dh->dh;
  800. DH_up_ref(dh->dh);
  801. return dh_new;
  802. }
  803. /** Return the length of the DH key in <b>dh</b>, in bytes.
  804. */
  805. int
  806. crypto_dh_get_bytes(crypto_dh_t *dh)
  807. {
  808. tor_assert(dh);
  809. return DH_size(dh->dh);
  810. }
  811. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  812. * success, -1 on failure.
  813. */
  814. int
  815. crypto_dh_generate_public(crypto_dh_t *dh)
  816. {
  817. #ifndef OPENSSL_1_1_API
  818. again:
  819. #endif
  820. if (!DH_generate_key(dh->dh)) {
  821. /* LCOV_EXCL_START
  822. * To test this we would need some way to tell openssl to break DH. */
  823. crypto_log_errors(LOG_WARN, "generating DH key");
  824. return -1;
  825. /* LCOV_EXCL_STOP */
  826. }
  827. #ifdef OPENSSL_1_1_API
  828. /* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
  829. * recreating the DH object. I have no idea what sort of aliasing madness
  830. * can occur here, so do the check, and just bail on failure.
  831. */
  832. const BIGNUM *pub_key, *priv_key;
  833. DH_get0_key(dh->dh, &pub_key, &priv_key);
  834. if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
  835. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  836. "the-universe chances really do happen. Treating as a failure.");
  837. return -1;
  838. }
  839. #else /* !(defined(OPENSSL_1_1_API)) */
  840. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  841. /* LCOV_EXCL_START
  842. * If this happens, then openssl's DH implementation is busted. */
  843. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  844. "the-universe chances really do happen. Trying again.");
  845. /* Free and clear the keys, so OpenSSL will actually try again. */
  846. BN_clear_free(dh->dh->pub_key);
  847. BN_clear_free(dh->dh->priv_key);
  848. dh->dh->pub_key = dh->dh->priv_key = NULL;
  849. goto again;
  850. /* LCOV_EXCL_STOP */
  851. }
  852. #endif /* defined(OPENSSL_1_1_API) */
  853. return 0;
  854. }
  855. /** Generate g^x as necessary, and write the g^x for the key exchange
  856. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  857. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  858. */
  859. int
  860. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  861. {
  862. int bytes;
  863. tor_assert(dh);
  864. const BIGNUM *dh_pub;
  865. #ifdef OPENSSL_1_1_API
  866. const BIGNUM *dh_priv;
  867. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  868. #else
  869. dh_pub = dh->dh->pub_key;
  870. #endif /* defined(OPENSSL_1_1_API) */
  871. if (!dh_pub) {
  872. if (crypto_dh_generate_public(dh)<0)
  873. return -1;
  874. else {
  875. #ifdef OPENSSL_1_1_API
  876. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  877. #else
  878. dh_pub = dh->dh->pub_key;
  879. #endif
  880. }
  881. }
  882. tor_assert(dh_pub);
  883. bytes = BN_num_bytes(dh_pub);
  884. tor_assert(bytes >= 0);
  885. if (pubkey_len < (size_t)bytes) {
  886. log_warn(LD_CRYPTO,
  887. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  888. (int) pubkey_len, bytes);
  889. return -1;
  890. }
  891. memset(pubkey, 0, pubkey_len);
  892. BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  893. return 0;
  894. }
  895. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  896. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  897. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  898. */
  899. static int
  900. tor_check_dh_key(int severity, const BIGNUM *bn)
  901. {
  902. BIGNUM *x;
  903. char *s;
  904. tor_assert(bn);
  905. x = BN_new();
  906. tor_assert(x);
  907. if (BUG(!dh_param_p))
  908. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  909. BN_set_word(x, 1);
  910. if (BN_cmp(bn,x)<=0) {
  911. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  912. goto err;
  913. }
  914. BN_copy(x,dh_param_p);
  915. BN_sub_word(x, 1);
  916. if (BN_cmp(bn,x)>=0) {
  917. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  918. goto err;
  919. }
  920. BN_clear_free(x);
  921. return 0;
  922. err:
  923. BN_clear_free(x);
  924. s = BN_bn2hex(bn);
  925. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  926. OPENSSL_free(s);
  927. return -1;
  928. }
  929. /** Given a DH key exchange object, and our peer's value of g^y (as a
  930. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  931. * <b>secret_bytes_out</b> bytes of shared key material and write them
  932. * to <b>secret_out</b>. Return the number of bytes generated on success,
  933. * or -1 on failure.
  934. *
  935. * (We generate key material by computing
  936. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  937. * where || is concatenation.)
  938. */
  939. ssize_t
  940. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  941. const char *pubkey, size_t pubkey_len,
  942. char *secret_out, size_t secret_bytes_out)
  943. {
  944. char *secret_tmp = NULL;
  945. BIGNUM *pubkey_bn = NULL;
  946. size_t secret_len=0, secret_tmp_len=0;
  947. int result=0;
  948. tor_assert(dh);
  949. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  950. tor_assert(pubkey_len < INT_MAX);
  951. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  952. (int)pubkey_len, NULL)))
  953. goto error;
  954. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  955. /* Check for invalid public keys. */
  956. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  957. goto error;
  958. }
  959. secret_tmp_len = crypto_dh_get_bytes(dh);
  960. secret_tmp = tor_malloc(secret_tmp_len);
  961. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  962. if (result < 0) {
  963. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  964. goto error;
  965. }
  966. secret_len = result;
  967. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  968. (uint8_t*)secret_out, secret_bytes_out)<0)
  969. goto error;
  970. secret_len = secret_bytes_out;
  971. goto done;
  972. error:
  973. result = -1;
  974. done:
  975. crypto_log_errors(LOG_WARN, "completing DH handshake");
  976. if (pubkey_bn)
  977. BN_clear_free(pubkey_bn);
  978. if (secret_tmp) {
  979. memwipe(secret_tmp, 0, secret_tmp_len);
  980. tor_free(secret_tmp);
  981. }
  982. if (result < 0)
  983. return result;
  984. else
  985. return secret_len;
  986. }
  987. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  988. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  989. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  990. * H(K | [00]) | H(K | [01]) | ....
  991. *
  992. * This is the key expansion algorithm used in the "TAP" circuit extension
  993. * mechanism; it shouldn't be used for new protocols.
  994. *
  995. * Return 0 on success, -1 on failure.
  996. */
  997. int
  998. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  999. uint8_t *key_out, size_t key_out_len)
  1000. {
  1001. int i, r = -1;
  1002. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  1003. uint8_t digest[DIGEST_LEN];
  1004. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1005. tor_assert(key_out_len <= DIGEST_LEN*256);
  1006. memcpy(tmp, key_in, key_in_len);
  1007. for (cp = key_out, i=0; cp < key_out+key_out_len;
  1008. ++i, cp += DIGEST_LEN) {
  1009. tmp[key_in_len] = i;
  1010. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1) < 0)
  1011. goto exit;
  1012. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  1013. }
  1014. r = 0;
  1015. exit:
  1016. memwipe(tmp, 0, key_in_len+1);
  1017. tor_free(tmp);
  1018. memwipe(digest, 0, sizeof(digest));
  1019. return r;
  1020. }
  1021. /** Expand some secret key material according to RFC5869, using SHA256 as the
  1022. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  1023. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  1024. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  1025. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  1026. * bytes to <b>key_out</b> and return 0. Assert on failure.
  1027. */
  1028. int
  1029. crypto_expand_key_material_rfc5869_sha256(
  1030. const uint8_t *key_in, size_t key_in_len,
  1031. const uint8_t *salt_in, size_t salt_in_len,
  1032. const uint8_t *info_in, size_t info_in_len,
  1033. uint8_t *key_out, size_t key_out_len)
  1034. {
  1035. uint8_t prk[DIGEST256_LEN];
  1036. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  1037. uint8_t mac[DIGEST256_LEN];
  1038. int i;
  1039. uint8_t *outp;
  1040. size_t tmp_len;
  1041. crypto_hmac_sha256((char*)prk,
  1042. (const char*)salt_in, salt_in_len,
  1043. (const char*)key_in, key_in_len);
  1044. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1045. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  1046. tor_assert(info_in_len <= 128);
  1047. memset(tmp, 0, sizeof(tmp));
  1048. outp = key_out;
  1049. i = 1;
  1050. while (key_out_len) {
  1051. size_t n;
  1052. if (i > 1) {
  1053. memcpy(tmp, mac, DIGEST256_LEN);
  1054. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  1055. tmp[DIGEST256_LEN+info_in_len] = i;
  1056. tmp_len = DIGEST256_LEN + info_in_len + 1;
  1057. } else {
  1058. memcpy(tmp, info_in, info_in_len);
  1059. tmp[info_in_len] = i;
  1060. tmp_len = info_in_len + 1;
  1061. }
  1062. crypto_hmac_sha256((char*)mac,
  1063. (const char*)prk, DIGEST256_LEN,
  1064. (const char*)tmp, tmp_len);
  1065. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  1066. memcpy(outp, mac, n);
  1067. key_out_len -= n;
  1068. outp += n;
  1069. ++i;
  1070. }
  1071. memwipe(tmp, 0, sizeof(tmp));
  1072. memwipe(mac, 0, sizeof(mac));
  1073. return 0;
  1074. }
  1075. /** Free a DH key exchange object.
  1076. */
  1077. void
  1078. crypto_dh_free_(crypto_dh_t *dh)
  1079. {
  1080. if (!dh)
  1081. return;
  1082. tor_assert(dh->dh);
  1083. DH_free(dh->dh);
  1084. tor_free(dh);
  1085. }
  1086. /* random numbers */
  1087. /** How many bytes of entropy we add at once.
  1088. *
  1089. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  1090. * work for us too. */
  1091. #define ADD_ENTROPY 32
  1092. /** Set the seed of the weak RNG to a random value. */
  1093. void
  1094. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  1095. {
  1096. unsigned seed;
  1097. crypto_rand((void*)&seed, sizeof(seed));
  1098. tor_init_weak_random(rng, seed);
  1099. }
  1100. #ifdef TOR_UNIT_TESTS
  1101. int break_strongest_rng_syscall = 0;
  1102. int break_strongest_rng_fallback = 0;
  1103. #endif
  1104. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1105. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  1106. * failure. A maximum request size of 256 bytes is imposed.
  1107. */
  1108. static int
  1109. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  1110. {
  1111. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  1112. #ifdef TOR_UNIT_TESTS
  1113. if (break_strongest_rng_syscall)
  1114. return -1;
  1115. #endif
  1116. #if defined(_WIN32)
  1117. static int provider_set = 0;
  1118. static HCRYPTPROV provider;
  1119. if (!provider_set) {
  1120. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1121. CRYPT_VERIFYCONTEXT)) {
  1122. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  1123. return -1;
  1124. }
  1125. provider_set = 1;
  1126. }
  1127. if (!CryptGenRandom(provider, out_len, out)) {
  1128. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  1129. return -1;
  1130. }
  1131. return 0;
  1132. #elif defined(__linux__) && defined(SYS_getrandom)
  1133. static int getrandom_works = 1; /* Be optimitic about our chances... */
  1134. /* getrandom() isn't as straight foward as getentropy(), and has
  1135. * no glibc wrapper.
  1136. *
  1137. * As far as I can tell from getrandom(2) and the source code, the
  1138. * requests we issue will always succeed (though it will block on the
  1139. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  1140. * GRND_NONBLOCK and the request is <= 256 bytes.
  1141. *
  1142. * The manpage is unclear on what happens if a signal interrupts the call
  1143. * while the request is blocked due to lack of entropy....
  1144. *
  1145. * We optimistically assume that getrandom() is available and functional
  1146. * because it is the way of the future, and 2 branch mispredicts pale in
  1147. * comparision to the overheads involved with failing to open
  1148. * /dev/srandom followed by opening and reading from /dev/urandom.
  1149. */
  1150. if (PREDICT_LIKELY(getrandom_works)) {
  1151. long ret;
  1152. /* A flag of '0' here means to read from '/dev/urandom', and to
  1153. * block if insufficient entropy is available to service the
  1154. * request.
  1155. */
  1156. const unsigned int flags = 0;
  1157. do {
  1158. ret = syscall(SYS_getrandom, out, out_len, flags);
  1159. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  1160. if (PREDICT_UNLIKELY(ret == -1)) {
  1161. /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
  1162. tor_assert(errno != EAGAIN);
  1163. tor_assert(errno != EINTR);
  1164. /* Useful log message for errno. */
  1165. if (errno == ENOSYS) {
  1166. log_warn(LD_CRYPTO, "Can't get entropy from getrandom()."
  1167. " You are running a version of Tor built to support"
  1168. " getrandom(), but the kernel doesn't implement this"
  1169. " function--probably because it is too old?");
  1170. } else {
  1171. log_warn(LD_CRYPTO, "Can't get entropy from getrandom(): %s.",
  1172. strerror(errno));
  1173. }
  1174. getrandom_works = 0; /* Don't bother trying again. */
  1175. return -1;
  1176. /* LCOV_EXCL_STOP */
  1177. }
  1178. tor_assert(ret == (long)out_len);
  1179. return 0;
  1180. }
  1181. return -1; /* getrandom() previously failed unexpectedly. */
  1182. #elif defined(HAVE_GETENTROPY)
  1183. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  1184. * the only gotcha is that requests are limited to 256 bytes.
  1185. */
  1186. return getentropy(out, out_len);
  1187. #else
  1188. (void) out;
  1189. #endif /* defined(_WIN32) || ... */
  1190. /* This platform doesn't have a supported syscall based random. */
  1191. return -1;
  1192. }
  1193. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1194. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  1195. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  1196. * is imposed.
  1197. */
  1198. static int
  1199. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  1200. {
  1201. #ifdef TOR_UNIT_TESTS
  1202. if (break_strongest_rng_fallback)
  1203. return -1;
  1204. #endif
  1205. #ifdef _WIN32
  1206. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  1207. (void)out;
  1208. (void)out_len;
  1209. return -1;
  1210. #else /* !(defined(_WIN32)) */
  1211. static const char *filenames[] = {
  1212. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1213. };
  1214. int fd, i;
  1215. size_t n;
  1216. for (i = 0; filenames[i]; ++i) {
  1217. log_debug(LD_FS, "Considering %s for entropy", filenames[i]);
  1218. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  1219. if (fd<0) continue;
  1220. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  1221. n = read_all(fd, (char*)out, out_len, 0);
  1222. close(fd);
  1223. if (n != out_len) {
  1224. /* LCOV_EXCL_START
  1225. * We can't make /dev/foorandom actually fail. */
  1226. log_warn(LD_CRYPTO,
  1227. "Error reading from entropy source (read only %lu bytes).",
  1228. (unsigned long)n);
  1229. return -1;
  1230. /* LCOV_EXCL_STOP */
  1231. }
  1232. return 0;
  1233. }
  1234. return -1;
  1235. #endif /* defined(_WIN32) */
  1236. }
  1237. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1238. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  1239. * request size of 256 bytes is imposed.
  1240. */
  1241. STATIC int
  1242. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  1243. {
  1244. static const size_t sanity_min_size = 16;
  1245. static const int max_attempts = 3;
  1246. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  1247. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  1248. * zero filling the buffer and ensuring that it actually was at least
  1249. * partially modified.
  1250. *
  1251. * Checking that any individual byte is non-zero seems like it would
  1252. * fail too often (p = out_len * 1/256) for comfort, but this is an
  1253. * "adjust according to taste" sort of check.
  1254. */
  1255. memwipe(out, 0, out_len);
  1256. for (int i = 0; i < max_attempts; i++) {
  1257. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  1258. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  1259. /* Try to use the less-favored mechanism to get strong entropy. */
  1260. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  1261. /* Welp, we tried. Hopefully the calling code terminates the process
  1262. * since we're basically boned without good entropy.
  1263. */
  1264. log_warn(LD_CRYPTO,
  1265. "Cannot get strong entropy: no entropy source found.");
  1266. return -1;
  1267. }
  1268. }
  1269. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  1270. return 0;
  1271. }
  1272. /* LCOV_EXCL_START
  1273. *
  1274. * We tried max_attempts times to fill a buffer >= 128 bits long,
  1275. * and each time it returned all '0's. Either the system entropy
  1276. * source is busted, or the user should go out and buy a ticket to
  1277. * every lottery on the planet.
  1278. */
  1279. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  1280. return -1;
  1281. /* LCOV_EXCL_STOP */
  1282. }
  1283. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1284. * storing it into <b>out</b>.
  1285. */
  1286. void
  1287. crypto_strongest_rand(uint8_t *out, size_t out_len)
  1288. {
  1289. #define DLEN SHA512_DIGEST_LENGTH
  1290. /* We're going to hash DLEN bytes from the system RNG together with some
  1291. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  1292. */
  1293. uint8_t inp[DLEN*2];
  1294. uint8_t tmp[DLEN];
  1295. tor_assert(out);
  1296. while (out_len) {
  1297. crypto_rand((char*) inp, DLEN);
  1298. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  1299. // LCOV_EXCL_START
  1300. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  1301. "important key. Exiting.");
  1302. /* Die with an assertion so we get a stack trace. */
  1303. tor_assert(0);
  1304. // LCOV_EXCL_STOP
  1305. }
  1306. if (out_len >= DLEN) {
  1307. SHA512(inp, sizeof(inp), out);
  1308. out += DLEN;
  1309. out_len -= DLEN;
  1310. } else {
  1311. SHA512(inp, sizeof(inp), tmp);
  1312. memcpy(out, tmp, out_len);
  1313. break;
  1314. }
  1315. }
  1316. memwipe(tmp, 0, sizeof(tmp));
  1317. memwipe(inp, 0, sizeof(inp));
  1318. #undef DLEN
  1319. }
  1320. /** Seed OpenSSL's random number generator with bytes from the operating
  1321. * system. Return 0 on success, -1 on failure.
  1322. */
  1323. int
  1324. crypto_seed_rng(void)
  1325. {
  1326. int rand_poll_ok = 0, load_entropy_ok = 0;
  1327. uint8_t buf[ADD_ENTROPY];
  1328. /* OpenSSL has a RAND_poll function that knows about more kinds of
  1329. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1330. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1331. rand_poll_ok = RAND_poll();
  1332. if (rand_poll_ok == 0)
  1333. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  1334. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  1335. if (load_entropy_ok) {
  1336. RAND_seed(buf, sizeof(buf));
  1337. }
  1338. memwipe(buf, 0, sizeof(buf));
  1339. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  1340. return 0;
  1341. else
  1342. return -1;
  1343. }
  1344. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  1345. * for unit tests.
  1346. *
  1347. * This function is not allowed to fail; if it would fail to generate strong
  1348. * entropy, it must terminate the process instead.
  1349. */
  1350. MOCK_IMPL(void,
  1351. crypto_rand, (char *to, size_t n))
  1352. {
  1353. crypto_rand_unmocked(to, n);
  1354. }
  1355. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  1356. * will want crypto_rand instead.
  1357. *
  1358. * This function is not allowed to fail; if it would fail to generate strong
  1359. * entropy, it must terminate the process instead.
  1360. */
  1361. void
  1362. crypto_rand_unmocked(char *to, size_t n)
  1363. {
  1364. int r;
  1365. if (n == 0)
  1366. return;
  1367. tor_assert(n < INT_MAX);
  1368. tor_assert(to);
  1369. r = RAND_bytes((unsigned char*)to, (int)n);
  1370. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  1371. * stack trace about where it happened.
  1372. */
  1373. tor_assert(r >= 0);
  1374. }
  1375. /** Return a pseudorandom integer, chosen uniformly from the values
  1376. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  1377. * INT_MAX+1, inclusive. */
  1378. int
  1379. crypto_rand_int(unsigned int max)
  1380. {
  1381. unsigned int val;
  1382. unsigned int cutoff;
  1383. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  1384. tor_assert(max > 0); /* don't div by 0 */
  1385. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1386. * distribution with clipping at the upper end of unsigned int's
  1387. * range.
  1388. */
  1389. cutoff = UINT_MAX - (UINT_MAX%max);
  1390. while (1) {
  1391. crypto_rand((char*)&val, sizeof(val));
  1392. if (val < cutoff)
  1393. return val % max;
  1394. }
  1395. }
  1396. /** Return a pseudorandom integer, chosen uniformly from the values i such
  1397. * that min <= i < max.
  1398. *
  1399. * <b>min</b> MUST be in range [0, <b>max</b>).
  1400. * <b>max</b> MUST be in range (min, INT_MAX].
  1401. */
  1402. int
  1403. crypto_rand_int_range(unsigned int min, unsigned int max)
  1404. {
  1405. tor_assert(min < max);
  1406. tor_assert(max <= INT_MAX);
  1407. /* The overflow is avoided here because crypto_rand_int() returns a value
  1408. * between 0 and (max - min) inclusive. */
  1409. return min + crypto_rand_int(max - min);
  1410. }
  1411. /** As crypto_rand_int_range, but supports uint64_t. */
  1412. uint64_t
  1413. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  1414. {
  1415. tor_assert(min < max);
  1416. return min + crypto_rand_uint64(max - min);
  1417. }
  1418. /** As crypto_rand_int_range, but supports time_t. */
  1419. time_t
  1420. crypto_rand_time_range(time_t min, time_t max)
  1421. {
  1422. tor_assert(min < max);
  1423. return min + (time_t)crypto_rand_uint64(max - min);
  1424. }
  1425. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  1426. * between 0 and <b>max</b>-1 inclusive. */
  1427. uint64_t
  1428. crypto_rand_uint64(uint64_t max)
  1429. {
  1430. uint64_t val;
  1431. uint64_t cutoff;
  1432. tor_assert(max < UINT64_MAX);
  1433. tor_assert(max > 0); /* don't div by 0 */
  1434. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1435. * distribution with clipping at the upper end of unsigned int's
  1436. * range.
  1437. */
  1438. cutoff = UINT64_MAX - (UINT64_MAX%max);
  1439. while (1) {
  1440. crypto_rand((char*)&val, sizeof(val));
  1441. if (val < cutoff)
  1442. return val % max;
  1443. }
  1444. }
  1445. /** Return a pseudorandom double d, chosen uniformly from the range
  1446. * 0.0 <= d < 1.0.
  1447. */
  1448. double
  1449. crypto_rand_double(void)
  1450. {
  1451. /* We just use an unsigned int here; we don't really care about getting
  1452. * more than 32 bits of resolution */
  1453. unsigned int u;
  1454. crypto_rand((char*)&u, sizeof(u));
  1455. #if SIZEOF_INT == 4
  1456. #define UINT_MAX_AS_DOUBLE 4294967296.0
  1457. #elif SIZEOF_INT == 8
  1458. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  1459. #else
  1460. #error SIZEOF_INT is neither 4 nor 8
  1461. #endif /* SIZEOF_INT == 4 || ... */
  1462. return ((double)u) / UINT_MAX_AS_DOUBLE;
  1463. }
  1464. /** Generate and return a new random hostname starting with <b>prefix</b>,
  1465. * ending with <b>suffix</b>, and containing no fewer than
  1466. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  1467. * characters. Does not check for failure.
  1468. *
  1469. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  1470. **/
  1471. char *
  1472. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  1473. const char *suffix)
  1474. {
  1475. char *result, *rand_bytes;
  1476. int randlen, rand_bytes_len;
  1477. size_t resultlen, prefixlen;
  1478. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  1479. max_rand_len = MAX_DNS_LABEL_SIZE;
  1480. if (min_rand_len > max_rand_len)
  1481. min_rand_len = max_rand_len;
  1482. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  1483. prefixlen = strlen(prefix);
  1484. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  1485. rand_bytes_len = ((randlen*5)+7)/8;
  1486. if (rand_bytes_len % 5)
  1487. rand_bytes_len += 5 - (rand_bytes_len%5);
  1488. rand_bytes = tor_malloc(rand_bytes_len);
  1489. crypto_rand(rand_bytes, rand_bytes_len);
  1490. result = tor_malloc(resultlen);
  1491. memcpy(result, prefix, prefixlen);
  1492. base32_encode(result+prefixlen, resultlen-prefixlen,
  1493. rand_bytes, rand_bytes_len);
  1494. tor_free(rand_bytes);
  1495. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  1496. return result;
  1497. }
  1498. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  1499. * is empty. */
  1500. void *
  1501. smartlist_choose(const smartlist_t *sl)
  1502. {
  1503. int len = smartlist_len(sl);
  1504. if (len)
  1505. return smartlist_get(sl,crypto_rand_int(len));
  1506. return NULL; /* no elements to choose from */
  1507. }
  1508. /** Scramble the elements of <b>sl</b> into a random order. */
  1509. void
  1510. smartlist_shuffle(smartlist_t *sl)
  1511. {
  1512. int i;
  1513. /* From the end of the list to the front, choose at random from the
  1514. positions we haven't looked at yet, and swap that position into the
  1515. current position. Remember to give "no swap" the same probability as
  1516. any other swap. */
  1517. for (i = smartlist_len(sl)-1; i > 0; --i) {
  1518. int j = crypto_rand_int(i+1);
  1519. smartlist_swap(sl, i, j);
  1520. }
  1521. }
  1522. /**
  1523. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  1524. * the value <b>byte</b>.
  1525. * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
  1526. *
  1527. * This function is preferable to memset, since many compilers will happily
  1528. * optimize out memset() when they can convince themselves that the data being
  1529. * cleared will never be read.
  1530. *
  1531. * Right now, our convention is to use this function when we are wiping data
  1532. * that's about to become inaccessible, such as stack buffers that are about
  1533. * to go out of scope or structures that are about to get freed. (In
  1534. * practice, it appears that the compilers we're currently using will optimize
  1535. * out the memset()s for stack-allocated buffers, but not those for
  1536. * about-to-be-freed structures. That could change, though, so we're being
  1537. * wary.) If there are live reads for the data, then you can just use
  1538. * memset().
  1539. */
  1540. void
  1541. memwipe(void *mem, uint8_t byte, size_t sz)
  1542. {
  1543. if (sz == 0) {
  1544. return;
  1545. }
  1546. /* If sz is nonzero, then mem must not be NULL. */
  1547. tor_assert(mem != NULL);
  1548. /* Data this large is likely to be an underflow. */
  1549. tor_assert(sz < SIZE_T_CEILING);
  1550. /* Because whole-program-optimization exists, we may not be able to just
  1551. * have this function call "memset". A smart compiler could inline it, then
  1552. * eliminate dead memsets, and declare itself to be clever. */
  1553. #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
  1554. /* Here's what you do on windows. */
  1555. SecureZeroMemory(mem,sz);
  1556. #elif defined(HAVE_RTLSECUREZEROMEMORY)
  1557. RtlSecureZeroMemory(mem,sz);
  1558. #elif defined(HAVE_EXPLICIT_BZERO)
  1559. /* The BSDs provide this. */
  1560. explicit_bzero(mem, sz);
  1561. #elif defined(HAVE_MEMSET_S)
  1562. /* This is in the C99 standard. */
  1563. memset_s(mem, sz, 0, sz);
  1564. #else
  1565. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  1566. * based on the pointer value, then uses that junk to update a global
  1567. * variable. It's an elaborate ruse to trick the compiler into not
  1568. * optimizing out the "wipe this memory" code. Read it if you like zany
  1569. * programming tricks! In later versions of Tor, we should look for better
  1570. * not-optimized-out memory wiping stuff...
  1571. *
  1572. * ...or maybe not. In practice, there are pure-asm implementations of
  1573. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  1574. **/
  1575. OPENSSL_cleanse(mem, sz);
  1576. #endif /* defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY) || ... */
  1577. /* Just in case some caller of memwipe() is relying on getting a buffer
  1578. * filled with a particular value, fill the buffer.
  1579. *
  1580. * If this function gets inlined, this memset might get eliminated, but
  1581. * that's okay: We only care about this particular memset in the case where
  1582. * the caller should have been using memset(), and the memset() wouldn't get
  1583. * eliminated. In other words, this is here so that we won't break anything
  1584. * if somebody accidentally calls memwipe() instead of memset().
  1585. **/
  1586. memset(mem, byte, sz);
  1587. }
  1588. /** @{ */
  1589. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  1590. * failure.
  1591. */
  1592. int
  1593. crypto_global_cleanup(void)
  1594. {
  1595. EVP_cleanup();
  1596. #ifndef NEW_THREAD_API
  1597. ERR_remove_thread_state(NULL);
  1598. #endif
  1599. ERR_free_strings();
  1600. if (dh_param_p)
  1601. BN_clear_free(dh_param_p);
  1602. if (dh_param_p_tls)
  1603. BN_clear_free(dh_param_p_tls);
  1604. if (dh_param_g)
  1605. BN_clear_free(dh_param_g);
  1606. dh_param_p = dh_param_p_tls = dh_param_g = NULL;
  1607. #ifndef DISABLE_ENGINES
  1608. ENGINE_cleanup();
  1609. #endif
  1610. CONF_modules_unload(1);
  1611. CRYPTO_cleanup_all_ex_data();
  1612. crypto_openssl_free_all();
  1613. crypto_early_initialized_ = 0;
  1614. crypto_global_initialized_ = 0;
  1615. have_seeded_siphash = 0;
  1616. siphash_unset_global_key();
  1617. return 0;
  1618. }
  1619. /** @} */
  1620. #ifdef USE_DMALLOC
  1621. /** Tell the crypto library to use Tor's allocation functions rather than
  1622. * calling libc's allocation functions directly. Return 0 on success, -1
  1623. * on failure. */
  1624. int
  1625. crypto_use_tor_alloc_functions(void)
  1626. {
  1627. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  1628. return r ? 0 : -1;
  1629. }
  1630. #endif /* defined(USE_DMALLOC) */