crypto.c 93 KB

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