crypto.c 29 KB

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