crypto.c 82 KB

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