crypto.c 89 KB

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