crypto.c 87 KB

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