crypto.c 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476
  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. /** Check a siglen-byte long signature at <b>sig</b> against
  352. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  353. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  354. * SHA1(data). Else return -1.
  355. */
  356. MOCK_IMPL(int,
  357. crypto_pk_public_checksig_digest,(crypto_pk_t *env, const char *data,
  358. size_t datalen, const char *sig,
  359. size_t siglen))
  360. {
  361. char digest[DIGEST_LEN];
  362. char *buf;
  363. size_t buflen;
  364. int r;
  365. tor_assert(env);
  366. tor_assert(data);
  367. tor_assert(sig);
  368. tor_assert(datalen < SIZE_T_CEILING);
  369. tor_assert(siglen < SIZE_T_CEILING);
  370. if (crypto_digest(digest,data,datalen)<0) {
  371. log_warn(LD_BUG, "couldn't compute digest");
  372. return -1;
  373. }
  374. buflen = crypto_pk_keysize(env);
  375. buf = tor_malloc(buflen);
  376. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  377. if (r != DIGEST_LEN) {
  378. log_warn(LD_CRYPTO, "Invalid signature");
  379. tor_free(buf);
  380. return -1;
  381. }
  382. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  383. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  384. tor_free(buf);
  385. return -1;
  386. }
  387. tor_free(buf);
  388. return 0;
  389. }
  390. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  391. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  392. * store it in <b>to</b>. Return the number of bytes written on
  393. * success, and -1 on failure.
  394. *
  395. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  396. * at least the length of the modulus of <b>env</b>.
  397. */
  398. int
  399. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  400. const char *from, size_t fromlen)
  401. {
  402. int r;
  403. char digest[DIGEST_LEN];
  404. if (crypto_digest(digest,from,fromlen)<0)
  405. return -1;
  406. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  407. memwipe(digest, 0, sizeof(digest));
  408. return r;
  409. }
  410. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  411. * bytes of data from <b>from</b>, with padding type 'padding',
  412. * storing the results on <b>to</b>.
  413. *
  414. * Returns the number of bytes written on success, -1 on failure.
  415. *
  416. * The encrypted data consists of:
  417. * - The source data, padded and encrypted with the public key, if the
  418. * padded source data is no longer than the public key, and <b>force</b>
  419. * is false, OR
  420. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  421. * padded and encrypted with the public key; followed by the rest of
  422. * the source data encrypted in AES-CTR mode with the symmetric key.
  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_public_hybrid_encrypt(crypto_pk_t *env,
  429. char *to, size_t tolen,
  430. const char *from,
  431. size_t fromlen,
  432. int padding, int force)
  433. {
  434. int overhead, outlen, r;
  435. size_t pkeylen, symlen;
  436. crypto_cipher_t *cipher = NULL;
  437. char *buf = NULL;
  438. tor_assert(env);
  439. tor_assert(from);
  440. tor_assert(to);
  441. tor_assert(fromlen < SIZE_T_CEILING);
  442. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  443. pkeylen = crypto_pk_keysize(env);
  444. if (!force && fromlen+overhead <= pkeylen) {
  445. /* It all fits in a single encrypt. */
  446. return crypto_pk_public_encrypt(env,to,
  447. tolen,
  448. from,fromlen,padding);
  449. }
  450. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  451. tor_assert(tolen >= pkeylen);
  452. char key[CIPHER_KEY_LEN];
  453. crypto_rand(key, sizeof(key)); /* generate a new key. */
  454. cipher = crypto_cipher_new(key);
  455. buf = tor_malloc(pkeylen+1);
  456. memcpy(buf, key, CIPHER_KEY_LEN);
  457. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  458. /* Length of symmetrically encrypted data. */
  459. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  460. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  461. if (outlen!=(int)pkeylen) {
  462. goto err;
  463. }
  464. r = crypto_cipher_encrypt(cipher, to+outlen,
  465. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  466. if (r<0) goto err;
  467. memwipe(buf, 0, pkeylen);
  468. memwipe(key, 0, sizeof(key));
  469. tor_free(buf);
  470. crypto_cipher_free(cipher);
  471. tor_assert(outlen+symlen < INT_MAX);
  472. return (int)(outlen + symlen);
  473. err:
  474. memwipe(buf, 0, pkeylen);
  475. memwipe(key, 0, sizeof(key));
  476. tor_free(buf);
  477. crypto_cipher_free(cipher);
  478. return -1;
  479. }
  480. /** Invert crypto_pk_obsolete_public_hybrid_encrypt. Returns the number of
  481. * bytes written on success, -1 on failure.
  482. *
  483. * NOTE that this format does not authenticate the symmetrically encrypted
  484. * part of the data, and SHOULD NOT BE USED for new protocols.
  485. */
  486. int
  487. crypto_pk_obsolete_private_hybrid_decrypt(crypto_pk_t *env,
  488. char *to,
  489. size_t tolen,
  490. const char *from,
  491. size_t fromlen,
  492. int padding, int warnOnFailure)
  493. {
  494. int outlen, r;
  495. size_t pkeylen;
  496. crypto_cipher_t *cipher = NULL;
  497. char *buf = NULL;
  498. tor_assert(fromlen < SIZE_T_CEILING);
  499. pkeylen = crypto_pk_keysize(env);
  500. if (fromlen <= pkeylen) {
  501. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  502. warnOnFailure);
  503. }
  504. buf = tor_malloc(pkeylen);
  505. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  506. warnOnFailure);
  507. if (outlen<0) {
  508. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  509. "Error decrypting public-key data");
  510. goto err;
  511. }
  512. if (outlen < CIPHER_KEY_LEN) {
  513. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  514. "No room for a symmetric key");
  515. goto err;
  516. }
  517. cipher = crypto_cipher_new(buf);
  518. if (!cipher) {
  519. goto err;
  520. }
  521. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  522. outlen -= CIPHER_KEY_LEN;
  523. tor_assert(tolen - outlen >= fromlen - pkeylen);
  524. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  525. if (r<0)
  526. goto err;
  527. memwipe(buf,0,pkeylen);
  528. tor_free(buf);
  529. crypto_cipher_free(cipher);
  530. tor_assert(outlen + fromlen < INT_MAX);
  531. return (int)(outlen + (fromlen-pkeylen));
  532. err:
  533. memwipe(buf,0,pkeylen);
  534. tor_free(buf);
  535. crypto_cipher_free(cipher);
  536. return -1;
  537. }
  538. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  539. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  540. * Return 0 on success, -1 on failure.
  541. */
  542. int
  543. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  544. {
  545. char *buf;
  546. size_t buflen;
  547. int len;
  548. int rv = -1;
  549. buflen = crypto_pk_keysize(pk)*2;
  550. buf = tor_malloc(buflen);
  551. len = crypto_pk_asn1_encode(pk, buf, buflen);
  552. if (len < 0)
  553. goto done;
  554. if (crypto_digest(digest_out, buf, len) < 0)
  555. goto done;
  556. rv = 0;
  557. done:
  558. tor_free(buf);
  559. return rv;
  560. }
  561. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  562. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  563. int
  564. crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
  565. {
  566. char *buf;
  567. size_t buflen;
  568. int len;
  569. int rv = -1;
  570. buflen = crypto_pk_keysize(pk)*2;
  571. buf = tor_malloc(buflen);
  572. len = crypto_pk_asn1_encode(pk, buf, buflen);
  573. if (len < 0)
  574. goto done;
  575. if (crypto_common_digests(digests_out, (char*)buf, len) < 0)
  576. goto done;
  577. rv = 0;
  578. done:
  579. tor_free(buf);
  580. return rv;
  581. }
  582. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  583. * every four characters. */
  584. void
  585. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  586. {
  587. int n = 0;
  588. char *end = out+outlen;
  589. tor_assert(outlen < SIZE_T_CEILING);
  590. while (*in && out<end) {
  591. *out++ = *in++;
  592. if (++n == 4 && *in && out<end) {
  593. n = 0;
  594. *out++ = ' ';
  595. }
  596. }
  597. tor_assert(out<end);
  598. *out = '\0';
  599. }
  600. /* symmetric crypto */
  601. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  602. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  603. * Does not check for failure.
  604. */
  605. int
  606. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  607. const char *from, size_t fromlen)
  608. {
  609. tor_assert(env);
  610. tor_assert(env);
  611. tor_assert(from);
  612. tor_assert(fromlen);
  613. tor_assert(to);
  614. tor_assert(fromlen < SIZE_T_CEILING);
  615. memcpy(to, from, fromlen);
  616. aes_crypt_inplace(env, to, fromlen);
  617. return 0;
  618. }
  619. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  620. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  621. * Does not check for failure.
  622. */
  623. int
  624. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  625. const char *from, size_t fromlen)
  626. {
  627. tor_assert(env);
  628. tor_assert(from);
  629. tor_assert(to);
  630. tor_assert(fromlen < SIZE_T_CEILING);
  631. memcpy(to, from, fromlen);
  632. aes_crypt_inplace(env, to, fromlen);
  633. return 0;
  634. }
  635. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  636. * on success. Does not check for failure.
  637. */
  638. void
  639. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  640. {
  641. tor_assert(len < SIZE_T_CEILING);
  642. aes_crypt_inplace(env, buf, len);
  643. }
  644. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  645. * <b>key</b> to the buffer in <b>to</b> of length
  646. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  647. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  648. * number of bytes written, on failure, return -1.
  649. */
  650. int
  651. crypto_cipher_encrypt_with_iv(const char *key,
  652. char *to, size_t tolen,
  653. const char *from, size_t fromlen)
  654. {
  655. crypto_cipher_t *cipher;
  656. tor_assert(from);
  657. tor_assert(to);
  658. tor_assert(fromlen < INT_MAX);
  659. if (fromlen < 1)
  660. return -1;
  661. if (tolen < fromlen + CIPHER_IV_LEN)
  662. return -1;
  663. char iv[CIPHER_IV_LEN];
  664. crypto_rand(iv, sizeof(iv));
  665. cipher = crypto_cipher_new_with_iv(key, iv);
  666. memcpy(to, iv, CIPHER_IV_LEN);
  667. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  668. crypto_cipher_free(cipher);
  669. memwipe(iv, 0, sizeof(iv));
  670. return (int)(fromlen + CIPHER_IV_LEN);
  671. }
  672. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  673. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  674. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  675. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  676. * number of bytes written, on failure, return -1.
  677. */
  678. int
  679. crypto_cipher_decrypt_with_iv(const char *key,
  680. char *to, size_t tolen,
  681. const char *from, size_t fromlen)
  682. {
  683. crypto_cipher_t *cipher;
  684. tor_assert(key);
  685. tor_assert(from);
  686. tor_assert(to);
  687. tor_assert(fromlen < INT_MAX);
  688. if (fromlen <= CIPHER_IV_LEN)
  689. return -1;
  690. if (tolen < fromlen - CIPHER_IV_LEN)
  691. return -1;
  692. cipher = crypto_cipher_new_with_iv(key, from);
  693. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  694. crypto_cipher_free(cipher);
  695. return (int)(fromlen - CIPHER_IV_LEN);
  696. }
  697. /* SHA-1 */
  698. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  699. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  700. * Return 0 on success, -1 on failure.
  701. */
  702. int
  703. crypto_digest(char *digest, const char *m, size_t len)
  704. {
  705. tor_assert(m);
  706. tor_assert(digest);
  707. if (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL)
  708. return -1;
  709. return 0;
  710. }
  711. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  712. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  713. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  714. int
  715. crypto_digest256(char *digest, const char *m, size_t len,
  716. digest_algorithm_t algorithm)
  717. {
  718. tor_assert(m);
  719. tor_assert(digest);
  720. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  721. int ret = 0;
  722. if (algorithm == DIGEST_SHA256)
  723. ret = (SHA256((const uint8_t*)m,len,(uint8_t*)digest) != NULL);
  724. else
  725. ret = (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  726. > -1);
  727. if (!ret)
  728. return -1;
  729. return 0;
  730. }
  731. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  732. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  733. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  734. int
  735. crypto_digest512(char *digest, const char *m, size_t len,
  736. digest_algorithm_t algorithm)
  737. {
  738. tor_assert(m);
  739. tor_assert(digest);
  740. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  741. int ret = 0;
  742. if (algorithm == DIGEST_SHA512)
  743. ret = (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
  744. != NULL);
  745. else
  746. ret = (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  747. > -1);
  748. if (!ret)
  749. return -1;
  750. return 0;
  751. }
  752. /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
  753. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  754. * success, -1 on failure. */
  755. int
  756. crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
  757. {
  758. tor_assert(ds_out);
  759. memset(ds_out, 0, sizeof(*ds_out));
  760. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  761. return -1;
  762. if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
  763. return -1;
  764. return 0;
  765. }
  766. /** Return the name of an algorithm, as used in directory documents. */
  767. const char *
  768. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  769. {
  770. switch (alg) {
  771. case DIGEST_SHA1:
  772. return "sha1";
  773. case DIGEST_SHA256:
  774. return "sha256";
  775. case DIGEST_SHA512:
  776. return "sha512";
  777. case DIGEST_SHA3_256:
  778. return "sha3-256";
  779. case DIGEST_SHA3_512:
  780. return "sha3-512";
  781. // LCOV_EXCL_START
  782. default:
  783. tor_fragile_assert();
  784. return "??unknown_digest??";
  785. // LCOV_EXCL_STOP
  786. }
  787. }
  788. /** Given the name of a digest algorithm, return its integer value, or -1 if
  789. * the name is not recognized. */
  790. int
  791. crypto_digest_algorithm_parse_name(const char *name)
  792. {
  793. if (!strcmp(name, "sha1"))
  794. return DIGEST_SHA1;
  795. else if (!strcmp(name, "sha256"))
  796. return DIGEST_SHA256;
  797. else if (!strcmp(name, "sha512"))
  798. return DIGEST_SHA512;
  799. else if (!strcmp(name, "sha3-256"))
  800. return DIGEST_SHA3_256;
  801. else if (!strcmp(name, "sha3-512"))
  802. return DIGEST_SHA3_512;
  803. else
  804. return -1;
  805. }
  806. /** Given an algorithm, return the digest length in bytes. */
  807. size_t
  808. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  809. {
  810. switch (alg) {
  811. case DIGEST_SHA1:
  812. return DIGEST_LEN;
  813. case DIGEST_SHA256:
  814. return DIGEST256_LEN;
  815. case DIGEST_SHA512:
  816. return DIGEST512_LEN;
  817. case DIGEST_SHA3_256:
  818. return DIGEST256_LEN;
  819. case DIGEST_SHA3_512:
  820. return DIGEST512_LEN;
  821. default:
  822. tor_assert(0); // LCOV_EXCL_LINE
  823. return 0; /* Unreachable */ // LCOV_EXCL_LINE
  824. }
  825. }
  826. /** Intermediate information about the digest of a stream of data. */
  827. struct crypto_digest_t {
  828. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  829. /** State for the digest we're using. Only one member of the
  830. * union is usable, depending on the value of <b>algorithm</b>. Note also
  831. * that space for other members might not even be allocated!
  832. */
  833. union {
  834. SHA_CTX sha1; /**< state for SHA1 */
  835. SHA256_CTX sha2; /**< state for SHA256 */
  836. SHA512_CTX sha512; /**< state for SHA512 */
  837. keccak_state sha3; /**< state for SHA3-[256,512] */
  838. } d;
  839. };
  840. #ifdef TOR_UNIT_TESTS
  841. digest_algorithm_t
  842. crypto_digest_get_algorithm(crypto_digest_t *digest)
  843. {
  844. tor_assert(digest);
  845. return digest->algorithm;
  846. }
  847. #endif /* defined(TOR_UNIT_TESTS) */
  848. /**
  849. * Return the number of bytes we need to malloc in order to get a
  850. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  851. * when we free one.
  852. */
  853. static size_t
  854. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  855. {
  856. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  857. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  858. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  859. #define END_OF_FIELD(f) (offsetof(crypto_digest_t, f) + \
  860. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  861. switch (alg) {
  862. case DIGEST_SHA1:
  863. return END_OF_FIELD(d.sha1);
  864. case DIGEST_SHA256:
  865. return END_OF_FIELD(d.sha2);
  866. case DIGEST_SHA512:
  867. return END_OF_FIELD(d.sha512);
  868. case DIGEST_SHA3_256:
  869. case DIGEST_SHA3_512:
  870. return END_OF_FIELD(d.sha3);
  871. default:
  872. tor_assert(0); // LCOV_EXCL_LINE
  873. return 0; // LCOV_EXCL_LINE
  874. }
  875. #undef END_OF_FIELD
  876. #undef STRUCT_FIELD_SIZE
  877. }
  878. /**
  879. * Internal function: create and return a new digest object for 'algorithm'.
  880. * Does not typecheck the algorithm.
  881. */
  882. static crypto_digest_t *
  883. crypto_digest_new_internal(digest_algorithm_t algorithm)
  884. {
  885. crypto_digest_t *r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  886. r->algorithm = algorithm;
  887. switch (algorithm)
  888. {
  889. case DIGEST_SHA1:
  890. SHA1_Init(&r->d.sha1);
  891. break;
  892. case DIGEST_SHA256:
  893. SHA256_Init(&r->d.sha2);
  894. break;
  895. case DIGEST_SHA512:
  896. SHA512_Init(&r->d.sha512);
  897. break;
  898. case DIGEST_SHA3_256:
  899. keccak_digest_init(&r->d.sha3, 256);
  900. break;
  901. case DIGEST_SHA3_512:
  902. keccak_digest_init(&r->d.sha3, 512);
  903. break;
  904. default:
  905. tor_assert_unreached();
  906. }
  907. return r;
  908. }
  909. /** Allocate and return a new digest object to compute SHA1 digests.
  910. */
  911. crypto_digest_t *
  912. crypto_digest_new(void)
  913. {
  914. return crypto_digest_new_internal(DIGEST_SHA1);
  915. }
  916. /** Allocate and return a new digest object to compute 256-bit digests
  917. * using <b>algorithm</b>. */
  918. crypto_digest_t *
  919. crypto_digest256_new(digest_algorithm_t algorithm)
  920. {
  921. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  922. return crypto_digest_new_internal(algorithm);
  923. }
  924. /** Allocate and return a new digest object to compute 512-bit digests
  925. * using <b>algorithm</b>. */
  926. crypto_digest_t *
  927. crypto_digest512_new(digest_algorithm_t algorithm)
  928. {
  929. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  930. return crypto_digest_new_internal(algorithm);
  931. }
  932. /** Deallocate a digest object.
  933. */
  934. void
  935. crypto_digest_free_(crypto_digest_t *digest)
  936. {
  937. if (!digest)
  938. return;
  939. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  940. memwipe(digest, 0, bytes);
  941. tor_free(digest);
  942. }
  943. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  944. */
  945. void
  946. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  947. size_t len)
  948. {
  949. tor_assert(digest);
  950. tor_assert(data);
  951. /* Using the SHA*_*() calls directly means we don't support doing
  952. * SHA in hardware. But so far the delay of getting the question
  953. * to the hardware, and hearing the answer, is likely higher than
  954. * just doing it ourselves. Hashes are fast.
  955. */
  956. switch (digest->algorithm) {
  957. case DIGEST_SHA1:
  958. SHA1_Update(&digest->d.sha1, (void*)data, len);
  959. break;
  960. case DIGEST_SHA256:
  961. SHA256_Update(&digest->d.sha2, (void*)data, len);
  962. break;
  963. case DIGEST_SHA512:
  964. SHA512_Update(&digest->d.sha512, (void*)data, len);
  965. break;
  966. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  967. case DIGEST_SHA3_512:
  968. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  969. break;
  970. default:
  971. /* LCOV_EXCL_START */
  972. tor_fragile_assert();
  973. break;
  974. /* LCOV_EXCL_STOP */
  975. }
  976. }
  977. /** Compute the hash of the data that has been passed to the digest
  978. * object; write the first out_len bytes of the result to <b>out</b>.
  979. * <b>out_len</b> must be \<= DIGEST512_LEN.
  980. */
  981. void
  982. crypto_digest_get_digest(crypto_digest_t *digest,
  983. char *out, size_t out_len)
  984. {
  985. unsigned char r[DIGEST512_LEN];
  986. crypto_digest_t tmpenv;
  987. tor_assert(digest);
  988. tor_assert(out);
  989. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  990. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  991. * short output buffers by truncating appropriately. */
  992. if (digest->algorithm == DIGEST_SHA3_256 ||
  993. digest->algorithm == DIGEST_SHA3_512) {
  994. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  995. return;
  996. }
  997. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  998. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  999. memcpy(&tmpenv, digest, alloc_bytes);
  1000. switch (digest->algorithm) {
  1001. case DIGEST_SHA1:
  1002. SHA1_Final(r, &tmpenv.d.sha1);
  1003. break;
  1004. case DIGEST_SHA256:
  1005. SHA256_Final(r, &tmpenv.d.sha2);
  1006. break;
  1007. case DIGEST_SHA512:
  1008. SHA512_Final(r, &tmpenv.d.sha512);
  1009. break;
  1010. //LCOV_EXCL_START
  1011. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1012. case DIGEST_SHA3_512:
  1013. default:
  1014. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  1015. /* This is fatal, because it should never happen. */
  1016. tor_assert_unreached();
  1017. break;
  1018. //LCOV_EXCL_STOP
  1019. }
  1020. memcpy(out, r, out_len);
  1021. memwipe(r, 0, sizeof(r));
  1022. }
  1023. /** Allocate and return a new digest object with the same state as
  1024. * <b>digest</b>
  1025. */
  1026. crypto_digest_t *
  1027. crypto_digest_dup(const crypto_digest_t *digest)
  1028. {
  1029. tor_assert(digest);
  1030. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1031. return tor_memdup(digest, alloc_bytes);
  1032. }
  1033. /** Replace the state of the digest object <b>into</b> with the state
  1034. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  1035. * have the same digest type.
  1036. */
  1037. void
  1038. crypto_digest_assign(crypto_digest_t *into,
  1039. const crypto_digest_t *from)
  1040. {
  1041. tor_assert(into);
  1042. tor_assert(from);
  1043. tor_assert(into->algorithm == from->algorithm);
  1044. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  1045. memcpy(into,from,alloc_bytes);
  1046. }
  1047. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1048. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  1049. * plus the optional string <b>append</b>, computed with the algorithm
  1050. * <b>alg</b>.
  1051. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  1052. void
  1053. crypto_digest_smartlist(char *digest_out, size_t len_out,
  1054. const smartlist_t *lst,
  1055. const char *append,
  1056. digest_algorithm_t alg)
  1057. {
  1058. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  1059. }
  1060. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1061. * at <b>digest_out</b> to the hash of the concatenation of: the
  1062. * optional string <b>prepend</b>, those strings,
  1063. * and the optional string <b>append</b>, computed with the algorithm
  1064. * <b>alg</b>.
  1065. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  1066. void
  1067. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  1068. const char *prepend,
  1069. const smartlist_t *lst,
  1070. const char *append,
  1071. digest_algorithm_t alg)
  1072. {
  1073. crypto_digest_t *d = crypto_digest_new_internal(alg);
  1074. if (prepend)
  1075. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  1076. SMARTLIST_FOREACH(lst, const char *, cp,
  1077. crypto_digest_add_bytes(d, cp, strlen(cp)));
  1078. if (append)
  1079. crypto_digest_add_bytes(d, append, strlen(append));
  1080. crypto_digest_get_digest(d, digest_out, len_out);
  1081. crypto_digest_free(d);
  1082. }
  1083. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1084. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  1085. * result in <b>hmac_out</b>. Asserts on failure.
  1086. */
  1087. void
  1088. crypto_hmac_sha256(char *hmac_out,
  1089. const char *key, size_t key_len,
  1090. const char *msg, size_t msg_len)
  1091. {
  1092. unsigned char *rv = NULL;
  1093. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  1094. tor_assert(key_len < INT_MAX);
  1095. tor_assert(msg_len < INT_MAX);
  1096. tor_assert(hmac_out);
  1097. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1098. (unsigned char*)hmac_out, NULL);
  1099. tor_assert(rv);
  1100. }
  1101. /** Compute a MAC using SHA3-256 of <b>msg_len</b> bytes in <b>msg</b> using a
  1102. * <b>key</b> of length <b>key_len</b> and a <b>salt</b> of length
  1103. * <b>salt_len</b>. Store the result of <b>len_out</b> bytes in in
  1104. * <b>mac_out</b>. This function can't fail. */
  1105. void
  1106. crypto_mac_sha3_256(uint8_t *mac_out, size_t len_out,
  1107. const uint8_t *key, size_t key_len,
  1108. const uint8_t *msg, size_t msg_len)
  1109. {
  1110. crypto_digest_t *digest;
  1111. const uint64_t key_len_netorder = tor_htonll(key_len);
  1112. tor_assert(mac_out);
  1113. tor_assert(key);
  1114. tor_assert(msg);
  1115. digest = crypto_digest256_new(DIGEST_SHA3_256);
  1116. /* Order matters here that is any subsystem using this function should
  1117. * expect this very precise ordering in the MAC construction. */
  1118. crypto_digest_add_bytes(digest, (const char *) &key_len_netorder,
  1119. sizeof(key_len_netorder));
  1120. crypto_digest_add_bytes(digest, (const char *) key, key_len);
  1121. crypto_digest_add_bytes(digest, (const char *) msg, msg_len);
  1122. crypto_digest_get_digest(digest, (char *) mac_out, len_out);
  1123. crypto_digest_free(digest);
  1124. }
  1125. /** Internal state for a eXtendable-Output Function (XOF). */
  1126. struct crypto_xof_t {
  1127. keccak_state s;
  1128. };
  1129. /** Allocate a new XOF object backed by SHAKE-256. The security level
  1130. * provided is a function of the length of the output used. Read and
  1131. * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
  1132. * Functions" before using this construct.
  1133. */
  1134. crypto_xof_t *
  1135. crypto_xof_new(void)
  1136. {
  1137. crypto_xof_t *xof;
  1138. xof = tor_malloc(sizeof(crypto_xof_t));
  1139. keccak_xof_init(&xof->s, 256);
  1140. return xof;
  1141. }
  1142. /** Absorb bytes into a XOF object. Must not be called after a call to
  1143. * crypto_xof_squeeze_bytes() for the same instance, and will assert
  1144. * if attempted.
  1145. */
  1146. void
  1147. crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
  1148. {
  1149. int i = keccak_xof_absorb(&xof->s, data, len);
  1150. tor_assert(i == 0);
  1151. }
  1152. /** Squeeze bytes out of a XOF object. Calling this routine will render
  1153. * the XOF instance ineligible to absorb further data.
  1154. */
  1155. void
  1156. crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
  1157. {
  1158. int i = keccak_xof_squeeze(&xof->s, out, len);
  1159. tor_assert(i == 0);
  1160. }
  1161. /** Cleanse and deallocate a XOF object. */
  1162. void
  1163. crypto_xof_free_(crypto_xof_t *xof)
  1164. {
  1165. if (!xof)
  1166. return;
  1167. memwipe(xof, 0, sizeof(crypto_xof_t));
  1168. tor_free(xof);
  1169. }
  1170. /* DH */
  1171. /** Our DH 'g' parameter */
  1172. #define DH_GENERATOR 2
  1173. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  1174. static BIGNUM *dh_param_p = NULL;
  1175. /** Shared P parameter for our TLS DH key exchanges. */
  1176. static BIGNUM *dh_param_p_tls = NULL;
  1177. /** Shared G parameter for our DH key exchanges. */
  1178. static BIGNUM *dh_param_g = NULL;
  1179. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  1180. * computationally expensive (milliseconds), so should only be called when
  1181. * the DH parameters change. Returns 0 on success, * -1 on failure.
  1182. */
  1183. static int
  1184. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  1185. {
  1186. DH *dh = NULL;
  1187. int ret = -1;
  1188. /* Copy into a temporary DH object, just so that DH_check() can be called. */
  1189. if (!(dh = DH_new()))
  1190. goto out;
  1191. #ifdef OPENSSL_1_1_API
  1192. BIGNUM *dh_p, *dh_g;
  1193. if (!(dh_p = BN_dup(p)))
  1194. goto out;
  1195. if (!(dh_g = BN_dup(g)))
  1196. goto out;
  1197. if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
  1198. goto out;
  1199. #else /* !(defined(OPENSSL_1_1_API)) */
  1200. if (!(dh->p = BN_dup(p)))
  1201. goto out;
  1202. if (!(dh->g = BN_dup(g)))
  1203. goto out;
  1204. #endif /* defined(OPENSSL_1_1_API) */
  1205. /* Perform the validation. */
  1206. int codes = 0;
  1207. if (!DH_check(dh, &codes))
  1208. goto out;
  1209. if (BN_is_word(g, DH_GENERATOR_2)) {
  1210. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  1211. *
  1212. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  1213. * IETF's primes are congruent to 23 when g = 2.
  1214. */
  1215. BN_ULONG residue = BN_mod_word(p, 24);
  1216. if (residue == 11 || residue == 23)
  1217. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  1218. }
  1219. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  1220. goto out;
  1221. /* Things are probably not evil. */
  1222. ret = 0;
  1223. out:
  1224. if (dh)
  1225. DH_free(dh);
  1226. return ret;
  1227. }
  1228. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  1229. * DH stuff.
  1230. */
  1231. static void
  1232. crypto_set_dh_generator(void)
  1233. {
  1234. BIGNUM *generator;
  1235. int r;
  1236. if (dh_param_g)
  1237. return;
  1238. generator = BN_new();
  1239. tor_assert(generator);
  1240. r = BN_set_word(generator, DH_GENERATOR);
  1241. tor_assert(r);
  1242. dh_param_g = generator;
  1243. }
  1244. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  1245. * modulus. */
  1246. void
  1247. crypto_set_tls_dh_prime(void)
  1248. {
  1249. BIGNUM *tls_prime = NULL;
  1250. int r;
  1251. /* If the space is occupied, free the previous TLS DH prime */
  1252. if (BUG(dh_param_p_tls)) {
  1253. /* LCOV_EXCL_START
  1254. *
  1255. * We shouldn't be calling this twice.
  1256. */
  1257. BN_clear_free(dh_param_p_tls);
  1258. dh_param_p_tls = NULL;
  1259. /* LCOV_EXCL_STOP */
  1260. }
  1261. tls_prime = BN_new();
  1262. tor_assert(tls_prime);
  1263. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  1264. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  1265. * prime.
  1266. */
  1267. r = BN_hex2bn(&tls_prime,
  1268. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  1269. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  1270. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  1271. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  1272. "B0E7393E0F24218EB3");
  1273. tor_assert(r);
  1274. tor_assert(tls_prime);
  1275. dh_param_p_tls = tls_prime;
  1276. crypto_set_dh_generator();
  1277. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  1278. }
  1279. /** Initialize dh_param_p and dh_param_g if they are not already
  1280. * set. */
  1281. static void
  1282. init_dh_param(void)
  1283. {
  1284. BIGNUM *circuit_dh_prime;
  1285. int r;
  1286. if (BUG(dh_param_p && dh_param_g))
  1287. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  1288. circuit_dh_prime = BN_new();
  1289. tor_assert(circuit_dh_prime);
  1290. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1291. supposedly it equals:
  1292. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1293. */
  1294. r = BN_hex2bn(&circuit_dh_prime,
  1295. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1296. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1297. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1298. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1299. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1300. tor_assert(r);
  1301. /* Set the new values as the global DH parameters. */
  1302. dh_param_p = circuit_dh_prime;
  1303. crypto_set_dh_generator();
  1304. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  1305. if (!dh_param_p_tls) {
  1306. crypto_set_tls_dh_prime();
  1307. }
  1308. }
  1309. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  1310. * handshake. Since we exponentiate by this value, choosing a smaller one
  1311. * lets our handhake go faster.
  1312. */
  1313. #define DH_PRIVATE_KEY_BITS 320
  1314. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  1315. * failure.
  1316. */
  1317. crypto_dh_t *
  1318. crypto_dh_new(int dh_type)
  1319. {
  1320. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  1321. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  1322. dh_type == DH_TYPE_REND);
  1323. if (!dh_param_p)
  1324. init_dh_param();
  1325. if (!(res->dh = DH_new()))
  1326. goto err;
  1327. #ifdef OPENSSL_1_1_API
  1328. BIGNUM *dh_p = NULL, *dh_g = NULL;
  1329. if (dh_type == DH_TYPE_TLS) {
  1330. dh_p = BN_dup(dh_param_p_tls);
  1331. } else {
  1332. dh_p = BN_dup(dh_param_p);
  1333. }
  1334. if (!dh_p)
  1335. goto err;
  1336. dh_g = BN_dup(dh_param_g);
  1337. if (!dh_g) {
  1338. BN_free(dh_p);
  1339. goto err;
  1340. }
  1341. if (!DH_set0_pqg(res->dh, dh_p, NULL, dh_g)) {
  1342. goto err;
  1343. }
  1344. if (!DH_set_length(res->dh, DH_PRIVATE_KEY_BITS))
  1345. goto err;
  1346. #else /* !(defined(OPENSSL_1_1_API)) */
  1347. if (dh_type == DH_TYPE_TLS) {
  1348. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  1349. goto err;
  1350. } else {
  1351. if (!(res->dh->p = BN_dup(dh_param_p)))
  1352. goto err;
  1353. }
  1354. if (!(res->dh->g = BN_dup(dh_param_g)))
  1355. goto err;
  1356. res->dh->length = DH_PRIVATE_KEY_BITS;
  1357. #endif /* defined(OPENSSL_1_1_API) */
  1358. return res;
  1359. /* LCOV_EXCL_START
  1360. * This error condition is only reached when an allocation fails */
  1361. err:
  1362. crypto_log_errors(LOG_WARN, "creating DH object");
  1363. if (res->dh) DH_free(res->dh); /* frees p and g too */
  1364. tor_free(res);
  1365. return NULL;
  1366. /* LCOV_EXCL_STOP */
  1367. }
  1368. /** Return a copy of <b>dh</b>, sharing its internal state. */
  1369. crypto_dh_t *
  1370. crypto_dh_dup(const crypto_dh_t *dh)
  1371. {
  1372. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  1373. tor_assert(dh);
  1374. tor_assert(dh->dh);
  1375. dh_new->dh = dh->dh;
  1376. DH_up_ref(dh->dh);
  1377. return dh_new;
  1378. }
  1379. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1380. */
  1381. int
  1382. crypto_dh_get_bytes(crypto_dh_t *dh)
  1383. {
  1384. tor_assert(dh);
  1385. return DH_size(dh->dh);
  1386. }
  1387. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1388. * success, -1 on failure.
  1389. */
  1390. int
  1391. crypto_dh_generate_public(crypto_dh_t *dh)
  1392. {
  1393. #ifndef OPENSSL_1_1_API
  1394. again:
  1395. #endif
  1396. if (!DH_generate_key(dh->dh)) {
  1397. /* LCOV_EXCL_START
  1398. * To test this we would need some way to tell openssl to break DH. */
  1399. crypto_log_errors(LOG_WARN, "generating DH key");
  1400. return -1;
  1401. /* LCOV_EXCL_STOP */
  1402. }
  1403. #ifdef OPENSSL_1_1_API
  1404. /* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
  1405. * recreating the DH object. I have no idea what sort of aliasing madness
  1406. * can occur here, so do the check, and just bail on failure.
  1407. */
  1408. const BIGNUM *pub_key, *priv_key;
  1409. DH_get0_key(dh->dh, &pub_key, &priv_key);
  1410. if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
  1411. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1412. "the-universe chances really do happen. Treating as a failure.");
  1413. return -1;
  1414. }
  1415. #else /* !(defined(OPENSSL_1_1_API)) */
  1416. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  1417. /* LCOV_EXCL_START
  1418. * If this happens, then openssl's DH implementation is busted. */
  1419. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1420. "the-universe chances really do happen. Trying again.");
  1421. /* Free and clear the keys, so OpenSSL will actually try again. */
  1422. BN_clear_free(dh->dh->pub_key);
  1423. BN_clear_free(dh->dh->priv_key);
  1424. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1425. goto again;
  1426. /* LCOV_EXCL_STOP */
  1427. }
  1428. #endif /* defined(OPENSSL_1_1_API) */
  1429. return 0;
  1430. }
  1431. /** Generate g^x as necessary, and write the g^x for the key exchange
  1432. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1433. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1434. */
  1435. int
  1436. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  1437. {
  1438. int bytes;
  1439. tor_assert(dh);
  1440. const BIGNUM *dh_pub;
  1441. #ifdef OPENSSL_1_1_API
  1442. const BIGNUM *dh_priv;
  1443. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  1444. #else
  1445. dh_pub = dh->dh->pub_key;
  1446. #endif /* defined(OPENSSL_1_1_API) */
  1447. if (!dh_pub) {
  1448. if (crypto_dh_generate_public(dh)<0)
  1449. return -1;
  1450. else {
  1451. #ifdef OPENSSL_1_1_API
  1452. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  1453. #else
  1454. dh_pub = dh->dh->pub_key;
  1455. #endif
  1456. }
  1457. }
  1458. tor_assert(dh_pub);
  1459. bytes = BN_num_bytes(dh_pub);
  1460. tor_assert(bytes >= 0);
  1461. if (pubkey_len < (size_t)bytes) {
  1462. log_warn(LD_CRYPTO,
  1463. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1464. (int) pubkey_len, bytes);
  1465. return -1;
  1466. }
  1467. memset(pubkey, 0, pubkey_len);
  1468. BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1469. return 0;
  1470. }
  1471. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  1472. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1473. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1474. */
  1475. static int
  1476. tor_check_dh_key(int severity, const BIGNUM *bn)
  1477. {
  1478. BIGNUM *x;
  1479. char *s;
  1480. tor_assert(bn);
  1481. x = BN_new();
  1482. tor_assert(x);
  1483. if (BUG(!dh_param_p))
  1484. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  1485. BN_set_word(x, 1);
  1486. if (BN_cmp(bn,x)<=0) {
  1487. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  1488. goto err;
  1489. }
  1490. BN_copy(x,dh_param_p);
  1491. BN_sub_word(x, 1);
  1492. if (BN_cmp(bn,x)>=0) {
  1493. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  1494. goto err;
  1495. }
  1496. BN_clear_free(x);
  1497. return 0;
  1498. err:
  1499. BN_clear_free(x);
  1500. s = BN_bn2hex(bn);
  1501. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1502. OPENSSL_free(s);
  1503. return -1;
  1504. }
  1505. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1506. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1507. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1508. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1509. * or -1 on failure.
  1510. *
  1511. * (We generate key material by computing
  1512. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1513. * where || is concatenation.)
  1514. */
  1515. ssize_t
  1516. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  1517. const char *pubkey, size_t pubkey_len,
  1518. char *secret_out, size_t secret_bytes_out)
  1519. {
  1520. char *secret_tmp = NULL;
  1521. BIGNUM *pubkey_bn = NULL;
  1522. size_t secret_len=0, secret_tmp_len=0;
  1523. int result=0;
  1524. tor_assert(dh);
  1525. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1526. tor_assert(pubkey_len < INT_MAX);
  1527. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  1528. (int)pubkey_len, NULL)))
  1529. goto error;
  1530. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  1531. /* Check for invalid public keys. */
  1532. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  1533. goto error;
  1534. }
  1535. secret_tmp_len = crypto_dh_get_bytes(dh);
  1536. secret_tmp = tor_malloc(secret_tmp_len);
  1537. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  1538. if (result < 0) {
  1539. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  1540. goto error;
  1541. }
  1542. secret_len = result;
  1543. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  1544. (uint8_t*)secret_out, secret_bytes_out)<0)
  1545. goto error;
  1546. secret_len = secret_bytes_out;
  1547. goto done;
  1548. error:
  1549. result = -1;
  1550. done:
  1551. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1552. if (pubkey_bn)
  1553. BN_clear_free(pubkey_bn);
  1554. if (secret_tmp) {
  1555. memwipe(secret_tmp, 0, secret_tmp_len);
  1556. tor_free(secret_tmp);
  1557. }
  1558. if (result < 0)
  1559. return result;
  1560. else
  1561. return secret_len;
  1562. }
  1563. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  1564. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  1565. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  1566. * H(K | [00]) | H(K | [01]) | ....
  1567. *
  1568. * This is the key expansion algorithm used in the "TAP" circuit extension
  1569. * mechanism; it shouldn't be used for new protocols.
  1570. *
  1571. * Return 0 on success, -1 on failure.
  1572. */
  1573. int
  1574. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  1575. uint8_t *key_out, size_t key_out_len)
  1576. {
  1577. int i, r = -1;
  1578. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  1579. uint8_t digest[DIGEST_LEN];
  1580. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1581. tor_assert(key_out_len <= DIGEST_LEN*256);
  1582. memcpy(tmp, key_in, key_in_len);
  1583. for (cp = key_out, i=0; cp < key_out+key_out_len;
  1584. ++i, cp += DIGEST_LEN) {
  1585. tmp[key_in_len] = i;
  1586. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1) < 0)
  1587. goto exit;
  1588. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  1589. }
  1590. r = 0;
  1591. exit:
  1592. memwipe(tmp, 0, key_in_len+1);
  1593. tor_free(tmp);
  1594. memwipe(digest, 0, sizeof(digest));
  1595. return r;
  1596. }
  1597. /** Expand some secret key material according to RFC5869, using SHA256 as the
  1598. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  1599. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  1600. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  1601. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  1602. * bytes to <b>key_out</b> and return 0. Assert on failure.
  1603. */
  1604. int
  1605. crypto_expand_key_material_rfc5869_sha256(
  1606. const uint8_t *key_in, size_t key_in_len,
  1607. const uint8_t *salt_in, size_t salt_in_len,
  1608. const uint8_t *info_in, size_t info_in_len,
  1609. uint8_t *key_out, size_t key_out_len)
  1610. {
  1611. uint8_t prk[DIGEST256_LEN];
  1612. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  1613. uint8_t mac[DIGEST256_LEN];
  1614. int i;
  1615. uint8_t *outp;
  1616. size_t tmp_len;
  1617. crypto_hmac_sha256((char*)prk,
  1618. (const char*)salt_in, salt_in_len,
  1619. (const char*)key_in, key_in_len);
  1620. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1621. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  1622. tor_assert(info_in_len <= 128);
  1623. memset(tmp, 0, sizeof(tmp));
  1624. outp = key_out;
  1625. i = 1;
  1626. while (key_out_len) {
  1627. size_t n;
  1628. if (i > 1) {
  1629. memcpy(tmp, mac, DIGEST256_LEN);
  1630. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  1631. tmp[DIGEST256_LEN+info_in_len] = i;
  1632. tmp_len = DIGEST256_LEN + info_in_len + 1;
  1633. } else {
  1634. memcpy(tmp, info_in, info_in_len);
  1635. tmp[info_in_len] = i;
  1636. tmp_len = info_in_len + 1;
  1637. }
  1638. crypto_hmac_sha256((char*)mac,
  1639. (const char*)prk, DIGEST256_LEN,
  1640. (const char*)tmp, tmp_len);
  1641. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  1642. memcpy(outp, mac, n);
  1643. key_out_len -= n;
  1644. outp += n;
  1645. ++i;
  1646. }
  1647. memwipe(tmp, 0, sizeof(tmp));
  1648. memwipe(mac, 0, sizeof(mac));
  1649. return 0;
  1650. }
  1651. /** Free a DH key exchange object.
  1652. */
  1653. void
  1654. crypto_dh_free_(crypto_dh_t *dh)
  1655. {
  1656. if (!dh)
  1657. return;
  1658. tor_assert(dh->dh);
  1659. DH_free(dh->dh);
  1660. tor_free(dh);
  1661. }
  1662. /* random numbers */
  1663. /** How many bytes of entropy we add at once.
  1664. *
  1665. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  1666. * work for us too. */
  1667. #define ADD_ENTROPY 32
  1668. /** Set the seed of the weak RNG to a random value. */
  1669. void
  1670. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  1671. {
  1672. unsigned seed;
  1673. crypto_rand((void*)&seed, sizeof(seed));
  1674. tor_init_weak_random(rng, seed);
  1675. }
  1676. #ifdef TOR_UNIT_TESTS
  1677. int break_strongest_rng_syscall = 0;
  1678. int break_strongest_rng_fallback = 0;
  1679. #endif
  1680. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1681. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  1682. * failure. A maximum request size of 256 bytes is imposed.
  1683. */
  1684. static int
  1685. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  1686. {
  1687. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  1688. #ifdef TOR_UNIT_TESTS
  1689. if (break_strongest_rng_syscall)
  1690. return -1;
  1691. #endif
  1692. #if defined(_WIN32)
  1693. static int provider_set = 0;
  1694. static HCRYPTPROV provider;
  1695. if (!provider_set) {
  1696. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1697. CRYPT_VERIFYCONTEXT)) {
  1698. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  1699. return -1;
  1700. }
  1701. provider_set = 1;
  1702. }
  1703. if (!CryptGenRandom(provider, out_len, out)) {
  1704. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  1705. return -1;
  1706. }
  1707. return 0;
  1708. #elif defined(__linux__) && defined(SYS_getrandom)
  1709. static int getrandom_works = 1; /* Be optimitic about our chances... */
  1710. /* getrandom() isn't as straightforward as getentropy(), and has
  1711. * no glibc wrapper.
  1712. *
  1713. * As far as I can tell from getrandom(2) and the source code, the
  1714. * requests we issue will always succeed (though it will block on the
  1715. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  1716. * GRND_NONBLOCK and the request is <= 256 bytes.
  1717. *
  1718. * The manpage is unclear on what happens if a signal interrupts the call
  1719. * while the request is blocked due to lack of entropy....
  1720. *
  1721. * We optimistically assume that getrandom() is available and functional
  1722. * because it is the way of the future, and 2 branch mispredicts pale in
  1723. * comparison to the overheads involved with failing to open
  1724. * /dev/srandom followed by opening and reading from /dev/urandom.
  1725. */
  1726. if (PREDICT_LIKELY(getrandom_works)) {
  1727. long ret;
  1728. /* A flag of '0' here means to read from '/dev/urandom', and to
  1729. * block if insufficient entropy is available to service the
  1730. * request.
  1731. */
  1732. const unsigned int flags = 0;
  1733. do {
  1734. ret = syscall(SYS_getrandom, out, out_len, flags);
  1735. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  1736. if (PREDICT_UNLIKELY(ret == -1)) {
  1737. /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
  1738. tor_assert(errno != EAGAIN);
  1739. tor_assert(errno != EINTR);
  1740. /* Useful log message for errno. */
  1741. if (errno == ENOSYS) {
  1742. log_warn(LD_CRYPTO, "Can't get entropy from getrandom()."
  1743. " You are running a version of Tor built to support"
  1744. " getrandom(), but the kernel doesn't implement this"
  1745. " function--probably because it is too old?");
  1746. } else {
  1747. log_warn(LD_CRYPTO, "Can't get entropy from getrandom(): %s.",
  1748. strerror(errno));
  1749. }
  1750. getrandom_works = 0; /* Don't bother trying again. */
  1751. return -1;
  1752. /* LCOV_EXCL_STOP */
  1753. }
  1754. tor_assert(ret == (long)out_len);
  1755. return 0;
  1756. }
  1757. return -1; /* getrandom() previously failed unexpectedly. */
  1758. #elif defined(HAVE_GETENTROPY)
  1759. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  1760. * the only gotcha is that requests are limited to 256 bytes.
  1761. */
  1762. return getentropy(out, out_len);
  1763. #else
  1764. (void) out;
  1765. #endif /* defined(_WIN32) || ... */
  1766. /* This platform doesn't have a supported syscall based random. */
  1767. return -1;
  1768. }
  1769. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1770. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  1771. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  1772. * is imposed.
  1773. */
  1774. static int
  1775. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  1776. {
  1777. #ifdef TOR_UNIT_TESTS
  1778. if (break_strongest_rng_fallback)
  1779. return -1;
  1780. #endif
  1781. #ifdef _WIN32
  1782. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  1783. (void)out;
  1784. (void)out_len;
  1785. return -1;
  1786. #else /* !(defined(_WIN32)) */
  1787. static const char *filenames[] = {
  1788. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1789. };
  1790. int fd, i;
  1791. size_t n;
  1792. for (i = 0; filenames[i]; ++i) {
  1793. log_debug(LD_FS, "Considering %s for entropy", filenames[i]);
  1794. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  1795. if (fd<0) continue;
  1796. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  1797. n = read_all(fd, (char*)out, out_len, 0);
  1798. close(fd);
  1799. if (n != out_len) {
  1800. /* LCOV_EXCL_START
  1801. * We can't make /dev/foorandom actually fail. */
  1802. log_warn(LD_CRYPTO,
  1803. "Error reading from entropy source (read only %lu bytes).",
  1804. (unsigned long)n);
  1805. return -1;
  1806. /* LCOV_EXCL_STOP */
  1807. }
  1808. return 0;
  1809. }
  1810. return -1;
  1811. #endif /* defined(_WIN32) */
  1812. }
  1813. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1814. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  1815. * request size of 256 bytes is imposed.
  1816. */
  1817. STATIC int
  1818. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  1819. {
  1820. static const size_t sanity_min_size = 16;
  1821. static const int max_attempts = 3;
  1822. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  1823. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  1824. * zero filling the buffer and ensuring that it actually was at least
  1825. * partially modified.
  1826. *
  1827. * Checking that any individual byte is non-zero seems like it would
  1828. * fail too often (p = out_len * 1/256) for comfort, but this is an
  1829. * "adjust according to taste" sort of check.
  1830. */
  1831. memwipe(out, 0, out_len);
  1832. for (int i = 0; i < max_attempts; i++) {
  1833. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  1834. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  1835. /* Try to use the less-favored mechanism to get strong entropy. */
  1836. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  1837. /* Welp, we tried. Hopefully the calling code terminates the process
  1838. * since we're basically boned without good entropy.
  1839. */
  1840. log_warn(LD_CRYPTO,
  1841. "Cannot get strong entropy: no entropy source found.");
  1842. return -1;
  1843. }
  1844. }
  1845. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  1846. return 0;
  1847. }
  1848. /* LCOV_EXCL_START
  1849. *
  1850. * We tried max_attempts times to fill a buffer >= 128 bits long,
  1851. * and each time it returned all '0's. Either the system entropy
  1852. * source is busted, or the user should go out and buy a ticket to
  1853. * every lottery on the planet.
  1854. */
  1855. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  1856. return -1;
  1857. /* LCOV_EXCL_STOP */
  1858. }
  1859. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  1860. * storing it into <b>out</b>.
  1861. */
  1862. void
  1863. crypto_strongest_rand(uint8_t *out, size_t out_len)
  1864. {
  1865. #define DLEN SHA512_DIGEST_LENGTH
  1866. /* We're going to hash DLEN bytes from the system RNG together with some
  1867. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  1868. */
  1869. uint8_t inp[DLEN*2];
  1870. uint8_t tmp[DLEN];
  1871. tor_assert(out);
  1872. while (out_len) {
  1873. crypto_rand((char*) inp, DLEN);
  1874. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  1875. // LCOV_EXCL_START
  1876. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  1877. "important key. Exiting.");
  1878. /* Die with an assertion so we get a stack trace. */
  1879. tor_assert(0);
  1880. // LCOV_EXCL_STOP
  1881. }
  1882. if (out_len >= DLEN) {
  1883. SHA512(inp, sizeof(inp), out);
  1884. out += DLEN;
  1885. out_len -= DLEN;
  1886. } else {
  1887. SHA512(inp, sizeof(inp), tmp);
  1888. memcpy(out, tmp, out_len);
  1889. break;
  1890. }
  1891. }
  1892. memwipe(tmp, 0, sizeof(tmp));
  1893. memwipe(inp, 0, sizeof(inp));
  1894. #undef DLEN
  1895. }
  1896. /** Seed OpenSSL's random number generator with bytes from the operating
  1897. * system. Return 0 on success, -1 on failure.
  1898. */
  1899. int
  1900. crypto_seed_rng(void)
  1901. {
  1902. int rand_poll_ok = 0, load_entropy_ok = 0;
  1903. uint8_t buf[ADD_ENTROPY];
  1904. /* OpenSSL has a RAND_poll function that knows about more kinds of
  1905. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1906. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1907. rand_poll_ok = RAND_poll();
  1908. if (rand_poll_ok == 0)
  1909. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  1910. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  1911. if (load_entropy_ok) {
  1912. RAND_seed(buf, sizeof(buf));
  1913. }
  1914. memwipe(buf, 0, sizeof(buf));
  1915. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  1916. return 0;
  1917. else
  1918. return -1;
  1919. }
  1920. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  1921. * for unit tests.
  1922. *
  1923. * This function is not allowed to fail; if it would fail to generate strong
  1924. * entropy, it must terminate the process instead.
  1925. */
  1926. MOCK_IMPL(void,
  1927. crypto_rand, (char *to, size_t n))
  1928. {
  1929. crypto_rand_unmocked(to, n);
  1930. }
  1931. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  1932. * will want crypto_rand instead.
  1933. *
  1934. * This function is not allowed to fail; if it would fail to generate strong
  1935. * entropy, it must terminate the process instead.
  1936. */
  1937. void
  1938. crypto_rand_unmocked(char *to, size_t n)
  1939. {
  1940. int r;
  1941. if (n == 0)
  1942. return;
  1943. tor_assert(n < INT_MAX);
  1944. tor_assert(to);
  1945. r = RAND_bytes((unsigned char*)to, (int)n);
  1946. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  1947. * stack trace about where it happened.
  1948. */
  1949. tor_assert(r >= 0);
  1950. }
  1951. /** Return a pseudorandom integer, chosen uniformly from the values
  1952. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  1953. * INT_MAX+1, inclusive. */
  1954. int
  1955. crypto_rand_int(unsigned int max)
  1956. {
  1957. unsigned int val;
  1958. unsigned int cutoff;
  1959. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  1960. tor_assert(max > 0); /* don't div by 0 */
  1961. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1962. * distribution with clipping at the upper end of unsigned int's
  1963. * range.
  1964. */
  1965. cutoff = UINT_MAX - (UINT_MAX%max);
  1966. while (1) {
  1967. crypto_rand((char*)&val, sizeof(val));
  1968. if (val < cutoff)
  1969. return val % max;
  1970. }
  1971. }
  1972. /** Return a pseudorandom integer, chosen uniformly from the values i such
  1973. * that min <= i < max.
  1974. *
  1975. * <b>min</b> MUST be in range [0, <b>max</b>).
  1976. * <b>max</b> MUST be in range (min, INT_MAX].
  1977. */
  1978. int
  1979. crypto_rand_int_range(unsigned int min, unsigned int max)
  1980. {
  1981. tor_assert(min < max);
  1982. tor_assert(max <= INT_MAX);
  1983. /* The overflow is avoided here because crypto_rand_int() returns a value
  1984. * between 0 and (max - min) inclusive. */
  1985. return min + crypto_rand_int(max - min);
  1986. }
  1987. /** As crypto_rand_int_range, but supports uint64_t. */
  1988. uint64_t
  1989. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  1990. {
  1991. tor_assert(min < max);
  1992. return min + crypto_rand_uint64(max - min);
  1993. }
  1994. /** As crypto_rand_int_range, but supports time_t. */
  1995. time_t
  1996. crypto_rand_time_range(time_t min, time_t max)
  1997. {
  1998. tor_assert(min < max);
  1999. return min + (time_t)crypto_rand_uint64(max - min);
  2000. }
  2001. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  2002. * between 0 and <b>max</b>-1 inclusive. */
  2003. uint64_t
  2004. crypto_rand_uint64(uint64_t max)
  2005. {
  2006. uint64_t val;
  2007. uint64_t cutoff;
  2008. tor_assert(max < UINT64_MAX);
  2009. tor_assert(max > 0); /* don't div by 0 */
  2010. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2011. * distribution with clipping at the upper end of unsigned int's
  2012. * range.
  2013. */
  2014. cutoff = UINT64_MAX - (UINT64_MAX%max);
  2015. while (1) {
  2016. crypto_rand((char*)&val, sizeof(val));
  2017. if (val < cutoff)
  2018. return val % max;
  2019. }
  2020. }
  2021. /** Return a pseudorandom double d, chosen uniformly from the range
  2022. * 0.0 <= d < 1.0.
  2023. */
  2024. double
  2025. crypto_rand_double(void)
  2026. {
  2027. /* We just use an unsigned int here; we don't really care about getting
  2028. * more than 32 bits of resolution */
  2029. unsigned int u;
  2030. crypto_rand((char*)&u, sizeof(u));
  2031. #if SIZEOF_INT == 4
  2032. #define UINT_MAX_AS_DOUBLE 4294967296.0
  2033. #elif SIZEOF_INT == 8
  2034. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  2035. #else
  2036. #error SIZEOF_INT is neither 4 nor 8
  2037. #endif /* SIZEOF_INT == 4 || ... */
  2038. return ((double)u) / UINT_MAX_AS_DOUBLE;
  2039. }
  2040. /** Generate and return a new random hostname starting with <b>prefix</b>,
  2041. * ending with <b>suffix</b>, and containing no fewer than
  2042. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  2043. * characters. Does not check for failure.
  2044. *
  2045. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  2046. **/
  2047. char *
  2048. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  2049. const char *suffix)
  2050. {
  2051. char *result, *rand_bytes;
  2052. int randlen, rand_bytes_len;
  2053. size_t resultlen, prefixlen;
  2054. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  2055. max_rand_len = MAX_DNS_LABEL_SIZE;
  2056. if (min_rand_len > max_rand_len)
  2057. min_rand_len = max_rand_len;
  2058. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  2059. prefixlen = strlen(prefix);
  2060. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  2061. rand_bytes_len = ((randlen*5)+7)/8;
  2062. if (rand_bytes_len % 5)
  2063. rand_bytes_len += 5 - (rand_bytes_len%5);
  2064. rand_bytes = tor_malloc(rand_bytes_len);
  2065. crypto_rand(rand_bytes, rand_bytes_len);
  2066. result = tor_malloc(resultlen);
  2067. memcpy(result, prefix, prefixlen);
  2068. base32_encode(result+prefixlen, resultlen-prefixlen,
  2069. rand_bytes, rand_bytes_len);
  2070. tor_free(rand_bytes);
  2071. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  2072. return result;
  2073. }
  2074. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  2075. * is empty. */
  2076. void *
  2077. smartlist_choose(const smartlist_t *sl)
  2078. {
  2079. int len = smartlist_len(sl);
  2080. if (len)
  2081. return smartlist_get(sl,crypto_rand_int(len));
  2082. return NULL; /* no elements to choose from */
  2083. }
  2084. /** Scramble the elements of <b>sl</b> into a random order. */
  2085. void
  2086. smartlist_shuffle(smartlist_t *sl)
  2087. {
  2088. int i;
  2089. /* From the end of the list to the front, choose at random from the
  2090. positions we haven't looked at yet, and swap that position into the
  2091. current position. Remember to give "no swap" the same probability as
  2092. any other swap. */
  2093. for (i = smartlist_len(sl)-1; i > 0; --i) {
  2094. int j = crypto_rand_int(i+1);
  2095. smartlist_swap(sl, i, j);
  2096. }
  2097. }
  2098. /**
  2099. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  2100. * the value <b>byte</b>.
  2101. * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
  2102. *
  2103. * This function is preferable to memset, since many compilers will happily
  2104. * optimize out memset() when they can convince themselves that the data being
  2105. * cleared will never be read.
  2106. *
  2107. * Right now, our convention is to use this function when we are wiping data
  2108. * that's about to become inaccessible, such as stack buffers that are about
  2109. * to go out of scope or structures that are about to get freed. (In
  2110. * practice, it appears that the compilers we're currently using will optimize
  2111. * out the memset()s for stack-allocated buffers, but not those for
  2112. * about-to-be-freed structures. That could change, though, so we're being
  2113. * wary.) If there are live reads for the data, then you can just use
  2114. * memset().
  2115. */
  2116. void
  2117. memwipe(void *mem, uint8_t byte, size_t sz)
  2118. {
  2119. if (sz == 0) {
  2120. return;
  2121. }
  2122. /* If sz is nonzero, then mem must not be NULL. */
  2123. tor_assert(mem != NULL);
  2124. /* Data this large is likely to be an underflow. */
  2125. tor_assert(sz < SIZE_T_CEILING);
  2126. /* Because whole-program-optimization exists, we may not be able to just
  2127. * have this function call "memset". A smart compiler could inline it, then
  2128. * eliminate dead memsets, and declare itself to be clever. */
  2129. #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
  2130. /* Here's what you do on windows. */
  2131. SecureZeroMemory(mem,sz);
  2132. #elif defined(HAVE_RTLSECUREZEROMEMORY)
  2133. RtlSecureZeroMemory(mem,sz);
  2134. #elif defined(HAVE_EXPLICIT_BZERO)
  2135. /* The BSDs provide this. */
  2136. explicit_bzero(mem, sz);
  2137. #elif defined(HAVE_MEMSET_S)
  2138. /* This is in the C99 standard. */
  2139. memset_s(mem, sz, 0, sz);
  2140. #else
  2141. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  2142. * based on the pointer value, then uses that junk to update a global
  2143. * variable. It's an elaborate ruse to trick the compiler into not
  2144. * optimizing out the "wipe this memory" code. Read it if you like zany
  2145. * programming tricks! In later versions of Tor, we should look for better
  2146. * not-optimized-out memory wiping stuff...
  2147. *
  2148. * ...or maybe not. In practice, there are pure-asm implementations of
  2149. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  2150. **/
  2151. OPENSSL_cleanse(mem, sz);
  2152. #endif /* defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY) || ... */
  2153. /* Just in case some caller of memwipe() is relying on getting a buffer
  2154. * filled with a particular value, fill the buffer.
  2155. *
  2156. * If this function gets inlined, this memset might get eliminated, but
  2157. * that's okay: We only care about this particular memset in the case where
  2158. * the caller should have been using memset(), and the memset() wouldn't get
  2159. * eliminated. In other words, this is here so that we won't break anything
  2160. * if somebody accidentally calls memwipe() instead of memset().
  2161. **/
  2162. memset(mem, byte, sz);
  2163. }
  2164. /** @{ */
  2165. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  2166. * failure.
  2167. */
  2168. int
  2169. crypto_global_cleanup(void)
  2170. {
  2171. EVP_cleanup();
  2172. #ifndef NEW_THREAD_API
  2173. ERR_remove_thread_state(NULL);
  2174. #endif
  2175. ERR_free_strings();
  2176. if (dh_param_p)
  2177. BN_clear_free(dh_param_p);
  2178. if (dh_param_p_tls)
  2179. BN_clear_free(dh_param_p_tls);
  2180. if (dh_param_g)
  2181. BN_clear_free(dh_param_g);
  2182. dh_param_p = dh_param_p_tls = dh_param_g = NULL;
  2183. #ifndef DISABLE_ENGINES
  2184. ENGINE_cleanup();
  2185. #endif
  2186. CONF_modules_unload(1);
  2187. CRYPTO_cleanup_all_ex_data();
  2188. crypto_openssl_free_all();
  2189. crypto_early_initialized_ = 0;
  2190. crypto_global_initialized_ = 0;
  2191. have_seeded_siphash = 0;
  2192. siphash_unset_global_key();
  2193. return 0;
  2194. }
  2195. /** @} */
  2196. #ifdef USE_DMALLOC
  2197. /** Tell the crypto library to use Tor's allocation functions rather than
  2198. * calling libc's allocation functions directly. Return 0 on success, -1
  2199. * on failure. */
  2200. int
  2201. crypto_use_tor_alloc_functions(void)
  2202. {
  2203. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  2204. return r ? 0 : -1;
  2205. }
  2206. #endif /* defined(USE_DMALLOC) */