crypto.c 94 KB

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