crypto.c 85 KB

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