crypto.c 96 KB

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