crypto.c 89 KB

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