crypto.c 95 KB

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