crypto.c 95 KB

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