crypto.c 63 KB

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