crypto.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "orconfig.h"
  5. #ifdef MS_WINDOWS
  6. #define WIN32_WINNT 0x400
  7. #define _WIN32_WINNT 0x400
  8. #define WIN32_LEAN_AND_MEAN
  9. #include <windows.h>
  10. #include <wincrypt.h>
  11. #endif
  12. #include <string.h>
  13. #include <openssl/err.h>
  14. #include <openssl/rsa.h>
  15. #include <openssl/pem.h>
  16. #include <openssl/evp.h>
  17. #include <openssl/rand.h>
  18. #include <openssl/opensslv.h>
  19. #include <openssl/bn.h>
  20. #include <openssl/dh.h>
  21. #include <openssl/rsa.h>
  22. #include <openssl/dh.h>
  23. #include <stdlib.h>
  24. #include <assert.h>
  25. #include <stdio.h>
  26. #include <limits.h>
  27. #ifdef HAVE_CTYPE_H
  28. #include <ctype.h>
  29. #endif
  30. #ifdef HAVE_UNISTD_H
  31. #include <unistd.h>
  32. #endif
  33. #ifdef HAVE_FCNTL_H
  34. #include <fcntl.h>
  35. #endif
  36. #ifdef HAVE_SYS_FCNTL_H
  37. #include <sys/fcntl.h>
  38. #endif
  39. #include "crypto.h"
  40. #include "log.h"
  41. #include "aes.h"
  42. #include "util.h"
  43. #if OPENSSL_VERSION_NUMBER < 0x00905000l
  44. #error "We require openssl >= 0.9.5"
  45. #elif OPENSSL_VERSION_NUMBER < 0x00906000l
  46. #define OPENSSL_095
  47. #endif
  48. /*
  49. * Certain functions that return a success code in OpenSSL 0.9.6 return void
  50. * (and don't indicate errors) in OpenSSL version 0.9.5.
  51. *
  52. * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
  53. */
  54. #ifdef OPENSSL_095
  55. #define RETURN_SSL_OUTCOME(exp) (exp); return 0
  56. #else
  57. #define RETURN_SSL_OUTCOME(exp) return !(exp)
  58. #endif
  59. #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
  60. #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
  61. struct crypto_pk_env_t
  62. {
  63. int refs; /* reference counting; so we don't have to copy keys */
  64. RSA *key;
  65. };
  66. struct crypto_cipher_env_t
  67. {
  68. unsigned char key[CIPHER_KEY_LEN];
  69. unsigned char iv[_ARRAYSIZE(CIPHER_IV_LEN)];
  70. aes_cnt_cipher_t *cipher;
  71. };
  72. struct crypto_dh_env_t {
  73. DH *dh;
  74. };
  75. static INLINE int
  76. crypto_get_rsa_padding_overhead(int padding) {
  77. switch(padding)
  78. {
  79. case RSA_NO_PADDING: return 0;
  80. case RSA_PKCS1_OAEP_PADDING: return 42;
  81. case RSA_PKCS1_PADDING: return 11;
  82. default: tor_assert(0); return -1;
  83. }
  84. }
  85. static INLINE int
  86. crypto_get_rsa_padding(int padding) {
  87. switch(padding)
  88. {
  89. case PK_NO_PADDING: return RSA_NO_PADDING;
  90. case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
  91. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  92. default: tor_assert(0); return -1;
  93. }
  94. }
  95. static int _crypto_global_initialized = 0;
  96. /* errors */
  97. static void
  98. crypto_log_errors(int severity, const char *doing)
  99. {
  100. int err;
  101. const char *msg, *lib, *func;
  102. while ((err = ERR_get_error()) != 0) {
  103. msg = (const char*)ERR_reason_error_string(err);
  104. lib = (const char*)ERR_lib_error_string(err);
  105. func = (const char*)ERR_func_error_string(err);
  106. if (!msg) msg = "(null)";
  107. if (doing) {
  108. log(severity, "crypto error while %s: %s (in %s:%s)", doing, msg, lib,func);
  109. } else {
  110. log(severity, "crypto error: %s (in %s:%s)", msg, lib, func);
  111. }
  112. }
  113. }
  114. int crypto_global_init()
  115. {
  116. if (!_crypto_global_initialized) {
  117. ERR_load_crypto_strings();
  118. _crypto_global_initialized = 1;
  119. }
  120. return 0;
  121. }
  122. int crypto_global_cleanup()
  123. {
  124. ERR_free_strings();
  125. return 0;
  126. }
  127. /* used by tortls.c */
  128. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
  129. {
  130. crypto_pk_env_t *env;
  131. tor_assert(rsa);
  132. env = tor_malloc(sizeof(crypto_pk_env_t));
  133. env->refs = 1;
  134. env->key = rsa;
  135. return env;
  136. }
  137. /* used by tortls.c */
  138. RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
  139. {
  140. return env->key;
  141. }
  142. /* used by tortls.c */
  143. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
  144. {
  145. RSA *key = NULL;
  146. EVP_PKEY *pkey = NULL;
  147. tor_assert(env->key);
  148. if (private) {
  149. if (!(key = RSAPrivateKey_dup(env->key)))
  150. goto error;
  151. } else {
  152. if (!(key = RSAPublicKey_dup(env->key)))
  153. goto error;
  154. }
  155. if (!(pkey = EVP_PKEY_new()))
  156. goto error;
  157. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  158. goto error;
  159. return pkey;
  160. error:
  161. if (pkey)
  162. EVP_PKEY_free(pkey);
  163. if (key)
  164. RSA_free(key);
  165. return NULL;
  166. }
  167. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh)
  168. {
  169. return dh->dh;
  170. }
  171. crypto_pk_env_t *crypto_new_pk_env(void)
  172. {
  173. RSA *rsa;
  174. rsa = RSA_new();
  175. if (!rsa) return NULL;
  176. return _crypto_new_pk_env_rsa(rsa);
  177. }
  178. void crypto_free_pk_env(crypto_pk_env_t *env)
  179. {
  180. tor_assert(env);
  181. if(--env->refs > 0)
  182. return;
  183. if (env->key)
  184. RSA_free(env->key);
  185. free(env);
  186. }
  187. /* Create a new crypto_cipher_env_t for a given onion cipher type, key,
  188. * iv, and encryption flag (1=encrypt, 0=decrypt). Return the crypto object
  189. * on success; NULL on failure.
  190. */
  191. crypto_cipher_env_t *
  192. crypto_create_init_cipher(const char *key, const char *iv, int encrypt_mode)
  193. {
  194. int r;
  195. crypto_cipher_env_t *crypto = NULL;
  196. if (! (crypto = crypto_new_cipher_env())) {
  197. log_fn(LOG_WARN, "Unable to allocate crypto object");
  198. return NULL;
  199. }
  200. if (crypto_cipher_set_key(crypto, key)) {
  201. crypto_log_errors(LOG_WARN, "setting symmetric key");
  202. goto error;
  203. }
  204. if (crypto_cipher_set_iv(crypto, iv)) {
  205. crypto_log_errors(LOG_WARN, "setting IV");
  206. goto error;
  207. }
  208. if (encrypt_mode)
  209. r = crypto_cipher_encrypt_init_cipher(crypto);
  210. else
  211. r = crypto_cipher_decrypt_init_cipher(crypto);
  212. if (r)
  213. goto error;
  214. return crypto;
  215. error:
  216. if (crypto)
  217. crypto_free_cipher_env(crypto);
  218. return NULL;
  219. }
  220. crypto_cipher_env_t *crypto_new_cipher_env()
  221. {
  222. crypto_cipher_env_t *env;
  223. env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
  224. env->cipher = aes_new_cipher();
  225. return env;
  226. }
  227. void crypto_free_cipher_env(crypto_cipher_env_t *env)
  228. {
  229. tor_assert(env);
  230. tor_assert(env->cipher);
  231. aes_free_cipher(env->cipher);
  232. tor_free(env);
  233. }
  234. /* public key crypto */
  235. int crypto_pk_generate_key(crypto_pk_env_t *env)
  236. {
  237. tor_assert(env);
  238. if (env->key)
  239. RSA_free(env->key);
  240. env->key = RSA_generate_key(PK_BITS,65537, NULL, NULL);
  241. if (!env->key) {
  242. crypto_log_errors(LOG_WARN, "generating RSA key");
  243. return -1;
  244. }
  245. return 0;
  246. }
  247. static int crypto_pk_read_private_key_from_file(crypto_pk_env_t *env,
  248. FILE *src)
  249. {
  250. tor_assert(env && src);
  251. if (env->key)
  252. RSA_free(env->key);
  253. env->key = PEM_read_RSAPrivateKey(src, NULL, NULL, NULL);
  254. if (!env->key) {
  255. crypto_log_errors(LOG_WARN, "reading private key from file");
  256. return -1;
  257. }
  258. return 0;
  259. }
  260. int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
  261. {
  262. FILE *f_pr;
  263. tor_assert(env && keyfile);
  264. if(strspn(keyfile,CONFIG_LEGAL_FILENAME_CHARACTERS) != strlen(keyfile)) {
  265. /* filename contains nonlegal characters */
  266. return -1;
  267. }
  268. /* open the keyfile */
  269. f_pr=fopen(keyfile,"rb");
  270. if (!f_pr)
  271. return -1;
  272. /* read the private key */
  273. if(crypto_pk_read_private_key_from_file(env, f_pr) < 0) {
  274. fclose(f_pr);
  275. return -1;
  276. }
  277. fclose(f_pr);
  278. /* check the private key */
  279. if (crypto_pk_check_key(env) <= 0)
  280. return -1;
  281. return 0;
  282. }
  283. int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, int *len) {
  284. BUF_MEM *buf;
  285. BIO *b;
  286. tor_assert(env && env->key && dest);
  287. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  288. /* Now you can treat b as if it were a file. Just use the
  289. * PEM_*_bio_* functions instead of the non-bio variants.
  290. */
  291. if(!PEM_write_bio_RSAPublicKey(b, env->key)) {
  292. crypto_log_errors(LOG_WARN, "writing public key to string");
  293. return -1;
  294. }
  295. BIO_get_mem_ptr(b, &buf);
  296. BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  297. BIO_free(b);
  298. *dest = tor_malloc(buf->length+1);
  299. memcpy(*dest, buf->data, buf->length);
  300. (*dest)[buf->length] = 0; /* null terminate it */
  301. *len = buf->length;
  302. BUF_MEM_free(buf);
  303. return 0;
  304. }
  305. int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, int len) {
  306. BIO *b;
  307. tor_assert(env && src);
  308. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  309. BIO_write(b, src, len);
  310. if (env->key)
  311. RSA_free(env->key);
  312. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  313. BIO_free(b);
  314. if(!env->key) {
  315. crypto_log_errors(LOG_WARN, "reading public key from string");
  316. return -1;
  317. }
  318. return 0;
  319. }
  320. int
  321. crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
  322. const char *fname)
  323. {
  324. BIO *bio;
  325. char *cp;
  326. long len;
  327. char *s;
  328. int r;
  329. tor_assert(PRIVATE_KEY_OK(env));
  330. if (!(bio = BIO_new(BIO_s_mem())))
  331. return -1;
  332. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  333. == 0) {
  334. crypto_log_errors(LOG_WARN, "writing private key");
  335. BIO_free(bio);
  336. return -1;
  337. }
  338. len = BIO_get_mem_data(bio, &cp);
  339. s = tor_malloc(len+1);
  340. strncpy(s, cp, len);
  341. s[len] = '\0';
  342. r = write_str_to_file(fname, s);
  343. BIO_free(bio);
  344. free(s);
  345. return r;
  346. }
  347. int crypto_pk_check_key(crypto_pk_env_t *env)
  348. {
  349. int r;
  350. tor_assert(env);
  351. r = RSA_check_key(env->key);
  352. if (r <= 0)
  353. crypto_log_errors(LOG_WARN,"checking RSA key");
  354. return r;
  355. }
  356. int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
  357. int result;
  358. if (!a || !b)
  359. return -1;
  360. if (!a->key || !b->key)
  361. return -1;
  362. tor_assert(PUBLIC_KEY_OK(a));
  363. tor_assert(PUBLIC_KEY_OK(b));
  364. result = BN_cmp((a->key)->n, (b->key)->n);
  365. if (result)
  366. return result;
  367. return BN_cmp((a->key)->e, (b->key)->e);
  368. }
  369. /* return the size of the public key modulus in 'env', in bytes. */
  370. int crypto_pk_keysize(crypto_pk_env_t *env)
  371. {
  372. tor_assert(env && env->key);
  373. return RSA_size(env->key);
  374. }
  375. crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
  376. tor_assert(env && env->key);
  377. env->refs++;
  378. return env;
  379. }
  380. int crypto_pk_public_encrypt(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to, int padding)
  381. {
  382. int r;
  383. tor_assert(env && from && to);
  384. r = RSA_public_encrypt(fromlen, (unsigned char*)from, to, env->key,
  385. crypto_get_rsa_padding(padding));
  386. if (r<0)
  387. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  388. return r;
  389. }
  390. int crypto_pk_private_decrypt(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to, int padding)
  391. {
  392. int r;
  393. tor_assert(env && from && to && env->key);
  394. if (!env->key->p)
  395. /* Not a private key */
  396. return -1;
  397. r = RSA_private_decrypt(fromlen, (unsigned char*)from, to, env->key,
  398. crypto_get_rsa_padding(padding));
  399. if (r<0)
  400. crypto_log_errors(LOG_WARN, "performing RSA decryption");
  401. return r;
  402. }
  403. int crypto_pk_public_checksig(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to)
  404. {
  405. int r;
  406. tor_assert(env && from && to);
  407. r = RSA_public_decrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
  408. if (r<0)
  409. crypto_log_errors(LOG_WARN, "checking RSA signature");
  410. return r;
  411. }
  412. int crypto_pk_private_sign(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to)
  413. {
  414. int r;
  415. tor_assert(env && from && to);
  416. if (!env->key->p)
  417. /* Not a private key */
  418. return -1;
  419. r = RSA_private_encrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
  420. if (r<0)
  421. crypto_log_errors(LOG_WARN, "generating RSA signature");
  422. return r;
  423. }
  424. /* Return 0 if sig is a correct signature for SHA1(data). Else return -1.
  425. */
  426. int crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const unsigned char *data, int datalen, const unsigned char *sig, int siglen)
  427. {
  428. char digest[DIGEST_LEN];
  429. char buf[PK_BYTES+1];
  430. int r;
  431. tor_assert(env && data && sig);
  432. if (crypto_digest(data,datalen,digest)<0) {
  433. log_fn(LOG_WARN, "couldn't compute digest");
  434. return -1;
  435. }
  436. r = crypto_pk_public_checksig(env,sig,siglen,buf);
  437. if (r != DIGEST_LEN) {
  438. log_fn(LOG_WARN, "Invalid signature");
  439. return -1;
  440. }
  441. if (memcmp(buf, digest, DIGEST_LEN)) {
  442. log_fn(LOG_WARN, "Signature mismatched with digest.");
  443. return -1;
  444. }
  445. return 0;
  446. }
  447. /* Fill 'to' with a signature of SHA1(from).
  448. */
  449. int crypto_pk_private_sign_digest(crypto_pk_env_t *env, const unsigned char *from, int fromlen, unsigned char *to)
  450. {
  451. char digest[DIGEST_LEN];
  452. if (crypto_digest(from,fromlen,digest)<0)
  453. return 0;
  454. return crypto_pk_private_sign(env,digest,DIGEST_LEN,to);
  455. }
  456. /* Perform a hybrid (public/secret) encryption on 'fromlen' bytes of data
  457. * from 'from', with padding type 'padding', storing the results on 'to'.
  458. *
  459. * If no padding is used, the public key must be at least as large as
  460. * 'from'.
  461. *
  462. * Returns the number of bytes written on success, -1 on failure.
  463. *
  464. * The encrypted data consists of:
  465. *
  466. * The source data, padded and encrypted with the public key, if the
  467. * padded source data is no longer than the public key, and "force"
  468. * is false.
  469. * OR
  470. * The beginning of the source data prefixed with a 16-byte symmetric key,
  471. * padded and encrypted with the public key; followed by the rest of
  472. * the source data encrypted in AES-CTR mode with the symmetric key.
  473. *
  474. */
  475. int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
  476. const unsigned char *from,
  477. int fromlen, unsigned char *to,
  478. int padding, int force)
  479. {
  480. int overhead, pkeylen, outlen, r, symlen;
  481. crypto_cipher_env_t *cipher = NULL;
  482. char buf[PK_BYTES+1];
  483. tor_assert(env && from && to);
  484. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  485. pkeylen = crypto_pk_keysize(env);
  486. if (padding == PK_NO_PADDING && fromlen < pkeylen)
  487. return -1;
  488. if (!force && fromlen+overhead <= pkeylen) {
  489. /* It all fits in a single encrypt. */
  490. return crypto_pk_public_encrypt(env,from,fromlen,to,padding);
  491. }
  492. cipher = crypto_new_cipher_env();
  493. if (!cipher) return -1;
  494. if (crypto_cipher_generate_key(cipher)<0)
  495. goto err;
  496. /* You can't just run around RSA-encrypting any bitstream: if it's
  497. * greater than the RSA key, then OpenSSL will happily encrypt, and
  498. * later decrypt to the wrong value. So we set the first bit of
  499. * 'cipher->key' to 0 if we aren't padding. This means that our
  500. * symmetric key is really only 127 bits.
  501. */
  502. if (padding == PK_NO_PADDING)
  503. cipher->key[0] &= 0x7f;
  504. if (crypto_cipher_encrypt_init_cipher(cipher)<0)
  505. goto err;
  506. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  507. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  508. /* Length of symmetrically encrypted data. */
  509. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  510. outlen = crypto_pk_public_encrypt(env,buf,pkeylen-overhead,to,padding);
  511. if (outlen!=pkeylen) {
  512. goto err;
  513. }
  514. r = crypto_cipher_encrypt(cipher,
  515. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen,
  516. to+outlen);
  517. if (r<0) goto err;
  518. memset(buf, 0, sizeof(buf));
  519. crypto_free_cipher_env(cipher);
  520. return outlen + symlen;
  521. err:
  522. memset(buf, 0, sizeof(buf));
  523. if (cipher) crypto_free_cipher_env(cipher);
  524. return -1;
  525. }
  526. /* Invert crypto_pk_public_hybrid_encrypt. */
  527. int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
  528. const unsigned char *from,
  529. int fromlen, unsigned char *to,
  530. int padding)
  531. {
  532. int overhead, pkeylen, outlen, r;
  533. crypto_cipher_env_t *cipher = NULL;
  534. char buf[PK_BYTES+1];
  535. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  536. pkeylen = crypto_pk_keysize(env);
  537. if (fromlen <= pkeylen) {
  538. return crypto_pk_private_decrypt(env,from,fromlen,to,padding);
  539. }
  540. outlen = crypto_pk_private_decrypt(env,from,pkeylen,buf,padding);
  541. if (outlen<0) {
  542. /* this is only log-levelinfo, because when we're decrypting
  543. * onions, we try several keys to see which will work */
  544. log_fn(LOG_INFO, "Error decrypting public-key data");
  545. return -1;
  546. }
  547. if (outlen < CIPHER_KEY_LEN) {
  548. log_fn(LOG_WARN, "No room for a symmetric key");
  549. return -1;
  550. }
  551. cipher = crypto_create_init_cipher(buf, NULL, 0);
  552. if (!cipher) {
  553. return -1;
  554. }
  555. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  556. outlen -= CIPHER_KEY_LEN;
  557. r = crypto_cipher_decrypt(cipher, from+pkeylen, fromlen-pkeylen,
  558. to+outlen);
  559. if (r<0)
  560. goto err;
  561. memset(buf,0,sizeof(buf));
  562. crypto_free_cipher_env(cipher);
  563. return outlen + (fromlen-pkeylen);
  564. err:
  565. memset(buf,0,sizeof(buf));
  566. if (cipher) crypto_free_cipher_env(cipher);
  567. return -1;
  568. }
  569. /* Encode the public portion of 'pk' into 'dest'. Return -1 on error,
  570. * or the number of characters used on success.
  571. */
  572. int crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
  573. {
  574. int len;
  575. unsigned char *buf, *cp;
  576. len = i2d_RSAPublicKey(pk->key, NULL);
  577. if (len < 0 || len > dest_len)
  578. return -1;
  579. cp = buf = tor_malloc(len+1);
  580. len = i2d_RSAPublicKey(pk->key, &cp);
  581. if (len < 0) {
  582. crypto_log_errors(LOG_WARN,"encoding public key");
  583. tor_free(buf);
  584. return -1;
  585. }
  586. /* We don't encode directly into 'dest', because that would be illegal
  587. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  588. */
  589. memcpy(dest,buf,len);
  590. tor_free(buf);
  591. return len;
  592. }
  593. /* Decode an ASN1-encoded public key from str.
  594. */
  595. crypto_pk_env_t *crypto_pk_asn1_decode(const char *str, int len)
  596. {
  597. RSA *rsa;
  598. unsigned char *buf;
  599. /* This ifdef suppresses a type warning. Take out the first case once
  600. * everybody is using openssl 0.9.7 or later.
  601. */
  602. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  603. unsigned char *cp;
  604. #else
  605. const unsigned char *cp;
  606. #endif
  607. cp = buf = tor_malloc(len);
  608. memcpy(buf,str,len);
  609. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  610. tor_free(buf);
  611. if (!rsa) {
  612. crypto_log_errors(LOG_WARN,"decoding public key");
  613. return NULL;
  614. }
  615. return _crypto_new_pk_env_rsa(rsa);
  616. }
  617. /* Given a private or public key pk, put a SHA1 hash of the public key into
  618. * digest_out (must have DIGEST_LEN bytes of space).
  619. */
  620. int crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
  621. {
  622. unsigned char *buf, *bufp;
  623. int len;
  624. len = i2d_RSAPublicKey(pk->key, NULL);
  625. if (len < 0)
  626. return -1;
  627. buf = bufp = tor_malloc(len+1);
  628. len = i2d_RSAPublicKey(pk->key, &bufp);
  629. if (len < 0) {
  630. crypto_log_errors(LOG_WARN,"encoding public key");
  631. free(buf);
  632. return -1;
  633. }
  634. if (crypto_digest(buf, len, digest_out) < 0) {
  635. free(buf);
  636. return -1;
  637. }
  638. free(buf);
  639. return 0;
  640. }
  641. /* Given a private or public key pk, put a fingerprint of the
  642. * public key into fp_out (must have at least FINGERPRINT_LEN+1 bytes of
  643. * space).
  644. */
  645. int
  646. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out)
  647. {
  648. unsigned char *bufp;
  649. unsigned char digest[DIGEST_LEN];
  650. unsigned char buf[FINGERPRINT_LEN+1];
  651. int i;
  652. if (crypto_pk_get_digest(pk, digest)) {
  653. return -1;
  654. }
  655. bufp = buf;
  656. for (i = 0; i < DIGEST_LEN; ++i) {
  657. sprintf(bufp,"%02X",digest[i]);
  658. bufp += 2;
  659. if (i%2 && i != 19) {
  660. *bufp++ = ' ';
  661. }
  662. }
  663. *bufp = '\0';
  664. tor_assert(strlen(buf) == FINGERPRINT_LEN);
  665. tor_assert(crypto_pk_check_fingerprint_syntax(buf));
  666. strcpy(fp_out, buf);
  667. return 0;
  668. }
  669. int
  670. crypto_pk_check_fingerprint_syntax(const char *s)
  671. {
  672. int i;
  673. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  674. if ((i%5) == 4) {
  675. if (!isspace((int)s[i])) return 0;
  676. } else {
  677. if (!isxdigit((int)s[i])) return 0;
  678. }
  679. }
  680. if (s[FINGERPRINT_LEN]) return 0;
  681. return 1;
  682. }
  683. /* symmetric crypto */
  684. int crypto_cipher_generate_key(crypto_cipher_env_t *env)
  685. {
  686. tor_assert(env);
  687. return crypto_rand(CIPHER_KEY_LEN, env->key);
  688. }
  689. int crypto_cipher_set_iv(crypto_cipher_env_t *env, const unsigned char *iv)
  690. {
  691. tor_assert(env && (CIPHER_IV_LEN==0 || iv));
  692. if (!CIPHER_IV_LEN)
  693. return 0;
  694. if (!env->iv)
  695. return -1;
  696. memcpy(env->iv, iv, CIPHER_IV_LEN);
  697. return 0;
  698. }
  699. int crypto_cipher_set_key(crypto_cipher_env_t *env, const unsigned char *key)
  700. {
  701. tor_assert(env && key);
  702. if (!env->key)
  703. return -1;
  704. memcpy(env->key, key, CIPHER_KEY_LEN);
  705. return 0;
  706. }
  707. const unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
  708. {
  709. return env->key;
  710. }
  711. int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  712. {
  713. tor_assert(env);
  714. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  715. return 0;
  716. }
  717. int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  718. {
  719. tor_assert(env);
  720. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  721. return 0;
  722. }
  723. int crypto_cipher_encrypt(crypto_cipher_env_t *env, const unsigned char *from, unsigned int fromlen, unsigned char *to)
  724. {
  725. tor_assert(env && env->cipher && from && fromlen && to);
  726. aes_crypt(env->cipher, from, fromlen, to);
  727. return 0;
  728. }
  729. int crypto_cipher_decrypt(crypto_cipher_env_t *env, const unsigned char *from, unsigned int fromlen, unsigned char *to)
  730. {
  731. tor_assert(env && from && to);
  732. aes_crypt(env->cipher, from, fromlen, to);
  733. return 0;
  734. }
  735. int
  736. crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
  737. {
  738. return crypto_cipher_advance(env, -delta);
  739. }
  740. int
  741. crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
  742. {
  743. aes_adjust_counter(env->cipher, delta);
  744. return 0;
  745. }
  746. /* SHA-1 */
  747. int crypto_digest(const unsigned char *m, int len, unsigned char *digest)
  748. {
  749. tor_assert(m && digest);
  750. return (SHA1(m,len,digest) == NULL);
  751. }
  752. struct crypto_digest_env_t {
  753. SHA_CTX d;
  754. };
  755. crypto_digest_env_t *
  756. crypto_new_digest_env(void)
  757. {
  758. crypto_digest_env_t *r;
  759. r = tor_malloc(sizeof(crypto_digest_env_t));
  760. SHA1_Init(&r->d);
  761. return r;
  762. }
  763. void
  764. crypto_free_digest_env(crypto_digest_env_t *digest) {
  765. tor_free(digest);
  766. }
  767. void
  768. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  769. size_t len)
  770. {
  771. tor_assert(digest);
  772. tor_assert(data);
  773. SHA1_Update(&digest->d, (void*)data, len);
  774. }
  775. void crypto_digest_get_digest(crypto_digest_env_t *digest,
  776. char *out, size_t out_len)
  777. {
  778. static char r[DIGEST_LEN];
  779. tor_assert(digest && out);
  780. tor_assert(out_len <= DIGEST_LEN);
  781. SHA1_Final(r, &digest->d);
  782. memcpy(out, r, out_len);
  783. }
  784. crypto_digest_env_t *
  785. crypto_digest_dup(const crypto_digest_env_t *digest)
  786. {
  787. crypto_digest_env_t *r;
  788. tor_assert(digest);
  789. r = tor_malloc(sizeof(crypto_digest_env_t));
  790. memcpy(r,digest,sizeof(crypto_digest_env_t));
  791. return r;
  792. }
  793. void
  794. crypto_digest_assign(crypto_digest_env_t *into,
  795. const crypto_digest_env_t *from)
  796. {
  797. tor_assert(into && from);
  798. memcpy(into,from,sizeof(crypto_digest_env_t));
  799. }
  800. /* DH */
  801. static BIGNUM *dh_param_p = NULL;
  802. static BIGNUM *dh_param_g = NULL;
  803. static void init_dh_param() {
  804. BIGNUM *p, *g;
  805. int r;
  806. if (dh_param_p && dh_param_g)
  807. return;
  808. p = BN_new();
  809. g = BN_new();
  810. tor_assert(p && g);
  811. #if 0
  812. /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
  813. prime, and supposedly it equals:
  814. 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
  815. */
  816. r = BN_hex2bn(&p,
  817. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
  818. "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
  819. "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
  820. "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
  821. "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
  822. "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
  823. "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
  824. "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
  825. #endif
  826. /* This is from rfc2409, section 6.2. It's a safe prime, and
  827. supposedly it equals:
  828. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  829. */
  830. /* See also rfc 3536 */
  831. r = BN_hex2bn(&p,
  832. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  833. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  834. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  835. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  836. "49286651ECE65381FFFFFFFFFFFFFFFF");
  837. tor_assert(r);
  838. r = BN_set_word(g, 2);
  839. tor_assert(r);
  840. dh_param_p = p;
  841. dh_param_g = g;
  842. }
  843. crypto_dh_env_t *crypto_dh_new()
  844. {
  845. crypto_dh_env_t *res = NULL;
  846. if (!dh_param_p)
  847. init_dh_param();
  848. res = tor_malloc(sizeof(crypto_dh_env_t));
  849. res->dh = NULL;
  850. if (!(res->dh = DH_new()))
  851. goto err;
  852. if (!(res->dh->p = BN_dup(dh_param_p)))
  853. goto err;
  854. if (!(res->dh->g = BN_dup(dh_param_g)))
  855. goto err;
  856. return res;
  857. err:
  858. crypto_log_errors(LOG_WARN, "creating DH object");
  859. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  860. if (res) free(res);
  861. return NULL;
  862. }
  863. int crypto_dh_get_bytes(crypto_dh_env_t *dh)
  864. {
  865. tor_assert(dh);
  866. return DH_size(dh->dh);
  867. }
  868. int crypto_dh_generate_public(crypto_dh_env_t *dh)
  869. {
  870. if (!DH_generate_key(dh->dh)) {
  871. crypto_log_errors(LOG_WARN, "generating DH key");
  872. return -1;
  873. }
  874. return 0;
  875. }
  876. int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, int pubkey_len)
  877. {
  878. int bytes;
  879. tor_assert(dh);
  880. if (!dh->dh->pub_key) {
  881. if (crypto_dh_generate_public(dh)<0)
  882. return -1;
  883. }
  884. tor_assert(dh->dh->pub_key);
  885. bytes = BN_num_bytes(dh->dh->pub_key);
  886. if (pubkey_len < bytes)
  887. return -1;
  888. memset(pubkey, 0, pubkey_len);
  889. BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
  890. return 0;
  891. }
  892. #undef MIN
  893. #define MIN(a,b) ((a)<(b)?(a):(b))
  894. int crypto_dh_compute_secret(crypto_dh_env_t *dh,
  895. const char *pubkey, int pubkey_len,
  896. char *secret_out, int secret_bytes_out)
  897. {
  898. unsigned char hash[DIGEST_LEN];
  899. unsigned char *secret_tmp = NULL;
  900. BIGNUM *pubkey_bn = NULL;
  901. int secret_len;
  902. int i;
  903. tor_assert(dh);
  904. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  905. if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
  906. goto error;
  907. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
  908. secret_len = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
  909. /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
  910. for (i = 0; i < secret_bytes_out; i += DIGEST_LEN) {
  911. secret_tmp[secret_len] = (unsigned char) i/DIGEST_LEN;
  912. if (crypto_digest(secret_tmp, secret_len+1, hash))
  913. goto error;
  914. memcpy(secret_out+i, hash, MIN(DIGEST_LEN, secret_bytes_out-i));
  915. }
  916. secret_len = secret_bytes_out;
  917. goto done;
  918. error:
  919. secret_len = -1;
  920. done:
  921. crypto_log_errors(LOG_WARN, "completing DH handshake");
  922. if (pubkey_bn)
  923. BN_free(pubkey_bn);
  924. tor_free(secret_tmp);
  925. return secret_len;
  926. }
  927. void crypto_dh_free(crypto_dh_env_t *dh)
  928. {
  929. tor_assert(dh && dh->dh);
  930. DH_free(dh->dh);
  931. free(dh);
  932. }
  933. /* random numbers */
  934. #ifdef MS_WINDOWS
  935. int crypto_seed_rng()
  936. {
  937. static int provider_set = 0;
  938. static HCRYPTPROV provider;
  939. char buf[DIGEST_LEN+1];
  940. if (!provider_set) {
  941. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, 0)) {
  942. if (GetLastError() != NTE_BAD_KEYSET) {
  943. log_fn(LOG_ERR,"Can't get CryptoAPI provider [1]");
  944. return -1;
  945. }
  946. /* Yes, we need to try it twice. */
  947. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  948. CRYPT_NEWKEYSET)) {
  949. log_fn(LOG_ERR,"Can't get CryptoAPI provider [2]");
  950. return -1;
  951. }
  952. }
  953. provider_set = 1;
  954. }
  955. if (!CryptGenRandom(provider, DIGEST_LEN, buf)) {
  956. log_fn(LOG_ERR,"Can't get entropy from CryptoAPI.");
  957. return -1;
  958. }
  959. RAND_seed(buf, DIGEST_LEN);
  960. /* And add the current screen state to the entopy pool for
  961. * good measure. */
  962. RAND_screen();
  963. return 0;
  964. }
  965. #else
  966. int crypto_seed_rng()
  967. {
  968. static char *filenames[] = {
  969. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  970. };
  971. int fd;
  972. int i, n;
  973. char buf[DIGEST_LEN+1];
  974. for (i = 0; filenames[i]; ++i) {
  975. fd = open(filenames[i], O_RDONLY, 0);
  976. if (fd<0) continue;
  977. log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
  978. n = read(fd, buf, DIGEST_LEN);
  979. close(fd);
  980. if (n != DIGEST_LEN) {
  981. log_fn(LOG_WARN, "Error reading from entropy source");
  982. return -1;
  983. }
  984. RAND_seed(buf, DIGEST_LEN);
  985. return 0;
  986. }
  987. log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
  988. return -1;
  989. }
  990. #endif
  991. int crypto_rand(unsigned int n, unsigned char *to)
  992. {
  993. int r;
  994. tor_assert(to);
  995. r = RAND_bytes(to, n);
  996. if (r == 0)
  997. crypto_log_errors(LOG_WARN, "generating random data");
  998. return (r != 1);
  999. }
  1000. void crypto_pseudo_rand(unsigned int n, unsigned char *to)
  1001. {
  1002. tor_assert(to);
  1003. if (RAND_pseudo_bytes(to, n) == -1) {
  1004. log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
  1005. crypto_log_errors(LOG_WARN, "generating random data");
  1006. exit(1);
  1007. }
  1008. }
  1009. /* return a pseudo random number between 0 and max-1 */
  1010. int crypto_pseudo_rand_int(unsigned int max) {
  1011. unsigned int val;
  1012. unsigned int cutoff;
  1013. tor_assert(max < UINT_MAX);
  1014. tor_assert(max > 0); /* don't div by 0 */
  1015. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1016. * distribution with clipping at the upper end of unsigned int's
  1017. * range.
  1018. */
  1019. cutoff = UINT_MAX - (UINT_MAX%max);
  1020. while(1) {
  1021. crypto_pseudo_rand(sizeof(val), (unsigned char*) &val);
  1022. if (val < cutoff)
  1023. return val % max;
  1024. }
  1025. }
  1026. int
  1027. base64_encode(char *dest, int destlen, const char *src, int srclen)
  1028. {
  1029. EVP_ENCODE_CTX ctx;
  1030. int len, ret;
  1031. /* 48 bytes of input -> 64 bytes of output plus newline.
  1032. Plus one more byte, in case I'm wrong.
  1033. */
  1034. if (destlen < ((srclen/48)+1)*66)
  1035. return -1;
  1036. EVP_EncodeInit(&ctx);
  1037. EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  1038. EVP_EncodeFinal(&ctx, dest+len, &ret);
  1039. ret += len;
  1040. return ret;
  1041. }
  1042. int
  1043. base64_decode(char *dest, int destlen, const char *src, int srclen)
  1044. {
  1045. EVP_ENCODE_CTX ctx;
  1046. int len, ret;
  1047. /* 64 bytes of input -> *up to* 48 bytes of output.
  1048. Plus one more byte, in caes I'm wrong.
  1049. */
  1050. if (destlen < ((srclen/64)+1)*49)
  1051. return -1;
  1052. EVP_DecodeInit(&ctx);
  1053. EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  1054. EVP_DecodeFinal(&ctx, dest, &ret);
  1055. ret += len;
  1056. return ret;
  1057. }
  1058. /* Implement base32 encoding as in rfc3548. Limitation: Requires that
  1059. * srclen is a multiple of 5.
  1060. */
  1061. int
  1062. base32_encode(char *dest, int destlen, const char *src, int srclen)
  1063. {
  1064. int nbits, i, bit, v, u;
  1065. nbits = srclen * 8;
  1066. if ((nbits%5) != 0)
  1067. /* We need an even multiple of 5 bits. */
  1068. return -1;
  1069. if ((nbits/5)+1 > destlen)
  1070. /* Not enough space. */
  1071. return -1;
  1072. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  1073. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  1074. v = ((uint8_t)src[bit/8]) << 8;
  1075. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  1076. /* set u to the 5-bit value at the bit'th bit of src. */
  1077. u = (v >> (11-(bit%8))) & 0x1F;
  1078. dest[i] = BASE32_CHARS[u];
  1079. }
  1080. dest[i] = '\0';
  1081. return 0;
  1082. }
  1083. /*
  1084. Local Variables:
  1085. mode:c
  1086. indent-tabs-mode:nil
  1087. c-basic-offset:2
  1088. End:
  1089. */