crypto.c 94 KB

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