crypto.c 48 KB

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