crypto.c 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035
  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-2015, 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.
  10. **/
  11. #include "orconfig.h"
  12. #ifdef _WIN32
  13. #include <winsock2.h>
  14. #include <windows.h>
  15. #include <wincrypt.h>
  16. /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
  17. * use either definition. */
  18. #undef OCSP_RESPONSE
  19. #endif
  20. #define CRYPTO_PRIVATE
  21. #include "crypto.h"
  22. #include "compat_openssl.h"
  23. #include "crypto_curve25519.h"
  24. #include "crypto_ed25519.h"
  25. #include "crypto_format.h"
  26. #include <openssl/err.h>
  27. #include <openssl/rsa.h>
  28. #include <openssl/pem.h>
  29. #include <openssl/evp.h>
  30. #include <openssl/engine.h>
  31. #include <openssl/rand.h>
  32. #include <openssl/bn.h>
  33. #include <openssl/dh.h>
  34. #include <openssl/conf.h>
  35. #include <openssl/hmac.h>
  36. #ifdef HAVE_CTYPE_H
  37. #include <ctype.h>
  38. #endif
  39. #ifdef HAVE_UNISTD_H
  40. #define _GNU_SOURCE
  41. #include <unistd.h>
  42. #endif
  43. #ifdef HAVE_FCNTL_H
  44. #include <fcntl.h>
  45. #endif
  46. #ifdef HAVE_SYS_FCNTL_H
  47. #include <sys/fcntl.h>
  48. #endif
  49. #ifdef HAVE_SYS_SYSCALL_H
  50. #include <sys/syscall.h>
  51. #endif
  52. #include "torlog.h"
  53. #include "aes.h"
  54. #include "util.h"
  55. #include "container.h"
  56. #include "compat.h"
  57. #include "sandbox.h"
  58. #include "util_format.h"
  59. #include "keccak-tiny/keccak-tiny.h"
  60. #ifdef ANDROID
  61. /* Android's OpenSSL seems to have removed all of its Engine support. */
  62. #define DISABLE_ENGINES
  63. #endif
  64. /** Longest recognized */
  65. #define MAX_DNS_LABEL_SIZE 63
  66. /** Largest strong entropy request */
  67. #define MAX_STRONGEST_RAND_SIZE 256
  68. /** Macro: is k a valid RSA public or private key? */
  69. #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
  70. /** Macro: is k a valid RSA private key? */
  71. #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
  72. /** A number of preallocated mutexes for use by OpenSSL. */
  73. static tor_mutex_t **openssl_mutexes_ = NULL;
  74. /** How many mutexes have we allocated for use by OpenSSL? */
  75. static int n_openssl_mutexes_ = 0;
  76. /** A public key, or a public/private key-pair. */
  77. struct crypto_pk_t
  78. {
  79. int refs; /**< reference count, so we don't have to copy keys */
  80. RSA *key; /**< The key itself */
  81. };
  82. /** Key and stream information for a stream cipher. */
  83. struct crypto_cipher_t
  84. {
  85. char key[CIPHER_KEY_LEN]; /**< The raw key. */
  86. char iv[CIPHER_IV_LEN]; /**< The initial IV. */
  87. aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
  88. * encryption */
  89. };
  90. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  91. * while we're waiting for the second.*/
  92. struct crypto_dh_t {
  93. DH *dh; /**< The openssl DH object */
  94. };
  95. static int setup_openssl_threading(void);
  96. static int tor_check_dh_key(int severity, BIGNUM *bn);
  97. /** Return the number of bytes added by padding method <b>padding</b>.
  98. */
  99. static inline int
  100. crypto_get_rsa_padding_overhead(int padding)
  101. {
  102. switch (padding)
  103. {
  104. case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
  105. default: tor_assert(0); return -1;
  106. }
  107. }
  108. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  109. */
  110. static inline int
  111. crypto_get_rsa_padding(int padding)
  112. {
  113. switch (padding)
  114. {
  115. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  116. default: tor_assert(0); return -1;
  117. }
  118. }
  119. /** Boolean: has OpenSSL's crypto been initialized? */
  120. static int crypto_early_initialized_ = 0;
  121. /** Boolean: has OpenSSL's crypto been initialized? */
  122. static int crypto_global_initialized_ = 0;
  123. /** Log all pending crypto errors at level <b>severity</b>. Use
  124. * <b>doing</b> to describe our current activities.
  125. */
  126. static void
  127. crypto_log_errors(int severity, const char *doing)
  128. {
  129. unsigned long err;
  130. const char *msg, *lib, *func;
  131. while ((err = ERR_get_error()) != 0) {
  132. msg = (const char*)ERR_reason_error_string(err);
  133. lib = (const char*)ERR_lib_error_string(err);
  134. func = (const char*)ERR_func_error_string(err);
  135. if (!msg) msg = "(null)";
  136. if (!lib) lib = "(null)";
  137. if (!func) func = "(null)";
  138. if (doing) {
  139. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  140. doing, msg, lib, func);
  141. } else {
  142. tor_log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)",
  143. msg, lib, func);
  144. }
  145. }
  146. }
  147. #ifndef DISABLE_ENGINES
  148. /** Log any OpenSSL engines we're using at NOTICE. */
  149. static void
  150. log_engine(const char *fn, ENGINE *e)
  151. {
  152. if (e) {
  153. const char *name, *id;
  154. name = ENGINE_get_name(e);
  155. id = ENGINE_get_id(e);
  156. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  157. fn, name?name:"?", id?id:"?");
  158. } else {
  159. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  160. }
  161. }
  162. #endif
  163. #ifndef DISABLE_ENGINES
  164. /** Try to load an engine in a shared library via fully qualified path.
  165. */
  166. static ENGINE *
  167. try_load_engine(const char *path, const char *engine)
  168. {
  169. ENGINE *e = ENGINE_by_id("dynamic");
  170. if (e) {
  171. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  172. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  173. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  174. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  175. ENGINE_free(e);
  176. e = NULL;
  177. }
  178. }
  179. return e;
  180. }
  181. #endif
  182. /* Returns a trimmed and human-readable version of an openssl version string
  183. * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
  184. * May 2012' and this will parse them into a form similar to '1.0.0b' */
  185. static char *
  186. parse_openssl_version_str(const char *raw_version)
  187. {
  188. const char *end_of_version = NULL;
  189. /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
  190. trim that down. */
  191. if (!strcmpstart(raw_version, "OpenSSL ")) {
  192. raw_version += strlen("OpenSSL ");
  193. end_of_version = strchr(raw_version, ' ');
  194. }
  195. if (end_of_version)
  196. return tor_strndup(raw_version,
  197. end_of_version-raw_version);
  198. else
  199. return tor_strdup(raw_version);
  200. }
  201. static char *crypto_openssl_version_str = NULL;
  202. /* Return a human-readable version of the run-time openssl version number. */
  203. const char *
  204. crypto_openssl_get_version_str(void)
  205. {
  206. if (crypto_openssl_version_str == NULL) {
  207. const char *raw_version = OpenSSL_version(OPENSSL_VERSION);
  208. crypto_openssl_version_str = parse_openssl_version_str(raw_version);
  209. }
  210. return crypto_openssl_version_str;
  211. }
  212. static char *crypto_openssl_header_version_str = NULL;
  213. /* Return a human-readable version of the compile-time openssl version
  214. * number. */
  215. const char *
  216. crypto_openssl_get_header_version_str(void)
  217. {
  218. if (crypto_openssl_header_version_str == NULL) {
  219. crypto_openssl_header_version_str =
  220. parse_openssl_version_str(OPENSSL_VERSION_TEXT);
  221. }
  222. return crypto_openssl_header_version_str;
  223. }
  224. /** Make sure that openssl is using its default PRNG. Return 1 if we had to
  225. * adjust it; 0 otherwise. */
  226. static int
  227. crypto_force_rand_ssleay(void)
  228. {
  229. RAND_METHOD *default_method;
  230. default_method = RAND_OpenSSL();
  231. if (RAND_get_rand_method() != default_method) {
  232. log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
  233. "a replacement the OpenSSL RNG. Resetting it to the default "
  234. "implementation.");
  235. RAND_set_rand_method(default_method);
  236. return 1;
  237. }
  238. return 0;
  239. }
  240. /** Set up the siphash key if we haven't already done so. */
  241. int
  242. crypto_init_siphash_key(void)
  243. {
  244. static int have_seeded_siphash = 0;
  245. struct sipkey key;
  246. if (have_seeded_siphash)
  247. return 0;
  248. crypto_rand((char*) &key, sizeof(key));
  249. siphash_set_global_key(&key);
  250. have_seeded_siphash = 1;
  251. return 0;
  252. }
  253. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  254. */
  255. int
  256. crypto_early_init(void)
  257. {
  258. if (!crypto_early_initialized_) {
  259. crypto_early_initialized_ = 1;
  260. ERR_load_crypto_strings();
  261. OpenSSL_add_all_algorithms();
  262. setup_openssl_threading();
  263. unsigned long version_num = OpenSSL_version_num();
  264. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  265. if (version_num == OPENSSL_VERSION_NUMBER &&
  266. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  267. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  268. "(%lx: %s).", version_num, version_str);
  269. } else {
  270. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  271. "version we're running with. If you get weird crashes, that "
  272. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  273. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  274. version_num, version_str);
  275. }
  276. crypto_force_rand_ssleay();
  277. if (crypto_seed_rng() < 0)
  278. return -1;
  279. if (crypto_init_siphash_key() < 0)
  280. return -1;
  281. curve25519_init();
  282. ed25519_init();
  283. }
  284. return 0;
  285. }
  286. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  287. */
  288. int
  289. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  290. {
  291. if (!crypto_global_initialized_) {
  292. if (crypto_early_init() < 0)
  293. return -1;
  294. crypto_global_initialized_ = 1;
  295. if (useAccel > 0) {
  296. #ifdef DISABLE_ENGINES
  297. (void)accelName;
  298. (void)accelDir;
  299. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  300. #else
  301. ENGINE *e = NULL;
  302. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  303. ENGINE_load_builtin_engines();
  304. ENGINE_register_all_complete();
  305. if (accelName) {
  306. if (accelDir) {
  307. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  308. " via path \"%s\".", accelName, accelDir);
  309. e = try_load_engine(accelName, accelDir);
  310. } else {
  311. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  312. " acceleration support.", accelName);
  313. e = ENGINE_by_id(accelName);
  314. }
  315. if (!e) {
  316. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  317. accelName);
  318. } else {
  319. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  320. accelName);
  321. }
  322. }
  323. if (e) {
  324. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  325. " setting default ciphers.");
  326. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  327. }
  328. /* Log, if available, the intersection of the set of algorithms
  329. used by Tor and the set of algorithms available in the engine */
  330. log_engine("RSA", ENGINE_get_default_RSA());
  331. log_engine("DH", ENGINE_get_default_DH());
  332. log_engine("ECDH", ENGINE_get_default_ECDH());
  333. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  334. log_engine("RAND", ENGINE_get_default_RAND());
  335. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  336. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  337. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  338. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  339. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  340. #ifdef NID_aes_128_ctr
  341. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  342. #endif
  343. #ifdef NID_aes_128_gcm
  344. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  345. #endif
  346. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  347. #ifdef NID_aes_256_gcm
  348. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  349. #endif
  350. #endif
  351. } else {
  352. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  353. }
  354. if (crypto_force_rand_ssleay()) {
  355. if (crypto_seed_rng() < 0)
  356. return -1;
  357. }
  358. evaluate_evp_for_aes(-1);
  359. evaluate_ctr_for_aes();
  360. }
  361. return 0;
  362. }
  363. /** Free crypto resources held by this thread. */
  364. void
  365. crypto_thread_cleanup(void)
  366. {
  367. ERR_remove_thread_state(NULL);
  368. }
  369. /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
  370. crypto_pk_t *
  371. crypto_new_pk_from_rsa_(RSA *rsa)
  372. {
  373. crypto_pk_t *env;
  374. tor_assert(rsa);
  375. env = tor_malloc(sizeof(crypto_pk_t));
  376. env->refs = 1;
  377. env->key = rsa;
  378. return env;
  379. }
  380. /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
  381. * crypto_pk_t. */
  382. RSA *
  383. crypto_pk_get_rsa_(crypto_pk_t *env)
  384. {
  385. return env->key;
  386. }
  387. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
  388. * private is set, include the private-key portion of the key. Return a valid
  389. * pointer on success, and NULL on failure. */
  390. MOCK_IMPL(EVP_PKEY *,
  391. crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
  392. {
  393. RSA *key = NULL;
  394. EVP_PKEY *pkey = NULL;
  395. tor_assert(env->key);
  396. if (private) {
  397. if (!(key = RSAPrivateKey_dup(env->key)))
  398. goto error;
  399. } else {
  400. if (!(key = RSAPublicKey_dup(env->key)))
  401. goto error;
  402. }
  403. if (!(pkey = EVP_PKEY_new()))
  404. goto error;
  405. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  406. goto error;
  407. return pkey;
  408. error:
  409. if (pkey)
  410. EVP_PKEY_free(pkey);
  411. if (key)
  412. RSA_free(key);
  413. return NULL;
  414. }
  415. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  416. */
  417. DH *
  418. crypto_dh_get_dh_(crypto_dh_t *dh)
  419. {
  420. return dh->dh;
  421. }
  422. /** Allocate and return storage for a public key. The key itself will not yet
  423. * be set.
  424. */
  425. MOCK_IMPL(crypto_pk_t *,
  426. crypto_pk_new,(void))
  427. {
  428. RSA *rsa;
  429. rsa = RSA_new();
  430. tor_assert(rsa);
  431. return crypto_new_pk_from_rsa_(rsa);
  432. }
  433. /** Release a reference to an asymmetric key; when all the references
  434. * are released, free the key.
  435. */
  436. void
  437. crypto_pk_free(crypto_pk_t *env)
  438. {
  439. if (!env)
  440. return;
  441. if (--env->refs > 0)
  442. return;
  443. tor_assert(env->refs == 0);
  444. if (env->key)
  445. RSA_free(env->key);
  446. tor_free(env);
  447. }
  448. /** Allocate and return a new symmetric cipher using the provided key and iv.
  449. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
  450. * provide NULL in place of either one, it is generated at random.
  451. */
  452. crypto_cipher_t *
  453. crypto_cipher_new_with_iv(const char *key, const char *iv)
  454. {
  455. crypto_cipher_t *env;
  456. env = tor_malloc_zero(sizeof(crypto_cipher_t));
  457. if (key == NULL)
  458. crypto_rand(env->key, CIPHER_KEY_LEN);
  459. else
  460. memcpy(env->key, key, CIPHER_KEY_LEN);
  461. if (iv == NULL)
  462. crypto_rand(env->iv, CIPHER_IV_LEN);
  463. else
  464. memcpy(env->iv, iv, CIPHER_IV_LEN);
  465. env->cipher = aes_new_cipher(env->key, env->iv);
  466. return env;
  467. }
  468. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  469. * zero bytes. */
  470. crypto_cipher_t *
  471. crypto_cipher_new(const char *key)
  472. {
  473. char zeroiv[CIPHER_IV_LEN];
  474. memset(zeroiv, 0, sizeof(zeroiv));
  475. return crypto_cipher_new_with_iv(key, zeroiv);
  476. }
  477. /** Free a symmetric cipher.
  478. */
  479. void
  480. crypto_cipher_free(crypto_cipher_t *env)
  481. {
  482. if (!env)
  483. return;
  484. tor_assert(env->cipher);
  485. aes_cipher_free(env->cipher);
  486. memwipe(env, 0, sizeof(crypto_cipher_t));
  487. tor_free(env);
  488. }
  489. /* public key crypto */
  490. /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
  491. * Return 0 on success, -1 on failure.
  492. */
  493. MOCK_IMPL(int,
  494. crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
  495. {
  496. tor_assert(env);
  497. if (env->key)
  498. RSA_free(env->key);
  499. {
  500. BIGNUM *e = BN_new();
  501. RSA *r = NULL;
  502. if (!e)
  503. goto done;
  504. if (! BN_set_word(e, 65537))
  505. goto done;
  506. r = RSA_new();
  507. if (!r)
  508. goto done;
  509. if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
  510. goto done;
  511. env->key = r;
  512. r = NULL;
  513. done:
  514. if (e)
  515. BN_clear_free(e);
  516. if (r)
  517. RSA_free(r);
  518. }
  519. if (!env->key) {
  520. crypto_log_errors(LOG_WARN, "generating RSA key");
  521. return -1;
  522. }
  523. return 0;
  524. }
  525. /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
  526. * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
  527. * the string is nul-terminated.
  528. */
  529. /* Used here, and used for testing. */
  530. int
  531. crypto_pk_read_private_key_from_string(crypto_pk_t *env,
  532. const char *s, ssize_t len)
  533. {
  534. BIO *b;
  535. tor_assert(env);
  536. tor_assert(s);
  537. tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
  538. /* Create a read-only memory BIO, backed by the string 's' */
  539. b = BIO_new_mem_buf((char*)s, (int)len);
  540. if (!b)
  541. return -1;
  542. if (env->key)
  543. RSA_free(env->key);
  544. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
  545. BIO_free(b);
  546. if (!env->key) {
  547. crypto_log_errors(LOG_WARN, "Error parsing private key");
  548. return -1;
  549. }
  550. return 0;
  551. }
  552. /** Read a PEM-encoded private key from the file named by
  553. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  554. */
  555. int
  556. crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
  557. const char *keyfile)
  558. {
  559. char *contents;
  560. int r;
  561. /* Read the file into a string. */
  562. contents = read_file_to_str(keyfile, 0, NULL);
  563. if (!contents) {
  564. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  565. return -1;
  566. }
  567. /* Try to parse it. */
  568. r = crypto_pk_read_private_key_from_string(env, contents, -1);
  569. memwipe(contents, 0, strlen(contents));
  570. tor_free(contents);
  571. if (r)
  572. return -1; /* read_private_key_from_string already warned, so we don't.*/
  573. /* Make sure it's valid. */
  574. if (crypto_pk_check_key(env) <= 0)
  575. return -1;
  576. return 0;
  577. }
  578. /** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
  579. * success, -1 on failure. */
  580. static int
  581. crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
  582. size_t *len, int is_public)
  583. {
  584. BUF_MEM *buf;
  585. BIO *b;
  586. int r;
  587. tor_assert(env);
  588. tor_assert(env->key);
  589. tor_assert(dest);
  590. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  591. if (!b)
  592. return -1;
  593. /* Now you can treat b as if it were a file. Just use the
  594. * PEM_*_bio_* functions instead of the non-bio variants.
  595. */
  596. if (is_public)
  597. r = PEM_write_bio_RSAPublicKey(b, env->key);
  598. else
  599. r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
  600. if (!r) {
  601. crypto_log_errors(LOG_WARN, "writing RSA key to string");
  602. BIO_free(b);
  603. return -1;
  604. }
  605. BIO_get_mem_ptr(b, &buf);
  606. (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  607. BIO_free(b);
  608. *dest = tor_malloc(buf->length+1);
  609. memcpy(*dest, buf->data, buf->length);
  610. (*dest)[buf->length] = 0; /* nul terminate it */
  611. *len = buf->length;
  612. BUF_MEM_free(buf);
  613. return 0;
  614. }
  615. /** PEM-encode the public key portion of <b>env</b> and write it to a
  616. * newly allocated string. On success, set *<b>dest</b> to the new
  617. * string, *<b>len</b> to the string's length, and return 0. On
  618. * failure, return -1.
  619. */
  620. int
  621. crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
  622. size_t *len)
  623. {
  624. return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
  625. }
  626. /** PEM-encode the private key portion of <b>env</b> and write it to a
  627. * newly allocated string. On success, set *<b>dest</b> to the new
  628. * string, *<b>len</b> to the string's length, and return 0. On
  629. * failure, return -1.
  630. */
  631. int
  632. crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
  633. size_t *len)
  634. {
  635. return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
  636. }
  637. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  638. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  639. * failure.
  640. */
  641. int
  642. crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
  643. size_t len)
  644. {
  645. BIO *b;
  646. tor_assert(env);
  647. tor_assert(src);
  648. tor_assert(len<INT_MAX);
  649. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  650. if (!b)
  651. return -1;
  652. BIO_write(b, src, (int)len);
  653. if (env->key)
  654. RSA_free(env->key);
  655. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  656. BIO_free(b);
  657. if (!env->key) {
  658. crypto_log_errors(LOG_WARN, "reading public key from string");
  659. return -1;
  660. }
  661. return 0;
  662. }
  663. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  664. * PEM-encoded. Return 0 on success, -1 on failure.
  665. */
  666. int
  667. crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
  668. const char *fname)
  669. {
  670. BIO *bio;
  671. char *cp;
  672. long len;
  673. char *s;
  674. int r;
  675. tor_assert(PRIVATE_KEY_OK(env));
  676. if (!(bio = BIO_new(BIO_s_mem())))
  677. return -1;
  678. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  679. == 0) {
  680. crypto_log_errors(LOG_WARN, "writing private key");
  681. BIO_free(bio);
  682. return -1;
  683. }
  684. len = BIO_get_mem_data(bio, &cp);
  685. tor_assert(len >= 0);
  686. s = tor_malloc(len+1);
  687. memcpy(s, cp, len);
  688. s[len]='\0';
  689. r = write_str_to_file(fname, s, 0);
  690. BIO_free(bio);
  691. memwipe(s, 0, strlen(s));
  692. tor_free(s);
  693. return r;
  694. }
  695. /** Return true iff <b>env</b> has a valid key.
  696. */
  697. int
  698. crypto_pk_check_key(crypto_pk_t *env)
  699. {
  700. int r;
  701. tor_assert(env);
  702. r = RSA_check_key(env->key);
  703. if (r <= 0)
  704. crypto_log_errors(LOG_WARN,"checking RSA key");
  705. return r;
  706. }
  707. /** Return true iff <b>key</b> contains the private-key portion of the RSA
  708. * key. */
  709. int
  710. crypto_pk_key_is_private(const crypto_pk_t *key)
  711. {
  712. tor_assert(key);
  713. return PRIVATE_KEY_OK(key);
  714. }
  715. /** Return true iff <b>env</b> contains a public key whose public exponent
  716. * equals 65537.
  717. */
  718. int
  719. crypto_pk_public_exponent_ok(crypto_pk_t *env)
  720. {
  721. tor_assert(env);
  722. tor_assert(env->key);
  723. return BN_is_word(env->key->e, 65537);
  724. }
  725. /** Compare the public-key components of a and b. Return less than 0
  726. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  727. * considered to be less than all non-NULL keys, and equal to itself.
  728. *
  729. * Note that this may leak information about the keys through timing.
  730. */
  731. int
  732. crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  733. {
  734. int result;
  735. char a_is_non_null = (a != NULL) && (a->key != NULL);
  736. char b_is_non_null = (b != NULL) && (b->key != NULL);
  737. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  738. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  739. if (an_argument_is_null)
  740. return result;
  741. tor_assert(PUBLIC_KEY_OK(a));
  742. tor_assert(PUBLIC_KEY_OK(b));
  743. result = BN_cmp((a->key)->n, (b->key)->n);
  744. if (result)
  745. return result;
  746. return BN_cmp((a->key)->e, (b->key)->e);
  747. }
  748. /** Compare the public-key components of a and b. Return non-zero iff
  749. * a==b. A NULL key is considered to be distinct from all non-NULL
  750. * keys, and equal to itself.
  751. *
  752. * Note that this may leak information about the keys through timing.
  753. */
  754. int
  755. crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  756. {
  757. return (crypto_pk_cmp_keys(a, b) == 0);
  758. }
  759. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  760. size_t
  761. crypto_pk_keysize(const crypto_pk_t *env)
  762. {
  763. tor_assert(env);
  764. tor_assert(env->key);
  765. return (size_t) RSA_size((RSA*)env->key);
  766. }
  767. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  768. int
  769. crypto_pk_num_bits(crypto_pk_t *env)
  770. {
  771. tor_assert(env);
  772. tor_assert(env->key);
  773. tor_assert(env->key->n);
  774. return BN_num_bits(env->key->n);
  775. }
  776. /** Increase the reference count of <b>env</b>, and return it.
  777. */
  778. crypto_pk_t *
  779. crypto_pk_dup_key(crypto_pk_t *env)
  780. {
  781. tor_assert(env);
  782. tor_assert(env->key);
  783. env->refs++;
  784. return env;
  785. }
  786. /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
  787. * Returns NULL on failure. */
  788. crypto_pk_t *
  789. crypto_pk_copy_full(crypto_pk_t *env)
  790. {
  791. RSA *new_key;
  792. int privatekey = 0;
  793. tor_assert(env);
  794. tor_assert(env->key);
  795. if (PRIVATE_KEY_OK(env)) {
  796. new_key = RSAPrivateKey_dup(env->key);
  797. privatekey = 1;
  798. } else {
  799. new_key = RSAPublicKey_dup(env->key);
  800. }
  801. if (!new_key) {
  802. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  803. privatekey?"private":"public");
  804. crypto_log_errors(LOG_ERR,
  805. privatekey ? "Duplicating a private key" :
  806. "Duplicating a public key");
  807. tor_fragile_assert();
  808. return NULL;
  809. }
  810. return crypto_new_pk_from_rsa_(new_key);
  811. }
  812. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  813. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  814. * write the result to <b>to</b>, and return the number of bytes
  815. * written. On failure, return -1.
  816. *
  817. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  818. * at least the length of the modulus of <b>env</b>.
  819. */
  820. int
  821. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  822. const char *from, size_t fromlen, int padding)
  823. {
  824. int r;
  825. tor_assert(env);
  826. tor_assert(from);
  827. tor_assert(to);
  828. tor_assert(fromlen<INT_MAX);
  829. tor_assert(tolen >= crypto_pk_keysize(env));
  830. r = RSA_public_encrypt((int)fromlen,
  831. (unsigned char*)from, (unsigned char*)to,
  832. env->key, crypto_get_rsa_padding(padding));
  833. if (r<0) {
  834. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  835. return -1;
  836. }
  837. return r;
  838. }
  839. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  840. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  841. * write the result to <b>to</b>, and return the number of bytes
  842. * written. On failure, return -1.
  843. *
  844. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  845. * at least the length of the modulus of <b>env</b>.
  846. */
  847. int
  848. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  849. size_t tolen,
  850. const char *from, size_t fromlen,
  851. int padding, int warnOnFailure)
  852. {
  853. int r;
  854. tor_assert(env);
  855. tor_assert(from);
  856. tor_assert(to);
  857. tor_assert(env->key);
  858. tor_assert(fromlen<INT_MAX);
  859. tor_assert(tolen >= crypto_pk_keysize(env));
  860. if (!env->key->p)
  861. /* Not a private key */
  862. return -1;
  863. r = RSA_private_decrypt((int)fromlen,
  864. (unsigned char*)from, (unsigned char*)to,
  865. env->key, crypto_get_rsa_padding(padding));
  866. if (r<0) {
  867. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  868. "performing RSA decryption");
  869. return -1;
  870. }
  871. return r;
  872. }
  873. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  874. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  875. * signed data to <b>to</b>, and return the number of bytes written.
  876. * On failure, return -1.
  877. *
  878. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  879. * at least the length of the modulus of <b>env</b>.
  880. */
  881. int
  882. crypto_pk_public_checksig(const crypto_pk_t *env, char *to,
  883. size_t tolen,
  884. const char *from, size_t fromlen)
  885. {
  886. int r;
  887. tor_assert(env);
  888. tor_assert(from);
  889. tor_assert(to);
  890. tor_assert(fromlen < INT_MAX);
  891. tor_assert(tolen >= crypto_pk_keysize(env));
  892. r = RSA_public_decrypt((int)fromlen,
  893. (unsigned char*)from, (unsigned char*)to,
  894. env->key, RSA_PKCS1_PADDING);
  895. if (r<0) {
  896. crypto_log_errors(LOG_INFO, "checking RSA signature");
  897. return -1;
  898. }
  899. return r;
  900. }
  901. /** Check a siglen-byte long signature at <b>sig</b> against
  902. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  903. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  904. * SHA1(data). Else return -1.
  905. */
  906. int
  907. crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
  908. size_t datalen, const char *sig, size_t siglen)
  909. {
  910. char digest[DIGEST_LEN];
  911. char *buf;
  912. size_t buflen;
  913. int r;
  914. tor_assert(env);
  915. tor_assert(data);
  916. tor_assert(sig);
  917. tor_assert(datalen < SIZE_T_CEILING);
  918. tor_assert(siglen < SIZE_T_CEILING);
  919. if (crypto_digest(digest,data,datalen)<0) {
  920. log_warn(LD_BUG, "couldn't compute digest");
  921. return -1;
  922. }
  923. buflen = crypto_pk_keysize(env);
  924. buf = tor_malloc(buflen);
  925. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  926. if (r != DIGEST_LEN) {
  927. log_warn(LD_CRYPTO, "Invalid signature");
  928. tor_free(buf);
  929. return -1;
  930. }
  931. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  932. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  933. tor_free(buf);
  934. return -1;
  935. }
  936. tor_free(buf);
  937. return 0;
  938. }
  939. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  940. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  941. * <b>to</b>, and return the number of bytes written. On failure, return
  942. * -1.
  943. *
  944. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  945. * at least the length of the modulus of <b>env</b>.
  946. */
  947. int
  948. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  949. const char *from, size_t fromlen)
  950. {
  951. int r;
  952. tor_assert(env);
  953. tor_assert(from);
  954. tor_assert(to);
  955. tor_assert(fromlen < INT_MAX);
  956. tor_assert(tolen >= crypto_pk_keysize(env));
  957. if (!env->key->p)
  958. /* Not a private key */
  959. return -1;
  960. r = RSA_private_encrypt((int)fromlen,
  961. (unsigned char*)from, (unsigned char*)to,
  962. (RSA*)env->key, RSA_PKCS1_PADDING);
  963. if (r<0) {
  964. crypto_log_errors(LOG_WARN, "generating RSA signature");
  965. return -1;
  966. }
  967. return r;
  968. }
  969. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  970. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  971. * store it in <b>to</b>. Return the number of bytes written on
  972. * success, and -1 on failure.
  973. *
  974. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  975. * at least the length of the modulus of <b>env</b>.
  976. */
  977. int
  978. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  979. const char *from, size_t fromlen)
  980. {
  981. int r;
  982. char digest[DIGEST_LEN];
  983. if (crypto_digest(digest,from,fromlen)<0)
  984. return -1;
  985. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  986. memwipe(digest, 0, sizeof(digest));
  987. return r;
  988. }
  989. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  990. * bytes of data from <b>from</b>, with padding type 'padding',
  991. * storing the results on <b>to</b>.
  992. *
  993. * Returns the number of bytes written on success, -1 on failure.
  994. *
  995. * The encrypted data consists of:
  996. * - The source data, padded and encrypted with the public key, if the
  997. * padded source data is no longer than the public key, and <b>force</b>
  998. * is false, OR
  999. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  1000. * padded and encrypted with the public key; followed by the rest of
  1001. * the source data encrypted in AES-CTR mode with the symmetric key.
  1002. */
  1003. int
  1004. crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
  1005. char *to, size_t tolen,
  1006. const char *from,
  1007. size_t fromlen,
  1008. int padding, int force)
  1009. {
  1010. int overhead, outlen, r;
  1011. size_t pkeylen, symlen;
  1012. crypto_cipher_t *cipher = NULL;
  1013. char *buf = NULL;
  1014. tor_assert(env);
  1015. tor_assert(from);
  1016. tor_assert(to);
  1017. tor_assert(fromlen < SIZE_T_CEILING);
  1018. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  1019. pkeylen = crypto_pk_keysize(env);
  1020. if (!force && fromlen+overhead <= pkeylen) {
  1021. /* It all fits in a single encrypt. */
  1022. return crypto_pk_public_encrypt(env,to,
  1023. tolen,
  1024. from,fromlen,padding);
  1025. }
  1026. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  1027. tor_assert(tolen >= pkeylen);
  1028. cipher = crypto_cipher_new(NULL); /* generate a new key. */
  1029. buf = tor_malloc(pkeylen+1);
  1030. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  1031. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  1032. /* Length of symmetrically encrypted data. */
  1033. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  1034. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  1035. if (outlen!=(int)pkeylen) {
  1036. goto err;
  1037. }
  1038. r = crypto_cipher_encrypt(cipher, to+outlen,
  1039. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  1040. if (r<0) goto err;
  1041. memwipe(buf, 0, pkeylen);
  1042. tor_free(buf);
  1043. crypto_cipher_free(cipher);
  1044. tor_assert(outlen+symlen < INT_MAX);
  1045. return (int)(outlen + symlen);
  1046. err:
  1047. memwipe(buf, 0, pkeylen);
  1048. tor_free(buf);
  1049. crypto_cipher_free(cipher);
  1050. return -1;
  1051. }
  1052. /** Invert crypto_pk_public_hybrid_encrypt. Returns the number of bytes
  1053. * written on success, -1 on failure. */
  1054. int
  1055. crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
  1056. char *to,
  1057. size_t tolen,
  1058. const char *from,
  1059. size_t fromlen,
  1060. int padding, int warnOnFailure)
  1061. {
  1062. int outlen, r;
  1063. size_t pkeylen;
  1064. crypto_cipher_t *cipher = NULL;
  1065. char *buf = NULL;
  1066. tor_assert(fromlen < SIZE_T_CEILING);
  1067. pkeylen = crypto_pk_keysize(env);
  1068. if (fromlen <= pkeylen) {
  1069. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  1070. warnOnFailure);
  1071. }
  1072. buf = tor_malloc(pkeylen);
  1073. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  1074. warnOnFailure);
  1075. if (outlen<0) {
  1076. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  1077. "Error decrypting public-key data");
  1078. goto err;
  1079. }
  1080. if (outlen < CIPHER_KEY_LEN) {
  1081. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  1082. "No room for a symmetric key");
  1083. goto err;
  1084. }
  1085. cipher = crypto_cipher_new(buf);
  1086. if (!cipher) {
  1087. goto err;
  1088. }
  1089. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  1090. outlen -= CIPHER_KEY_LEN;
  1091. tor_assert(tolen - outlen >= fromlen - pkeylen);
  1092. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  1093. if (r<0)
  1094. goto err;
  1095. memwipe(buf,0,pkeylen);
  1096. tor_free(buf);
  1097. crypto_cipher_free(cipher);
  1098. tor_assert(outlen + fromlen < INT_MAX);
  1099. return (int)(outlen + (fromlen-pkeylen));
  1100. err:
  1101. memwipe(buf,0,pkeylen);
  1102. tor_free(buf);
  1103. crypto_cipher_free(cipher);
  1104. return -1;
  1105. }
  1106. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  1107. * Return -1 on error, or the number of characters used on success.
  1108. */
  1109. int
  1110. crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
  1111. {
  1112. int len;
  1113. unsigned char *buf = NULL;
  1114. len = i2d_RSAPublicKey(pk->key, &buf);
  1115. if (len < 0 || buf == NULL)
  1116. return -1;
  1117. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  1118. OPENSSL_free(buf);
  1119. return -1;
  1120. }
  1121. /* We don't encode directly into 'dest', because that would be illegal
  1122. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  1123. */
  1124. memcpy(dest,buf,len);
  1125. OPENSSL_free(buf);
  1126. return len;
  1127. }
  1128. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  1129. * success and NULL on failure.
  1130. */
  1131. crypto_pk_t *
  1132. crypto_pk_asn1_decode(const char *str, size_t len)
  1133. {
  1134. RSA *rsa;
  1135. unsigned char *buf;
  1136. const unsigned char *cp;
  1137. cp = buf = tor_malloc(len);
  1138. memcpy(buf,str,len);
  1139. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  1140. tor_free(buf);
  1141. if (!rsa) {
  1142. crypto_log_errors(LOG_WARN,"decoding public key");
  1143. return NULL;
  1144. }
  1145. return crypto_new_pk_from_rsa_(rsa);
  1146. }
  1147. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  1148. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  1149. * Return 0 on success, -1 on failure.
  1150. */
  1151. int
  1152. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  1153. {
  1154. unsigned char *buf = NULL;
  1155. int len;
  1156. len = i2d_RSAPublicKey((RSA*)pk->key, &buf);
  1157. if (len < 0 || buf == NULL)
  1158. return -1;
  1159. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  1160. OPENSSL_free(buf);
  1161. return -1;
  1162. }
  1163. OPENSSL_free(buf);
  1164. return 0;
  1165. }
  1166. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  1167. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  1168. int
  1169. crypto_pk_get_all_digests(crypto_pk_t *pk, digests_t *digests_out)
  1170. {
  1171. unsigned char *buf = NULL;
  1172. int len;
  1173. len = i2d_RSAPublicKey(pk->key, &buf);
  1174. if (len < 0 || buf == NULL)
  1175. return -1;
  1176. if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
  1177. OPENSSL_free(buf);
  1178. return -1;
  1179. }
  1180. OPENSSL_free(buf);
  1181. return 0;
  1182. }
  1183. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  1184. * every four characters. */
  1185. void
  1186. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  1187. {
  1188. int n = 0;
  1189. char *end = out+outlen;
  1190. tor_assert(outlen < SIZE_T_CEILING);
  1191. while (*in && out<end) {
  1192. *out++ = *in++;
  1193. if (++n == 4 && *in && out<end) {
  1194. n = 0;
  1195. *out++ = ' ';
  1196. }
  1197. }
  1198. tor_assert(out<end);
  1199. *out = '\0';
  1200. }
  1201. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  1202. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  1203. * space). Return 0 on success, -1 on failure.
  1204. *
  1205. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  1206. * of the public key, converted to hexadecimal, in upper case, with a
  1207. * space after every four digits.
  1208. *
  1209. * If <b>add_space</b> is false, omit the spaces.
  1210. */
  1211. int
  1212. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  1213. {
  1214. char digest[DIGEST_LEN];
  1215. char hexdigest[HEX_DIGEST_LEN+1];
  1216. if (crypto_pk_get_digest(pk, digest)) {
  1217. return -1;
  1218. }
  1219. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  1220. if (add_space) {
  1221. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  1222. } else {
  1223. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  1224. }
  1225. return 0;
  1226. }
  1227. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  1228. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  1229. * bytes of space). Return 0 on success, -1 on failure.
  1230. *
  1231. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  1232. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  1233. * upper case.
  1234. */
  1235. int
  1236. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  1237. {
  1238. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  1239. if (crypto_pk_get_digest(pk, digest)) {
  1240. return -1;
  1241. }
  1242. if (crypto_digest(hashed_digest, digest, DIGEST_LEN)) {
  1243. return -1;
  1244. }
  1245. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  1246. return 0;
  1247. }
  1248. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  1249. * Base64 encoding of the DER representation of the private key as a NUL
  1250. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  1251. * sucess, -1 on failure.
  1252. *
  1253. * It is the caller's responsibility to sanitize and free the resulting buffer.
  1254. */
  1255. int
  1256. crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
  1257. {
  1258. unsigned char *der = NULL;
  1259. int der_len;
  1260. int ret = -1;
  1261. *priv_out = NULL;
  1262. der_len = i2d_RSAPrivateKey(pk->key, &der);
  1263. if (der_len < 0 || der == NULL)
  1264. return ret;
  1265. size_t priv_len = base64_encode_size(der_len, 0) + 1;
  1266. char *priv = tor_malloc_zero(priv_len);
  1267. if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
  1268. *priv_out = priv;
  1269. ret = 0;
  1270. } else {
  1271. tor_free(priv);
  1272. }
  1273. memwipe(der, 0, der_len);
  1274. OPENSSL_free(der);
  1275. return ret;
  1276. }
  1277. /** Given a string containing the Base64 encoded DER representation of the
  1278. * private key <b>str</b>, decode and return the result on success, or NULL
  1279. * on failure.
  1280. */
  1281. crypto_pk_t *
  1282. crypto_pk_base64_decode(const char *str, size_t len)
  1283. {
  1284. crypto_pk_t *pk = NULL;
  1285. char *der = tor_malloc_zero(len + 1);
  1286. int der_len = base64_decode(der, len, str, len);
  1287. if (der_len <= 0) {
  1288. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  1289. goto out;
  1290. }
  1291. const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
  1292. RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
  1293. if (!rsa) {
  1294. crypto_log_errors(LOG_WARN, "decoding private key");
  1295. goto out;
  1296. }
  1297. pk = crypto_new_pk_from_rsa_(rsa);
  1298. /* Make sure it's valid. */
  1299. if (crypto_pk_check_key(pk) <= 0) {
  1300. crypto_pk_free(pk);
  1301. pk = NULL;
  1302. goto out;
  1303. }
  1304. out:
  1305. memwipe(der, 0, len + 1);
  1306. tor_free(der);
  1307. return pk;
  1308. }
  1309. /* symmetric crypto */
  1310. /** Return a pointer to the key set for the cipher in <b>env</b>.
  1311. */
  1312. const char *
  1313. crypto_cipher_get_key(crypto_cipher_t *env)
  1314. {
  1315. return env->key;
  1316. }
  1317. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1318. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1319. * Does not check for failure.
  1320. */
  1321. int
  1322. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  1323. const char *from, size_t fromlen)
  1324. {
  1325. tor_assert(env);
  1326. tor_assert(env->cipher);
  1327. tor_assert(from);
  1328. tor_assert(fromlen);
  1329. tor_assert(to);
  1330. tor_assert(fromlen < SIZE_T_CEILING);
  1331. aes_crypt(env->cipher, from, fromlen, to);
  1332. return 0;
  1333. }
  1334. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1335. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1336. * Does not check for failure.
  1337. */
  1338. int
  1339. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  1340. const char *from, size_t fromlen)
  1341. {
  1342. tor_assert(env);
  1343. tor_assert(from);
  1344. tor_assert(to);
  1345. tor_assert(fromlen < SIZE_T_CEILING);
  1346. aes_crypt(env->cipher, from, fromlen, to);
  1347. return 0;
  1348. }
  1349. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1350. * on success, return 0. Does not check for failure.
  1351. */
  1352. int
  1353. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  1354. {
  1355. tor_assert(len < SIZE_T_CEILING);
  1356. aes_crypt_inplace(env->cipher, buf, len);
  1357. return 0;
  1358. }
  1359. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1360. * <b>key</b> to the buffer in <b>to</b> of length
  1361. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1362. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1363. * number of bytes written, on failure, return -1.
  1364. */
  1365. int
  1366. crypto_cipher_encrypt_with_iv(const char *key,
  1367. char *to, size_t tolen,
  1368. const char *from, size_t fromlen)
  1369. {
  1370. crypto_cipher_t *cipher;
  1371. tor_assert(from);
  1372. tor_assert(to);
  1373. tor_assert(fromlen < INT_MAX);
  1374. if (fromlen < 1)
  1375. return -1;
  1376. if (tolen < fromlen + CIPHER_IV_LEN)
  1377. return -1;
  1378. cipher = crypto_cipher_new_with_iv(key, NULL);
  1379. memcpy(to, cipher->iv, CIPHER_IV_LEN);
  1380. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1381. crypto_cipher_free(cipher);
  1382. return (int)(fromlen + CIPHER_IV_LEN);
  1383. }
  1384. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1385. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  1386. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1387. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1388. * number of bytes written, on failure, return -1.
  1389. */
  1390. int
  1391. crypto_cipher_decrypt_with_iv(const char *key,
  1392. char *to, size_t tolen,
  1393. const char *from, size_t fromlen)
  1394. {
  1395. crypto_cipher_t *cipher;
  1396. tor_assert(key);
  1397. tor_assert(from);
  1398. tor_assert(to);
  1399. tor_assert(fromlen < INT_MAX);
  1400. if (fromlen <= CIPHER_IV_LEN)
  1401. return -1;
  1402. if (tolen < fromlen - CIPHER_IV_LEN)
  1403. return -1;
  1404. cipher = crypto_cipher_new_with_iv(key, from);
  1405. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1406. crypto_cipher_free(cipher);
  1407. return (int)(fromlen - CIPHER_IV_LEN);
  1408. }
  1409. /* SHA-1 */
  1410. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  1411. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1412. * Return 0 on success, 1 on failure.
  1413. */
  1414. int
  1415. crypto_digest(char *digest, const char *m, size_t len)
  1416. {
  1417. tor_assert(m);
  1418. tor_assert(digest);
  1419. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1420. }
  1421. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1422. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  1423. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1424. int
  1425. crypto_digest256(char *digest, const char *m, size_t len,
  1426. digest_algorithm_t algorithm)
  1427. {
  1428. tor_assert(m);
  1429. tor_assert(digest);
  1430. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1431. if (algorithm == DIGEST_SHA256)
  1432. return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1433. else
  1434. return (sha3_256((uint8_t *)digest, DIGEST256_LEN, (const uint8_t *)m, len) == -1);
  1435. }
  1436. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1437. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  1438. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1439. int
  1440. crypto_digest512(char *digest, const char *m, size_t len,
  1441. digest_algorithm_t algorithm)
  1442. {
  1443. tor_assert(m);
  1444. tor_assert(digest);
  1445. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1446. if (algorithm == DIGEST_SHA512)
  1447. return (SHA512((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1448. else
  1449. return (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len) == -1);
  1450. }
  1451. /** Set the digests_t in <b>ds_out</b> to contain every digest on the
  1452. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  1453. * success, -1 on failure. */
  1454. int
  1455. crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
  1456. {
  1457. int i;
  1458. tor_assert(ds_out);
  1459. memset(ds_out, 0, sizeof(*ds_out));
  1460. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  1461. return -1;
  1462. for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
  1463. switch (i) {
  1464. case DIGEST_SHA256: /* FALLSTHROUGH */
  1465. case DIGEST_SHA3_256:
  1466. if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
  1467. return -1;
  1468. break;
  1469. case DIGEST_SHA512:
  1470. case DIGEST_SHA3_512: /* FALLSTHROUGH */
  1471. if (crypto_digest512(ds_out->d[i], m, len, i) < 0)
  1472. return -1;
  1473. break;
  1474. default:
  1475. return -1;
  1476. }
  1477. }
  1478. return 0;
  1479. }
  1480. /** Return the name of an algorithm, as used in directory documents. */
  1481. const char *
  1482. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  1483. {
  1484. switch (alg) {
  1485. case DIGEST_SHA1:
  1486. return "sha1";
  1487. case DIGEST_SHA256:
  1488. return "sha256";
  1489. case DIGEST_SHA512:
  1490. return "sha512";
  1491. case DIGEST_SHA3_256:
  1492. return "sha3-256";
  1493. case DIGEST_SHA3_512:
  1494. return "sha3-512";
  1495. default:
  1496. tor_fragile_assert();
  1497. return "??unknown_digest??";
  1498. }
  1499. }
  1500. /** Given the name of a digest algorithm, return its integer value, or -1 if
  1501. * the name is not recognized. */
  1502. int
  1503. crypto_digest_algorithm_parse_name(const char *name)
  1504. {
  1505. if (!strcmp(name, "sha1"))
  1506. return DIGEST_SHA1;
  1507. else if (!strcmp(name, "sha256"))
  1508. return DIGEST_SHA256;
  1509. else if (!strcmp(name, "sha512"))
  1510. return DIGEST_SHA512;
  1511. else if (!strcmp(name, "sha3-256"))
  1512. return DIGEST_SHA3_256;
  1513. else if (!strcmp(name, "sha3-512"))
  1514. return DIGEST_SHA3_512;
  1515. else
  1516. return -1;
  1517. }
  1518. /** Given an algorithm, return the digest length in bytes. */
  1519. static inline size_t
  1520. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  1521. {
  1522. switch (alg) {
  1523. case DIGEST_SHA1:
  1524. return DIGEST_LEN;
  1525. case DIGEST_SHA256:
  1526. return DIGEST256_LEN;
  1527. case DIGEST_SHA512:
  1528. return DIGEST512_LEN;
  1529. case DIGEST_SHA3_256:
  1530. return DIGEST256_LEN;
  1531. case DIGEST_SHA3_512:
  1532. return DIGEST512_LEN;
  1533. default:
  1534. tor_assert(0);
  1535. }
  1536. }
  1537. /** Intermediate information about the digest of a stream of data. */
  1538. struct crypto_digest_t {
  1539. union {
  1540. SHA_CTX sha1; /**< state for SHA1 */
  1541. SHA256_CTX sha2; /**< state for SHA256 */
  1542. SHA512_CTX sha512; /**< state for SHA512 */
  1543. keccak_state sha3; /**< state for SHA3-[256,512] */
  1544. } d; /**< State for the digest we're using. Only one member of the
  1545. * union is usable, depending on the value of <b>algorithm</b>. */
  1546. digest_algorithm_bitfield_t algorithm : 8; /**< Which algorithm is in use? */
  1547. };
  1548. /** Allocate and return a new digest object to compute SHA1 digests.
  1549. */
  1550. crypto_digest_t *
  1551. crypto_digest_new(void)
  1552. {
  1553. crypto_digest_t *r;
  1554. r = tor_malloc(sizeof(crypto_digest_t));
  1555. SHA1_Init(&r->d.sha1);
  1556. r->algorithm = DIGEST_SHA1;
  1557. return r;
  1558. }
  1559. /** Allocate and return a new digest object to compute 256-bit digests
  1560. * using <b>algorithm</b>. */
  1561. crypto_digest_t *
  1562. crypto_digest256_new(digest_algorithm_t algorithm)
  1563. {
  1564. crypto_digest_t *r;
  1565. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1566. r = tor_malloc(sizeof(crypto_digest_t));
  1567. if (algorithm == DIGEST_SHA256)
  1568. SHA256_Init(&r->d.sha2);
  1569. else
  1570. keccak_digest_init(&r->d.sha3, 256);
  1571. r->algorithm = algorithm;
  1572. return r;
  1573. }
  1574. /** Allocate and return a new digest object to compute 512-bit digests
  1575. * using <b>algorithm</b>. */
  1576. crypto_digest_t *
  1577. crypto_digest512_new(digest_algorithm_t algorithm)
  1578. {
  1579. crypto_digest_t *r;
  1580. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1581. r = tor_malloc(sizeof(crypto_digest_t));
  1582. if (algorithm == DIGEST_SHA512)
  1583. SHA512_Init(&r->d.sha512);
  1584. else
  1585. keccak_digest_init(&r->d.sha3, 512);
  1586. r->algorithm = algorithm;
  1587. return r;
  1588. }
  1589. /** Deallocate a digest object.
  1590. */
  1591. void
  1592. crypto_digest_free(crypto_digest_t *digest)
  1593. {
  1594. if (!digest)
  1595. return;
  1596. memwipe(digest, 0, sizeof(crypto_digest_t));
  1597. tor_free(digest);
  1598. }
  1599. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1600. */
  1601. void
  1602. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  1603. size_t len)
  1604. {
  1605. tor_assert(digest);
  1606. tor_assert(data);
  1607. /* Using the SHA*_*() calls directly means we don't support doing
  1608. * SHA in hardware. But so far the delay of getting the question
  1609. * to the hardware, and hearing the answer, is likely higher than
  1610. * just doing it ourselves. Hashes are fast.
  1611. */
  1612. switch (digest->algorithm) {
  1613. case DIGEST_SHA1:
  1614. SHA1_Update(&digest->d.sha1, (void*)data, len);
  1615. break;
  1616. case DIGEST_SHA256:
  1617. SHA256_Update(&digest->d.sha2, (void*)data, len);
  1618. break;
  1619. case DIGEST_SHA512:
  1620. SHA512_Update(&digest->d.sha512, (void*)data, len);
  1621. break;
  1622. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1623. case DIGEST_SHA3_512:
  1624. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  1625. break;
  1626. default:
  1627. tor_fragile_assert();
  1628. break;
  1629. }
  1630. }
  1631. /** Compute the hash of the data that has been passed to the digest
  1632. * object; write the first out_len bytes of the result to <b>out</b>.
  1633. * <b>out_len</b> must be \<= DIGEST512_LEN.
  1634. */
  1635. void
  1636. crypto_digest_get_digest(crypto_digest_t *digest,
  1637. char *out, size_t out_len)
  1638. {
  1639. unsigned char r[DIGEST512_LEN];
  1640. crypto_digest_t tmpenv;
  1641. tor_assert(digest);
  1642. tor_assert(out);
  1643. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  1644. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  1645. * short output buffers by truncating appropriately. */
  1646. if (digest->algorithm == DIGEST_SHA3_256 ||
  1647. digest->algorithm == DIGEST_SHA3_512) {
  1648. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  1649. return;
  1650. }
  1651. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  1652. memcpy(&tmpenv, digest, sizeof(crypto_digest_t));
  1653. switch (digest->algorithm) {
  1654. case DIGEST_SHA1:
  1655. SHA1_Final(r, &tmpenv.d.sha1);
  1656. break;
  1657. case DIGEST_SHA256:
  1658. SHA256_Final(r, &tmpenv.d.sha2);
  1659. break;
  1660. case DIGEST_SHA512:
  1661. SHA512_Final(r, &tmpenv.d.sha512);
  1662. break;
  1663. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1664. case DIGEST_SHA3_512:
  1665. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  1666. tor_assert(0); /* This is fatal, because it should never happen. */
  1667. default:
  1668. log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
  1669. /* If fragile_assert is not enabled, then we should at least not
  1670. * leak anything. */
  1671. memwipe(r, 0xff, sizeof(r));
  1672. memwipe(&tmpenv, 0, sizeof(crypto_digest_t));
  1673. tor_fragile_assert();
  1674. break;
  1675. }
  1676. memcpy(out, r, out_len);
  1677. memwipe(r, 0, sizeof(r));
  1678. }
  1679. /** Allocate and return a new digest object with the same state as
  1680. * <b>digest</b>
  1681. */
  1682. crypto_digest_t *
  1683. crypto_digest_dup(const crypto_digest_t *digest)
  1684. {
  1685. crypto_digest_t *r;
  1686. tor_assert(digest);
  1687. r = tor_malloc(sizeof(crypto_digest_t));
  1688. memcpy(r,digest,sizeof(crypto_digest_t));
  1689. return r;
  1690. }
  1691. /** Replace the state of the digest object <b>into</b> with the state
  1692. * of the digest object <b>from</b>.
  1693. */
  1694. void
  1695. crypto_digest_assign(crypto_digest_t *into,
  1696. const crypto_digest_t *from)
  1697. {
  1698. tor_assert(into);
  1699. tor_assert(from);
  1700. memcpy(into,from,sizeof(crypto_digest_t));
  1701. }
  1702. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1703. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  1704. * plus the optional string <b>append</b>, computed with the algorithm
  1705. * <b>alg</b>.
  1706. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  1707. void
  1708. crypto_digest_smartlist(char *digest_out, size_t len_out,
  1709. const smartlist_t *lst,
  1710. const char *append,
  1711. digest_algorithm_t alg)
  1712. {
  1713. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  1714. }
  1715. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1716. * at <b>digest_out</b> to the hash of the concatenation of: the
  1717. * optional string <b>prepend</b>, those strings,
  1718. * and the optional string <b>append</b>, computed with the algorithm
  1719. * <b>alg</b>.
  1720. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  1721. void
  1722. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  1723. const char *prepend,
  1724. const smartlist_t *lst,
  1725. const char *append,
  1726. digest_algorithm_t alg)
  1727. {
  1728. crypto_digest_t *d = NULL;
  1729. switch (alg) {
  1730. case DIGEST_SHA1:
  1731. d = crypto_digest_new();
  1732. break;
  1733. case DIGEST_SHA256: /* FALLSTHROUGH */
  1734. case DIGEST_SHA3_256:
  1735. d = crypto_digest256_new(alg);
  1736. break;
  1737. case DIGEST_SHA512: /* FALLSTHROUGH */
  1738. case DIGEST_SHA3_512:
  1739. d = crypto_digest512_new(alg);
  1740. break;
  1741. default:
  1742. log_warn(LD_BUG, "Called with unknown algorithm %d", alg);
  1743. /* If fragile_assert is not enabled, wipe output and return
  1744. * without running any calculations */
  1745. memwipe(digest_out, 0xff, len_out);
  1746. tor_fragile_assert();
  1747. goto free;
  1748. }
  1749. if (prepend)
  1750. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  1751. SMARTLIST_FOREACH(lst, const char *, cp,
  1752. crypto_digest_add_bytes(d, cp, strlen(cp)));
  1753. if (append)
  1754. crypto_digest_add_bytes(d, append, strlen(append));
  1755. crypto_digest_get_digest(d, digest_out, len_out);
  1756. free:
  1757. crypto_digest_free(d);
  1758. }
  1759. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1760. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  1761. * result in <b>hmac_out</b>. Asserts on failure.
  1762. */
  1763. void
  1764. crypto_hmac_sha256(char *hmac_out,
  1765. const char *key, size_t key_len,
  1766. const char *msg, size_t msg_len)
  1767. {
  1768. unsigned char *rv = NULL;
  1769. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  1770. tor_assert(key_len < INT_MAX);
  1771. tor_assert(msg_len < INT_MAX);
  1772. tor_assert(hmac_out);
  1773. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1774. (unsigned char*)hmac_out, NULL);
  1775. tor_assert(rv);
  1776. }
  1777. /* DH */
  1778. /** Our DH 'g' parameter */
  1779. #define DH_GENERATOR 2
  1780. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  1781. static BIGNUM *dh_param_p = NULL;
  1782. /** Shared P parameter for our TLS DH key exchanges. */
  1783. static BIGNUM *dh_param_p_tls = NULL;
  1784. /** Shared G parameter for our DH key exchanges. */
  1785. static BIGNUM *dh_param_g = NULL;
  1786. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  1787. * modulus. */
  1788. void
  1789. crypto_set_tls_dh_prime(void)
  1790. {
  1791. BIGNUM *tls_prime = NULL;
  1792. int r;
  1793. /* If the space is occupied, free the previous TLS DH prime */
  1794. if (dh_param_p_tls) {
  1795. BN_clear_free(dh_param_p_tls);
  1796. dh_param_p_tls = NULL;
  1797. }
  1798. tls_prime = BN_new();
  1799. tor_assert(tls_prime);
  1800. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  1801. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  1802. * prime.
  1803. */
  1804. r = BN_hex2bn(&tls_prime,
  1805. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  1806. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  1807. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  1808. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  1809. "B0E7393E0F24218EB3");
  1810. tor_assert(r);
  1811. tor_assert(tls_prime);
  1812. dh_param_p_tls = tls_prime;
  1813. }
  1814. /** Initialize dh_param_p and dh_param_g if they are not already
  1815. * set. */
  1816. static void
  1817. init_dh_param(void)
  1818. {
  1819. BIGNUM *circuit_dh_prime, *generator;
  1820. int r;
  1821. if (dh_param_p && dh_param_g)
  1822. return;
  1823. circuit_dh_prime = BN_new();
  1824. generator = BN_new();
  1825. tor_assert(circuit_dh_prime && generator);
  1826. /* Set our generator for all DH parameters */
  1827. r = BN_set_word(generator, DH_GENERATOR);
  1828. tor_assert(r);
  1829. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1830. supposedly it equals:
  1831. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1832. */
  1833. r = BN_hex2bn(&circuit_dh_prime,
  1834. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1835. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1836. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1837. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1838. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1839. tor_assert(r);
  1840. /* Set the new values as the global DH parameters. */
  1841. dh_param_p = circuit_dh_prime;
  1842. dh_param_g = generator;
  1843. if (!dh_param_p_tls) {
  1844. crypto_set_tls_dh_prime();
  1845. }
  1846. }
  1847. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  1848. * handshake. Since we exponentiate by this value, choosing a smaller one
  1849. * lets our handhake go faster.
  1850. */
  1851. #define DH_PRIVATE_KEY_BITS 320
  1852. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  1853. * failure.
  1854. */
  1855. crypto_dh_t *
  1856. crypto_dh_new(int dh_type)
  1857. {
  1858. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  1859. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  1860. dh_type == DH_TYPE_REND);
  1861. if (!dh_param_p)
  1862. init_dh_param();
  1863. if (!(res->dh = DH_new()))
  1864. goto err;
  1865. if (dh_type == DH_TYPE_TLS) {
  1866. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  1867. goto err;
  1868. } else {
  1869. if (!(res->dh->p = BN_dup(dh_param_p)))
  1870. goto err;
  1871. }
  1872. if (!(res->dh->g = BN_dup(dh_param_g)))
  1873. goto err;
  1874. res->dh->length = DH_PRIVATE_KEY_BITS;
  1875. return res;
  1876. err:
  1877. crypto_log_errors(LOG_WARN, "creating DH object");
  1878. if (res->dh) DH_free(res->dh); /* frees p and g too */
  1879. tor_free(res);
  1880. return NULL;
  1881. }
  1882. /** Return a copy of <b>dh</b>, sharing its internal state. */
  1883. crypto_dh_t *
  1884. crypto_dh_dup(const crypto_dh_t *dh)
  1885. {
  1886. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  1887. tor_assert(dh);
  1888. tor_assert(dh->dh);
  1889. dh_new->dh = dh->dh;
  1890. DH_up_ref(dh->dh);
  1891. return dh_new;
  1892. }
  1893. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1894. */
  1895. int
  1896. crypto_dh_get_bytes(crypto_dh_t *dh)
  1897. {
  1898. tor_assert(dh);
  1899. return DH_size(dh->dh);
  1900. }
  1901. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1902. * success, -1 on failure.
  1903. */
  1904. int
  1905. crypto_dh_generate_public(crypto_dh_t *dh)
  1906. {
  1907. again:
  1908. if (!DH_generate_key(dh->dh)) {
  1909. crypto_log_errors(LOG_WARN, "generating DH key");
  1910. return -1;
  1911. }
  1912. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  1913. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1914. "the-universe chances really do happen. Trying again.");
  1915. /* Free and clear the keys, so OpenSSL will actually try again. */
  1916. BN_clear_free(dh->dh->pub_key);
  1917. BN_clear_free(dh->dh->priv_key);
  1918. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1919. goto again;
  1920. }
  1921. return 0;
  1922. }
  1923. /** Generate g^x as necessary, and write the g^x for the key exchange
  1924. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1925. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1926. */
  1927. int
  1928. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  1929. {
  1930. int bytes;
  1931. tor_assert(dh);
  1932. if (!dh->dh->pub_key) {
  1933. if (crypto_dh_generate_public(dh)<0)
  1934. return -1;
  1935. }
  1936. tor_assert(dh->dh->pub_key);
  1937. bytes = BN_num_bytes(dh->dh->pub_key);
  1938. tor_assert(bytes >= 0);
  1939. if (pubkey_len < (size_t)bytes) {
  1940. log_warn(LD_CRYPTO,
  1941. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1942. (int) pubkey_len, bytes);
  1943. return -1;
  1944. }
  1945. memset(pubkey, 0, pubkey_len);
  1946. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1947. return 0;
  1948. }
  1949. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  1950. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1951. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1952. */
  1953. static int
  1954. tor_check_dh_key(int severity, BIGNUM *bn)
  1955. {
  1956. BIGNUM *x;
  1957. char *s;
  1958. tor_assert(bn);
  1959. x = BN_new();
  1960. tor_assert(x);
  1961. if (!dh_param_p)
  1962. init_dh_param();
  1963. BN_set_word(x, 1);
  1964. if (BN_cmp(bn,x)<=0) {
  1965. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  1966. goto err;
  1967. }
  1968. BN_copy(x,dh_param_p);
  1969. BN_sub_word(x, 1);
  1970. if (BN_cmp(bn,x)>=0) {
  1971. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  1972. goto err;
  1973. }
  1974. BN_clear_free(x);
  1975. return 0;
  1976. err:
  1977. BN_clear_free(x);
  1978. s = BN_bn2hex(bn);
  1979. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1980. OPENSSL_free(s);
  1981. return -1;
  1982. }
  1983. #undef MIN
  1984. #define MIN(a,b) ((a)<(b)?(a):(b))
  1985. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1986. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1987. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1988. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1989. * or -1 on failure.
  1990. *
  1991. * (We generate key material by computing
  1992. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1993. * where || is concatenation.)
  1994. */
  1995. ssize_t
  1996. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  1997. const char *pubkey, size_t pubkey_len,
  1998. char *secret_out, size_t secret_bytes_out)
  1999. {
  2000. char *secret_tmp = NULL;
  2001. BIGNUM *pubkey_bn = NULL;
  2002. size_t secret_len=0, secret_tmp_len=0;
  2003. int result=0;
  2004. tor_assert(dh);
  2005. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  2006. tor_assert(pubkey_len < INT_MAX);
  2007. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  2008. (int)pubkey_len, NULL)))
  2009. goto error;
  2010. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  2011. /* Check for invalid public keys. */
  2012. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  2013. goto error;
  2014. }
  2015. secret_tmp_len = crypto_dh_get_bytes(dh);
  2016. secret_tmp = tor_malloc(secret_tmp_len);
  2017. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  2018. if (result < 0) {
  2019. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  2020. goto error;
  2021. }
  2022. secret_len = result;
  2023. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  2024. (uint8_t*)secret_out, secret_bytes_out)<0)
  2025. goto error;
  2026. secret_len = secret_bytes_out;
  2027. goto done;
  2028. error:
  2029. result = -1;
  2030. done:
  2031. crypto_log_errors(LOG_WARN, "completing DH handshake");
  2032. if (pubkey_bn)
  2033. BN_clear_free(pubkey_bn);
  2034. if (secret_tmp) {
  2035. memwipe(secret_tmp, 0, secret_tmp_len);
  2036. tor_free(secret_tmp);
  2037. }
  2038. if (result < 0)
  2039. return result;
  2040. else
  2041. return secret_len;
  2042. }
  2043. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  2044. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  2045. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  2046. * H(K | [00]) | H(K | [01]) | ....
  2047. *
  2048. * This is the key expansion algorithm used in the "TAP" circuit extension
  2049. * mechanism; it shouldn't be used for new protocols.
  2050. *
  2051. * Return 0 on success, -1 on failure.
  2052. */
  2053. int
  2054. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  2055. uint8_t *key_out, size_t key_out_len)
  2056. {
  2057. int i, r = -1;
  2058. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  2059. uint8_t digest[DIGEST_LEN];
  2060. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2061. tor_assert(key_out_len <= DIGEST_LEN*256);
  2062. memcpy(tmp, key_in, key_in_len);
  2063. for (cp = key_out, i=0; cp < key_out+key_out_len;
  2064. ++i, cp += DIGEST_LEN) {
  2065. tmp[key_in_len] = i;
  2066. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
  2067. goto exit;
  2068. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  2069. }
  2070. r = 0;
  2071. exit:
  2072. memwipe(tmp, 0, key_in_len+1);
  2073. tor_free(tmp);
  2074. memwipe(digest, 0, sizeof(digest));
  2075. return r;
  2076. }
  2077. /** Expand some secret key material according to RFC5869, using SHA256 as the
  2078. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  2079. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  2080. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  2081. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  2082. * bytes to <b>key_out</b> and return 0. Assert on failure.
  2083. */
  2084. int
  2085. crypto_expand_key_material_rfc5869_sha256(
  2086. const uint8_t *key_in, size_t key_in_len,
  2087. const uint8_t *salt_in, size_t salt_in_len,
  2088. const uint8_t *info_in, size_t info_in_len,
  2089. uint8_t *key_out, size_t key_out_len)
  2090. {
  2091. uint8_t prk[DIGEST256_LEN];
  2092. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  2093. uint8_t mac[DIGEST256_LEN];
  2094. int i;
  2095. uint8_t *outp;
  2096. size_t tmp_len;
  2097. crypto_hmac_sha256((char*)prk,
  2098. (const char*)salt_in, salt_in_len,
  2099. (const char*)key_in, key_in_len);
  2100. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2101. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  2102. tor_assert(info_in_len <= 128);
  2103. memset(tmp, 0, sizeof(tmp));
  2104. outp = key_out;
  2105. i = 1;
  2106. while (key_out_len) {
  2107. size_t n;
  2108. if (i > 1) {
  2109. memcpy(tmp, mac, DIGEST256_LEN);
  2110. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  2111. tmp[DIGEST256_LEN+info_in_len] = i;
  2112. tmp_len = DIGEST256_LEN + info_in_len + 1;
  2113. } else {
  2114. memcpy(tmp, info_in, info_in_len);
  2115. tmp[info_in_len] = i;
  2116. tmp_len = info_in_len + 1;
  2117. }
  2118. crypto_hmac_sha256((char*)mac,
  2119. (const char*)prk, DIGEST256_LEN,
  2120. (const char*)tmp, tmp_len);
  2121. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  2122. memcpy(outp, mac, n);
  2123. key_out_len -= n;
  2124. outp += n;
  2125. ++i;
  2126. }
  2127. memwipe(tmp, 0, sizeof(tmp));
  2128. memwipe(mac, 0, sizeof(mac));
  2129. return 0;
  2130. }
  2131. /** Free a DH key exchange object.
  2132. */
  2133. void
  2134. crypto_dh_free(crypto_dh_t *dh)
  2135. {
  2136. if (!dh)
  2137. return;
  2138. tor_assert(dh->dh);
  2139. DH_free(dh->dh);
  2140. tor_free(dh);
  2141. }
  2142. /* random numbers */
  2143. /** How many bytes of entropy we add at once.
  2144. *
  2145. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  2146. * work for us too. */
  2147. #define ADD_ENTROPY 32
  2148. /** Set the seed of the weak RNG to a random value. */
  2149. void
  2150. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  2151. {
  2152. unsigned seed;
  2153. crypto_rand((void*)&seed, sizeof(seed));
  2154. tor_init_weak_random(rng, seed);
  2155. }
  2156. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2157. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  2158. * failure. A maximum request size of 256 bytes is imposed.
  2159. */
  2160. static int
  2161. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  2162. {
  2163. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2164. #if defined(_WIN32)
  2165. static int provider_set = 0;
  2166. static HCRYPTPROV provider;
  2167. if (!provider_set) {
  2168. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  2169. CRYPT_VERIFYCONTEXT)) {
  2170. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  2171. return -1;
  2172. }
  2173. provider_set = 1;
  2174. }
  2175. if (!CryptGenRandom(provider, out_len, out)) {
  2176. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  2177. return -1;
  2178. }
  2179. return 0;
  2180. #elif defined(__linux__) && defined(SYS_getrandom)
  2181. static int getrandom_works = 1; /* Be optimitic about our chances... */
  2182. /* getrandom() isn't as straight foward as getentropy(), and has
  2183. * no glibc wrapper.
  2184. *
  2185. * As far as I can tell from getrandom(2) and the source code, the
  2186. * requests we issue will always succeed (though it will block on the
  2187. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  2188. * GRND_NONBLOCK and the request is <= 256 bytes.
  2189. *
  2190. * The manpage is unclear on what happens if a signal interrupts the call
  2191. * while the request is blocked due to lack of entropy....
  2192. *
  2193. * We optimistically assume that getrandom() is available and functional
  2194. * because it is the way of the future, and 2 branch mispredicts pale in
  2195. * comparision to the overheads involved with failing to open
  2196. * /dev/srandom followed by opening and reading from /dev/urandom.
  2197. */
  2198. if (PREDICT_LIKELY(getrandom_works)) {
  2199. long ret;
  2200. /* A flag of '0' here means to read from '/dev/urandom', and to
  2201. * block if insufficient entropy is available to service the
  2202. * request.
  2203. */
  2204. const unsigned int flags = 0;
  2205. do {
  2206. ret = syscall(SYS_getrandom, out, out_len, flags);
  2207. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  2208. if (PREDICT_UNLIKELY(ret == -1)) {
  2209. tor_assert(errno != EAGAIN);
  2210. tor_assert(errno != EINTR);
  2211. /* Probably ENOSYS. */
  2212. log_warn(LD_CRYPTO, "Can't get entropy from getrandom().");
  2213. getrandom_works = 0; /* Don't bother trying again. */
  2214. return -1;
  2215. }
  2216. tor_assert(ret == (long)out_len);
  2217. return 0;
  2218. }
  2219. return -1; /* getrandom() previously failed unexpectedly. */
  2220. #elif defined(HAVE_GETENTROPY)
  2221. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  2222. * the only gotcha is that requests are limited to 256 bytes.
  2223. */
  2224. return getentropy(out, out_len);
  2225. #else
  2226. (void) out;
  2227. #endif
  2228. /* This platform doesn't have a supported syscall based random. */
  2229. return -1;
  2230. }
  2231. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2232. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  2233. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  2234. * is imposed.
  2235. */
  2236. static int
  2237. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  2238. {
  2239. #ifdef _WIN32
  2240. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  2241. (void)out;
  2242. (void)out_len;
  2243. return -1;
  2244. #else
  2245. static const char *filenames[] = {
  2246. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  2247. };
  2248. int fd, i;
  2249. size_t n;
  2250. for (i = 0; filenames[i]; ++i) {
  2251. log_debug(LD_FS, "Opening %s for entropy", filenames[i]);
  2252. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  2253. if (fd<0) continue;
  2254. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  2255. n = read_all(fd, (char*)out, out_len, 0);
  2256. close(fd);
  2257. if (n != out_len) {
  2258. log_warn(LD_CRYPTO,
  2259. "Error reading from entropy source (read only %lu bytes).",
  2260. (unsigned long)n);
  2261. return -1;
  2262. }
  2263. return 0;
  2264. }
  2265. return -1;
  2266. #endif
  2267. }
  2268. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2269. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  2270. * request size of 256 bytes is imposed.
  2271. */
  2272. static int
  2273. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  2274. {
  2275. static const size_t sanity_min_size = 16;
  2276. static const int max_attempts = 3;
  2277. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2278. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  2279. * zero filling the buffer and ensuring that it actually was at least
  2280. * partially modified.
  2281. *
  2282. * Checking that any individual byte is non-zero seems like it would
  2283. * fail too often (p = out_len * 1/256) for comfort, but this is an
  2284. * "adjust according to taste" sort of check.
  2285. */
  2286. memwipe(out, 0, out_len);
  2287. for (int i = 0; i < max_attempts; i++) {
  2288. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  2289. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  2290. /* Try to use the less-favored mechanism to get strong entropy. */
  2291. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  2292. /* Welp, we tried. Hopefully the calling code terminates the process
  2293. * since we're basically boned without good entropy.
  2294. */
  2295. log_warn(LD_CRYPTO,
  2296. "Cannot get strong entropy: no entropy source found.");
  2297. return -1;
  2298. }
  2299. }
  2300. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  2301. return 0;
  2302. }
  2303. /* We tried max_attempts times to fill a buffer >= 128 bits long,
  2304. * and each time it returned all '0's. Either the system entropy
  2305. * source is busted, or the user should go out and buy a ticket to
  2306. * every lottery on the planet.
  2307. */
  2308. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  2309. return -1;
  2310. }
  2311. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2312. * storing it into <b>out</b>.
  2313. */
  2314. void
  2315. crypto_strongest_rand(uint8_t *out, size_t out_len)
  2316. {
  2317. #define DLEN SHA512_DIGEST_LENGTH
  2318. /* We're going to hash DLEN bytes from the system RNG together with some
  2319. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  2320. */
  2321. uint8_t inp[DLEN*2];
  2322. uint8_t tmp[DLEN];
  2323. tor_assert(out);
  2324. while (out_len) {
  2325. crypto_rand((char*) inp, DLEN);
  2326. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  2327. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  2328. "important key. Exiting.");
  2329. /* Die with an assertion so we get a stack trace. */
  2330. tor_assert(0);
  2331. }
  2332. if (out_len >= DLEN) {
  2333. SHA512(inp, sizeof(inp), out);
  2334. out += DLEN;
  2335. out_len -= DLEN;
  2336. } else {
  2337. SHA512(inp, sizeof(inp), tmp);
  2338. memcpy(out, tmp, out_len);
  2339. break;
  2340. }
  2341. }
  2342. memwipe(tmp, 0, sizeof(tmp));
  2343. memwipe(inp, 0, sizeof(inp));
  2344. #undef DLEN
  2345. }
  2346. /** Seed OpenSSL's random number generator with bytes from the operating
  2347. * system. Return 0 on success, -1 on failure.
  2348. */
  2349. int
  2350. crypto_seed_rng(void)
  2351. {
  2352. int rand_poll_ok = 0, load_entropy_ok = 0;
  2353. uint8_t buf[ADD_ENTROPY];
  2354. /* OpenSSL has a RAND_poll function that knows about more kinds of
  2355. * entropy than we do. We'll try calling that, *and* calling our own entropy
  2356. * functions. If one succeeds, we'll accept the RNG as seeded. */
  2357. rand_poll_ok = RAND_poll();
  2358. if (rand_poll_ok == 0)
  2359. log_warn(LD_CRYPTO, "RAND_poll() failed.");
  2360. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  2361. if (load_entropy_ok) {
  2362. RAND_seed(buf, sizeof(buf));
  2363. }
  2364. memwipe(buf, 0, sizeof(buf));
  2365. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  2366. return 0;
  2367. else
  2368. return -1;
  2369. }
  2370. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  2371. * for unit tests.
  2372. *
  2373. * This function is not allowed to fail; if it would fail to generate strong
  2374. * entropy, it must terminate the process instead.
  2375. */
  2376. MOCK_IMPL(void,
  2377. crypto_rand, (char *to, size_t n))
  2378. {
  2379. crypto_rand_unmocked(to, n);
  2380. }
  2381. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  2382. * will want crypto_rand instead.
  2383. *
  2384. * This function is not allowed to fail; if it would fail to generate strong
  2385. * entropy, it must terminate the process instead.
  2386. */
  2387. void
  2388. crypto_rand_unmocked(char *to, size_t n)
  2389. {
  2390. int r;
  2391. if (n == 0)
  2392. return;
  2393. tor_assert(n < INT_MAX);
  2394. tor_assert(to);
  2395. r = RAND_bytes((unsigned char*)to, (int)n);
  2396. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  2397. * stack trace about where it happened.
  2398. */
  2399. tor_assert(r >= 0);
  2400. }
  2401. /** Return a pseudorandom integer, chosen uniformly from the values
  2402. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  2403. * INT_MAX+1, inclusive. */
  2404. int
  2405. crypto_rand_int(unsigned int max)
  2406. {
  2407. unsigned int val;
  2408. unsigned int cutoff;
  2409. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  2410. tor_assert(max > 0); /* don't div by 0 */
  2411. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2412. * distribution with clipping at the upper end of unsigned int's
  2413. * range.
  2414. */
  2415. cutoff = UINT_MAX - (UINT_MAX%max);
  2416. while (1) {
  2417. crypto_rand((char*)&val, sizeof(val));
  2418. if (val < cutoff)
  2419. return val % max;
  2420. }
  2421. }
  2422. /** Return a pseudorandom integer, chosen uniformly from the values i such
  2423. * that min <= i < max.
  2424. *
  2425. * <b>min</b> MUST be in range [0, <b>max</b>).
  2426. * <b>max</b> MUST be in range (min, INT_MAX].
  2427. */
  2428. int
  2429. crypto_rand_int_range(unsigned int min, unsigned int max)
  2430. {
  2431. tor_assert(min < max);
  2432. tor_assert(max <= INT_MAX);
  2433. /* The overflow is avoided here because crypto_rand_int() returns a value
  2434. * between 0 and (max - min) inclusive. */
  2435. return min + crypto_rand_int(max - min);
  2436. }
  2437. /** As crypto_rand_int_range, but supports uint64_t. */
  2438. uint64_t
  2439. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  2440. {
  2441. tor_assert(min < max);
  2442. return min + crypto_rand_uint64(max - min);
  2443. }
  2444. /** As crypto_rand_int_range, but supports time_t. */
  2445. time_t
  2446. crypto_rand_time_range(time_t min, time_t max)
  2447. {
  2448. tor_assert(min < max);
  2449. return min + (time_t)crypto_rand_uint64(max - min);
  2450. }
  2451. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  2452. * between 0 and <b>max</b>-1 inclusive. */
  2453. uint64_t
  2454. crypto_rand_uint64(uint64_t max)
  2455. {
  2456. uint64_t val;
  2457. uint64_t cutoff;
  2458. tor_assert(max < UINT64_MAX);
  2459. tor_assert(max > 0); /* don't div by 0 */
  2460. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2461. * distribution with clipping at the upper end of unsigned int's
  2462. * range.
  2463. */
  2464. cutoff = UINT64_MAX - (UINT64_MAX%max);
  2465. while (1) {
  2466. crypto_rand((char*)&val, sizeof(val));
  2467. if (val < cutoff)
  2468. return val % max;
  2469. }
  2470. }
  2471. /** Return a pseudorandom double d, chosen uniformly from the range
  2472. * 0.0 <= d < 1.0.
  2473. */
  2474. double
  2475. crypto_rand_double(void)
  2476. {
  2477. /* We just use an unsigned int here; we don't really care about getting
  2478. * more than 32 bits of resolution */
  2479. unsigned int uint;
  2480. crypto_rand((char*)&uint, sizeof(uint));
  2481. #if SIZEOF_INT == 4
  2482. #define UINT_MAX_AS_DOUBLE 4294967296.0
  2483. #elif SIZEOF_INT == 8
  2484. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  2485. #else
  2486. #error SIZEOF_INT is neither 4 nor 8
  2487. #endif
  2488. return ((double)uint) / UINT_MAX_AS_DOUBLE;
  2489. }
  2490. /** Generate and return a new random hostname starting with <b>prefix</b>,
  2491. * ending with <b>suffix</b>, and containing no fewer than
  2492. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  2493. * characters. Does not check for failure.
  2494. *
  2495. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  2496. **/
  2497. char *
  2498. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  2499. const char *suffix)
  2500. {
  2501. char *result, *rand_bytes;
  2502. int randlen, rand_bytes_len;
  2503. size_t resultlen, prefixlen;
  2504. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  2505. max_rand_len = MAX_DNS_LABEL_SIZE;
  2506. if (min_rand_len > max_rand_len)
  2507. min_rand_len = max_rand_len;
  2508. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  2509. prefixlen = strlen(prefix);
  2510. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  2511. rand_bytes_len = ((randlen*5)+7)/8;
  2512. if (rand_bytes_len % 5)
  2513. rand_bytes_len += 5 - (rand_bytes_len%5);
  2514. rand_bytes = tor_malloc(rand_bytes_len);
  2515. crypto_rand(rand_bytes, rand_bytes_len);
  2516. result = tor_malloc(resultlen);
  2517. memcpy(result, prefix, prefixlen);
  2518. base32_encode(result+prefixlen, resultlen-prefixlen,
  2519. rand_bytes, rand_bytes_len);
  2520. tor_free(rand_bytes);
  2521. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  2522. return result;
  2523. }
  2524. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  2525. * is empty. */
  2526. void *
  2527. smartlist_choose(const smartlist_t *sl)
  2528. {
  2529. int len = smartlist_len(sl);
  2530. if (len)
  2531. return smartlist_get(sl,crypto_rand_int(len));
  2532. return NULL; /* no elements to choose from */
  2533. }
  2534. /** Scramble the elements of <b>sl</b> into a random order. */
  2535. void
  2536. smartlist_shuffle(smartlist_t *sl)
  2537. {
  2538. int i;
  2539. /* From the end of the list to the front, choose at random from the
  2540. positions we haven't looked at yet, and swap that position into the
  2541. current position. Remember to give "no swap" the same probability as
  2542. any other swap. */
  2543. for (i = smartlist_len(sl)-1; i > 0; --i) {
  2544. int j = crypto_rand_int(i+1);
  2545. smartlist_swap(sl, i, j);
  2546. }
  2547. }
  2548. /**
  2549. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  2550. * the value <b>byte</b>.
  2551. *
  2552. * This function is preferable to memset, since many compilers will happily
  2553. * optimize out memset() when they can convince themselves that the data being
  2554. * cleared will never be read.
  2555. *
  2556. * Right now, our convention is to use this function when we are wiping data
  2557. * that's about to become inaccessible, such as stack buffers that are about
  2558. * to go out of scope or structures that are about to get freed. (In
  2559. * practice, it appears that the compilers we're currently using will optimize
  2560. * out the memset()s for stack-allocated buffers, but not those for
  2561. * about-to-be-freed structures. That could change, though, so we're being
  2562. * wary.) If there are live reads for the data, then you can just use
  2563. * memset().
  2564. */
  2565. void
  2566. memwipe(void *mem, uint8_t byte, size_t sz)
  2567. {
  2568. /* Because whole-program-optimization exists, we may not be able to just
  2569. * have this function call "memset". A smart compiler could inline it, then
  2570. * eliminate dead memsets, and declare itself to be clever. */
  2571. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  2572. * based on the pointer value, then uses that junk to update a global
  2573. * variable. It's an elaborate ruse to trick the compiler into not
  2574. * optimizing out the "wipe this memory" code. Read it if you like zany
  2575. * programming tricks! In later versions of Tor, we should look for better
  2576. * not-optimized-out memory wiping stuff...
  2577. *
  2578. * ...or maybe not. In practice, there are pure-asm implementations of
  2579. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  2580. **/
  2581. OPENSSL_cleanse(mem, sz);
  2582. /* Just in case some caller of memwipe() is relying on getting a buffer
  2583. * filled with a particular value, fill the buffer.
  2584. *
  2585. * If this function gets inlined, this memset might get eliminated, but
  2586. * that's okay: We only care about this particular memset in the case where
  2587. * the caller should have been using memset(), and the memset() wouldn't get
  2588. * eliminated. In other words, this is here so that we won't break anything
  2589. * if somebody accidentally calls memwipe() instead of memset().
  2590. **/
  2591. memset(mem, byte, sz);
  2592. }
  2593. #ifndef OPENSSL_THREADS
  2594. #error OpenSSL has been built without thread support. Tor requires an \
  2595. OpenSSL library with thread support enabled.
  2596. #endif
  2597. /** Helper: OpenSSL uses this callback to manipulate mutexes. */
  2598. static void
  2599. openssl_locking_cb_(int mode, int n, const char *file, int line)
  2600. {
  2601. (void)file;
  2602. (void)line;
  2603. if (!openssl_mutexes_)
  2604. /* This is not a really good fix for the
  2605. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  2606. * it can't hurt. */
  2607. return;
  2608. if (mode & CRYPTO_LOCK)
  2609. tor_mutex_acquire(openssl_mutexes_[n]);
  2610. else
  2611. tor_mutex_release(openssl_mutexes_[n]);
  2612. }
  2613. /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
  2614. * as a lock. */
  2615. struct CRYPTO_dynlock_value {
  2616. tor_mutex_t *lock;
  2617. };
  2618. /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
  2619. * documentation in OpenSSL's docs for more info. */
  2620. static struct CRYPTO_dynlock_value *
  2621. openssl_dynlock_create_cb_(const char *file, int line)
  2622. {
  2623. struct CRYPTO_dynlock_value *v;
  2624. (void)file;
  2625. (void)line;
  2626. v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
  2627. v->lock = tor_mutex_new();
  2628. return v;
  2629. }
  2630. /** OpenSSL callback function to acquire or release a lock: see
  2631. * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
  2632. static void
  2633. openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
  2634. const char *file, int line)
  2635. {
  2636. (void)file;
  2637. (void)line;
  2638. if (mode & CRYPTO_LOCK)
  2639. tor_mutex_acquire(v->lock);
  2640. else
  2641. tor_mutex_release(v->lock);
  2642. }
  2643. /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
  2644. * documentation in OpenSSL's docs for more info. */
  2645. static void
  2646. openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
  2647. const char *file, int line)
  2648. {
  2649. (void)file;
  2650. (void)line;
  2651. tor_mutex_free(v->lock);
  2652. tor_free(v);
  2653. }
  2654. static void
  2655. tor_set_openssl_thread_id(CRYPTO_THREADID *threadid)
  2656. {
  2657. CRYPTO_THREADID_set_numeric(threadid, tor_get_thread_id());
  2658. }
  2659. /** @{ */
  2660. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  2661. * multithreaded. Returns 0. */
  2662. static int
  2663. setup_openssl_threading(void)
  2664. {
  2665. int i;
  2666. int n = CRYPTO_num_locks();
  2667. n_openssl_mutexes_ = n;
  2668. openssl_mutexes_ = tor_calloc(n, sizeof(tor_mutex_t *));
  2669. for (i=0; i < n; ++i)
  2670. openssl_mutexes_[i] = tor_mutex_new();
  2671. CRYPTO_set_locking_callback(openssl_locking_cb_);
  2672. CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id);
  2673. CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
  2674. CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
  2675. CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
  2676. return 0;
  2677. }
  2678. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  2679. * failure.
  2680. */
  2681. int
  2682. crypto_global_cleanup(void)
  2683. {
  2684. EVP_cleanup();
  2685. ERR_remove_thread_state(NULL);
  2686. ERR_free_strings();
  2687. if (dh_param_p)
  2688. BN_clear_free(dh_param_p);
  2689. if (dh_param_p_tls)
  2690. BN_clear_free(dh_param_p_tls);
  2691. if (dh_param_g)
  2692. BN_clear_free(dh_param_g);
  2693. #ifndef DISABLE_ENGINES
  2694. ENGINE_cleanup();
  2695. #endif
  2696. CONF_modules_unload(1);
  2697. CRYPTO_cleanup_all_ex_data();
  2698. if (n_openssl_mutexes_) {
  2699. int n = n_openssl_mutexes_;
  2700. tor_mutex_t **ms = openssl_mutexes_;
  2701. int i;
  2702. openssl_mutexes_ = NULL;
  2703. n_openssl_mutexes_ = 0;
  2704. for (i=0;i<n;++i) {
  2705. tor_mutex_free(ms[i]);
  2706. }
  2707. tor_free(ms);
  2708. }
  2709. tor_free(crypto_openssl_version_str);
  2710. tor_free(crypto_openssl_header_version_str);
  2711. return 0;
  2712. }
  2713. /** @} */