crypto.c 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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, const 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(const 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. /* return a pseudo random number between 0 and max-1 */
  857. int crypto_pseudo_rand_int(unsigned int max) {
  858. unsigned int val;
  859. unsigned int cutoff;
  860. assert(max < UINT_MAX);
  861. assert(max > 0); /* don't div by 0 */
  862. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  863. * distribution with clipping at the upper end of unsigned int's
  864. * range.
  865. */
  866. cutoff = UINT_MAX - (UINT_MAX%max);
  867. while(1) {
  868. crypto_pseudo_rand(sizeof(val), (unsigned char*) &val);
  869. if (val < cutoff)
  870. return val % max;
  871. }
  872. }
  873. /* errors */
  874. char *crypto_perror()
  875. {
  876. return (char *)ERR_reason_error_string(ERR_get_error());
  877. }
  878. int
  879. base64_encode(char *dest, int destlen, const char *src, int srclen)
  880. {
  881. EVP_ENCODE_CTX ctx;
  882. int len, ret;
  883. /* 48 bytes of input -> 64 bytes of output plus newline.
  884. Plus one more byte, in case I'm wrong.
  885. */
  886. if (destlen < ((srclen/48)+1)*66)
  887. return -1;
  888. EVP_EncodeInit(&ctx);
  889. EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  890. EVP_EncodeFinal(&ctx, dest+len, &ret);
  891. ret += len;
  892. return ret;
  893. }
  894. int
  895. base64_decode(char *dest, int destlen, const char *src, int srclen)
  896. {
  897. EVP_ENCODE_CTX ctx;
  898. int len, ret;
  899. /* 64 bytes of input -> *up to* 48 bytes of output.
  900. Plus one more byte, in caes I'm wrong.
  901. */
  902. if (destlen < ((srclen/64)+1)*49)
  903. return -1;
  904. EVP_DecodeInit(&ctx);
  905. EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  906. EVP_DecodeFinal(&ctx, dest, &ret);
  907. ret += len;
  908. return ret;
  909. }