crypto.c 89 KB

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