crypto.c 48 KB

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