crypto.c 53 KB

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