crypto.c 91 KB

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