crypto.c 84 KB

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