crypto.c 49 KB

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