crypto.c 82 KB

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