crypto.c 94 KB

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