crypto.c 48 KB

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