crypto.c 72 KB

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