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