crypto.c 93 KB

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