crypto.c 48 KB

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