crypto.c 91 KB

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