crypto.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include <string.h>
  5. #include <openssl/err.h>
  6. #include <openssl/rsa.h>
  7. #include <openssl/pem.h>
  8. #include <openssl/evp.h>
  9. #include <openssl/rand.h>
  10. #include <openssl/opensslv.h>
  11. #include <openssl/bn.h>
  12. #include <openssl/dh.h>
  13. #include <stdlib.h>
  14. #include <assert.h>
  15. #include <stdio.h>
  16. #include <limits.h>
  17. #include "crypto.h"
  18. #include "../or/or.h"
  19. #include "log.h"
  20. #include "aes.h"
  21. #if OPENSSL_VERSION_NUMBER < 0x00905000l
  22. #error "We require openssl >= 0.9.5"
  23. #elif OPENSSL_VERSION_NUMBER < 0x00906000l
  24. #define OPENSSL_095
  25. #endif
  26. /*
  27. * Certain functions that return a success code in OpenSSL 0.9.6 return void
  28. * (and don't indicate errors) in OpenSSL version 0.9.5.
  29. *
  30. * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
  31. */
  32. #ifdef OPENSSL_095
  33. #define RETURN_SSL_OUTCOME(exp) (exp); return 0
  34. #else
  35. #define RETURN_SSL_OUTCOME(exp) return !(exp)
  36. #endif
  37. struct crypto_pk_env_t
  38. {
  39. int type;
  40. int refs; /* reference counting; so we don't have to copy keys */
  41. unsigned char *key;
  42. /* auxiliary data structure(s) used by the underlying crypto library */
  43. unsigned char *aux;
  44. };
  45. struct crypto_cipher_env_t
  46. {
  47. int type;
  48. unsigned char *key;
  49. unsigned char *iv;
  50. /* auxiliary data structure(s) used by the underlying crypto library */
  51. unsigned char *aux;
  52. };
  53. /* static INLINE const EVP_CIPHER *
  54. crypto_cipher_evp_cipher(int type, int enc);
  55. */
  56. static INLINE int
  57. crypto_cipher_iv_length(int type) {
  58. /*
  59. printf("%d -> %d IV\n",type, EVP_CIPHER_iv_length(
  60. crypto_cipher_evp_cipher(type,0)));
  61. */
  62. switch(type)
  63. {
  64. case CRYPTO_CIPHER_IDENTITY: return 0;
  65. case CRYPTO_CIPHER_DES: return 8;
  66. case CRYPTO_CIPHER_RC4: return 16;
  67. case CRYPTO_CIPHER_3DES: return 8;
  68. case CRYPTO_CIPHER_AES_CTR: return 0;
  69. default: assert(0); return -1;
  70. }
  71. }
  72. static INLINE int
  73. crypto_cipher_key_length(int type) {
  74. /*
  75. printf("%d -> %d\n",type, EVP_CIPHER_key_length(
  76. crypto_cipher_evp_cipher(type,0)));
  77. */
  78. switch(type)
  79. {
  80. case CRYPTO_CIPHER_IDENTITY: return 0;
  81. case CRYPTO_CIPHER_DES: return 8;
  82. case CRYPTO_CIPHER_RC4: return 16;
  83. case CRYPTO_CIPHER_3DES: return 16;
  84. case CRYPTO_CIPHER_AES_CTR: return 16;
  85. default: assert(0); return -1;
  86. }
  87. }
  88. static INLINE const EVP_CIPHER *
  89. crypto_cipher_evp_cipher(int type, int enc) {
  90. switch(type)
  91. {
  92. case CRYPTO_CIPHER_IDENTITY: return EVP_enc_null();
  93. case CRYPTO_CIPHER_DES: return EVP_des_ofb();
  94. case CRYPTO_CIPHER_RC4: return EVP_rc4();
  95. case CRYPTO_CIPHER_3DES: return EVP_des_ede_ofb();
  96. default: return NULL;
  97. }
  98. }
  99. static int _crypto_global_initialized = 0;
  100. int crypto_global_init()
  101. {
  102. if (!_crypto_global_initialized) {
  103. ERR_load_crypto_strings();
  104. _crypto_global_initialized = 1;
  105. }
  106. return 0;
  107. }
  108. int crypto_global_cleanup()
  109. {
  110. ERR_free_strings();
  111. return 0;
  112. }
  113. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
  114. {
  115. crypto_pk_env_t *env;
  116. assert(rsa);
  117. env = (crypto_pk_env_t *)tor_malloc(sizeof(crypto_pk_env_t));
  118. env->type = CRYPTO_PK_RSA;
  119. env->refs = 1;
  120. env->key = (unsigned char*)rsa;
  121. env->aux = NULL;
  122. return env;
  123. }
  124. RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
  125. {
  126. if (env->type != CRYPTO_PK_RSA)
  127. return NULL;
  128. return (RSA*)env->key;
  129. }
  130. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env)
  131. {
  132. RSA *key = NULL;
  133. EVP_PKEY *pkey = NULL;
  134. if (env->type != CRYPTO_PK_RSA)
  135. return NULL;
  136. assert(env->key);
  137. if (!(key = RSAPrivateKey_dup((RSA*)env->key)))
  138. goto error;
  139. if (!(pkey = EVP_PKEY_new()))
  140. goto error;
  141. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  142. goto error;
  143. return pkey;
  144. error:
  145. if (pkey)
  146. EVP_PKEY_free(pkey);
  147. if (key)
  148. RSA_free(key);
  149. return NULL;
  150. }
  151. crypto_pk_env_t *crypto_new_pk_env(int type)
  152. {
  153. RSA *rsa;
  154. switch(type) {
  155. case CRYPTO_PK_RSA:
  156. rsa = RSA_new();
  157. if (!rsa) return NULL;
  158. return _crypto_new_pk_env_rsa(rsa);
  159. default:
  160. return NULL;
  161. }
  162. }
  163. void crypto_free_pk_env(crypto_pk_env_t *env)
  164. {
  165. assert(env);
  166. if(--env->refs > 0)
  167. return;
  168. switch(env->type) {
  169. case CRYPTO_PK_RSA:
  170. if (env->key)
  171. RSA_free((RSA *)env->key);
  172. break;
  173. default:
  174. break;
  175. }
  176. free(env);
  177. }
  178. /* Create a new crypto_cipher_env_t for a given onion cipher type, key,
  179. * iv, and encryption flag (1=encrypt, 0=decrypt). Return the crypto object
  180. * on success; NULL on failure.
  181. */
  182. crypto_cipher_env_t *
  183. crypto_create_init_cipher(int cipher_type, char *key, char *iv, int encrypt_mode)
  184. {
  185. int r;
  186. crypto_cipher_env_t *crypto = NULL;
  187. if (! (crypto = crypto_new_cipher_env(cipher_type))) {
  188. log_fn(LOG_WARN, "Unable to allocate crypto object");
  189. return NULL;
  190. }
  191. if (crypto_cipher_set_key(crypto, key)) {
  192. log_fn(LOG_WARN, "Unable to set key: %s", crypto_perror());
  193. goto error;
  194. }
  195. if (crypto_cipher_set_iv(crypto, iv)) {
  196. log_fn(LOG_WARN, "Unable to set iv: %s", crypto_perror());
  197. goto error;
  198. }
  199. if (encrypt_mode)
  200. r = crypto_cipher_encrypt_init_cipher(crypto);
  201. else
  202. r = crypto_cipher_decrypt_init_cipher(crypto);
  203. if (r) {
  204. log_fn(LOG_WARN, "Unable to initialize cipher: %s", crypto_perror());
  205. goto error;
  206. }
  207. return crypto;
  208. error:
  209. if (crypto)
  210. crypto_free_cipher_env(crypto);
  211. return NULL;
  212. }
  213. crypto_cipher_env_t *crypto_new_cipher_env(int type)
  214. {
  215. crypto_cipher_env_t *env;
  216. int iv_len, key_len;
  217. env = (crypto_cipher_env_t *)tor_malloc(sizeof(crypto_cipher_env_t));
  218. env->type = type;
  219. env->key = NULL;
  220. env->iv = NULL;
  221. env->aux = NULL;
  222. iv_len = crypto_cipher_iv_length(type);
  223. key_len = crypto_cipher_key_length(type);
  224. if (type == CRYPTO_CIPHER_AES_CTR) {
  225. env->aux = (unsigned char *)aes_new_cipher();
  226. } else if (! crypto_cipher_evp_cipher(type,0))
  227. /* This is not an openssl cipher */
  228. goto err;
  229. else {
  230. env->aux = (unsigned char *)tor_malloc(sizeof(EVP_CIPHER_CTX));
  231. EVP_CIPHER_CTX_init((EVP_CIPHER_CTX *)env->aux);
  232. }
  233. if(iv_len)
  234. env->iv = (unsigned char *)tor_malloc(iv_len);
  235. if(key_len)
  236. env->key = (unsigned char *)tor_malloc(key_len);
  237. return env;
  238. err:
  239. if (env->key)
  240. free(env->key);
  241. if (env->iv)
  242. free(env->iv);
  243. if (env->aux)
  244. free(env->aux);
  245. if (env)
  246. free(env);
  247. return NULL;
  248. }
  249. void crypto_free_cipher_env(crypto_cipher_env_t *env)
  250. {
  251. assert(env);
  252. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  253. assert(env->aux);
  254. aes_free_cipher((aes_cnt_cipher_t*)env->aux);
  255. env->aux = NULL;
  256. } else if (crypto_cipher_evp_cipher(env->type,0)) {
  257. /* This is an openssl cipher */
  258. assert(env->aux);
  259. EVP_CIPHER_CTX_cleanup((EVP_CIPHER_CTX *)env->aux);
  260. }
  261. if (env->aux)
  262. free((void *)env->aux);
  263. if (env->iv)
  264. free((void *)env->iv);
  265. if (env->key)
  266. free((void *)env->key);
  267. free((void *)env);
  268. }
  269. /* public key crypto */
  270. int crypto_pk_generate_key(crypto_pk_env_t *env)
  271. {
  272. assert(env);
  273. switch(env->type) {
  274. case CRYPTO_PK_RSA:
  275. if (env->key)
  276. RSA_free((RSA *)env->key);
  277. env->key = (unsigned char *)RSA_generate_key(1024,65537, NULL, NULL);
  278. if (!env->key)
  279. return -1;
  280. break;
  281. default:
  282. return -1;
  283. }
  284. return 0;
  285. }
  286. int crypto_pk_read_private_key_from_file(crypto_pk_env_t *env, FILE *src)
  287. {
  288. assert(env && src);
  289. switch(env->type) {
  290. case CRYPTO_PK_RSA:
  291. if (env->key)
  292. RSA_free((RSA *)env->key);
  293. env->key = (unsigned char *)PEM_read_RSAPrivateKey(src, NULL, NULL, NULL);
  294. if (!env->key)
  295. return -1;
  296. break;
  297. default :
  298. return -1;
  299. }
  300. return 0;
  301. }
  302. int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
  303. {
  304. FILE *f_pr;
  305. assert(env && keyfile);
  306. if(strspn(keyfile,CONFIG_LEGAL_FILENAME_CHARACTERS) != strlen(keyfile)) {
  307. /* filename contains nonlegal characters */
  308. return -1;
  309. }
  310. /* open the keyfile */
  311. f_pr=fopen(keyfile,"rb");
  312. if (!f_pr)
  313. return -1;
  314. /* read the private key */
  315. if(crypto_pk_read_private_key_from_file(env, f_pr) < 0) {
  316. log_fn(LOG_WARN,"Error reading private key : %s",crypto_perror());
  317. fclose(f_pr);
  318. return -1;
  319. }
  320. fclose(f_pr);
  321. /* check the private key */
  322. switch(crypto_pk_check_key(env)) {
  323. case 0:
  324. log_fn(LOG_WARN,"Private key read but is invalid : %s.", crypto_perror());
  325. return -1;
  326. case -1:
  327. log_fn(LOG_WARN,"Private key read but validity checking failed : %s",crypto_perror());
  328. return -1;
  329. /* case 1: fall through */
  330. }
  331. return 0;
  332. }
  333. int crypto_pk_read_public_key_from_file(crypto_pk_env_t *env, FILE *src)
  334. {
  335. assert(env && src);
  336. switch(env->type) {
  337. case CRYPTO_PK_RSA:
  338. if(env->key)
  339. RSA_free((RSA *)env->key);
  340. env->key = (unsigned char *)PEM_read_RSAPublicKey(src, NULL, NULL, NULL);
  341. if (!env->key)
  342. return -1;
  343. break;
  344. default :
  345. return -1;
  346. }
  347. return 0;
  348. }
  349. int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, int *len) {
  350. BUF_MEM *buf;
  351. BIO *b;
  352. assert(env && env->key && dest);
  353. switch(env->type) {
  354. case CRYPTO_PK_RSA:
  355. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  356. /* Now you can treat b as if it were a file. Just use the
  357. * PEM_*_bio_* functions instead of the non-bio variants.
  358. */
  359. if(!PEM_write_bio_RSAPublicKey(b, (RSA *)env->key))
  360. return -1;
  361. BIO_get_mem_ptr(b, &buf);
  362. BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  363. BIO_free(b);
  364. *dest = tor_malloc(buf->length+1);
  365. memcpy(*dest, buf->data, buf->length);
  366. (*dest)[buf->length] = 0; /* null terminate it */
  367. *len = buf->length;
  368. BUF_MEM_free(buf);
  369. break;
  370. default:
  371. return -1;
  372. }
  373. return 0;
  374. }
  375. int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, char *src, int len) {
  376. BIO *b;
  377. assert(env && src);
  378. switch(env->type) {
  379. case CRYPTO_PK_RSA:
  380. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  381. BIO_write(b, src, len);
  382. RSA_free((RSA *)env->key);
  383. env->key = (unsigned char *)PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  384. if(!env->key)
  385. return -1;
  386. BIO_free(b);
  387. break;
  388. default:
  389. return -1;
  390. }
  391. return 0;
  392. }
  393. int
  394. crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
  395. const char *fname)
  396. {
  397. BIO *bio;
  398. char *cp;
  399. long len;
  400. char *s;
  401. int r;
  402. assert(env->type == CRYPTO_PK_RSA);
  403. if (!(bio = BIO_new(BIO_s_mem())))
  404. return -1;
  405. if (PEM_write_bio_RSAPrivateKey(bio, (RSA*)env->key, NULL,NULL,0,NULL,NULL)
  406. == 0) {
  407. BIO_free(bio);
  408. return -1;
  409. }
  410. len = BIO_get_mem_data(bio, &cp);
  411. s = tor_malloc(len+1);
  412. strncpy(s, cp, len);
  413. s[len] = '\0';
  414. r = write_str_to_file(fname, s);
  415. BIO_free(bio);
  416. free(s);
  417. return r;
  418. }
  419. int crypto_pk_write_private_key_to_file(crypto_pk_env_t *env, FILE *dest)
  420. {
  421. assert(env && dest);
  422. switch(env->type) {
  423. case CRYPTO_PK_RSA:
  424. if (!env->key)
  425. return -1;
  426. if (PEM_write_RSAPrivateKey(dest, (RSA *)env->key, NULL, NULL, 0,0, NULL) == 0)
  427. return -1;
  428. break;
  429. default :
  430. return -1;
  431. }
  432. return 0;
  433. }
  434. int crypto_pk_write_public_key_to_file(crypto_pk_env_t *env, FILE *dest)
  435. {
  436. assert(env && dest);
  437. switch(env->type) {
  438. case CRYPTO_PK_RSA:
  439. if (!env->key)
  440. return -1;
  441. if (PEM_write_RSAPublicKey(dest, (RSA *)env->key) == 0)
  442. return -1;
  443. break;
  444. default :
  445. return -1;
  446. }
  447. return 0;
  448. }
  449. int crypto_pk_check_key(crypto_pk_env_t *env)
  450. {
  451. assert(env);
  452. switch(env->type) {
  453. case CRYPTO_PK_RSA:
  454. return RSA_check_key((RSA *)env->key);
  455. default:
  456. return -1;
  457. }
  458. }
  459. int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
  460. int result;
  461. if (!a || !b)
  462. return -1;
  463. if (!a->key || !b->key)
  464. return -1;
  465. if (a->type != b->type)
  466. return -1;
  467. switch(a->type) {
  468. case CRYPTO_PK_RSA:
  469. assert(((RSA *)a->key)->n && ((RSA *)a->key)->e && ((RSA *)b->key)->n && ((RSA *)b->key)->e);
  470. result = BN_cmp(((RSA *)a->key)->n, ((RSA *)b->key)->n);
  471. if (result)
  472. return result;
  473. return BN_cmp(((RSA *)a->key)->e, ((RSA *)b->key)->e);
  474. default:
  475. return -1;
  476. }
  477. }
  478. int crypto_pk_keysize(crypto_pk_env_t *env)
  479. {
  480. assert(env && env->key);
  481. return RSA_size((RSA *)env->key);
  482. }
  483. crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
  484. assert(env && env->key);
  485. switch(env->type) {
  486. case CRYPTO_PK_RSA:
  487. env->refs++;
  488. break;
  489. default:
  490. return NULL;
  491. }
  492. return env;
  493. }
  494. int crypto_pk_public_encrypt(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to, int padding)
  495. {
  496. assert(env && from && to);
  497. switch(env->type) {
  498. case CRYPTO_PK_RSA:
  499. return RSA_public_encrypt(fromlen, from, to, (RSA *)env->key, padding);
  500. default:
  501. return -1;
  502. }
  503. }
  504. int crypto_pk_private_decrypt(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to, int padding)
  505. {
  506. assert(env && from && to);
  507. switch(env->type) {
  508. case CRYPTO_PK_RSA:
  509. if (!(((RSA*)env->key)->p))
  510. return -1;
  511. return RSA_private_decrypt(fromlen, from, to, (RSA *)env->key, padding);
  512. default:
  513. return -1;
  514. }
  515. }
  516. int crypto_pk_public_checksig(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to)
  517. {
  518. assert(env && from && to);
  519. switch(env->type) {
  520. case CRYPTO_PK_RSA:
  521. return RSA_public_decrypt(fromlen, from, to, (RSA *)env->key,
  522. RSA_PKCS1_PADDING);
  523. default:
  524. return -1;
  525. }
  526. }
  527. int crypto_pk_private_sign(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to)
  528. {
  529. assert(env && from && to);
  530. switch(env->type) {
  531. case CRYPTO_PK_RSA:
  532. if (!(((RSA*)env->key)->p))
  533. return -1;
  534. return RSA_private_encrypt(fromlen, from, to, (RSA *)env->key,
  535. RSA_PKCS1_PADDING);
  536. default:
  537. return -1;
  538. }
  539. }
  540. int
  541. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out)
  542. {
  543. unsigned char *buf, *bufp;
  544. unsigned char digest[20];
  545. int len;
  546. int i;
  547. assert(pk->type == CRYPTO_PK_RSA);
  548. len = i2d_RSAPublicKey((RSA*)pk->key, NULL);
  549. if (len < 0)
  550. return -1;
  551. if (len<FINGERPRINT_LEN+1) len = FINGERPRINT_LEN+1;
  552. buf = bufp = tor_malloc(len+1);
  553. len = i2d_RSAPublicKey((RSA*)pk->key, &bufp);
  554. if (len < 0) {
  555. free(buf);
  556. return -1;
  557. }
  558. if (crypto_SHA_digest(buf, len, digest) < 0) {
  559. free(buf);
  560. return -1;
  561. }
  562. bufp = buf;
  563. for (i = 0; i < 20; ++i) {
  564. sprintf(bufp,"%02X",digest[i]);
  565. bufp += 2;
  566. if (i%2 && i != 19) {
  567. *bufp++ = ' ';
  568. }
  569. }
  570. *bufp = '\0';
  571. assert(strlen(buf) == FINGERPRINT_LEN);
  572. assert(crypto_pk_check_fingerprint_syntax(buf));
  573. strcpy(fp_out, buf);
  574. free(buf);
  575. return 0;
  576. }
  577. int
  578. crypto_pk_check_fingerprint_syntax(const char *s)
  579. {
  580. int i;
  581. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  582. if ((i%5) == 4) {
  583. if (!isspace(s[i])) return 0;
  584. } else {
  585. if (!isxdigit(s[i])) return 0;
  586. }
  587. }
  588. if (s[FINGERPRINT_LEN]) return 0;
  589. return 1;
  590. }
  591. /* symmetric crypto */
  592. int crypto_cipher_generate_key(crypto_cipher_env_t *env)
  593. {
  594. int key_len;
  595. assert(env);
  596. key_len = crypto_cipher_key_length(env->type);
  597. if (key_len > 0)
  598. return crypto_rand(key_len, env->key);
  599. else if (key_len == 0)
  600. return 0;
  601. else
  602. return -1;
  603. }
  604. int crypto_cipher_set_iv(crypto_cipher_env_t *env, unsigned char *iv)
  605. {
  606. int iv_len;
  607. assert(env && iv);
  608. iv_len = crypto_cipher_iv_length(env->type);
  609. if (!iv_len)
  610. return 0;
  611. if (!env->iv)
  612. return -1;
  613. memcpy((void*)env->iv, (void*)iv, iv_len);
  614. return 0;
  615. }
  616. int crypto_cipher_set_key(crypto_cipher_env_t *env, unsigned char *key)
  617. {
  618. int key_len;
  619. assert(env && key);
  620. key_len = crypto_cipher_key_length(env->type);
  621. if (!key_len)
  622. return 0;
  623. if (!env->key)
  624. return -1;
  625. memcpy((void*)env->key, (void*)key, key_len);
  626. return 0;
  627. }
  628. unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
  629. {
  630. return env->key;
  631. }
  632. int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  633. {
  634. assert(env);
  635. if (crypto_cipher_evp_cipher(env->type, 1)) {
  636. RETURN_SSL_OUTCOME(EVP_EncryptInit((EVP_CIPHER_CTX *)env->aux,
  637. crypto_cipher_evp_cipher(env->type, 1),
  638. env->key, env->iv));
  639. } else if (env->type == CRYPTO_CIPHER_AES_CTR) {
  640. aes_set_key((aes_cnt_cipher_t*)env->aux, env->key, 128);
  641. return 0;
  642. } else {
  643. return -1;
  644. }
  645. }
  646. int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  647. {
  648. assert(env);
  649. if (crypto_cipher_evp_cipher(env->type, 0)) {
  650. RETURN_SSL_OUTCOME(EVP_EncryptInit((EVP_CIPHER_CTX *)env->aux,
  651. crypto_cipher_evp_cipher(env->type, 0),
  652. env->key, env->iv));
  653. } else if (env->type == CRYPTO_CIPHER_AES_CTR) {
  654. aes_set_key((aes_cnt_cipher_t*)env->aux, env->key, 128);
  655. return 0;
  656. } else {
  657. return -1;
  658. }
  659. }
  660. int crypto_cipher_encrypt(crypto_cipher_env_t *env, unsigned char *from, unsigned int fromlen, unsigned char *to)
  661. {
  662. int tolen;
  663. assert(env && from && to);
  664. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  665. aes_crypt((aes_cnt_cipher_t*)env->aux, from, fromlen, to);
  666. return 0;
  667. } else {
  668. RETURN_SSL_OUTCOME(EVP_EncryptUpdate((EVP_CIPHER_CTX *)env->aux, to, &tolen, from, fromlen));
  669. }
  670. }
  671. int crypto_cipher_decrypt(crypto_cipher_env_t *env, unsigned char *from, unsigned int fromlen, unsigned char *to)
  672. {
  673. int tolen;
  674. assert(env && from && to);
  675. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  676. aes_crypt((aes_cnt_cipher_t*)env->aux, from, fromlen, to);
  677. return 0;
  678. } else {
  679. RETURN_SSL_OUTCOME(EVP_DecryptUpdate((EVP_CIPHER_CTX *)env->aux, to, &tolen, from, fromlen));
  680. }
  681. }
  682. int
  683. crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
  684. {
  685. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  686. aes_adjust_counter((aes_cnt_cipher_t*)env->aux, delta);
  687. return 0;
  688. } else {
  689. return -1;
  690. }
  691. }
  692. /* SHA-1 */
  693. int crypto_SHA_digest(unsigned char *m, int len, unsigned char *digest)
  694. {
  695. assert(m && digest);
  696. return (SHA1(m,len,digest) == NULL);
  697. }
  698. static BIGNUM *dh_param_p = NULL;
  699. static BIGNUM *dh_param_g = NULL;
  700. static void init_dh_param() {
  701. BIGNUM *p, *g;
  702. int r;
  703. if (dh_param_p && dh_param_g)
  704. return;
  705. p = BN_new();
  706. g = BN_new();
  707. assert(p && g);
  708. #if 0
  709. /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
  710. prime, and supposedly it equals:
  711. 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
  712. */
  713. r = BN_hex2bn(&p,
  714. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
  715. "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
  716. "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
  717. "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
  718. "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
  719. "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
  720. "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
  721. "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
  722. #endif
  723. /* This is from rfc2409, section 6.2. It's a safe prime, and
  724. supposedly it equals:
  725. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  726. */
  727. /* See also rfc 3536 */
  728. r = BN_hex2bn(&p,
  729. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  730. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  731. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  732. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  733. "49286651ECE65381FFFFFFFFFFFFFFFF");
  734. assert(r);
  735. r = BN_set_word(g, 2);
  736. assert(r);
  737. dh_param_p = p;
  738. dh_param_g = g;
  739. }
  740. crypto_dh_env_t *crypto_dh_new()
  741. {
  742. crypto_dh_env_t *res = NULL;
  743. if (!dh_param_p)
  744. init_dh_param();
  745. res = tor_malloc(sizeof(crypto_dh_env_t));
  746. res->dh = NULL;
  747. if (!(res->dh = DH_new()))
  748. goto err;
  749. if (!(res->dh->p = BN_dup(dh_param_p)))
  750. goto err;
  751. if (!(res->dh->g = BN_dup(dh_param_g)))
  752. goto err;
  753. return res;
  754. err:
  755. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  756. if (res) free(res);
  757. return NULL;
  758. }
  759. int crypto_dh_get_bytes(crypto_dh_env_t *dh)
  760. {
  761. assert(dh);
  762. return DH_size(dh->dh);
  763. }
  764. int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, int pubkey_len)
  765. {
  766. int bytes;
  767. assert(dh);
  768. if (!DH_generate_key(dh->dh))
  769. return -1;
  770. assert(dh->dh->pub_key);
  771. bytes = BN_num_bytes(dh->dh->pub_key);
  772. if (pubkey_len < bytes)
  773. return -1;
  774. memset(pubkey, 0, pubkey_len);
  775. BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
  776. return 0;
  777. }
  778. #undef MIN
  779. #define MIN(a,b) ((a)<(b)?(a):(b))
  780. int crypto_dh_compute_secret(crypto_dh_env_t *dh,
  781. char *pubkey, int pubkey_len,
  782. char *secret_out, int secret_bytes_out)
  783. {
  784. unsigned char hash[20];
  785. unsigned char *secret_tmp = NULL;
  786. BIGNUM *pubkey_bn = NULL;
  787. int secret_len;
  788. int i;
  789. assert(dh);
  790. assert(secret_bytes_out/20 <= 255);
  791. if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
  792. goto error;
  793. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
  794. secret_len = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
  795. for (i = 0; i < secret_bytes_out; i += 20) {
  796. secret_tmp[secret_len] = (unsigned char) i/20;
  797. if (crypto_SHA_digest(secret_tmp, secret_len+1, hash))
  798. goto error;
  799. memcpy(secret_out+i, hash, MIN(20, secret_bytes_out-i));
  800. }
  801. secret_len = secret_bytes_out;
  802. goto done;
  803. error:
  804. secret_len = -1;
  805. done:
  806. if (pubkey_bn)
  807. BN_free(pubkey_bn);
  808. if (secret_tmp)
  809. free(secret_tmp);
  810. return secret_len;
  811. }
  812. void crypto_dh_free(crypto_dh_env_t *dh)
  813. {
  814. assert(dh && dh->dh);
  815. DH_free(dh->dh);
  816. free(dh);
  817. }
  818. /* random numbers */
  819. int crypto_seed_rng()
  820. {
  821. static char *filenames[] = {
  822. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  823. };
  824. int i, n;
  825. char buf[21];
  826. FILE *f;
  827. for (i = 0; filenames[i]; ++i) {
  828. f = fopen(filenames[i], "rb");
  829. if (!f) continue;
  830. log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
  831. n = fread(buf, 1, 20, f);
  832. fclose(f);
  833. if (n != 20) {
  834. log_fn(LOG_WARN, "Error reading from entropy source");
  835. return -1;
  836. }
  837. RAND_seed(buf, 20);
  838. return 0;
  839. }
  840. log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
  841. return -1;
  842. }
  843. int crypto_rand(unsigned int n, unsigned char *to)
  844. {
  845. assert(to);
  846. return (RAND_bytes(to, n) != 1);
  847. }
  848. void crypto_pseudo_rand(unsigned int n, unsigned char *to)
  849. {
  850. assert(to);
  851. if (RAND_pseudo_bytes(to, n) == -1) {
  852. log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
  853. exit(1);
  854. }
  855. }
  856. int crypto_pseudo_rand_int(unsigned int max) {
  857. unsigned int val;
  858. unsigned int cutoff;
  859. assert(max < UINT_MAX);
  860. assert(max > 0); /* don't div by 0 */
  861. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  862. * distribution with clipping at the upper end of unsigned int's
  863. * range.
  864. */
  865. cutoff = UINT_MAX - (UINT_MAX%max);
  866. while(1) {
  867. crypto_pseudo_rand(sizeof(val), (unsigned char*) &val);
  868. if (val < cutoff)
  869. return val % max;
  870. }
  871. }
  872. /* errors */
  873. char *crypto_perror()
  874. {
  875. return (char *)ERR_reason_error_string(ERR_get_error());
  876. }
  877. int
  878. base64_encode(char *dest, int destlen, char *src, int srclen)
  879. {
  880. EVP_ENCODE_CTX ctx;
  881. int len, ret;
  882. /* 48 bytes of input -> 64 bytes of output plus newline.
  883. Plus one more byte, in case I'm wrong.
  884. */
  885. if (destlen < ((srclen/48)+1)*66)
  886. return -1;
  887. EVP_EncodeInit(&ctx);
  888. EVP_EncodeUpdate(&ctx, dest, &len, src, srclen);
  889. EVP_EncodeFinal(&ctx, dest+len, &ret);
  890. ret += len;
  891. return ret;
  892. }
  893. int
  894. base64_decode(char *dest, int destlen, char *src, int srclen)
  895. {
  896. EVP_ENCODE_CTX ctx;
  897. int len, ret;
  898. /* 64 bytes of input -> *up to* 48 bytes of output.
  899. Plus one more byte, in caes I'm wrong.
  900. */
  901. if (destlen < ((srclen/64)+1)*49)
  902. return -1;
  903. EVP_DecodeInit(&ctx);
  904. EVP_DecodeUpdate(&ctx, dest, &len, src, srclen);
  905. EVP_DecodeFinal(&ctx, dest, &ret);
  906. ret += len;
  907. return ret;
  908. }