crypto.c 82 KB

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