crypto.c 23 KB

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