crypto.c 82 KB

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