crypto.c 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271
  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. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  820. privatekey?"private":"public");
  821. crypto_log_errors(LOG_ERR,
  822. privatekey ? "Duplicating a private key" :
  823. "Duplicating a public key");
  824. tor_fragile_assert();
  825. return NULL;
  826. }
  827. return crypto_new_pk_from_rsa_(new_key);
  828. }
  829. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  830. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  831. * write the result to <b>to</b>, and return the number of bytes
  832. * written. On failure, return -1.
  833. *
  834. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  835. * at least the length of the modulus of <b>env</b>.
  836. */
  837. int
  838. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  839. const char *from, size_t fromlen, int padding)
  840. {
  841. int r;
  842. tor_assert(env);
  843. tor_assert(from);
  844. tor_assert(to);
  845. tor_assert(fromlen<INT_MAX);
  846. tor_assert(tolen >= crypto_pk_keysize(env));
  847. r = RSA_public_encrypt((int)fromlen,
  848. (unsigned char*)from, (unsigned char*)to,
  849. env->key, crypto_get_rsa_padding(padding));
  850. if (r<0) {
  851. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  852. return -1;
  853. }
  854. return r;
  855. }
  856. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  857. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  858. * write the result to <b>to</b>, and return the number of bytes
  859. * written. On failure, return -1.
  860. *
  861. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  862. * at least the length of the modulus of <b>env</b>.
  863. */
  864. int
  865. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  866. size_t tolen,
  867. const char *from, size_t fromlen,
  868. int padding, int warnOnFailure)
  869. {
  870. int r;
  871. tor_assert(env);
  872. tor_assert(from);
  873. tor_assert(to);
  874. tor_assert(env->key);
  875. tor_assert(fromlen<INT_MAX);
  876. tor_assert(tolen >= crypto_pk_keysize(env));
  877. if (!env->key->p)
  878. /* Not a private key */
  879. return -1;
  880. r = RSA_private_decrypt((int)fromlen,
  881. (unsigned char*)from, (unsigned char*)to,
  882. env->key, crypto_get_rsa_padding(padding));
  883. if (r<0) {
  884. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  885. "performing RSA decryption");
  886. return -1;
  887. }
  888. return r;
  889. }
  890. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  891. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  892. * signed data to <b>to</b>, and return the number of bytes written.
  893. * On failure, return -1.
  894. *
  895. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  896. * at least the length of the modulus of <b>env</b>.
  897. */
  898. int
  899. crypto_pk_public_checksig(const crypto_pk_t *env, char *to,
  900. size_t tolen,
  901. const char *from, size_t fromlen)
  902. {
  903. int r;
  904. tor_assert(env);
  905. tor_assert(from);
  906. tor_assert(to);
  907. tor_assert(fromlen < INT_MAX);
  908. tor_assert(tolen >= crypto_pk_keysize(env));
  909. r = RSA_public_decrypt((int)fromlen,
  910. (unsigned char*)from, (unsigned char*)to,
  911. env->key, RSA_PKCS1_PADDING);
  912. if (r<0) {
  913. crypto_log_errors(LOG_INFO, "checking RSA signature");
  914. return -1;
  915. }
  916. return r;
  917. }
  918. /** Check a siglen-byte long signature at <b>sig</b> against
  919. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  920. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  921. * SHA1(data). Else return -1.
  922. */
  923. int
  924. crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
  925. size_t datalen, const char *sig, size_t siglen)
  926. {
  927. char digest[DIGEST_LEN];
  928. char *buf;
  929. size_t buflen;
  930. int r;
  931. tor_assert(env);
  932. tor_assert(data);
  933. tor_assert(sig);
  934. tor_assert(datalen < SIZE_T_CEILING);
  935. tor_assert(siglen < SIZE_T_CEILING);
  936. if (crypto_digest(digest,data,datalen)<0) {
  937. log_warn(LD_BUG, "couldn't compute digest");
  938. return -1;
  939. }
  940. buflen = crypto_pk_keysize(env);
  941. buf = tor_malloc(buflen);
  942. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  943. if (r != DIGEST_LEN) {
  944. log_warn(LD_CRYPTO, "Invalid signature");
  945. tor_free(buf);
  946. return -1;
  947. }
  948. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  949. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  950. tor_free(buf);
  951. return -1;
  952. }
  953. tor_free(buf);
  954. return 0;
  955. }
  956. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  957. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  958. * <b>to</b>, and return the number of bytes written. On failure, return
  959. * -1.
  960. *
  961. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  962. * at least the length of the modulus of <b>env</b>.
  963. */
  964. int
  965. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  966. const char *from, size_t fromlen)
  967. {
  968. int r;
  969. tor_assert(env);
  970. tor_assert(from);
  971. tor_assert(to);
  972. tor_assert(fromlen < INT_MAX);
  973. tor_assert(tolen >= crypto_pk_keysize(env));
  974. if (!env->key->p)
  975. /* Not a private key */
  976. return -1;
  977. r = RSA_private_encrypt((int)fromlen,
  978. (unsigned char*)from, (unsigned char*)to,
  979. (RSA*)env->key, RSA_PKCS1_PADDING);
  980. if (r<0) {
  981. crypto_log_errors(LOG_WARN, "generating RSA signature");
  982. return -1;
  983. }
  984. return r;
  985. }
  986. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  987. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  988. * store it in <b>to</b>. Return the number of bytes written on
  989. * success, and -1 on failure.
  990. *
  991. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  992. * at least the length of the modulus of <b>env</b>.
  993. */
  994. int
  995. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  996. const char *from, size_t fromlen)
  997. {
  998. int r;
  999. char digest[DIGEST_LEN];
  1000. if (crypto_digest(digest,from,fromlen)<0)
  1001. return -1;
  1002. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  1003. memwipe(digest, 0, sizeof(digest));
  1004. return r;
  1005. }
  1006. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  1007. * bytes of data from <b>from</b>, with padding type 'padding',
  1008. * storing the results on <b>to</b>.
  1009. *
  1010. * Returns the number of bytes written on success, -1 on failure.
  1011. *
  1012. * The encrypted data consists of:
  1013. * - The source data, padded and encrypted with the public key, if the
  1014. * padded source data is no longer than the public key, and <b>force</b>
  1015. * is false, OR
  1016. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  1017. * padded and encrypted with the public key; followed by the rest of
  1018. * the source data encrypted in AES-CTR mode with the symmetric key.
  1019. */
  1020. int
  1021. crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
  1022. char *to, size_t tolen,
  1023. const char *from,
  1024. size_t fromlen,
  1025. int padding, int force)
  1026. {
  1027. int overhead, outlen, r;
  1028. size_t pkeylen, symlen;
  1029. crypto_cipher_t *cipher = NULL;
  1030. char *buf = NULL;
  1031. tor_assert(env);
  1032. tor_assert(from);
  1033. tor_assert(to);
  1034. tor_assert(fromlen < SIZE_T_CEILING);
  1035. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  1036. pkeylen = crypto_pk_keysize(env);
  1037. if (!force && fromlen+overhead <= pkeylen) {
  1038. /* It all fits in a single encrypt. */
  1039. return crypto_pk_public_encrypt(env,to,
  1040. tolen,
  1041. from,fromlen,padding);
  1042. }
  1043. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  1044. tor_assert(tolen >= pkeylen);
  1045. cipher = crypto_cipher_new(NULL); /* generate a new key. */
  1046. buf = tor_malloc(pkeylen+1);
  1047. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  1048. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  1049. /* Length of symmetrically encrypted data. */
  1050. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  1051. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  1052. if (outlen!=(int)pkeylen) {
  1053. goto err;
  1054. }
  1055. r = crypto_cipher_encrypt(cipher, to+outlen,
  1056. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  1057. if (r<0) goto err;
  1058. memwipe(buf, 0, pkeylen);
  1059. tor_free(buf);
  1060. crypto_cipher_free(cipher);
  1061. tor_assert(outlen+symlen < INT_MAX);
  1062. return (int)(outlen + symlen);
  1063. err:
  1064. memwipe(buf, 0, pkeylen);
  1065. tor_free(buf);
  1066. crypto_cipher_free(cipher);
  1067. return -1;
  1068. }
  1069. /** Invert crypto_pk_public_hybrid_encrypt. Returns the number of bytes
  1070. * written on success, -1 on failure. */
  1071. int
  1072. crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
  1073. char *to,
  1074. size_t tolen,
  1075. const char *from,
  1076. size_t fromlen,
  1077. int padding, int warnOnFailure)
  1078. {
  1079. int outlen, r;
  1080. size_t pkeylen;
  1081. crypto_cipher_t *cipher = NULL;
  1082. char *buf = NULL;
  1083. tor_assert(fromlen < SIZE_T_CEILING);
  1084. pkeylen = crypto_pk_keysize(env);
  1085. if (fromlen <= pkeylen) {
  1086. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  1087. warnOnFailure);
  1088. }
  1089. buf = tor_malloc(pkeylen);
  1090. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  1091. warnOnFailure);
  1092. if (outlen<0) {
  1093. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  1094. "Error decrypting public-key data");
  1095. goto err;
  1096. }
  1097. if (outlen < CIPHER_KEY_LEN) {
  1098. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  1099. "No room for a symmetric key");
  1100. goto err;
  1101. }
  1102. cipher = crypto_cipher_new(buf);
  1103. if (!cipher) {
  1104. goto err;
  1105. }
  1106. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  1107. outlen -= CIPHER_KEY_LEN;
  1108. tor_assert(tolen - outlen >= fromlen - pkeylen);
  1109. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  1110. if (r<0)
  1111. goto err;
  1112. memwipe(buf,0,pkeylen);
  1113. tor_free(buf);
  1114. crypto_cipher_free(cipher);
  1115. tor_assert(outlen + fromlen < INT_MAX);
  1116. return (int)(outlen + (fromlen-pkeylen));
  1117. err:
  1118. memwipe(buf,0,pkeylen);
  1119. tor_free(buf);
  1120. crypto_cipher_free(cipher);
  1121. return -1;
  1122. }
  1123. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  1124. * Return -1 on error, or the number of characters used on success.
  1125. */
  1126. int
  1127. crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
  1128. {
  1129. int len;
  1130. unsigned char *buf = NULL;
  1131. len = i2d_RSAPublicKey(pk->key, &buf);
  1132. if (len < 0 || buf == NULL)
  1133. return -1;
  1134. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  1135. OPENSSL_free(buf);
  1136. return -1;
  1137. }
  1138. /* We don't encode directly into 'dest', because that would be illegal
  1139. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  1140. */
  1141. memcpy(dest,buf,len);
  1142. OPENSSL_free(buf);
  1143. return len;
  1144. }
  1145. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  1146. * success and NULL on failure.
  1147. */
  1148. crypto_pk_t *
  1149. crypto_pk_asn1_decode(const char *str, size_t len)
  1150. {
  1151. RSA *rsa;
  1152. unsigned char *buf;
  1153. const unsigned char *cp;
  1154. cp = buf = tor_malloc(len);
  1155. memcpy(buf,str,len);
  1156. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  1157. tor_free(buf);
  1158. if (!rsa) {
  1159. crypto_log_errors(LOG_WARN,"decoding public key");
  1160. return NULL;
  1161. }
  1162. return crypto_new_pk_from_rsa_(rsa);
  1163. }
  1164. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  1165. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  1166. * Return 0 on success, -1 on failure.
  1167. */
  1168. int
  1169. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  1170. {
  1171. unsigned char *buf = NULL;
  1172. int len;
  1173. len = i2d_RSAPublicKey((RSA*)pk->key, &buf);
  1174. if (len < 0 || buf == NULL)
  1175. return -1;
  1176. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  1177. OPENSSL_free(buf);
  1178. return -1;
  1179. }
  1180. OPENSSL_free(buf);
  1181. return 0;
  1182. }
  1183. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  1184. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  1185. int
  1186. crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
  1187. {
  1188. unsigned char *buf = NULL;
  1189. int len;
  1190. len = i2d_RSAPublicKey(pk->key, &buf);
  1191. if (len < 0 || buf == NULL)
  1192. return -1;
  1193. if (crypto_common_digests(digests_out, (char*)buf, len) < 0) {
  1194. OPENSSL_free(buf);
  1195. return -1;
  1196. }
  1197. OPENSSL_free(buf);
  1198. return 0;
  1199. }
  1200. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  1201. * every four characters. */
  1202. void
  1203. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  1204. {
  1205. int n = 0;
  1206. char *end = out+outlen;
  1207. tor_assert(outlen < SIZE_T_CEILING);
  1208. while (*in && out<end) {
  1209. *out++ = *in++;
  1210. if (++n == 4 && *in && out<end) {
  1211. n = 0;
  1212. *out++ = ' ';
  1213. }
  1214. }
  1215. tor_assert(out<end);
  1216. *out = '\0';
  1217. }
  1218. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  1219. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  1220. * space). Return 0 on success, -1 on failure.
  1221. *
  1222. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  1223. * of the public key, converted to hexadecimal, in upper case, with a
  1224. * space after every four digits.
  1225. *
  1226. * If <b>add_space</b> is false, omit the spaces.
  1227. */
  1228. int
  1229. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  1230. {
  1231. char digest[DIGEST_LEN];
  1232. char hexdigest[HEX_DIGEST_LEN+1];
  1233. if (crypto_pk_get_digest(pk, digest)) {
  1234. return -1;
  1235. }
  1236. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  1237. if (add_space) {
  1238. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  1239. } else {
  1240. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  1241. }
  1242. return 0;
  1243. }
  1244. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  1245. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  1246. * bytes of space). Return 0 on success, -1 on failure.
  1247. *
  1248. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  1249. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  1250. * upper case.
  1251. */
  1252. int
  1253. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  1254. {
  1255. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  1256. if (crypto_pk_get_digest(pk, digest)) {
  1257. return -1;
  1258. }
  1259. if (crypto_digest(hashed_digest, digest, DIGEST_LEN)) {
  1260. return -1;
  1261. }
  1262. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  1263. return 0;
  1264. }
  1265. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  1266. * Base64 encoding of the DER representation of the private key as a NUL
  1267. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  1268. * sucess, -1 on failure.
  1269. *
  1270. * It is the caller's responsibility to sanitize and free the resulting buffer.
  1271. */
  1272. int
  1273. crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
  1274. {
  1275. unsigned char *der = NULL;
  1276. int der_len;
  1277. int ret = -1;
  1278. *priv_out = NULL;
  1279. der_len = i2d_RSAPrivateKey(pk->key, &der);
  1280. if (der_len < 0 || der == NULL)
  1281. return ret;
  1282. size_t priv_len = base64_encode_size(der_len, 0) + 1;
  1283. char *priv = tor_malloc_zero(priv_len);
  1284. if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
  1285. *priv_out = priv;
  1286. ret = 0;
  1287. } else {
  1288. tor_free(priv);
  1289. }
  1290. memwipe(der, 0, der_len);
  1291. OPENSSL_free(der);
  1292. return ret;
  1293. }
  1294. /** Given a string containing the Base64 encoded DER representation of the
  1295. * private key <b>str</b>, decode and return the result on success, or NULL
  1296. * on failure.
  1297. */
  1298. crypto_pk_t *
  1299. crypto_pk_base64_decode(const char *str, size_t len)
  1300. {
  1301. crypto_pk_t *pk = NULL;
  1302. char *der = tor_malloc_zero(len + 1);
  1303. int der_len = base64_decode(der, len, str, len);
  1304. if (der_len <= 0) {
  1305. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  1306. goto out;
  1307. }
  1308. const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
  1309. RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
  1310. if (!rsa) {
  1311. crypto_log_errors(LOG_WARN, "decoding private key");
  1312. goto out;
  1313. }
  1314. pk = crypto_new_pk_from_rsa_(rsa);
  1315. /* Make sure it's valid. */
  1316. if (crypto_pk_check_key(pk) <= 0) {
  1317. crypto_pk_free(pk);
  1318. pk = NULL;
  1319. goto out;
  1320. }
  1321. out:
  1322. memwipe(der, 0, len + 1);
  1323. tor_free(der);
  1324. return pk;
  1325. }
  1326. /* symmetric crypto */
  1327. /** Return a pointer to the key set for the cipher in <b>env</b>.
  1328. */
  1329. const char *
  1330. crypto_cipher_get_key(crypto_cipher_t *env)
  1331. {
  1332. return env->key;
  1333. }
  1334. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1335. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1336. * Does not check for failure.
  1337. */
  1338. int
  1339. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  1340. const char *from, size_t fromlen)
  1341. {
  1342. tor_assert(env);
  1343. tor_assert(env->cipher);
  1344. tor_assert(from);
  1345. tor_assert(fromlen);
  1346. tor_assert(to);
  1347. tor_assert(fromlen < SIZE_T_CEILING);
  1348. memcpy(to, from, fromlen);
  1349. aes_crypt_inplace(env->cipher, to, fromlen);
  1350. return 0;
  1351. }
  1352. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1353. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1354. * Does not check for failure.
  1355. */
  1356. int
  1357. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  1358. const char *from, size_t fromlen)
  1359. {
  1360. tor_assert(env);
  1361. tor_assert(from);
  1362. tor_assert(to);
  1363. tor_assert(fromlen < SIZE_T_CEILING);
  1364. memcpy(to, from, fromlen);
  1365. aes_crypt_inplace(env->cipher, to, fromlen);
  1366. return 0;
  1367. }
  1368. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1369. * on success. Does not check for failure.
  1370. */
  1371. void
  1372. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  1373. {
  1374. tor_assert(len < SIZE_T_CEILING);
  1375. aes_crypt_inplace(env->cipher, buf, len);
  1376. }
  1377. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1378. * <b>key</b> to the buffer in <b>to</b> of length
  1379. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1380. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1381. * number of bytes written, on failure, return -1.
  1382. */
  1383. int
  1384. crypto_cipher_encrypt_with_iv(const char *key,
  1385. char *to, size_t tolen,
  1386. const char *from, size_t fromlen)
  1387. {
  1388. crypto_cipher_t *cipher;
  1389. tor_assert(from);
  1390. tor_assert(to);
  1391. tor_assert(fromlen < INT_MAX);
  1392. if (fromlen < 1)
  1393. return -1;
  1394. if (tolen < fromlen + CIPHER_IV_LEN)
  1395. return -1;
  1396. cipher = crypto_cipher_new_with_iv(key, NULL);
  1397. memcpy(to, cipher->iv, CIPHER_IV_LEN);
  1398. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1399. crypto_cipher_free(cipher);
  1400. return (int)(fromlen + CIPHER_IV_LEN);
  1401. }
  1402. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1403. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  1404. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1405. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1406. * number of bytes written, on failure, return -1.
  1407. */
  1408. int
  1409. crypto_cipher_decrypt_with_iv(const char *key,
  1410. char *to, size_t tolen,
  1411. const char *from, size_t fromlen)
  1412. {
  1413. crypto_cipher_t *cipher;
  1414. tor_assert(key);
  1415. tor_assert(from);
  1416. tor_assert(to);
  1417. tor_assert(fromlen < INT_MAX);
  1418. if (fromlen <= CIPHER_IV_LEN)
  1419. return -1;
  1420. if (tolen < fromlen - CIPHER_IV_LEN)
  1421. return -1;
  1422. cipher = crypto_cipher_new_with_iv(key, from);
  1423. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1424. crypto_cipher_free(cipher);
  1425. return (int)(fromlen - CIPHER_IV_LEN);
  1426. }
  1427. /* SHA-1 */
  1428. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  1429. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1430. * Return 0 on success, 1 on failure.
  1431. */
  1432. int
  1433. crypto_digest(char *digest, const char *m, size_t len)
  1434. {
  1435. tor_assert(m);
  1436. tor_assert(digest);
  1437. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1438. }
  1439. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1440. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  1441. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1442. int
  1443. crypto_digest256(char *digest, const char *m, size_t len,
  1444. digest_algorithm_t algorithm)
  1445. {
  1446. tor_assert(m);
  1447. tor_assert(digest);
  1448. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1449. if (algorithm == DIGEST_SHA256)
  1450. return (SHA256((const uint8_t*)m,len,(uint8_t*)digest) == NULL);
  1451. else
  1452. return (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  1453. == -1);
  1454. }
  1455. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1456. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  1457. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1458. int
  1459. crypto_digest512(char *digest, const char *m, size_t len,
  1460. digest_algorithm_t algorithm)
  1461. {
  1462. tor_assert(m);
  1463. tor_assert(digest);
  1464. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1465. if (algorithm == DIGEST_SHA512)
  1466. return (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
  1467. == NULL);
  1468. else
  1469. return (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  1470. == -1);
  1471. }
  1472. /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
  1473. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  1474. * success, -1 on failure. */
  1475. int
  1476. crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
  1477. {
  1478. tor_assert(ds_out);
  1479. memset(ds_out, 0, sizeof(*ds_out));
  1480. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  1481. return -1;
  1482. if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
  1483. return -1;
  1484. return 0;
  1485. }
  1486. /** Return the name of an algorithm, as used in directory documents. */
  1487. const char *
  1488. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  1489. {
  1490. switch (alg) {
  1491. case DIGEST_SHA1:
  1492. return "sha1";
  1493. case DIGEST_SHA256:
  1494. return "sha256";
  1495. case DIGEST_SHA512:
  1496. return "sha512";
  1497. case DIGEST_SHA3_256:
  1498. return "sha3-256";
  1499. case DIGEST_SHA3_512:
  1500. return "sha3-512";
  1501. default:
  1502. tor_fragile_assert();
  1503. return "??unknown_digest??";
  1504. }
  1505. }
  1506. /** Given the name of a digest algorithm, return its integer value, or -1 if
  1507. * the name is not recognized. */
  1508. int
  1509. crypto_digest_algorithm_parse_name(const char *name)
  1510. {
  1511. if (!strcmp(name, "sha1"))
  1512. return DIGEST_SHA1;
  1513. else if (!strcmp(name, "sha256"))
  1514. return DIGEST_SHA256;
  1515. else if (!strcmp(name, "sha512"))
  1516. return DIGEST_SHA512;
  1517. else if (!strcmp(name, "sha3-256"))
  1518. return DIGEST_SHA3_256;
  1519. else if (!strcmp(name, "sha3-512"))
  1520. return DIGEST_SHA3_512;
  1521. else
  1522. return -1;
  1523. }
  1524. /** Given an algorithm, return the digest length in bytes. */
  1525. static inline size_t
  1526. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  1527. {
  1528. switch (alg) {
  1529. case DIGEST_SHA1:
  1530. return DIGEST_LEN;
  1531. case DIGEST_SHA256:
  1532. return DIGEST256_LEN;
  1533. case DIGEST_SHA512:
  1534. return DIGEST512_LEN;
  1535. case DIGEST_SHA3_256:
  1536. return DIGEST256_LEN;
  1537. case DIGEST_SHA3_512:
  1538. return DIGEST512_LEN;
  1539. default:
  1540. tor_assert(0); // LCOV_EXCL_LINE
  1541. return 0; /* Unreachable */ // LCOV_EXCL_LINE
  1542. }
  1543. }
  1544. /** Intermediate information about the digest of a stream of data. */
  1545. struct crypto_digest_t {
  1546. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  1547. /** State for the digest we're using. Only one member of the
  1548. * union is usable, depending on the value of <b>algorithm</b>. Note also
  1549. * that space for other members might not even be allocated!
  1550. */
  1551. union {
  1552. SHA_CTX sha1; /**< state for SHA1 */
  1553. SHA256_CTX sha2; /**< state for SHA256 */
  1554. SHA512_CTX sha512; /**< state for SHA512 */
  1555. keccak_state sha3; /**< state for SHA3-[256,512] */
  1556. } d;
  1557. };
  1558. /**
  1559. * Return the number of bytes we need to malloc in order to get a
  1560. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  1561. * when we free one.
  1562. */
  1563. static size_t
  1564. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  1565. {
  1566. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  1567. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  1568. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  1569. #define END_OF_FIELD(f) (STRUCT_OFFSET(crypto_digest_t, f) + \
  1570. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  1571. switch (alg) {
  1572. case DIGEST_SHA1:
  1573. return END_OF_FIELD(d.sha1);
  1574. case DIGEST_SHA256:
  1575. return END_OF_FIELD(d.sha2);
  1576. case DIGEST_SHA512:
  1577. return END_OF_FIELD(d.sha512);
  1578. case DIGEST_SHA3_256:
  1579. case DIGEST_SHA3_512:
  1580. return END_OF_FIELD(d.sha3);
  1581. default:
  1582. tor_assert(0); // LCOV_EXCL_LINE
  1583. return 0; // LCOV_EXCL_LINE
  1584. }
  1585. #undef END_OF_FIELD
  1586. #undef STRUCT_FIELD_SIZE
  1587. }
  1588. /** Allocate and return a new digest object to compute SHA1 digests.
  1589. */
  1590. crypto_digest_t *
  1591. crypto_digest_new(void)
  1592. {
  1593. crypto_digest_t *r;
  1594. r = tor_malloc(crypto_digest_alloc_bytes(DIGEST_SHA1));
  1595. SHA1_Init(&r->d.sha1);
  1596. r->algorithm = DIGEST_SHA1;
  1597. return r;
  1598. }
  1599. /** Allocate and return a new digest object to compute 256-bit digests
  1600. * using <b>algorithm</b>. */
  1601. crypto_digest_t *
  1602. crypto_digest256_new(digest_algorithm_t algorithm)
  1603. {
  1604. crypto_digest_t *r;
  1605. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1606. r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  1607. if (algorithm == DIGEST_SHA256)
  1608. SHA256_Init(&r->d.sha2);
  1609. else
  1610. keccak_digest_init(&r->d.sha3, 256);
  1611. r->algorithm = algorithm;
  1612. return r;
  1613. }
  1614. /** Allocate and return a new digest object to compute 512-bit digests
  1615. * using <b>algorithm</b>. */
  1616. crypto_digest_t *
  1617. crypto_digest512_new(digest_algorithm_t algorithm)
  1618. {
  1619. crypto_digest_t *r;
  1620. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1621. r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  1622. if (algorithm == DIGEST_SHA512)
  1623. SHA512_Init(&r->d.sha512);
  1624. else
  1625. keccak_digest_init(&r->d.sha3, 512);
  1626. r->algorithm = algorithm;
  1627. return r;
  1628. }
  1629. /** Deallocate a digest object.
  1630. */
  1631. void
  1632. crypto_digest_free(crypto_digest_t *digest)
  1633. {
  1634. if (!digest)
  1635. return;
  1636. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1637. memwipe(digest, 0, bytes);
  1638. tor_free(digest);
  1639. }
  1640. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1641. */
  1642. void
  1643. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  1644. size_t len)
  1645. {
  1646. tor_assert(digest);
  1647. tor_assert(data);
  1648. /* Using the SHA*_*() calls directly means we don't support doing
  1649. * SHA in hardware. But so far the delay of getting the question
  1650. * to the hardware, and hearing the answer, is likely higher than
  1651. * just doing it ourselves. Hashes are fast.
  1652. */
  1653. switch (digest->algorithm) {
  1654. case DIGEST_SHA1:
  1655. SHA1_Update(&digest->d.sha1, (void*)data, len);
  1656. break;
  1657. case DIGEST_SHA256:
  1658. SHA256_Update(&digest->d.sha2, (void*)data, len);
  1659. break;
  1660. case DIGEST_SHA512:
  1661. SHA512_Update(&digest->d.sha512, (void*)data, len);
  1662. break;
  1663. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1664. case DIGEST_SHA3_512:
  1665. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  1666. break;
  1667. default:
  1668. tor_fragile_assert();
  1669. break;
  1670. }
  1671. }
  1672. /** Compute the hash of the data that has been passed to the digest
  1673. * object; write the first out_len bytes of the result to <b>out</b>.
  1674. * <b>out_len</b> must be \<= DIGEST512_LEN.
  1675. */
  1676. void
  1677. crypto_digest_get_digest(crypto_digest_t *digest,
  1678. char *out, size_t out_len)
  1679. {
  1680. unsigned char r[DIGEST512_LEN];
  1681. crypto_digest_t tmpenv;
  1682. tor_assert(digest);
  1683. tor_assert(out);
  1684. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  1685. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  1686. * short output buffers by truncating appropriately. */
  1687. if (digest->algorithm == DIGEST_SHA3_256 ||
  1688. digest->algorithm == DIGEST_SHA3_512) {
  1689. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  1690. return;
  1691. }
  1692. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1693. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  1694. memcpy(&tmpenv, digest, alloc_bytes);
  1695. switch (digest->algorithm) {
  1696. case DIGEST_SHA1:
  1697. SHA1_Final(r, &tmpenv.d.sha1);
  1698. break;
  1699. case DIGEST_SHA256:
  1700. SHA256_Final(r, &tmpenv.d.sha2);
  1701. break;
  1702. case DIGEST_SHA512:
  1703. SHA512_Final(r, &tmpenv.d.sha512);
  1704. break;
  1705. //LCOV_EXCL_START
  1706. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1707. case DIGEST_SHA3_512:
  1708. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  1709. tor_assert(0); /* This is fatal, because it should never happen. */
  1710. default:
  1711. tor_assert(0); /* Unreachable. */
  1712. break;
  1713. //LCOV_EXCL_STOP
  1714. }
  1715. memcpy(out, r, out_len);
  1716. memwipe(r, 0, sizeof(r));
  1717. }
  1718. /** Allocate and return a new digest object with the same state as
  1719. * <b>digest</b>
  1720. */
  1721. crypto_digest_t *
  1722. crypto_digest_dup(const crypto_digest_t *digest)
  1723. {
  1724. tor_assert(digest);
  1725. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1726. return tor_memdup(digest, alloc_bytes);
  1727. }
  1728. /** Replace the state of the digest object <b>into</b> with the state
  1729. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  1730. * have the same digest type.
  1731. */
  1732. void
  1733. crypto_digest_assign(crypto_digest_t *into,
  1734. const crypto_digest_t *from)
  1735. {
  1736. tor_assert(into);
  1737. tor_assert(from);
  1738. tor_assert(into->algorithm == from->algorithm);
  1739. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  1740. memcpy(into,from,alloc_bytes);
  1741. }
  1742. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1743. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  1744. * plus the optional string <b>append</b>, computed with the algorithm
  1745. * <b>alg</b>.
  1746. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  1747. void
  1748. crypto_digest_smartlist(char *digest_out, size_t len_out,
  1749. const smartlist_t *lst,
  1750. const char *append,
  1751. digest_algorithm_t alg)
  1752. {
  1753. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  1754. }
  1755. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1756. * at <b>digest_out</b> to the hash of the concatenation of: the
  1757. * optional string <b>prepend</b>, those strings,
  1758. * and the optional string <b>append</b>, computed with the algorithm
  1759. * <b>alg</b>.
  1760. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  1761. void
  1762. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  1763. const char *prepend,
  1764. const smartlist_t *lst,
  1765. const char *append,
  1766. digest_algorithm_t alg)
  1767. {
  1768. crypto_digest_t *d = NULL;
  1769. switch (alg) {
  1770. case DIGEST_SHA1:
  1771. d = crypto_digest_new();
  1772. break;
  1773. case DIGEST_SHA256: /* FALLSTHROUGH */
  1774. case DIGEST_SHA3_256:
  1775. d = crypto_digest256_new(alg);
  1776. break;
  1777. case DIGEST_SHA512: /* FALLSTHROUGH */
  1778. case DIGEST_SHA3_512:
  1779. d = crypto_digest512_new(alg);
  1780. break;
  1781. default:
  1782. log_warn(LD_BUG, "Called with unknown algorithm %d", alg);
  1783. /* If fragile_assert is not enabled, wipe output and return
  1784. * without running any calculations */
  1785. memwipe(digest_out, 0xff, len_out);
  1786. tor_fragile_assert();
  1787. goto free;
  1788. }
  1789. if (prepend)
  1790. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  1791. SMARTLIST_FOREACH(lst, const char *, cp,
  1792. crypto_digest_add_bytes(d, cp, strlen(cp)));
  1793. if (append)
  1794. crypto_digest_add_bytes(d, append, strlen(append));
  1795. crypto_digest_get_digest(d, digest_out, len_out);
  1796. free:
  1797. crypto_digest_free(d);
  1798. }
  1799. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1800. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  1801. * result in <b>hmac_out</b>. Asserts on failure.
  1802. */
  1803. void
  1804. crypto_hmac_sha256(char *hmac_out,
  1805. const char *key, size_t key_len,
  1806. const char *msg, size_t msg_len)
  1807. {
  1808. unsigned char *rv = NULL;
  1809. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  1810. tor_assert(key_len < INT_MAX);
  1811. tor_assert(msg_len < INT_MAX);
  1812. tor_assert(hmac_out);
  1813. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1814. (unsigned char*)hmac_out, NULL);
  1815. tor_assert(rv);
  1816. }
  1817. /** Internal state for a eXtendable-Output Function (XOF). */
  1818. struct crypto_xof_t {
  1819. keccak_state s;
  1820. };
  1821. /** Allocate a new XOF object backed by SHAKE-256. The security level
  1822. * provided is a function of the length of the output used. Read and
  1823. * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
  1824. * Functions" before using this construct.
  1825. */
  1826. crypto_xof_t *
  1827. crypto_xof_new(void)
  1828. {
  1829. crypto_xof_t *xof;
  1830. xof = tor_malloc(sizeof(crypto_xof_t));
  1831. keccak_xof_init(&xof->s, 256);
  1832. return xof;
  1833. }
  1834. /** Absorb bytes into a XOF object. Must not be called after a call to
  1835. * crypto_xof_squeeze_bytes() for the same instance, and will assert
  1836. * if attempted.
  1837. */
  1838. void
  1839. crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
  1840. {
  1841. int i = keccak_xof_absorb(&xof->s, data, len);
  1842. tor_assert(i == 0);
  1843. }
  1844. /** Squeeze bytes out of a XOF object. Calling this routine will render
  1845. * the XOF instance ineligible to absorb further data.
  1846. */
  1847. void
  1848. crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
  1849. {
  1850. int i = keccak_xof_squeeze(&xof->s, out, len);
  1851. tor_assert(i == 0);
  1852. }
  1853. /** Cleanse and deallocate a XOF object. */
  1854. void
  1855. crypto_xof_free(crypto_xof_t *xof)
  1856. {
  1857. if (!xof)
  1858. return;
  1859. memwipe(xof, 0, sizeof(crypto_xof_t));
  1860. tor_free(xof);
  1861. }
  1862. /* DH */
  1863. /** Our DH 'g' parameter */
  1864. #define DH_GENERATOR 2
  1865. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  1866. static BIGNUM *dh_param_p = NULL;
  1867. /** Shared P parameter for our TLS DH key exchanges. */
  1868. static BIGNUM *dh_param_p_tls = NULL;
  1869. /** Shared G parameter for our DH key exchanges. */
  1870. static BIGNUM *dh_param_g = NULL;
  1871. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  1872. * computationally expensive (milliseconds), so should only be called when
  1873. * the DH parameters change. Returns 0 on success, * -1 on failure.
  1874. */
  1875. static int
  1876. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  1877. {
  1878. DH *dh = NULL;
  1879. int ret = -1;
  1880. /* Copy into a temporary DH object. */
  1881. if (!(dh = DH_new()))
  1882. goto out;
  1883. if (!(dh->p = BN_dup(p)))
  1884. goto out;
  1885. if (!(dh->g = BN_dup(g)))
  1886. goto out;
  1887. /* Perform the validation. */
  1888. int codes = 0;
  1889. if (!DH_check(dh, &codes))
  1890. goto out;
  1891. if (BN_is_word(dh->g, DH_GENERATOR_2)) {
  1892. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  1893. *
  1894. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  1895. * IETF's primes are congruent to 23 when g = 2.
  1896. */
  1897. BN_ULONG residue = BN_mod_word(dh->p, 24);
  1898. if (residue == 11 || residue == 23)
  1899. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  1900. }
  1901. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  1902. goto out;
  1903. /* Things are probably not evil. */
  1904. ret = 0;
  1905. out:
  1906. if (dh)
  1907. DH_free(dh);
  1908. return ret;
  1909. }
  1910. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  1911. * DH stuff.
  1912. */
  1913. static void
  1914. crypto_set_dh_generator(void)
  1915. {
  1916. BIGNUM *generator;
  1917. int r;
  1918. if (dh_param_g)
  1919. return;
  1920. generator = BN_new();
  1921. tor_assert(generator);
  1922. r = BN_set_word(generator, DH_GENERATOR);
  1923. tor_assert(r);
  1924. dh_param_g = generator;
  1925. }
  1926. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  1927. * modulus. */
  1928. void
  1929. crypto_set_tls_dh_prime(void)
  1930. {
  1931. BIGNUM *tls_prime = NULL;
  1932. int r;
  1933. /* If the space is occupied, free the previous TLS DH prime */
  1934. if (BUG(dh_param_p_tls)) {
  1935. /* LCOV_EXCL_START
  1936. *
  1937. * We shouldn't be calling this twice.
  1938. */
  1939. BN_clear_free(dh_param_p_tls);
  1940. dh_param_p_tls = NULL;
  1941. /* LCOV_EXCL_STOP */
  1942. }
  1943. tls_prime = BN_new();
  1944. tor_assert(tls_prime);
  1945. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  1946. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  1947. * prime.
  1948. */
  1949. r = BN_hex2bn(&tls_prime,
  1950. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  1951. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  1952. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  1953. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  1954. "B0E7393E0F24218EB3");
  1955. tor_assert(r);
  1956. tor_assert(tls_prime);
  1957. dh_param_p_tls = tls_prime;
  1958. crypto_set_dh_generator();
  1959. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  1960. }
  1961. /** Initialize dh_param_p and dh_param_g if they are not already
  1962. * set. */
  1963. static void
  1964. init_dh_param(void)
  1965. {
  1966. BIGNUM *circuit_dh_prime;
  1967. int r;
  1968. if (BUG(dh_param_p && dh_param_g))
  1969. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  1970. circuit_dh_prime = BN_new();
  1971. tor_assert(circuit_dh_prime);
  1972. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1973. supposedly it equals:
  1974. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1975. */
  1976. r = BN_hex2bn(&circuit_dh_prime,
  1977. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1978. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1979. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1980. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1981. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1982. tor_assert(r);
  1983. /* Set the new values as the global DH parameters. */
  1984. dh_param_p = circuit_dh_prime;
  1985. crypto_set_dh_generator();
  1986. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  1987. if (!dh_param_p_tls) {
  1988. crypto_set_tls_dh_prime();
  1989. }
  1990. }
  1991. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  1992. * handshake. Since we exponentiate by this value, choosing a smaller one
  1993. * lets our handhake go faster.
  1994. */
  1995. #define DH_PRIVATE_KEY_BITS 320
  1996. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  1997. * failure.
  1998. */
  1999. crypto_dh_t *
  2000. crypto_dh_new(int dh_type)
  2001. {
  2002. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  2003. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  2004. dh_type == DH_TYPE_REND);
  2005. if (!dh_param_p)
  2006. init_dh_param();
  2007. if (!(res->dh = DH_new()))
  2008. goto err;
  2009. if (dh_type == DH_TYPE_TLS) {
  2010. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  2011. goto err;
  2012. } else {
  2013. if (!(res->dh->p = BN_dup(dh_param_p)))
  2014. goto err;
  2015. }
  2016. if (!(res->dh->g = BN_dup(dh_param_g)))
  2017. goto err;
  2018. res->dh->length = DH_PRIVATE_KEY_BITS;
  2019. return res;
  2020. err:
  2021. /* LCOV_EXCL_START
  2022. * This error condition is only reached when an allocation fails */
  2023. crypto_log_errors(LOG_WARN, "creating DH object");
  2024. if (res->dh) DH_free(res->dh); /* frees p and g too */
  2025. tor_free(res);
  2026. return NULL;
  2027. /* LCOV_EXCL_STOP */
  2028. }
  2029. /** Return a copy of <b>dh</b>, sharing its internal state. */
  2030. crypto_dh_t *
  2031. crypto_dh_dup(const crypto_dh_t *dh)
  2032. {
  2033. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  2034. tor_assert(dh);
  2035. tor_assert(dh->dh);
  2036. dh_new->dh = dh->dh;
  2037. DH_up_ref(dh->dh);
  2038. return dh_new;
  2039. }
  2040. /** Return the length of the DH key in <b>dh</b>, in bytes.
  2041. */
  2042. int
  2043. crypto_dh_get_bytes(crypto_dh_t *dh)
  2044. {
  2045. tor_assert(dh);
  2046. return DH_size(dh->dh);
  2047. }
  2048. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  2049. * success, -1 on failure.
  2050. */
  2051. int
  2052. crypto_dh_generate_public(crypto_dh_t *dh)
  2053. {
  2054. again:
  2055. if (!DH_generate_key(dh->dh)) {
  2056. /* LCOV_EXCL_START
  2057. * To test this we would need some way to tell openssl to break DH. */
  2058. crypto_log_errors(LOG_WARN, "generating DH key");
  2059. return -1;
  2060. /* LCOV_EXCL_STOP */
  2061. }
  2062. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  2063. /* LCOV_EXCL_START
  2064. * If this happens, then openssl's DH implementation is busted. */
  2065. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  2066. "the-universe chances really do happen. Trying again.");
  2067. /* Free and clear the keys, so OpenSSL will actually try again. */
  2068. BN_clear_free(dh->dh->pub_key);
  2069. BN_clear_free(dh->dh->priv_key);
  2070. dh->dh->pub_key = dh->dh->priv_key = NULL;
  2071. goto again;
  2072. /* LCOV_EXCL_STOP */
  2073. }
  2074. return 0;
  2075. }
  2076. /** Generate g^x as necessary, and write the g^x for the key exchange
  2077. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  2078. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  2079. */
  2080. int
  2081. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  2082. {
  2083. int bytes;
  2084. tor_assert(dh);
  2085. if (!dh->dh->pub_key) {
  2086. if (crypto_dh_generate_public(dh)<0)
  2087. return -1;
  2088. }
  2089. tor_assert(dh->dh->pub_key);
  2090. bytes = BN_num_bytes(dh->dh->pub_key);
  2091. tor_assert(bytes >= 0);
  2092. if (pubkey_len < (size_t)bytes) {
  2093. log_warn(LD_CRYPTO,
  2094. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  2095. (int) pubkey_len, bytes);
  2096. return -1;
  2097. }
  2098. memset(pubkey, 0, pubkey_len);
  2099. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  2100. return 0;
  2101. }
  2102. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  2103. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  2104. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  2105. */
  2106. static int
  2107. tor_check_dh_key(int severity, BIGNUM *bn)
  2108. {
  2109. BIGNUM *x;
  2110. char *s;
  2111. tor_assert(bn);
  2112. x = BN_new();
  2113. tor_assert(x);
  2114. if (BUG(!dh_param_p))
  2115. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  2116. BN_set_word(x, 1);
  2117. if (BN_cmp(bn,x)<=0) {
  2118. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  2119. goto err;
  2120. }
  2121. BN_copy(x,dh_param_p);
  2122. BN_sub_word(x, 1);
  2123. if (BN_cmp(bn,x)>=0) {
  2124. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  2125. goto err;
  2126. }
  2127. BN_clear_free(x);
  2128. return 0;
  2129. err:
  2130. BN_clear_free(x);
  2131. s = BN_bn2hex(bn);
  2132. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  2133. OPENSSL_free(s);
  2134. return -1;
  2135. }
  2136. /** Given a DH key exchange object, and our peer's value of g^y (as a
  2137. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  2138. * <b>secret_bytes_out</b> bytes of shared key material and write them
  2139. * to <b>secret_out</b>. Return the number of bytes generated on success,
  2140. * or -1 on failure.
  2141. *
  2142. * (We generate key material by computing
  2143. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  2144. * where || is concatenation.)
  2145. */
  2146. ssize_t
  2147. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  2148. const char *pubkey, size_t pubkey_len,
  2149. char *secret_out, size_t secret_bytes_out)
  2150. {
  2151. char *secret_tmp = NULL;
  2152. BIGNUM *pubkey_bn = NULL;
  2153. size_t secret_len=0, secret_tmp_len=0;
  2154. int result=0;
  2155. tor_assert(dh);
  2156. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  2157. tor_assert(pubkey_len < INT_MAX);
  2158. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  2159. (int)pubkey_len, NULL)))
  2160. goto error;
  2161. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  2162. /* Check for invalid public keys. */
  2163. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  2164. goto error;
  2165. }
  2166. secret_tmp_len = crypto_dh_get_bytes(dh);
  2167. secret_tmp = tor_malloc(secret_tmp_len);
  2168. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  2169. if (result < 0) {
  2170. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  2171. goto error;
  2172. }
  2173. secret_len = result;
  2174. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  2175. (uint8_t*)secret_out, secret_bytes_out)<0)
  2176. goto error;
  2177. secret_len = secret_bytes_out;
  2178. goto done;
  2179. error:
  2180. result = -1;
  2181. done:
  2182. crypto_log_errors(LOG_WARN, "completing DH handshake");
  2183. if (pubkey_bn)
  2184. BN_clear_free(pubkey_bn);
  2185. if (secret_tmp) {
  2186. memwipe(secret_tmp, 0, secret_tmp_len);
  2187. tor_free(secret_tmp);
  2188. }
  2189. if (result < 0)
  2190. return result;
  2191. else
  2192. return secret_len;
  2193. }
  2194. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  2195. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  2196. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  2197. * H(K | [00]) | H(K | [01]) | ....
  2198. *
  2199. * This is the key expansion algorithm used in the "TAP" circuit extension
  2200. * mechanism; it shouldn't be used for new protocols.
  2201. *
  2202. * Return 0 on success, -1 on failure.
  2203. */
  2204. int
  2205. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  2206. uint8_t *key_out, size_t key_out_len)
  2207. {
  2208. int i, r = -1;
  2209. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  2210. uint8_t digest[DIGEST_LEN];
  2211. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2212. tor_assert(key_out_len <= DIGEST_LEN*256);
  2213. memcpy(tmp, key_in, key_in_len);
  2214. for (cp = key_out, i=0; cp < key_out+key_out_len;
  2215. ++i, cp += DIGEST_LEN) {
  2216. tmp[key_in_len] = i;
  2217. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
  2218. goto exit;
  2219. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  2220. }
  2221. r = 0;
  2222. exit:
  2223. memwipe(tmp, 0, key_in_len+1);
  2224. tor_free(tmp);
  2225. memwipe(digest, 0, sizeof(digest));
  2226. return r;
  2227. }
  2228. /** Expand some secret key material according to RFC5869, using SHA256 as the
  2229. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  2230. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  2231. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  2232. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  2233. * bytes to <b>key_out</b> and return 0. Assert on failure.
  2234. */
  2235. int
  2236. crypto_expand_key_material_rfc5869_sha256(
  2237. const uint8_t *key_in, size_t key_in_len,
  2238. const uint8_t *salt_in, size_t salt_in_len,
  2239. const uint8_t *info_in, size_t info_in_len,
  2240. uint8_t *key_out, size_t key_out_len)
  2241. {
  2242. uint8_t prk[DIGEST256_LEN];
  2243. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  2244. uint8_t mac[DIGEST256_LEN];
  2245. int i;
  2246. uint8_t *outp;
  2247. size_t tmp_len;
  2248. crypto_hmac_sha256((char*)prk,
  2249. (const char*)salt_in, salt_in_len,
  2250. (const char*)key_in, key_in_len);
  2251. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2252. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  2253. tor_assert(info_in_len <= 128);
  2254. memset(tmp, 0, sizeof(tmp));
  2255. outp = key_out;
  2256. i = 1;
  2257. while (key_out_len) {
  2258. size_t n;
  2259. if (i > 1) {
  2260. memcpy(tmp, mac, DIGEST256_LEN);
  2261. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  2262. tmp[DIGEST256_LEN+info_in_len] = i;
  2263. tmp_len = DIGEST256_LEN + info_in_len + 1;
  2264. } else {
  2265. memcpy(tmp, info_in, info_in_len);
  2266. tmp[info_in_len] = i;
  2267. tmp_len = info_in_len + 1;
  2268. }
  2269. crypto_hmac_sha256((char*)mac,
  2270. (const char*)prk, DIGEST256_LEN,
  2271. (const char*)tmp, tmp_len);
  2272. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  2273. memcpy(outp, mac, n);
  2274. key_out_len -= n;
  2275. outp += n;
  2276. ++i;
  2277. }
  2278. memwipe(tmp, 0, sizeof(tmp));
  2279. memwipe(mac, 0, sizeof(mac));
  2280. return 0;
  2281. }
  2282. /** Free a DH key exchange object.
  2283. */
  2284. void
  2285. crypto_dh_free(crypto_dh_t *dh)
  2286. {
  2287. if (!dh)
  2288. return;
  2289. tor_assert(dh->dh);
  2290. DH_free(dh->dh);
  2291. tor_free(dh);
  2292. }
  2293. /* random numbers */
  2294. /** How many bytes of entropy we add at once.
  2295. *
  2296. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  2297. * work for us too. */
  2298. #define ADD_ENTROPY 32
  2299. /** Set the seed of the weak RNG to a random value. */
  2300. void
  2301. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  2302. {
  2303. unsigned seed;
  2304. crypto_rand((void*)&seed, sizeof(seed));
  2305. tor_init_weak_random(rng, seed);
  2306. }
  2307. #ifdef TOR_UNIT_TESTS
  2308. int break_strongest_rng_syscall = 0;
  2309. int break_strongest_rng_fallback = 0;
  2310. #endif
  2311. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2312. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  2313. * failure. A maximum request size of 256 bytes is imposed.
  2314. */
  2315. static int
  2316. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  2317. {
  2318. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2319. #ifdef TOR_UNIT_TESTS
  2320. if (break_strongest_rng_syscall)
  2321. return -1;
  2322. #endif
  2323. #if defined(_WIN32)
  2324. static int provider_set = 0;
  2325. static HCRYPTPROV provider;
  2326. if (!provider_set) {
  2327. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  2328. CRYPT_VERIFYCONTEXT)) {
  2329. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  2330. return -1;
  2331. }
  2332. provider_set = 1;
  2333. }
  2334. if (!CryptGenRandom(provider, out_len, out)) {
  2335. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  2336. return -1;
  2337. }
  2338. return 0;
  2339. #elif defined(__linux__) && defined(SYS_getrandom)
  2340. static int getrandom_works = 1; /* Be optimitic about our chances... */
  2341. /* getrandom() isn't as straight foward as getentropy(), and has
  2342. * no glibc wrapper.
  2343. *
  2344. * As far as I can tell from getrandom(2) and the source code, the
  2345. * requests we issue will always succeed (though it will block on the
  2346. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  2347. * GRND_NONBLOCK and the request is <= 256 bytes.
  2348. *
  2349. * The manpage is unclear on what happens if a signal interrupts the call
  2350. * while the request is blocked due to lack of entropy....
  2351. *
  2352. * We optimistically assume that getrandom() is available and functional
  2353. * because it is the way of the future, and 2 branch mispredicts pale in
  2354. * comparision to the overheads involved with failing to open
  2355. * /dev/srandom followed by opening and reading from /dev/urandom.
  2356. */
  2357. if (PREDICT_LIKELY(getrandom_works)) {
  2358. long ret;
  2359. /* A flag of '0' here means to read from '/dev/urandom', and to
  2360. * block if insufficient entropy is available to service the
  2361. * request.
  2362. */
  2363. const unsigned int flags = 0;
  2364. do {
  2365. ret = syscall(SYS_getrandom, out, out_len, flags);
  2366. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  2367. if (PREDICT_UNLIKELY(ret == -1)) {
  2368. /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
  2369. tor_assert(errno != EAGAIN);
  2370. tor_assert(errno != EINTR);
  2371. /* Probably ENOSYS. */
  2372. log_warn(LD_CRYPTO, "Can't get entropy from getrandom().");
  2373. getrandom_works = 0; /* Don't bother trying again. */
  2374. return -1;
  2375. /* LCOV_EXCL_STOP */
  2376. }
  2377. tor_assert(ret == (long)out_len);
  2378. return 0;
  2379. }
  2380. return -1; /* getrandom() previously failed unexpectedly. */
  2381. #elif defined(HAVE_GETENTROPY)
  2382. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  2383. * the only gotcha is that requests are limited to 256 bytes.
  2384. */
  2385. return getentropy(out, out_len);
  2386. #else
  2387. (void) out;
  2388. #endif
  2389. /* This platform doesn't have a supported syscall based random. */
  2390. return -1;
  2391. }
  2392. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2393. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  2394. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  2395. * is imposed.
  2396. */
  2397. static int
  2398. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  2399. {
  2400. #ifdef TOR_UNIT_TESTS
  2401. if (break_strongest_rng_fallback)
  2402. return -1;
  2403. #endif
  2404. #ifdef _WIN32
  2405. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  2406. (void)out;
  2407. (void)out_len;
  2408. return -1;
  2409. #else
  2410. static const char *filenames[] = {
  2411. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  2412. };
  2413. int fd, i;
  2414. size_t n;
  2415. for (i = 0; filenames[i]; ++i) {
  2416. log_debug(LD_FS, "Opening %s for entropy", filenames[i]);
  2417. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  2418. if (fd<0) continue;
  2419. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  2420. n = read_all(fd, (char*)out, out_len, 0);
  2421. close(fd);
  2422. if (n != out_len) {
  2423. /* LCOV_EXCL_START
  2424. * We can't make /dev/foorandom actually fail. */
  2425. log_warn(LD_CRYPTO,
  2426. "Error reading from entropy source (read only %lu bytes).",
  2427. (unsigned long)n);
  2428. return -1;
  2429. /* LCOV_EXCL_STOP */
  2430. }
  2431. return 0;
  2432. }
  2433. return -1;
  2434. #endif
  2435. }
  2436. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2437. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  2438. * request size of 256 bytes is imposed.
  2439. */
  2440. STATIC int
  2441. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  2442. {
  2443. static const size_t sanity_min_size = 16;
  2444. static const int max_attempts = 3;
  2445. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2446. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  2447. * zero filling the buffer and ensuring that it actually was at least
  2448. * partially modified.
  2449. *
  2450. * Checking that any individual byte is non-zero seems like it would
  2451. * fail too often (p = out_len * 1/256) for comfort, but this is an
  2452. * "adjust according to taste" sort of check.
  2453. */
  2454. memwipe(out, 0, out_len);
  2455. for (int i = 0; i < max_attempts; i++) {
  2456. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  2457. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  2458. /* Try to use the less-favored mechanism to get strong entropy. */
  2459. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  2460. /* Welp, we tried. Hopefully the calling code terminates the process
  2461. * since we're basically boned without good entropy.
  2462. */
  2463. log_warn(LD_CRYPTO,
  2464. "Cannot get strong entropy: no entropy source found.");
  2465. return -1;
  2466. }
  2467. }
  2468. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  2469. return 0;
  2470. }
  2471. /* LCOV_EXCL_START
  2472. *
  2473. * We tried max_attempts times to fill a buffer >= 128 bits long,
  2474. * and each time it returned all '0's. Either the system entropy
  2475. * source is busted, or the user should go out and buy a ticket to
  2476. * every lottery on the planet.
  2477. */
  2478. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  2479. return -1;
  2480. /* LCOV_EXCL_STOP */
  2481. }
  2482. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2483. * storing it into <b>out</b>.
  2484. */
  2485. void
  2486. crypto_strongest_rand(uint8_t *out, size_t out_len)
  2487. {
  2488. #define DLEN SHA512_DIGEST_LENGTH
  2489. /* We're going to hash DLEN bytes from the system RNG together with some
  2490. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  2491. */
  2492. uint8_t inp[DLEN*2];
  2493. uint8_t tmp[DLEN];
  2494. tor_assert(out);
  2495. while (out_len) {
  2496. crypto_rand((char*) inp, DLEN);
  2497. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  2498. // LCOV_EXCL_START
  2499. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  2500. "important key. Exiting.");
  2501. /* Die with an assertion so we get a stack trace. */
  2502. tor_assert(0);
  2503. // LCOV_EXCL_STOP
  2504. }
  2505. if (out_len >= DLEN) {
  2506. SHA512(inp, sizeof(inp), out);
  2507. out += DLEN;
  2508. out_len -= DLEN;
  2509. } else {
  2510. SHA512(inp, sizeof(inp), tmp);
  2511. memcpy(out, tmp, out_len);
  2512. break;
  2513. }
  2514. }
  2515. memwipe(tmp, 0, sizeof(tmp));
  2516. memwipe(inp, 0, sizeof(inp));
  2517. #undef DLEN
  2518. }
  2519. /** Seed OpenSSL's random number generator with bytes from the operating
  2520. * system. Return 0 on success, -1 on failure.
  2521. */
  2522. int
  2523. crypto_seed_rng(void)
  2524. {
  2525. int rand_poll_ok = 0, load_entropy_ok = 0;
  2526. uint8_t buf[ADD_ENTROPY];
  2527. /* OpenSSL has a RAND_poll function that knows about more kinds of
  2528. * entropy than we do. We'll try calling that, *and* calling our own entropy
  2529. * functions. If one succeeds, we'll accept the RNG as seeded. */
  2530. rand_poll_ok = RAND_poll();
  2531. if (rand_poll_ok == 0)
  2532. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  2533. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  2534. if (load_entropy_ok) {
  2535. RAND_seed(buf, sizeof(buf));
  2536. }
  2537. memwipe(buf, 0, sizeof(buf));
  2538. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  2539. return 0;
  2540. else
  2541. return -1;
  2542. }
  2543. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  2544. * for unit tests.
  2545. *
  2546. * This function is not allowed to fail; if it would fail to generate strong
  2547. * entropy, it must terminate the process instead.
  2548. */
  2549. MOCK_IMPL(void,
  2550. crypto_rand, (char *to, size_t n))
  2551. {
  2552. crypto_rand_unmocked(to, n);
  2553. }
  2554. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  2555. * will want crypto_rand instead.
  2556. *
  2557. * This function is not allowed to fail; if it would fail to generate strong
  2558. * entropy, it must terminate the process instead.
  2559. */
  2560. void
  2561. crypto_rand_unmocked(char *to, size_t n)
  2562. {
  2563. int r;
  2564. if (n == 0)
  2565. return;
  2566. tor_assert(n < INT_MAX);
  2567. tor_assert(to);
  2568. r = RAND_bytes((unsigned char*)to, (int)n);
  2569. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  2570. * stack trace about where it happened.
  2571. */
  2572. tor_assert(r >= 0);
  2573. }
  2574. /** Return a pseudorandom integer, chosen uniformly from the values
  2575. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  2576. * INT_MAX+1, inclusive. */
  2577. int
  2578. crypto_rand_int(unsigned int max)
  2579. {
  2580. unsigned int val;
  2581. unsigned int cutoff;
  2582. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  2583. tor_assert(max > 0); /* don't div by 0 */
  2584. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2585. * distribution with clipping at the upper end of unsigned int's
  2586. * range.
  2587. */
  2588. cutoff = UINT_MAX - (UINT_MAX%max);
  2589. while (1) {
  2590. crypto_rand((char*)&val, sizeof(val));
  2591. if (val < cutoff)
  2592. return val % max;
  2593. }
  2594. }
  2595. /** Return a pseudorandom integer, chosen uniformly from the values i such
  2596. * that min <= i < max.
  2597. *
  2598. * <b>min</b> MUST be in range [0, <b>max</b>).
  2599. * <b>max</b> MUST be in range (min, INT_MAX].
  2600. */
  2601. int
  2602. crypto_rand_int_range(unsigned int min, unsigned int max)
  2603. {
  2604. tor_assert(min < max);
  2605. tor_assert(max <= INT_MAX);
  2606. /* The overflow is avoided here because crypto_rand_int() returns a value
  2607. * between 0 and (max - min) inclusive. */
  2608. return min + crypto_rand_int(max - min);
  2609. }
  2610. /** As crypto_rand_int_range, but supports uint64_t. */
  2611. uint64_t
  2612. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  2613. {
  2614. tor_assert(min < max);
  2615. return min + crypto_rand_uint64(max - min);
  2616. }
  2617. /** As crypto_rand_int_range, but supports time_t. */
  2618. time_t
  2619. crypto_rand_time_range(time_t min, time_t max)
  2620. {
  2621. tor_assert(min < max);
  2622. return min + (time_t)crypto_rand_uint64(max - min);
  2623. }
  2624. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  2625. * between 0 and <b>max</b>-1 inclusive. */
  2626. uint64_t
  2627. crypto_rand_uint64(uint64_t max)
  2628. {
  2629. uint64_t val;
  2630. uint64_t cutoff;
  2631. tor_assert(max < UINT64_MAX);
  2632. tor_assert(max > 0); /* don't div by 0 */
  2633. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2634. * distribution with clipping at the upper end of unsigned int's
  2635. * range.
  2636. */
  2637. cutoff = UINT64_MAX - (UINT64_MAX%max);
  2638. while (1) {
  2639. crypto_rand((char*)&val, sizeof(val));
  2640. if (val < cutoff)
  2641. return val % max;
  2642. }
  2643. }
  2644. /** Return a pseudorandom double d, chosen uniformly from the range
  2645. * 0.0 <= d < 1.0.
  2646. */
  2647. double
  2648. crypto_rand_double(void)
  2649. {
  2650. /* We just use an unsigned int here; we don't really care about getting
  2651. * more than 32 bits of resolution */
  2652. unsigned int uint;
  2653. crypto_rand((char*)&uint, sizeof(uint));
  2654. #if SIZEOF_INT == 4
  2655. #define UINT_MAX_AS_DOUBLE 4294967296.0
  2656. #elif SIZEOF_INT == 8
  2657. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  2658. #else
  2659. #error SIZEOF_INT is neither 4 nor 8
  2660. #endif
  2661. return ((double)uint) / UINT_MAX_AS_DOUBLE;
  2662. }
  2663. /** Generate and return a new random hostname starting with <b>prefix</b>,
  2664. * ending with <b>suffix</b>, and containing no fewer than
  2665. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  2666. * characters. Does not check for failure.
  2667. *
  2668. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  2669. **/
  2670. char *
  2671. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  2672. const char *suffix)
  2673. {
  2674. char *result, *rand_bytes;
  2675. int randlen, rand_bytes_len;
  2676. size_t resultlen, prefixlen;
  2677. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  2678. max_rand_len = MAX_DNS_LABEL_SIZE;
  2679. if (min_rand_len > max_rand_len)
  2680. min_rand_len = max_rand_len;
  2681. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  2682. prefixlen = strlen(prefix);
  2683. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  2684. rand_bytes_len = ((randlen*5)+7)/8;
  2685. if (rand_bytes_len % 5)
  2686. rand_bytes_len += 5 - (rand_bytes_len%5);
  2687. rand_bytes = tor_malloc(rand_bytes_len);
  2688. crypto_rand(rand_bytes, rand_bytes_len);
  2689. result = tor_malloc(resultlen);
  2690. memcpy(result, prefix, prefixlen);
  2691. base32_encode(result+prefixlen, resultlen-prefixlen,
  2692. rand_bytes, rand_bytes_len);
  2693. tor_free(rand_bytes);
  2694. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  2695. return result;
  2696. }
  2697. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  2698. * is empty. */
  2699. void *
  2700. smartlist_choose(const smartlist_t *sl)
  2701. {
  2702. int len = smartlist_len(sl);
  2703. if (len)
  2704. return smartlist_get(sl,crypto_rand_int(len));
  2705. return NULL; /* no elements to choose from */
  2706. }
  2707. /** Scramble the elements of <b>sl</b> into a random order. */
  2708. void
  2709. smartlist_shuffle(smartlist_t *sl)
  2710. {
  2711. int i;
  2712. /* From the end of the list to the front, choose at random from the
  2713. positions we haven't looked at yet, and swap that position into the
  2714. current position. Remember to give "no swap" the same probability as
  2715. any other swap. */
  2716. for (i = smartlist_len(sl)-1; i > 0; --i) {
  2717. int j = crypto_rand_int(i+1);
  2718. smartlist_swap(sl, i, j);
  2719. }
  2720. }
  2721. /**
  2722. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  2723. * the value <b>byte</b>.
  2724. * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
  2725. *
  2726. * This function is preferable to memset, since many compilers will happily
  2727. * optimize out memset() when they can convince themselves that the data being
  2728. * cleared will never be read.
  2729. *
  2730. * Right now, our convention is to use this function when we are wiping data
  2731. * that's about to become inaccessible, such as stack buffers that are about
  2732. * to go out of scope or structures that are about to get freed. (In
  2733. * practice, it appears that the compilers we're currently using will optimize
  2734. * out the memset()s for stack-allocated buffers, but not those for
  2735. * about-to-be-freed structures. That could change, though, so we're being
  2736. * wary.) If there are live reads for the data, then you can just use
  2737. * memset().
  2738. */
  2739. void
  2740. memwipe(void *mem, uint8_t byte, size_t sz)
  2741. {
  2742. if (sz == 0) {
  2743. return;
  2744. }
  2745. /* If sz is nonzero, then mem must not be NULL. */
  2746. tor_assert(mem != NULL);
  2747. /* Data this large is likely to be an underflow. */
  2748. tor_assert(sz < SIZE_T_CEILING);
  2749. /* Because whole-program-optimization exists, we may not be able to just
  2750. * have this function call "memset". A smart compiler could inline it, then
  2751. * eliminate dead memsets, and declare itself to be clever. */
  2752. #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
  2753. /* Here's what you do on windows. */
  2754. SecureZeroMemory(mem,sz);
  2755. #elif defined(HAVE_RTLSECUREZEROMEMORY)
  2756. RtlSecureZeroMemory(mem,sz);
  2757. #elif defined(HAVE_EXPLICIT_BZERO)
  2758. /* The BSDs provide this. */
  2759. explicit_bzero(mem, sz);
  2760. #elif defined(HAVE_MEMSET_S)
  2761. /* This is in the C99 standard. */
  2762. memset_s(mem, sz, 0, sz);
  2763. #else
  2764. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  2765. * based on the pointer value, then uses that junk to update a global
  2766. * variable. It's an elaborate ruse to trick the compiler into not
  2767. * optimizing out the "wipe this memory" code. Read it if you like zany
  2768. * programming tricks! In later versions of Tor, we should look for better
  2769. * not-optimized-out memory wiping stuff...
  2770. *
  2771. * ...or maybe not. In practice, there are pure-asm implementations of
  2772. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  2773. **/
  2774. OPENSSL_cleanse(mem, sz);
  2775. #endif
  2776. /* Just in case some caller of memwipe() is relying on getting a buffer
  2777. * filled with a particular value, fill the buffer.
  2778. *
  2779. * If this function gets inlined, this memset might get eliminated, but
  2780. * that's okay: We only care about this particular memset in the case where
  2781. * the caller should have been using memset(), and the memset() wouldn't get
  2782. * eliminated. In other words, this is here so that we won't break anything
  2783. * if somebody accidentally calls memwipe() instead of memset().
  2784. **/
  2785. memset(mem, byte, sz);
  2786. }
  2787. #ifndef OPENSSL_THREADS
  2788. #error OpenSSL has been built without thread support. Tor requires an \
  2789. OpenSSL library with thread support enabled.
  2790. #endif
  2791. #ifndef NEW_THREAD_API
  2792. /** Helper: OpenSSL uses this callback to manipulate mutexes. */
  2793. static void
  2794. openssl_locking_cb_(int mode, int n, const char *file, int line)
  2795. {
  2796. (void)file;
  2797. (void)line;
  2798. if (!openssl_mutexes_)
  2799. /* This is not a really good fix for the
  2800. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  2801. * it can't hurt. */
  2802. return;
  2803. if (mode & CRYPTO_LOCK)
  2804. tor_mutex_acquire(openssl_mutexes_[n]);
  2805. else
  2806. tor_mutex_release(openssl_mutexes_[n]);
  2807. }
  2808. static void
  2809. tor_set_openssl_thread_id(CRYPTO_THREADID *threadid)
  2810. {
  2811. CRYPTO_THREADID_set_numeric(threadid, tor_get_thread_id());
  2812. }
  2813. #endif
  2814. #if 0
  2815. /* This code is disabled, because OpenSSL never actually uses these callbacks.
  2816. */
  2817. /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
  2818. * as a lock. */
  2819. struct CRYPTO_dynlock_value {
  2820. tor_mutex_t *lock;
  2821. };
  2822. /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
  2823. * documentation in OpenSSL's docs for more info. */
  2824. static struct CRYPTO_dynlock_value *
  2825. openssl_dynlock_create_cb_(const char *file, int line)
  2826. {
  2827. struct CRYPTO_dynlock_value *v;
  2828. (void)file;
  2829. (void)line;
  2830. v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
  2831. v->lock = tor_mutex_new();
  2832. return v;
  2833. }
  2834. /** OpenSSL callback function to acquire or release a lock: see
  2835. * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
  2836. static void
  2837. openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
  2838. const char *file, int line)
  2839. {
  2840. (void)file;
  2841. (void)line;
  2842. if (mode & CRYPTO_LOCK)
  2843. tor_mutex_acquire(v->lock);
  2844. else
  2845. tor_mutex_release(v->lock);
  2846. }
  2847. /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
  2848. * documentation in OpenSSL's docs for more info. */
  2849. static void
  2850. openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
  2851. const char *file, int line)
  2852. {
  2853. (void)file;
  2854. (void)line;
  2855. tor_mutex_free(v->lock);
  2856. tor_free(v);
  2857. }
  2858. #endif
  2859. /** @{ */
  2860. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  2861. * multithreaded. Returns 0. */
  2862. static int
  2863. setup_openssl_threading(void)
  2864. {
  2865. #ifndef NEW_THREAD_API
  2866. int i;
  2867. int n = CRYPTO_num_locks();
  2868. n_openssl_mutexes_ = n;
  2869. openssl_mutexes_ = tor_calloc(n, sizeof(tor_mutex_t *));
  2870. for (i=0; i < n; ++i)
  2871. openssl_mutexes_[i] = tor_mutex_new();
  2872. CRYPTO_set_locking_callback(openssl_locking_cb_);
  2873. CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id);
  2874. #endif
  2875. #if 0
  2876. CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
  2877. CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
  2878. CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
  2879. #endif
  2880. return 0;
  2881. }
  2882. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  2883. * failure.
  2884. */
  2885. int
  2886. crypto_global_cleanup(void)
  2887. {
  2888. EVP_cleanup();
  2889. #ifdef NEW_THREAD_API
  2890. ERR_remove_thread_state();
  2891. #else
  2892. ERR_remove_thread_state(NULL);
  2893. #endif
  2894. ERR_free_strings();
  2895. if (dh_param_p)
  2896. BN_clear_free(dh_param_p);
  2897. if (dh_param_p_tls)
  2898. BN_clear_free(dh_param_p_tls);
  2899. if (dh_param_g)
  2900. BN_clear_free(dh_param_g);
  2901. #ifndef DISABLE_ENGINES
  2902. ENGINE_cleanup();
  2903. #endif
  2904. CONF_modules_unload(1);
  2905. CRYPTO_cleanup_all_ex_data();
  2906. #ifndef NEW_THREAD_API
  2907. if (n_openssl_mutexes_) {
  2908. int n = n_openssl_mutexes_;
  2909. tor_mutex_t **ms = openssl_mutexes_;
  2910. int i;
  2911. openssl_mutexes_ = NULL;
  2912. n_openssl_mutexes_ = 0;
  2913. for (i=0;i<n;++i) {
  2914. tor_mutex_free(ms[i]);
  2915. }
  2916. tor_free(ms);
  2917. }
  2918. #endif
  2919. tor_free(crypto_openssl_version_str);
  2920. tor_free(crypto_openssl_header_version_str);
  2921. return 0;
  2922. }
  2923. /** @} */