crypto.c 91 KB

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