crypto.c 98 KB

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