crypto.c 26 KB

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