crypto.c 94 KB

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