crypto.c 95 KB

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