crypto.c 81 KB

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