crypto.c 90 KB

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