crypto.c 74 KB

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