crypto.c 28 KB

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