crypto.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar.
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char crypto_c_id[] =
  6. "$Id$";
  7. /**
  8. * \file crypto.c
  9. * \brief Wrapper functions to present a consistent interface to
  10. * public-key and symmetric cryptography operations from OpenSSL.
  11. **/
  12. #include "orconfig.h"
  13. #ifdef MS_WINDOWS
  14. #define WIN32_WINNT 0x400
  15. #define _WIN32_WINNT 0x400
  16. #define WIN32_LEAN_AND_MEAN
  17. #include <windows.h>
  18. #include <wincrypt.h>
  19. #endif
  20. #include <string.h>
  21. #include <openssl/err.h>
  22. #include <openssl/rsa.h>
  23. #include <openssl/pem.h>
  24. #include <openssl/evp.h>
  25. #include <openssl/rand.h>
  26. #include <openssl/opensslv.h>
  27. #include <openssl/bn.h>
  28. #include <openssl/dh.h>
  29. #include <openssl/rsa.h>
  30. #include <openssl/dh.h>
  31. #include <openssl/conf.h>
  32. #include <stdlib.h>
  33. #include <assert.h>
  34. #include <stdio.h>
  35. #include <limits.h>
  36. #ifdef HAVE_CTYPE_H
  37. #include <ctype.h>
  38. #endif
  39. #ifdef HAVE_UNISTD_H
  40. #include <unistd.h>
  41. #endif
  42. #ifdef HAVE_FCNTL_H
  43. #include <fcntl.h>
  44. #endif
  45. #ifdef HAVE_SYS_FCNTL_H
  46. #include <sys/fcntl.h>
  47. #endif
  48. #include "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 < 0x00905000l
  55. #error "We require openssl >= 0.9.5"
  56. #elif OPENSSL_VERSION_NUMBER < 0x00906000l
  57. #define OPENSSL_095
  58. #endif
  59. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  60. #define OPENSSL_PRE_097
  61. #define NO_ENGINES
  62. #else
  63. #include <openssl/engine.h>
  64. #endif
  65. /* Certain functions that return a success code in OpenSSL 0.9.6 return void
  66. * (and don't indicate errors) in OpenSSL version 0.9.5.
  67. *
  68. * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
  69. */
  70. #ifdef OPENSSL_095
  71. #define RETURN_SSL_OUTCOME(exp) (exp); return 0
  72. #else
  73. #define RETURN_SSL_OUTCOME(exp) return !(exp)
  74. #endif
  75. /** Macro: is k a valid RSA public or private key? */
  76. #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
  77. /** Macro: is k a valid RSA private key? */
  78. #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
  79. #ifdef TOR_IS_MULTITHREADED
  80. static tor_mutex_t **_openssl_mutexes = NULL;
  81. static int _n_openssl_mutexes = -1;
  82. #endif
  83. /** A public key, or a public/private keypair. */
  84. struct crypto_pk_env_t
  85. {
  86. int refs; /* reference counting so we don't have to copy keys */
  87. RSA *key;
  88. };
  89. /** Key and stream information for a stream cipher. */
  90. struct crypto_cipher_env_t
  91. {
  92. char key[CIPHER_KEY_LEN];
  93. aes_cnt_cipher_t *cipher;
  94. };
  95. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  96. * while we're waiting for the second.*/
  97. struct crypto_dh_env_t {
  98. DH *dh;
  99. };
  100. /* Prototypes for functions only used by tortls.c */
  101. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
  102. RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
  103. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
  104. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
  105. static int setup_openssl_threading(void);
  106. static int tor_check_dh_key(BIGNUM *bn);
  107. /** Return the number of bytes added by padding method <b>padding</b>.
  108. */
  109. static INLINE int
  110. crypto_get_rsa_padding_overhead(int padding)
  111. {
  112. switch (padding)
  113. {
  114. case RSA_NO_PADDING: return 0;
  115. case RSA_PKCS1_OAEP_PADDING: return 42;
  116. case RSA_PKCS1_PADDING: return 11;
  117. default: tor_assert(0); return -1;
  118. }
  119. }
  120. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  121. */
  122. static INLINE int
  123. crypto_get_rsa_padding(int padding)
  124. {
  125. switch (padding)
  126. {
  127. case PK_NO_PADDING: return RSA_NO_PADDING;
  128. case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
  129. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  130. default: tor_assert(0); return -1;
  131. }
  132. }
  133. /** Boolean: has OpenSSL's crypto been initialized? */
  134. static int _crypto_global_initialized = 0;
  135. /** Log all pending crypto errors at level <b>severity</b>. Use
  136. * <b>doing</b> to describe our current activities.
  137. */
  138. static void
  139. crypto_log_errors(int severity, const char *doing)
  140. {
  141. unsigned int err;
  142. const char *msg, *lib, *func;
  143. while ((err = ERR_get_error()) != 0) {
  144. msg = (const char*)ERR_reason_error_string(err);
  145. lib = (const char*)ERR_lib_error_string(err);
  146. func = (const char*)ERR_func_error_string(err);
  147. if (!msg) msg = "(null)";
  148. if (doing) {
  149. log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  150. doing, msg, lib, func);
  151. } else {
  152. log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
  153. }
  154. }
  155. }
  156. #ifndef NO_ENGINES
  157. static void
  158. log_engine(const char *fn, ENGINE *e)
  159. {
  160. if (e) {
  161. const char *name, *id;
  162. name = ENGINE_get_name(e);
  163. id = ENGINE_get_id(e);
  164. log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
  165. name?name:"?", id?id:"?", fn);
  166. } else {
  167. log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
  168. }
  169. }
  170. #endif
  171. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  172. */
  173. int
  174. crypto_global_init(int useAccel)
  175. {
  176. if (!_crypto_global_initialized) {
  177. ERR_load_crypto_strings();
  178. OpenSSL_add_all_algorithms();
  179. _crypto_global_initialized = 1;
  180. setup_openssl_threading();
  181. #ifndef NO_ENGINES
  182. if (useAccel) {
  183. if (useAccel < 0)
  184. warn(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
  185. info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  186. ENGINE_load_builtin_engines();
  187. if (!ENGINE_register_all_complete())
  188. return -1;
  189. /* XXXX make sure this isn't leaking. */
  190. log_engine("RSA", ENGINE_get_default_RSA());
  191. log_engine("DH", ENGINE_get_default_DH());
  192. log_engine("RAND", ENGINE_get_default_RAND());
  193. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  194. log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
  195. log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  196. }
  197. #endif
  198. }
  199. return 0;
  200. }
  201. /** Free crypto resources held by this thread. */
  202. void
  203. crypto_thread_cleanup(void)
  204. {
  205. ERR_remove_state(0);
  206. }
  207. /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
  208. */
  209. int
  210. crypto_global_cleanup(void)
  211. {
  212. EVP_cleanup();
  213. ERR_remove_state(0);
  214. ERR_free_strings();
  215. #ifndef NO_ENGINES
  216. ENGINE_cleanup();
  217. CONF_modules_unload(1);
  218. CRYPTO_cleanup_all_ex_data();
  219. #endif
  220. #ifdef TOR_IS_MULTITHREADED
  221. if (_n_openssl_mutexes) {
  222. int n = _n_openssl_mutexes;
  223. tor_mutex_t **ms = _openssl_mutexes;
  224. int i;
  225. _openssl_mutexes = NULL;
  226. _n_openssl_mutexes = 0;
  227. for (i=0;i<n;++i) {
  228. tor_mutex_free(ms[i]);
  229. }
  230. tor_free(ms);
  231. }
  232. #endif
  233. return 0;
  234. }
  235. /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
  236. crypto_pk_env_t *
  237. _crypto_new_pk_env_rsa(RSA *rsa)
  238. {
  239. crypto_pk_env_t *env;
  240. tor_assert(rsa);
  241. env = tor_malloc(sizeof(crypto_pk_env_t));
  242. env->refs = 1;
  243. env->key = rsa;
  244. return env;
  245. }
  246. /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
  247. RSA *
  248. _crypto_pk_env_get_rsa(crypto_pk_env_t *env)
  249. {
  250. return env->key;
  251. }
  252. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
  253. * private is set, include the private-key portion of the key. */
  254. EVP_PKEY *
  255. _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
  256. {
  257. RSA *key = NULL;
  258. EVP_PKEY *pkey = NULL;
  259. tor_assert(env->key);
  260. if (private) {
  261. if (!(key = RSAPrivateKey_dup(env->key)))
  262. goto error;
  263. } else {
  264. if (!(key = RSAPublicKey_dup(env->key)))
  265. goto error;
  266. }
  267. if (!(pkey = EVP_PKEY_new()))
  268. goto error;
  269. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  270. goto error;
  271. return pkey;
  272. error:
  273. if (pkey)
  274. EVP_PKEY_free(pkey);
  275. if (key)
  276. RSA_free(key);
  277. return NULL;
  278. }
  279. /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
  280. */
  281. DH *
  282. _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
  283. {
  284. return dh->dh;
  285. }
  286. /** Allocate and return storage for a public key. The key itself will not yet
  287. * be set.
  288. */
  289. crypto_pk_env_t *
  290. crypto_new_pk_env(void)
  291. {
  292. RSA *rsa;
  293. rsa = RSA_new();
  294. if (!rsa) return NULL;
  295. return _crypto_new_pk_env_rsa(rsa);
  296. }
  297. /** Release a reference to an asymmetric key; when all the references
  298. * are released, free the key.
  299. */
  300. void
  301. crypto_free_pk_env(crypto_pk_env_t *env)
  302. {
  303. tor_assert(env);
  304. if (--env->refs > 0)
  305. return;
  306. if (env->key)
  307. RSA_free(env->key);
  308. tor_free(env);
  309. }
  310. /** Create a new symmetric cipher for a given key and encryption flag
  311. * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
  312. * on failure.
  313. */
  314. crypto_cipher_env_t *
  315. crypto_create_init_cipher(const char *key, int encrypt_mode)
  316. {
  317. int r;
  318. crypto_cipher_env_t *crypto = NULL;
  319. if (! (crypto = crypto_new_cipher_env())) {
  320. warn(LD_CRYPTO, "Unable to allocate crypto object");
  321. return NULL;
  322. }
  323. if (crypto_cipher_set_key(crypto, key)) {
  324. crypto_log_errors(LOG_WARN, "setting symmetric key");
  325. goto error;
  326. }
  327. if (encrypt_mode)
  328. r = crypto_cipher_encrypt_init_cipher(crypto);
  329. else
  330. r = crypto_cipher_decrypt_init_cipher(crypto);
  331. if (r)
  332. goto error;
  333. return crypto;
  334. error:
  335. if (crypto)
  336. crypto_free_cipher_env(crypto);
  337. return NULL;
  338. }
  339. /** Allocate and return a new symmetric cipher.
  340. */
  341. crypto_cipher_env_t *
  342. crypto_new_cipher_env(void)
  343. {
  344. crypto_cipher_env_t *env;
  345. env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
  346. env->cipher = aes_new_cipher();
  347. return env;
  348. }
  349. /** Free a symmetric cipher.
  350. */
  351. void
  352. crypto_free_cipher_env(crypto_cipher_env_t *env)
  353. {
  354. tor_assert(env);
  355. tor_assert(env->cipher);
  356. aes_free_cipher(env->cipher);
  357. tor_free(env);
  358. }
  359. /* public key crypto */
  360. /** Generate a new public/private keypair in <b>env</b>. Return 0 on
  361. * success, -1 on failure.
  362. */
  363. int
  364. crypto_pk_generate_key(crypto_pk_env_t *env)
  365. {
  366. tor_assert(env);
  367. if (env->key)
  368. RSA_free(env->key);
  369. env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
  370. if (!env->key) {
  371. crypto_log_errors(LOG_WARN, "generating RSA key");
  372. return -1;
  373. }
  374. return 0;
  375. }
  376. /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
  377. * Return 0 on success, -1 on failure.
  378. */
  379. static int
  380. crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
  381. const char *s)
  382. {
  383. BIO *b;
  384. tor_assert(env);
  385. tor_assert(s);
  386. /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
  387. b = BIO_new_mem_buf((char*)s, -1);
  388. if (env->key)
  389. RSA_free(env->key);
  390. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
  391. BIO_free(b);
  392. if (!env->key) {
  393. crypto_log_errors(LOG_WARN, "Error parsing private key");
  394. return -1;
  395. }
  396. return 0;
  397. }
  398. /** Read a PEM-encoded private key from the file named by
  399. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  400. */
  401. int
  402. crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
  403. const char *keyfile)
  404. {
  405. char *contents;
  406. int r;
  407. /* Read the file into a string. */
  408. contents = read_file_to_str(keyfile, 0);
  409. if (!contents) {
  410. warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  411. return -1;
  412. }
  413. /* Try to parse it. */
  414. r = crypto_pk_read_private_key_from_string(env, contents);
  415. tor_free(contents);
  416. if (r)
  417. return -1; /* read_private_key_from_string already warned, so we don't.*/
  418. /* Make sure it's valid. */
  419. if (crypto_pk_check_key(env) <= 0)
  420. return -1;
  421. return 0;
  422. }
  423. /** PEM-encode the public key portion of <b>env</b> and write it to a
  424. * newly allocated string. On success, set *<b>dest</b> to the new
  425. * string, *<b>len</b> to the string's length, and return 0. On
  426. * failure, return -1.
  427. */
  428. int
  429. crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
  430. size_t *len)
  431. {
  432. BUF_MEM *buf;
  433. BIO *b;
  434. tor_assert(env);
  435. tor_assert(env->key);
  436. tor_assert(dest);
  437. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  438. /* Now you can treat b as if it were a file. Just use the
  439. * PEM_*_bio_* functions instead of the non-bio variants.
  440. */
  441. if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
  442. crypto_log_errors(LOG_WARN, "writing public key to string");
  443. return -1;
  444. }
  445. BIO_get_mem_ptr(b, &buf);
  446. BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  447. BIO_free(b);
  448. tor_assert(buf->length >= 0);
  449. *dest = tor_malloc(buf->length+1);
  450. memcpy(*dest, buf->data, buf->length);
  451. (*dest)[buf->length] = 0; /* null terminate it */
  452. *len = buf->length;
  453. BUF_MEM_free(buf);
  454. return 0;
  455. }
  456. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  457. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  458. * failure.
  459. */
  460. int
  461. crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
  462. size_t len)
  463. {
  464. BIO *b;
  465. tor_assert(env);
  466. tor_assert(src);
  467. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  468. BIO_write(b, src, len);
  469. if (env->key)
  470. RSA_free(env->key);
  471. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  472. BIO_free(b);
  473. if (!env->key) {
  474. crypto_log_errors(LOG_WARN, "reading public key from string");
  475. return -1;
  476. }
  477. return 0;
  478. }
  479. /* Write the private key from 'env' into the file named by 'fname',
  480. * PEM-encoded. Return 0 on success, -1 on failure.
  481. */
  482. int
  483. crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
  484. const char *fname)
  485. {
  486. BIO *bio;
  487. char *cp;
  488. long len;
  489. char *s;
  490. int r;
  491. tor_assert(PRIVATE_KEY_OK(env));
  492. if (!(bio = BIO_new(BIO_s_mem())))
  493. return -1;
  494. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  495. == 0) {
  496. crypto_log_errors(LOG_WARN, "writing private key");
  497. BIO_free(bio);
  498. return -1;
  499. }
  500. len = BIO_get_mem_data(bio, &cp);
  501. tor_assert(len >= 0);
  502. s = tor_malloc(len+1);
  503. memcpy(s, cp, len);
  504. s[len]='\0';
  505. r = write_str_to_file(fname, s, 0);
  506. BIO_free(bio);
  507. tor_free(s);
  508. return r;
  509. }
  510. /** Allocate a new string in *<b>out</b>, containing the public portion of the
  511. * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
  512. * length of the encoded representation on success, and -1 on failure.
  513. *
  514. * <i>This function is for temporary use only. We need a simple
  515. * one-line representation for keys to work around a bug in parsing
  516. * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
  517. * in versions of Tor up to 0.0.9pre2.</i>
  518. */
  519. int
  520. crypto_pk_DER64_encode_public_key(crypto_pk_env_t *env, char **out)
  521. {
  522. int len;
  523. char buf[PK_BYTES*2]; /* Too long, but hey, stacks are big. */
  524. tor_assert(env);
  525. tor_assert(out);
  526. len = crypto_pk_asn1_encode(env, buf, sizeof(buf));
  527. if (len < 0) {
  528. return -1;
  529. }
  530. *out = tor_malloc(len * 2); /* too long, but safe. */
  531. if (base64_encode(*out, len*2, buf, len) < 0) {
  532. warn(LD_CRYPTO, "Error base64-encoding DER-encoded key");
  533. tor_free(*out);
  534. return -1;
  535. }
  536. /* Remove spaces */
  537. tor_strstrip(*out, " \r\n\t");
  538. return strlen(*out);
  539. }
  540. /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
  541. * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
  542. *
  543. * <i>This function is for temporary use only. We need a simple
  544. * one-line representation for keys to work around a bug in parsing
  545. * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
  546. * in versions of Tor up to 0.0.9pre2.</i>
  547. */
  548. crypto_pk_env_t *
  549. crypto_pk_DER64_decode_public_key(const char *in)
  550. {
  551. char partitioned[PK_BYTES*2 + 16];
  552. char buf[PK_BYTES*2];
  553. int len;
  554. tor_assert(in);
  555. len = strlen(in);
  556. if (strlen(in) > PK_BYTES*2) {
  557. return NULL;
  558. }
  559. /* base64_decode doesn't work unless we insert linebreaks every 64
  560. * characters. how dumb. */
  561. if (tor_strpartition(partitioned, sizeof(partitioned), in, "\n", 64,
  562. ALWAYS_TERMINATE))
  563. return NULL;
  564. len = base64_decode(buf, sizeof(buf), partitioned, strlen(partitioned));
  565. if (len<0) {
  566. warn(LD_CRYPTO,"Error base-64 decoding key");
  567. return NULL;
  568. }
  569. return crypto_pk_asn1_decode(buf, len);
  570. }
  571. /** Return true iff <b>env</b> has a valid key.
  572. */
  573. int
  574. crypto_pk_check_key(crypto_pk_env_t *env)
  575. {
  576. int r;
  577. tor_assert(env);
  578. r = RSA_check_key(env->key);
  579. if (r <= 0)
  580. crypto_log_errors(LOG_WARN,"checking RSA key");
  581. return r;
  582. }
  583. /** Compare the public-key components of a and b. Return -1 if a\<b, 0
  584. * if a==b, and 1 if a\>b.
  585. */
  586. int
  587. crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
  588. {
  589. int result;
  590. if (!a || !b)
  591. return -1;
  592. if (!a->key || !b->key)
  593. return -1;
  594. tor_assert(PUBLIC_KEY_OK(a));
  595. tor_assert(PUBLIC_KEY_OK(b));
  596. result = BN_cmp((a->key)->n, (b->key)->n);
  597. if (result)
  598. return result;
  599. return BN_cmp((a->key)->e, (b->key)->e);
  600. }
  601. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  602. size_t
  603. crypto_pk_keysize(crypto_pk_env_t *env)
  604. {
  605. tor_assert(env);
  606. tor_assert(env->key);
  607. return (size_t) RSA_size(env->key);
  608. }
  609. /** Increase the reference count of <b>env</b>, and return it.
  610. */
  611. crypto_pk_env_t *
  612. crypto_pk_dup_key(crypto_pk_env_t *env)
  613. {
  614. tor_assert(env);
  615. tor_assert(env->key);
  616. env->refs++;
  617. return env;
  618. }
  619. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  620. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  621. * write the result to <b>to</b>, and return the number of bytes
  622. * written. On failure, return -1.
  623. */
  624. int
  625. crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
  626. const char *from, size_t fromlen, int padding)
  627. {
  628. int r;
  629. tor_assert(env);
  630. tor_assert(from);
  631. tor_assert(to);
  632. r = RSA_public_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  633. env->key, crypto_get_rsa_padding(padding));
  634. if (r<0) {
  635. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  636. return -1;
  637. }
  638. return r;
  639. }
  640. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  641. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  642. * write the result to <b>to</b>, and return the number of bytes
  643. * written. On failure, return -1.
  644. */
  645. int
  646. crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
  647. const char *from, size_t fromlen,
  648. int padding, int warnOnFailure)
  649. {
  650. int r;
  651. tor_assert(env);
  652. tor_assert(from);
  653. tor_assert(to);
  654. tor_assert(env->key);
  655. if (!env->key->p)
  656. /* Not a private key */
  657. return -1;
  658. r = RSA_private_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  659. env->key, crypto_get_rsa_padding(padding));
  660. if (r<0) {
  661. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  662. "performing RSA decryption");
  663. return -1;
  664. }
  665. return r;
  666. }
  667. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  668. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  669. * signed data to <b>to</b>, and return the number of bytes written.
  670. * On failure, return -1.
  671. */
  672. int
  673. crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
  674. const char *from, size_t fromlen)
  675. {
  676. int r;
  677. tor_assert(env);
  678. tor_assert(from);
  679. tor_assert(to);
  680. r = RSA_public_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  681. env->key, RSA_PKCS1_PADDING);
  682. if (r<0) {
  683. crypto_log_errors(LOG_WARN, "checking RSA signature");
  684. return -1;
  685. }
  686. return r;
  687. }
  688. /** Check a siglen-byte long signature at <b>sig</b> against
  689. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  690. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  691. * SHA1(data). Else return -1.
  692. */
  693. int
  694. crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
  695. int datalen, const char *sig, int siglen)
  696. {
  697. char digest[DIGEST_LEN];
  698. char buf[PK_BYTES+1];
  699. int r;
  700. tor_assert(env);
  701. tor_assert(data);
  702. tor_assert(sig);
  703. if (crypto_digest(digest,data,datalen)<0) {
  704. warn(LD_CRYPTO, "couldn't compute digest");
  705. return -1;
  706. }
  707. r = crypto_pk_public_checksig(env,buf,sig,siglen);
  708. if (r != DIGEST_LEN) {
  709. warn(LD_CRYPTO, "Invalid signature");
  710. return -1;
  711. }
  712. if (memcmp(buf, digest, DIGEST_LEN)) {
  713. warn(LD_CRYPTO, "Signature mismatched with digest.");
  714. return -1;
  715. }
  716. return 0;
  717. }
  718. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  719. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  720. * <b>to</b>, and return the number of bytes written. On failure, return
  721. * -1.
  722. */
  723. int
  724. crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
  725. const char *from, size_t fromlen)
  726. {
  727. int r;
  728. tor_assert(env);
  729. tor_assert(from);
  730. tor_assert(to);
  731. if (!env->key->p)
  732. /* Not a private key */
  733. return -1;
  734. r = RSA_private_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  735. env->key, RSA_PKCS1_PADDING);
  736. if (r<0) {
  737. crypto_log_errors(LOG_WARN, "generating RSA signature");
  738. return -1;
  739. }
  740. return r;
  741. }
  742. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  743. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  744. * store it in <b>to</b>. Return the number of bytes written on
  745. * success, and -1 on failure.
  746. */
  747. int
  748. crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
  749. const char *from, size_t fromlen)
  750. {
  751. char digest[DIGEST_LEN];
  752. if (crypto_digest(digest,from,fromlen)<0)
  753. return -1;
  754. return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
  755. }
  756. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  757. * bytes of data from <b>from</b>, with padding type 'padding',
  758. * storing the results on <b>to</b>.
  759. *
  760. * If no padding is used, the public key must be at least as large as
  761. * <b>from</b>.
  762. *
  763. * Returns the number of bytes written on success, -1 on failure.
  764. *
  765. * The encrypted data consists of:
  766. * - The source data, padded and encrypted with the public key, if the
  767. * padded source data is no longer than the public key, and <b>force</b>
  768. * is false, OR
  769. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  770. * padded and encrypted with the public key; followed by the rest of
  771. * the source data encrypted in AES-CTR mode with the symmetric key.
  772. */
  773. int
  774. crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
  775. char *to,
  776. const char *from,
  777. size_t fromlen,
  778. int padding, int force)
  779. {
  780. int overhead, outlen, r, symlen;
  781. size_t pkeylen;
  782. crypto_cipher_env_t *cipher = NULL;
  783. char buf[PK_BYTES+1];
  784. tor_assert(env);
  785. tor_assert(from);
  786. tor_assert(to);
  787. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  788. pkeylen = crypto_pk_keysize(env);
  789. if (padding == PK_NO_PADDING && fromlen < pkeylen)
  790. return -1;
  791. if (!force && fromlen+overhead <= pkeylen) {
  792. /* It all fits in a single encrypt. */
  793. return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
  794. }
  795. cipher = crypto_new_cipher_env();
  796. if (!cipher) return -1;
  797. if (crypto_cipher_generate_key(cipher)<0)
  798. goto err;
  799. /* You can't just run around RSA-encrypting any bitstream: if it's
  800. * greater than the RSA key, then OpenSSL will happily encrypt, and
  801. * later decrypt to the wrong value. So we set the first bit of
  802. * 'cipher->key' to 0 if we aren't padding. This means that our
  803. * symmetric key is really only 127 bits.
  804. */
  805. if (padding == PK_NO_PADDING)
  806. cipher->key[0] &= 0x7f;
  807. if (crypto_cipher_encrypt_init_cipher(cipher)<0)
  808. goto err;
  809. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  810. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  811. /* Length of symmetrically encrypted data. */
  812. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  813. outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
  814. if (outlen!=(int)pkeylen) {
  815. goto err;
  816. }
  817. r = crypto_cipher_encrypt(cipher, to+outlen,
  818. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  819. if (r<0) goto err;
  820. memset(buf, 0, sizeof(buf));
  821. crypto_free_cipher_env(cipher);
  822. return outlen + symlen;
  823. err:
  824. memset(buf, 0, sizeof(buf));
  825. if (cipher) crypto_free_cipher_env(cipher);
  826. return -1;
  827. }
  828. /** Invert crypto_pk_public_hybrid_encrypt. */
  829. int
  830. crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
  831. char *to,
  832. const char *from,
  833. size_t fromlen,
  834. int padding, int warnOnFailure)
  835. {
  836. int overhead, outlen, r;
  837. size_t pkeylen;
  838. crypto_cipher_env_t *cipher = NULL;
  839. char buf[PK_BYTES+1];
  840. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  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. outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
  847. warnOnFailure);
  848. if (outlen<0) {
  849. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  850. "Error decrypting public-key data");
  851. return -1;
  852. }
  853. if (outlen < CIPHER_KEY_LEN) {
  854. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  855. "No room for a symmetric key");
  856. return -1;
  857. }
  858. cipher = crypto_create_init_cipher(buf, 0);
  859. if (!cipher) {
  860. return -1;
  861. }
  862. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  863. outlen -= CIPHER_KEY_LEN;
  864. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  865. if (r<0)
  866. goto err;
  867. memset(buf,0,sizeof(buf));
  868. crypto_free_cipher_env(cipher);
  869. return outlen + (fromlen-pkeylen);
  870. err:
  871. memset(buf,0,sizeof(buf));
  872. if (cipher) crypto_free_cipher_env(cipher);
  873. return -1;
  874. }
  875. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  876. * Return -1 on error, or the number of characters used on success.
  877. */
  878. int
  879. crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
  880. {
  881. int len;
  882. unsigned char *buf, *cp;
  883. len = i2d_RSAPublicKey(pk->key, NULL);
  884. if (len < 0 || len > dest_len)
  885. return -1;
  886. cp = buf = tor_malloc(len+1);
  887. len = i2d_RSAPublicKey(pk->key, &cp);
  888. if (len < 0) {
  889. crypto_log_errors(LOG_WARN,"encoding public key");
  890. tor_free(buf);
  891. return -1;
  892. }
  893. /* We don't encode directly into 'dest', because that would be illegal
  894. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  895. */
  896. memcpy(dest,buf,len);
  897. tor_free(buf);
  898. return len;
  899. }
  900. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  901. * success and NULL on failure.
  902. */
  903. crypto_pk_env_t *
  904. crypto_pk_asn1_decode(const char *str, size_t len)
  905. {
  906. RSA *rsa;
  907. unsigned char *buf;
  908. /* This ifdef suppresses a type warning. Take out the first case once
  909. * everybody is using openssl 0.9.7 or later.
  910. */
  911. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  912. unsigned char *cp;
  913. #else
  914. const unsigned char *cp;
  915. #endif
  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. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  953. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  954. * space). Return 0 on success, -1 on failure.
  955. *
  956. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  957. * of the public key, converted to hexadecimal, in upper case, with a
  958. * space after every four digits.
  959. *
  960. * If <b>add_space</b> is false, omit the spaces.
  961. */
  962. int
  963. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
  964. {
  965. char digest[DIGEST_LEN];
  966. char hexdigest[HEX_DIGEST_LEN+1];
  967. if (crypto_pk_get_digest(pk, digest)) {
  968. return -1;
  969. }
  970. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  971. if (add_space) {
  972. if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
  973. NEVER_TERMINATE)<0)
  974. return -1;
  975. } else {
  976. strcpy(fp_out, hexdigest);
  977. }
  978. return 0;
  979. }
  980. /** Return true iff <b>s</b> is in the correct format for a fingerprint.
  981. */
  982. int
  983. crypto_pk_check_fingerprint_syntax(const char *s)
  984. {
  985. int i;
  986. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  987. if ((i%5) == 4) {
  988. if (!TOR_ISSPACE(s[i])) return 0;
  989. } else {
  990. if (!TOR_ISXDIGIT(s[i])) return 0;
  991. }
  992. }
  993. if (s[FINGERPRINT_LEN]) return 0;
  994. return 1;
  995. }
  996. /* symmetric crypto */
  997. /** Generate a new random key for the symmetric cipher in <b>env</b>.
  998. * Return 0 on success, -1 on failure. Does not initialize the cipher.
  999. */
  1000. int
  1001. crypto_cipher_generate_key(crypto_cipher_env_t *env)
  1002. {
  1003. tor_assert(env);
  1004. return crypto_rand(env->key, CIPHER_KEY_LEN);
  1005. }
  1006. /** Set the symmetric key for the cipher in <b>env</b> to the first
  1007. * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
  1008. * Return 0 on success, -1 on failure.
  1009. */
  1010. int
  1011. crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
  1012. {
  1013. tor_assert(env);
  1014. tor_assert(key);
  1015. if (!env->key)
  1016. return -1;
  1017. memcpy(env->key, key, CIPHER_KEY_LEN);
  1018. return 0;
  1019. }
  1020. /** Return a pointer to the key set for the cipher in <b>env</b>.
  1021. */
  1022. const char *
  1023. crypto_cipher_get_key(crypto_cipher_env_t *env)
  1024. {
  1025. return env->key;
  1026. }
  1027. /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
  1028. * success, -1 on failure.
  1029. */
  1030. int
  1031. crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  1032. {
  1033. tor_assert(env);
  1034. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  1035. return 0;
  1036. }
  1037. /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
  1038. * success, -1 on failure.
  1039. */
  1040. int
  1041. crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  1042. {
  1043. tor_assert(env);
  1044. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  1045. return 0;
  1046. }
  1047. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1048. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1049. * On failure, return -1.
  1050. */
  1051. int
  1052. crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
  1053. const char *from, size_t fromlen)
  1054. {
  1055. tor_assert(env);
  1056. tor_assert(env->cipher);
  1057. tor_assert(from);
  1058. tor_assert(fromlen);
  1059. tor_assert(to);
  1060. aes_crypt(env->cipher, from, fromlen, to);
  1061. return 0;
  1062. }
  1063. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1064. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1065. * On failure, return -1.
  1066. */
  1067. int
  1068. crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
  1069. const char *from, size_t fromlen)
  1070. {
  1071. tor_assert(env);
  1072. tor_assert(from);
  1073. tor_assert(to);
  1074. aes_crypt(env->cipher, from, fromlen, to);
  1075. return 0;
  1076. }
  1077. /* SHA-1 */
  1078. /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
  1079. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1080. * Return 0 on success, -1 on failure.
  1081. */
  1082. int
  1083. crypto_digest(char *digest, const char *m, size_t len)
  1084. {
  1085. tor_assert(m);
  1086. tor_assert(digest);
  1087. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1088. }
  1089. /** Intermediate information about the digest of a stream of data. */
  1090. struct crypto_digest_env_t {
  1091. SHA_CTX d;
  1092. };
  1093. /** Allocate and return a new digest object.
  1094. */
  1095. crypto_digest_env_t *
  1096. crypto_new_digest_env(void)
  1097. {
  1098. crypto_digest_env_t *r;
  1099. r = tor_malloc(sizeof(crypto_digest_env_t));
  1100. SHA1_Init(&r->d);
  1101. return r;
  1102. }
  1103. /** Deallocate a digest object.
  1104. */
  1105. void
  1106. crypto_free_digest_env(crypto_digest_env_t *digest)
  1107. {
  1108. tor_free(digest);
  1109. }
  1110. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1111. */
  1112. void
  1113. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  1114. size_t len)
  1115. {
  1116. tor_assert(digest);
  1117. tor_assert(data);
  1118. /* Using the SHA1_*() calls directly means we don't support doing
  1119. * sha1 in hardware. But so far the delay of getting the question
  1120. * to the hardware, and hearing the answer, is likely higher than
  1121. * just doing it ourselves. Hashes are fast.
  1122. */
  1123. SHA1_Update(&digest->d, (void*)data, len);
  1124. }
  1125. /** Compute the hash of the data that has been passed to the digest
  1126. * object; write the first out_len bytes of the result to <b>out</b>.
  1127. * <b>out_len</b> must be \<= DIGEST_LEN.
  1128. */
  1129. void
  1130. crypto_digest_get_digest(crypto_digest_env_t *digest,
  1131. char *out, size_t out_len)
  1132. {
  1133. static unsigned char r[DIGEST_LEN];
  1134. SHA_CTX tmpctx;
  1135. tor_assert(digest);
  1136. tor_assert(out);
  1137. tor_assert(out_len <= DIGEST_LEN);
  1138. /* memcpy into a temporary ctx, since SHA1_Final clears the context */
  1139. memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
  1140. SHA1_Final(r, &tmpctx);
  1141. memcpy(out, r, out_len);
  1142. }
  1143. /** Allocate and return a new digest object with the same state as
  1144. * <b>digest</b>
  1145. */
  1146. crypto_digest_env_t *
  1147. crypto_digest_dup(const crypto_digest_env_t *digest)
  1148. {
  1149. crypto_digest_env_t *r;
  1150. tor_assert(digest);
  1151. r = tor_malloc(sizeof(crypto_digest_env_t));
  1152. memcpy(r,digest,sizeof(crypto_digest_env_t));
  1153. return r;
  1154. }
  1155. /** Replace the state of the digest object <b>into</b> with the state
  1156. * of the digest object <b>from</b>.
  1157. */
  1158. void
  1159. crypto_digest_assign(crypto_digest_env_t *into,
  1160. const crypto_digest_env_t *from)
  1161. {
  1162. tor_assert(into);
  1163. tor_assert(from);
  1164. memcpy(into,from,sizeof(crypto_digest_env_t));
  1165. }
  1166. /* DH */
  1167. /** Shared P parameter for our DH key exchanged. */
  1168. static BIGNUM *dh_param_p = NULL;
  1169. /** Shared G parameter for our DH key exchanges. */
  1170. static BIGNUM *dh_param_g = NULL;
  1171. /** Initialize dh_param_p and dh_param_g if they are not already
  1172. * set. */
  1173. static void
  1174. init_dh_param(void)
  1175. {
  1176. BIGNUM *p, *g;
  1177. int r;
  1178. if (dh_param_p && dh_param_g)
  1179. return;
  1180. p = BN_new();
  1181. g = BN_new();
  1182. tor_assert(p);
  1183. tor_assert(g);
  1184. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1185. supposedly it equals:
  1186. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1187. */
  1188. r = BN_hex2bn(&p,
  1189. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1190. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1191. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1192. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1193. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1194. tor_assert(r);
  1195. r = BN_set_word(g, 2);
  1196. tor_assert(r);
  1197. dh_param_p = p;
  1198. dh_param_g = g;
  1199. }
  1200. #define DH_PRIVATE_KEY_BITS 320
  1201. /** Allocate and return a new DH object for a key exchange.
  1202. */
  1203. crypto_dh_env_t *
  1204. crypto_dh_new(void)
  1205. {
  1206. crypto_dh_env_t *res = NULL;
  1207. if (!dh_param_p)
  1208. init_dh_param();
  1209. res = tor_malloc_zero(sizeof(crypto_dh_env_t));
  1210. if (!(res->dh = DH_new()))
  1211. goto err;
  1212. if (!(res->dh->p = BN_dup(dh_param_p)))
  1213. goto err;
  1214. if (!(res->dh->g = BN_dup(dh_param_g)))
  1215. goto err;
  1216. res->dh->length = DH_PRIVATE_KEY_BITS;
  1217. return res;
  1218. err:
  1219. crypto_log_errors(LOG_WARN, "creating DH object");
  1220. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  1221. if (res) tor_free(res);
  1222. return NULL;
  1223. }
  1224. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1225. */
  1226. int
  1227. crypto_dh_get_bytes(crypto_dh_env_t *dh)
  1228. {
  1229. tor_assert(dh);
  1230. return DH_size(dh->dh);
  1231. }
  1232. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1233. * success, -1 on failure.
  1234. */
  1235. int
  1236. crypto_dh_generate_public(crypto_dh_env_t *dh)
  1237. {
  1238. again:
  1239. if (!DH_generate_key(dh->dh)) {
  1240. crypto_log_errors(LOG_WARN, "generating DH key");
  1241. return -1;
  1242. }
  1243. if (tor_check_dh_key(dh->dh->pub_key)<0) {
  1244. warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1245. "the-universe chances really do happen. Trying again.");
  1246. /* Free and clear the keys, so openssl will actually try again. */
  1247. BN_free(dh->dh->pub_key);
  1248. BN_free(dh->dh->priv_key);
  1249. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1250. goto again;
  1251. }
  1252. return 0;
  1253. }
  1254. /** Generate g^x as necessary, and write the g^x for the key exchange
  1255. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1256. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1257. */
  1258. int
  1259. crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
  1260. {
  1261. int bytes;
  1262. tor_assert(dh);
  1263. if (!dh->dh->pub_key) {
  1264. if (crypto_dh_generate_public(dh)<0)
  1265. return -1;
  1266. }
  1267. tor_assert(dh->dh->pub_key);
  1268. bytes = BN_num_bytes(dh->dh->pub_key);
  1269. tor_assert(bytes >= 0);
  1270. if (pubkey_len < (size_t)bytes) {
  1271. warn(LD_CRYPTO, "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1272. (int) pubkey_len, bytes);
  1273. return -1;
  1274. }
  1275. memset(pubkey, 0, pubkey_len);
  1276. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1277. return 0;
  1278. }
  1279. /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
  1280. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1281. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1282. */
  1283. static int
  1284. tor_check_dh_key(BIGNUM *bn)
  1285. {
  1286. BIGNUM *x;
  1287. char *s;
  1288. tor_assert(bn);
  1289. x = BN_new();
  1290. tor_assert(x);
  1291. if (!dh_param_p)
  1292. init_dh_param();
  1293. BN_set_word(x, 1);
  1294. if (BN_cmp(bn,x)<=0) {
  1295. warn(LD_CRYPTO, "DH key must be at least 2.");
  1296. goto err;
  1297. }
  1298. BN_copy(x,dh_param_p);
  1299. BN_sub_word(x, 1);
  1300. if (BN_cmp(bn,x)>=0) {
  1301. warn(LD_CRYPTO, "DH key must be at most p-2.");
  1302. goto err;
  1303. }
  1304. BN_free(x);
  1305. return 0;
  1306. err:
  1307. BN_free(x);
  1308. s = BN_bn2hex(bn);
  1309. warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1310. OPENSSL_free(s);
  1311. return -1;
  1312. }
  1313. #undef MIN
  1314. #define MIN(a,b) ((a)<(b)?(a):(b))
  1315. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1316. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1317. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1318. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1319. * or -1 on failure.
  1320. *
  1321. * (We generate key material by computing
  1322. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1323. * where || is concatenation.)
  1324. */
  1325. int
  1326. crypto_dh_compute_secret(crypto_dh_env_t *dh,
  1327. const char *pubkey, size_t pubkey_len,
  1328. char *secret_out, size_t secret_bytes_out)
  1329. {
  1330. char *secret_tmp = NULL;
  1331. BIGNUM *pubkey_bn = NULL;
  1332. size_t secret_len=0;
  1333. int result=0;
  1334. tor_assert(dh);
  1335. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1336. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
  1337. goto error;
  1338. if (tor_check_dh_key(pubkey_bn)<0) {
  1339. /* Check for invalid public keys. */
  1340. warn(LD_CRYPTO,"Rejected invalid g^x");
  1341. goto error;
  1342. }
  1343. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
  1344. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  1345. if (result < 0) {
  1346. warn(LD_CRYPTO,"DH_compute_key() failed.");
  1347. goto error;
  1348. }
  1349. secret_len = result;
  1350. /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
  1351. /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
  1352. * Leading zeros MUST be preserved, so that ZZ occupies as many
  1353. * octets as p. For instance, if p is 1024 bits, ZZ should be 128
  1354. * bytes long.
  1355. * What are the security implications here?
  1356. */
  1357. if (crypto_expand_key_material(secret_tmp, secret_len,
  1358. secret_out, secret_bytes_out)<0)
  1359. goto error;
  1360. secret_len = secret_bytes_out;
  1361. goto done;
  1362. error:
  1363. result = -1;
  1364. done:
  1365. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1366. if (pubkey_bn)
  1367. BN_free(pubkey_bn);
  1368. tor_free(secret_tmp);
  1369. if (result < 0)
  1370. return result;
  1371. else
  1372. return secret_len;
  1373. }
  1374. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  1375. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  1376. * <b>key_out</b> by taking the first key_out_len bytes of
  1377. * H(K | [00]) | H(K | [01]) | ....
  1378. *
  1379. * Return 0 on success, -1 on failure.
  1380. */
  1381. int
  1382. crypto_expand_key_material(const char *key_in, size_t key_in_len,
  1383. char *key_out, size_t key_out_len)
  1384. {
  1385. int i;
  1386. char *cp, *tmp = tor_malloc(key_in_len+1);
  1387. char digest[DIGEST_LEN];
  1388. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1389. tor_assert(key_out_len <= DIGEST_LEN*256);
  1390. memcpy(tmp, key_in, key_in_len);
  1391. for (cp = key_out, i=0; key_out_len; ++i, cp += DIGEST_LEN) {
  1392. tmp[key_in_len] = i;
  1393. if (crypto_digest(digest, tmp, key_in_len+1))
  1394. goto err;
  1395. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len));
  1396. if (key_out_len < DIGEST_LEN)
  1397. break;
  1398. key_out_len -= DIGEST_LEN;
  1399. }
  1400. memset(tmp, 0, key_in_len+1);
  1401. tor_free(tmp);
  1402. return 0;
  1403. err:
  1404. memset(tmp, 0, key_in_len+1);
  1405. tor_free(tmp);
  1406. return -1;
  1407. }
  1408. /** Free a DH key exchange object.
  1409. */
  1410. void
  1411. crypto_dh_free(crypto_dh_env_t *dh)
  1412. {
  1413. tor_assert(dh);
  1414. tor_assert(dh->dh);
  1415. DH_free(dh->dh);
  1416. tor_free(dh);
  1417. }
  1418. /* random numbers */
  1419. /* This is how much entropy OpenSSL likes to add right now, so maybe it will
  1420. * work for us too. */
  1421. #define ADD_ENTROPY 32
  1422. /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
  1423. "release".) */
  1424. #define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
  1425. /** Seed OpenSSL's random number generator with bytes from the
  1426. * operating system. Return 0 on success, -1 on failure.
  1427. */
  1428. int
  1429. crypto_seed_rng(void)
  1430. {
  1431. char buf[ADD_ENTROPY];
  1432. int rand_poll_status;
  1433. /* local variables */
  1434. #ifdef MS_WINDOWS
  1435. static int provider_set = 0;
  1436. static HCRYPTPROV provider;
  1437. #else
  1438. static const char *filenames[] = {
  1439. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1440. };
  1441. int fd;
  1442. int i, n;
  1443. #endif
  1444. #if USE_RAND_POLL
  1445. /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
  1446. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1447. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1448. rand_poll_status = RAND_poll();
  1449. if (rand_poll_status == 0)
  1450. warn(LD_CRYPTO, "RAND_poll() failed.");
  1451. #else
  1452. rand_poll_status = 0;
  1453. #endif
  1454. #ifdef MS_WINDOWS
  1455. if (!provider_set) {
  1456. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1457. CRYPT_VERIFYCONTEXT)) {
  1458. if (GetLastError() != NTE_BAD_KEYSET) {
  1459. warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  1460. return rand_poll_status ? 0 : -1;
  1461. }
  1462. }
  1463. provider_set = 1;
  1464. }
  1465. if (!CryptGenRandom(provider, sizeof(buf), buf)) {
  1466. warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  1467. return rand_poll_status ? 0 : -1;
  1468. }
  1469. RAND_seed(buf, sizeof(buf));
  1470. return 0;
  1471. #else
  1472. for (i = 0; filenames[i]; ++i) {
  1473. fd = open(filenames[i], O_RDONLY, 0);
  1474. if (fd<0) continue;
  1475. info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
  1476. n = read_all(fd, buf, sizeof(buf), 0);
  1477. close(fd);
  1478. if (n != sizeof(buf)) {
  1479. warn(LD_CRYPTO,
  1480. "Error reading from entropy source (read only %d bytes).", n);
  1481. return -1;
  1482. }
  1483. RAND_seed(buf, sizeof(buf));
  1484. return 0;
  1485. }
  1486. warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
  1487. return rand_poll_status ? 0 : -1;
  1488. #endif
  1489. }
  1490. /** Write n bytes of strong random data to <b>to</b>. Return 0 on
  1491. * success, -1 on failure.
  1492. */
  1493. int
  1494. crypto_rand(char *to, size_t n)
  1495. {
  1496. int r;
  1497. tor_assert(to);
  1498. r = RAND_bytes((unsigned char*)to, n);
  1499. if (r == 0)
  1500. crypto_log_errors(LOG_WARN, "generating random data");
  1501. return (r == 1) ? 0 : -1;
  1502. }
  1503. /** Return a pseudorandom integer, chosen uniformly from the values
  1504. * between 0 and max-1. */
  1505. int
  1506. crypto_rand_int(unsigned int max)
  1507. {
  1508. unsigned int val;
  1509. unsigned int cutoff;
  1510. tor_assert(max < UINT_MAX);
  1511. tor_assert(max > 0); /* don't div by 0 */
  1512. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1513. * distribution with clipping at the upper end of unsigned int's
  1514. * range.
  1515. */
  1516. cutoff = UINT_MAX - (UINT_MAX%max);
  1517. while (1) {
  1518. crypto_rand((char*)&val, sizeof(val));
  1519. if (val < cutoff)
  1520. return val % max;
  1521. }
  1522. }
  1523. /** Return a randomly chosen element of sl; or NULL if sl is empty.
  1524. */
  1525. void *
  1526. smartlist_choose(const smartlist_t *sl)
  1527. {
  1528. size_t len;
  1529. len = smartlist_len(sl);
  1530. if (len)
  1531. return smartlist_get(sl,crypto_rand_int(len));
  1532. return NULL; /* no elements to choose from */
  1533. }
  1534. /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  1535. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1536. * bytes. Return the number of bytes written on success; -1 if
  1537. * destlen is too short, or other failure.
  1538. */
  1539. int
  1540. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1541. {
  1542. EVP_ENCODE_CTX ctx;
  1543. int len, ret;
  1544. /* 48 bytes of input -> 64 bytes of output plus newline.
  1545. Plus one more byte, in case I'm wrong.
  1546. */
  1547. if (destlen < ((srclen/48)+1)*66)
  1548. return -1;
  1549. if (destlen > SIZE_T_CEILING)
  1550. return -1;
  1551. EVP_EncodeInit(&ctx);
  1552. EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
  1553. (unsigned char*)src, srclen);
  1554. EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
  1555. ret += len;
  1556. return ret;
  1557. }
  1558. /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  1559. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1560. * bytes. Return the number of bytes written on success; -1 if
  1561. * destlen is too short, or other failure.
  1562. *
  1563. * NOTE: destlen should be a little longer than the amount of data it
  1564. * will contain, since we check for sufficient space conservatively.
  1565. * Here, "a little" is around 64-ish bytes.
  1566. */
  1567. int
  1568. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1569. {
  1570. EVP_ENCODE_CTX ctx;
  1571. int len, ret;
  1572. /* 64 bytes of input -> *up to* 48 bytes of output.
  1573. Plus one more byte, in case I'm wrong.
  1574. */
  1575. if (destlen < ((srclen/64)+1)*49)
  1576. return -1;
  1577. if (destlen > SIZE_T_CEILING)
  1578. return -1;
  1579. EVP_DecodeInit(&ctx);
  1580. EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
  1581. (unsigned char*)src, srclen);
  1582. EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
  1583. ret += len;
  1584. return ret;
  1585. }
  1586. int
  1587. digest_to_base64(char *d64, const char *digest)
  1588. {
  1589. char buf[256];
  1590. base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
  1591. buf[BASE64_DIGEST_LEN] = '\0';
  1592. memcpy(d64, buf, BASE64_DIGEST_LEN+1);
  1593. return 0;
  1594. }
  1595. int
  1596. digest_from_base64(char *digest, const char *d64)
  1597. {
  1598. char buf_in[BASE64_DIGEST_LEN+3];
  1599. char buf[256];
  1600. if (strlen(d64) != BASE64_DIGEST_LEN)
  1601. return -1;
  1602. memcpy(buf_in, d64, BASE64_DIGEST_LEN);
  1603. memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
  1604. if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
  1605. return -1;
  1606. memcpy(digest, buf, DIGEST_LEN);
  1607. return 0;
  1608. }
  1609. /** Implements base32 encoding as in rfc3548. Limitation: Requires
  1610. * that srclen*8 is a multiple of 5.
  1611. */
  1612. void
  1613. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1614. {
  1615. unsigned int nbits, i, bit, v, u;
  1616. nbits = srclen * 8;
  1617. tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
  1618. tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
  1619. tor_assert(destlen < SIZE_T_CEILING);
  1620. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  1621. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  1622. v = ((uint8_t)src[bit/8]) << 8;
  1623. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  1624. /* set u to the 5-bit value at the bit'th bit of src. */
  1625. u = (v >> (11-(bit%8))) & 0x1F;
  1626. dest[i] = BASE32_CHARS[u];
  1627. }
  1628. dest[i] = '\0';
  1629. }
  1630. /** Implement RFC2440-style iterated-salted S2K conversion: convert the
  1631. * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
  1632. * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
  1633. * are a salt; the 9th byte describes how much iteration to do.
  1634. * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
  1635. */
  1636. void
  1637. secret_to_key(char *key_out, size_t key_out_len, const char *secret,
  1638. size_t secret_len, const char *s2k_specifier)
  1639. {
  1640. crypto_digest_env_t *d;
  1641. uint8_t c;
  1642. size_t count;
  1643. char *tmp;
  1644. tor_assert(key_out_len < SIZE_T_CEILING);
  1645. #define EXPBIAS 6
  1646. c = s2k_specifier[8];
  1647. count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
  1648. #undef EXPBIAS
  1649. tor_assert(key_out_len <= DIGEST_LEN);
  1650. d = crypto_new_digest_env();
  1651. tmp = tor_malloc(8+secret_len);
  1652. memcpy(tmp,s2k_specifier,8);
  1653. memcpy(tmp+8,secret,secret_len);
  1654. secret_len += 8;
  1655. while (count) {
  1656. if (count >= secret_len) {
  1657. crypto_digest_add_bytes(d, tmp, secret_len);
  1658. count -= secret_len;
  1659. } else {
  1660. crypto_digest_add_bytes(d, tmp, count);
  1661. count = 0;
  1662. }
  1663. }
  1664. crypto_digest_get_digest(d, key_out, key_out_len);
  1665. tor_free(tmp);
  1666. crypto_free_digest_env(d);
  1667. }
  1668. #ifdef TOR_IS_MULTITHREADED
  1669. static void
  1670. _openssl_locking_cb(int mode, int n, const char *file, int line)
  1671. {
  1672. if (!_openssl_mutexes)
  1673. /* This is not a really good fix for the
  1674. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  1675. * it can't hurt. */
  1676. return;
  1677. if (mode & CRYPTO_LOCK)
  1678. tor_mutex_acquire(_openssl_mutexes[n]);
  1679. else
  1680. tor_mutex_release(_openssl_mutexes[n]);
  1681. }
  1682. static int
  1683. setup_openssl_threading(void)
  1684. {
  1685. int i;
  1686. int n = CRYPTO_num_locks();
  1687. _n_openssl_mutexes = n;
  1688. _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
  1689. for (i=0; i < n; ++i)
  1690. _openssl_mutexes[i] = tor_mutex_new();
  1691. CRYPTO_set_locking_callback(_openssl_locking_cb);
  1692. CRYPTO_set_id_callback(tor_get_thread_id);
  1693. return 0;
  1694. }
  1695. #else
  1696. static int
  1697. setup_openssl_threading(void)
  1698. {
  1699. return 0;
  1700. }
  1701. #endif