crypto.c 90 KB

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