crypto.c 89 KB

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