crypto.c 30 KB

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