crypto.c 90 KB

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