crypto.c 83 KB

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