crypto.c 48 KB

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