crypto.c 30 KB

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