crypto.c 93 KB

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