crypto_rsa.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto_rsa.c
  8. * \brief Block of functions related with RSA utilities and operations.
  9. **/
  10. #include "lib/crypt_ops/crypto_cipher.h"
  11. #include "lib/crypt_ops/crypto_curve25519.h"
  12. #include "lib/crypt_ops/crypto_digest.h"
  13. #include "lib/crypt_ops/crypto_format.h"
  14. #include "lib/crypt_ops/compat_openssl.h"
  15. #include "lib/crypt_ops/crypto_rand.h"
  16. #include "lib/crypt_ops/crypto_rsa.h"
  17. #include "lib/crypt_ops/crypto_util.h"
  18. #include "lib/ctime/di_ops.h"
  19. #include "lib/log/util_bug.h"
  20. #include "lib/fs/files.h"
  21. DISABLE_GCC_WARNING(redundant-decls)
  22. #include <openssl/err.h>
  23. #include <openssl/rsa.h>
  24. #include <openssl/pem.h>
  25. #include <openssl/evp.h>
  26. #include <openssl/engine.h>
  27. #include <openssl/rand.h>
  28. #include <openssl/bn.h>
  29. #include <openssl/dh.h>
  30. #include <openssl/conf.h>
  31. #include <openssl/hmac.h>
  32. ENABLE_GCC_WARNING(redundant-decls)
  33. #include "lib/log/log.h"
  34. #include "lib/encoding/binascii.h"
  35. #include <string.h>
  36. /** Declaration for crypto_pk_t structure. */
  37. struct crypto_pk_t
  38. {
  39. int refs; /**< reference count, so we don't have to copy keys */
  40. RSA *key; /**< The key itself */
  41. };
  42. /** Return the number of bytes added by padding method <b>padding</b>.
  43. */
  44. int
  45. crypto_get_rsa_padding_overhead(int padding)
  46. {
  47. switch (padding)
  48. {
  49. case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
  50. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  51. }
  52. }
  53. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  54. */
  55. int
  56. crypto_get_rsa_padding(int padding)
  57. {
  58. switch (padding)
  59. {
  60. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  61. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  62. }
  63. }
  64. /** used internally: quicly validate a crypto_pk_t object as a private key.
  65. * Return 1 iff the public key is valid, 0 if obviously invalid.
  66. */
  67. static int
  68. crypto_pk_private_ok(const crypto_pk_t *k)
  69. {
  70. #ifdef OPENSSL_1_1_API
  71. if (!k || !k->key)
  72. return 0;
  73. const BIGNUM *p, *q;
  74. RSA_get0_factors(k->key, &p, &q);
  75. return p != NULL; /* XXX/yawning: Should we check q? */
  76. #else /* !(defined(OPENSSL_1_1_API)) */
  77. return k && k->key && k->key->p;
  78. #endif /* defined(OPENSSL_1_1_API) */
  79. }
  80. /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
  81. crypto_pk_t *
  82. crypto_new_pk_from_rsa_(RSA *rsa)
  83. {
  84. crypto_pk_t *env;
  85. tor_assert(rsa);
  86. env = tor_malloc(sizeof(crypto_pk_t));
  87. env->refs = 1;
  88. env->key = rsa;
  89. return env;
  90. }
  91. /** Helper, used by tor-gencert.c. Return the RSA from a
  92. * crypto_pk_t. */
  93. RSA *
  94. crypto_pk_get_rsa_(crypto_pk_t *env)
  95. {
  96. return env->key;
  97. }
  98. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
  99. * private is set, include the private-key portion of the key. Return a valid
  100. * pointer on success, and NULL on failure. */
  101. MOCK_IMPL(EVP_PKEY *,
  102. crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
  103. {
  104. RSA *key = NULL;
  105. EVP_PKEY *pkey = NULL;
  106. tor_assert(env->key);
  107. if (private) {
  108. if (!(key = RSAPrivateKey_dup(env->key)))
  109. goto error;
  110. } else {
  111. if (!(key = RSAPublicKey_dup(env->key)))
  112. goto error;
  113. }
  114. if (!(pkey = EVP_PKEY_new()))
  115. goto error;
  116. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  117. goto error;
  118. return pkey;
  119. error:
  120. if (pkey)
  121. EVP_PKEY_free(pkey);
  122. if (key)
  123. RSA_free(key);
  124. return NULL;
  125. }
  126. /** Allocate and return storage for a public key. The key itself will not yet
  127. * be set.
  128. */
  129. MOCK_IMPL(crypto_pk_t *,
  130. crypto_pk_new,(void))
  131. {
  132. RSA *rsa;
  133. rsa = RSA_new();
  134. tor_assert(rsa);
  135. return crypto_new_pk_from_rsa_(rsa);
  136. }
  137. /** Release a reference to an asymmetric key; when all the references
  138. * are released, free the key.
  139. */
  140. void
  141. crypto_pk_free_(crypto_pk_t *env)
  142. {
  143. if (!env)
  144. return;
  145. if (--env->refs > 0)
  146. return;
  147. tor_assert(env->refs == 0);
  148. if (env->key)
  149. RSA_free(env->key);
  150. tor_free(env);
  151. }
  152. /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
  153. * Return 0 on success, -1 on failure.
  154. */
  155. MOCK_IMPL(int,
  156. crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
  157. {
  158. tor_assert(env);
  159. if (env->key) {
  160. RSA_free(env->key);
  161. env->key = NULL;
  162. }
  163. {
  164. BIGNUM *e = BN_new();
  165. RSA *r = NULL;
  166. if (!e)
  167. goto done;
  168. if (! BN_set_word(e, 65537))
  169. goto done;
  170. r = RSA_new();
  171. if (!r)
  172. goto done;
  173. if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
  174. goto done;
  175. env->key = r;
  176. r = NULL;
  177. done:
  178. if (e)
  179. BN_clear_free(e);
  180. if (r)
  181. RSA_free(r);
  182. }
  183. if (!env->key) {
  184. crypto_openssl_log_errors(LOG_WARN, "generating RSA key");
  185. return -1;
  186. }
  187. return 0;
  188. }
  189. /** A PEM callback that always reports a failure to get a password */
  190. static int
  191. pem_no_password_cb(char *buf, int size, int rwflag, void *u)
  192. {
  193. (void)buf;
  194. (void)size;
  195. (void)rwflag;
  196. (void)u;
  197. return -1;
  198. }
  199. /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
  200. * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
  201. * the string is nul-terminated.
  202. */
  203. int
  204. crypto_pk_read_private_key_from_string(crypto_pk_t *env,
  205. const char *s, ssize_t len)
  206. {
  207. BIO *b;
  208. tor_assert(env);
  209. tor_assert(s);
  210. tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
  211. /* Create a read-only memory BIO, backed by the string 's' */
  212. b = BIO_new_mem_buf((char*)s, (int)len);
  213. if (!b)
  214. return -1;
  215. if (env->key)
  216. RSA_free(env->key);
  217. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,pem_no_password_cb,NULL);
  218. BIO_free(b);
  219. if (!env->key) {
  220. crypto_openssl_log_errors(LOG_WARN, "Error parsing private key");
  221. return -1;
  222. }
  223. return 0;
  224. }
  225. /** Read a PEM-encoded private key from the file named by
  226. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  227. */
  228. int
  229. crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
  230. const char *keyfile)
  231. {
  232. char *contents;
  233. int r;
  234. /* Read the file into a string. */
  235. contents = read_file_to_str(keyfile, 0, NULL);
  236. if (!contents) {
  237. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  238. return -1;
  239. }
  240. /* Try to parse it. */
  241. r = crypto_pk_read_private_key_from_string(env, contents, -1);
  242. memwipe(contents, 0, strlen(contents));
  243. tor_free(contents);
  244. if (r)
  245. return -1; /* read_private_key_from_string already warned, so we don't.*/
  246. /* Make sure it's valid. */
  247. if (crypto_pk_check_key(env) <= 0)
  248. return -1;
  249. return 0;
  250. }
  251. /** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
  252. * success, -1 on failure. */
  253. static int
  254. crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
  255. size_t *len, int is_public)
  256. {
  257. BUF_MEM *buf;
  258. BIO *b;
  259. int r;
  260. tor_assert(env);
  261. tor_assert(env->key);
  262. tor_assert(dest);
  263. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  264. if (!b)
  265. return -1;
  266. /* Now you can treat b as if it were a file. Just use the
  267. * PEM_*_bio_* functions instead of the non-bio variants.
  268. */
  269. if (is_public)
  270. r = PEM_write_bio_RSAPublicKey(b, env->key);
  271. else
  272. r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
  273. if (!r) {
  274. crypto_openssl_log_errors(LOG_WARN, "writing RSA key to string");
  275. BIO_free(b);
  276. return -1;
  277. }
  278. BIO_get_mem_ptr(b, &buf);
  279. *dest = tor_malloc(buf->length+1);
  280. memcpy(*dest, buf->data, buf->length);
  281. (*dest)[buf->length] = 0; /* nul terminate it */
  282. *len = buf->length;
  283. BIO_free(b);
  284. return 0;
  285. }
  286. /** PEM-encode the public key portion of <b>env</b> and write it to a
  287. * newly allocated string. On success, set *<b>dest</b> to the new
  288. * string, *<b>len</b> to the string's length, and return 0. On
  289. * failure, return -1.
  290. */
  291. int
  292. crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
  293. size_t *len)
  294. {
  295. return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
  296. }
  297. /** PEM-encode the private key portion of <b>env</b> and write it to a
  298. * newly allocated string. On success, set *<b>dest</b> to the new
  299. * string, *<b>len</b> to the string's length, and return 0. On
  300. * failure, return -1.
  301. */
  302. int
  303. crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
  304. size_t *len)
  305. {
  306. return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
  307. }
  308. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  309. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  310. * failure.
  311. */
  312. int
  313. crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
  314. size_t len)
  315. {
  316. BIO *b;
  317. tor_assert(env);
  318. tor_assert(src);
  319. tor_assert(len<INT_MAX);
  320. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  321. if (!b)
  322. return -1;
  323. BIO_write(b, src, (int)len);
  324. if (env->key)
  325. RSA_free(env->key);
  326. env->key = PEM_read_bio_RSAPublicKey(b, NULL, pem_no_password_cb, NULL);
  327. BIO_free(b);
  328. if (!env->key) {
  329. crypto_openssl_log_errors(LOG_WARN, "reading public key from string");
  330. return -1;
  331. }
  332. return 0;
  333. }
  334. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  335. * PEM-encoded. Return 0 on success, -1 on failure.
  336. */
  337. int
  338. crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
  339. const char *fname)
  340. {
  341. BIO *bio;
  342. char *cp;
  343. long len;
  344. char *s;
  345. int r;
  346. tor_assert(crypto_pk_private_ok(env));
  347. if (!(bio = BIO_new(BIO_s_mem())))
  348. return -1;
  349. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  350. == 0) {
  351. crypto_openssl_log_errors(LOG_WARN, "writing private key");
  352. BIO_free(bio);
  353. return -1;
  354. }
  355. len = BIO_get_mem_data(bio, &cp);
  356. tor_assert(len >= 0);
  357. s = tor_malloc(len+1);
  358. memcpy(s, cp, len);
  359. s[len]='\0';
  360. r = write_str_to_file(fname, s, 0);
  361. BIO_free(bio);
  362. memwipe(s, 0, strlen(s));
  363. tor_free(s);
  364. return r;
  365. }
  366. /** Return true iff <b>env</b> has a valid key.
  367. */
  368. int
  369. crypto_pk_check_key(crypto_pk_t *env)
  370. {
  371. int r;
  372. tor_assert(env);
  373. r = RSA_check_key(env->key);
  374. if (r <= 0)
  375. crypto_openssl_log_errors(LOG_WARN,"checking RSA key");
  376. return r;
  377. }
  378. /** Return true iff <b>key</b> contains the private-key portion of the RSA
  379. * key. */
  380. int
  381. crypto_pk_key_is_private(const crypto_pk_t *key)
  382. {
  383. tor_assert(key);
  384. return crypto_pk_private_ok(key);
  385. }
  386. /** Return true iff <b>env</b> contains a public key whose public exponent
  387. * equals 65537.
  388. */
  389. int
  390. crypto_pk_public_exponent_ok(crypto_pk_t *env)
  391. {
  392. tor_assert(env);
  393. tor_assert(env->key);
  394. const BIGNUM *e;
  395. #ifdef OPENSSL_1_1_API
  396. const BIGNUM *n, *d;
  397. RSA_get0_key(env->key, &n, &e, &d);
  398. #else
  399. e = env->key->e;
  400. #endif /* defined(OPENSSL_1_1_API) */
  401. return BN_is_word(e, 65537);
  402. }
  403. /** Compare the public-key components of a and b. Return less than 0
  404. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  405. * considered to be less than all non-NULL keys, and equal to itself.
  406. *
  407. * Note that this may leak information about the keys through timing.
  408. */
  409. int
  410. crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  411. {
  412. int result;
  413. char a_is_non_null = (a != NULL) && (a->key != NULL);
  414. char b_is_non_null = (b != NULL) && (b->key != NULL);
  415. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  416. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  417. if (an_argument_is_null)
  418. return result;
  419. const BIGNUM *a_n, *a_e;
  420. const BIGNUM *b_n, *b_e;
  421. #ifdef OPENSSL_1_1_API
  422. const BIGNUM *a_d, *b_d;
  423. RSA_get0_key(a->key, &a_n, &a_e, &a_d);
  424. RSA_get0_key(b->key, &b_n, &b_e, &b_d);
  425. #else
  426. a_n = a->key->n;
  427. a_e = a->key->e;
  428. b_n = b->key->n;
  429. b_e = b->key->e;
  430. #endif /* defined(OPENSSL_1_1_API) */
  431. tor_assert(a_n != NULL && a_e != NULL);
  432. tor_assert(b_n != NULL && b_e != NULL);
  433. result = BN_cmp(a_n, b_n);
  434. if (result)
  435. return result;
  436. return BN_cmp(a_e, b_e);
  437. }
  438. /** Compare the public-key components of a and b. Return non-zero iff
  439. * a==b. A NULL key is considered to be distinct from all non-NULL
  440. * keys, and equal to itself.
  441. *
  442. * Note that this may leak information about the keys through timing.
  443. */
  444. int
  445. crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  446. {
  447. return (crypto_pk_cmp_keys(a, b) == 0);
  448. }
  449. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  450. size_t
  451. crypto_pk_keysize(const crypto_pk_t *env)
  452. {
  453. tor_assert(env);
  454. tor_assert(env->key);
  455. return (size_t) RSA_size((RSA*)env->key);
  456. }
  457. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  458. int
  459. crypto_pk_num_bits(crypto_pk_t *env)
  460. {
  461. tor_assert(env);
  462. tor_assert(env->key);
  463. #ifdef OPENSSL_1_1_API
  464. /* It's so stupid that there's no other way to check that n is valid
  465. * before calling RSA_bits().
  466. */
  467. const BIGNUM *n, *e, *d;
  468. RSA_get0_key(env->key, &n, &e, &d);
  469. tor_assert(n != NULL);
  470. return RSA_bits(env->key);
  471. #else /* !(defined(OPENSSL_1_1_API)) */
  472. tor_assert(env->key->n);
  473. return BN_num_bits(env->key->n);
  474. #endif /* defined(OPENSSL_1_1_API) */
  475. }
  476. /** Increase the reference count of <b>env</b>, and return it.
  477. */
  478. crypto_pk_t *
  479. crypto_pk_dup_key(crypto_pk_t *env)
  480. {
  481. tor_assert(env);
  482. tor_assert(env->key);
  483. env->refs++;
  484. return env;
  485. }
  486. #ifdef TOR_UNIT_TESTS
  487. /** For testing: replace dest with src. (Dest must have a refcount
  488. * of 1) */
  489. void
  490. crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
  491. {
  492. tor_assert(dest);
  493. tor_assert(dest->refs == 1);
  494. tor_assert(src);
  495. RSA_free(dest->key);
  496. dest->key = RSAPrivateKey_dup(src->key);
  497. }
  498. #endif /* defined(TOR_UNIT_TESTS) */
  499. /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
  500. * Returns NULL on failure. */
  501. crypto_pk_t *
  502. crypto_pk_copy_full(crypto_pk_t *env)
  503. {
  504. RSA *new_key;
  505. int privatekey = 0;
  506. tor_assert(env);
  507. tor_assert(env->key);
  508. if (crypto_pk_private_ok(env)) {
  509. new_key = RSAPrivateKey_dup(env->key);
  510. privatekey = 1;
  511. } else {
  512. new_key = RSAPublicKey_dup(env->key);
  513. }
  514. if (!new_key) {
  515. /* LCOV_EXCL_START
  516. *
  517. * We can't cause RSA*Key_dup() to fail, so we can't really test this.
  518. */
  519. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  520. privatekey?"private":"public");
  521. crypto_openssl_log_errors(LOG_ERR,
  522. privatekey ? "Duplicating a private key" :
  523. "Duplicating a public key");
  524. tor_fragile_assert();
  525. return NULL;
  526. /* LCOV_EXCL_STOP */
  527. }
  528. return crypto_new_pk_from_rsa_(new_key);
  529. }
  530. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  531. * bytes of data from <b>from</b>, with padding type 'padding',
  532. * storing the results on <b>to</b>.
  533. *
  534. * Returns the number of bytes written on success, -1 on failure.
  535. *
  536. * The encrypted data consists of:
  537. * - The source data, padded and encrypted with the public key, if the
  538. * padded source data is no longer than the public key, and <b>force</b>
  539. * is false, OR
  540. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  541. * padded and encrypted with the public key; followed by the rest of
  542. * the source data encrypted in AES-CTR mode with the symmetric key.
  543. *
  544. * NOTE that this format does not authenticate the symmetrically encrypted
  545. * part of the data, and SHOULD NOT BE USED for new protocols.
  546. */
  547. int
  548. crypto_pk_obsolete_public_hybrid_encrypt(crypto_pk_t *env,
  549. char *to, size_t tolen,
  550. const char *from,
  551. size_t fromlen,
  552. int padding, int force)
  553. {
  554. int overhead, outlen, r;
  555. size_t pkeylen, symlen;
  556. crypto_cipher_t *cipher = NULL;
  557. char *buf = NULL;
  558. tor_assert(env);
  559. tor_assert(from);
  560. tor_assert(to);
  561. tor_assert(fromlen < SIZE_T_CEILING);
  562. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  563. pkeylen = crypto_pk_keysize(env);
  564. if (!force && fromlen+overhead <= pkeylen) {
  565. /* It all fits in a single encrypt. */
  566. return crypto_pk_public_encrypt(env,to,
  567. tolen,
  568. from,fromlen,padding);
  569. }
  570. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  571. tor_assert(tolen >= pkeylen);
  572. char key[CIPHER_KEY_LEN];
  573. crypto_rand(key, sizeof(key)); /* generate a new key. */
  574. cipher = crypto_cipher_new(key);
  575. buf = tor_malloc(pkeylen+1);
  576. memcpy(buf, key, CIPHER_KEY_LEN);
  577. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  578. /* Length of symmetrically encrypted data. */
  579. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  580. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  581. if (outlen!=(int)pkeylen) {
  582. goto err;
  583. }
  584. r = crypto_cipher_encrypt(cipher, to+outlen,
  585. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  586. if (r<0) goto err;
  587. memwipe(buf, 0, pkeylen);
  588. memwipe(key, 0, sizeof(key));
  589. tor_free(buf);
  590. crypto_cipher_free(cipher);
  591. tor_assert(outlen+symlen < INT_MAX);
  592. return (int)(outlen + symlen);
  593. err:
  594. memwipe(buf, 0, pkeylen);
  595. memwipe(key, 0, sizeof(key));
  596. tor_free(buf);
  597. crypto_cipher_free(cipher);
  598. return -1;
  599. }
  600. /** Invert crypto_pk_obsolete_public_hybrid_encrypt. Returns the number of
  601. * bytes written on success, -1 on failure.
  602. *
  603. * NOTE that this format does not authenticate the symmetrically encrypted
  604. * part of the data, and SHOULD NOT BE USED for new protocols.
  605. */
  606. int
  607. crypto_pk_obsolete_private_hybrid_decrypt(crypto_pk_t *env,
  608. char *to,
  609. size_t tolen,
  610. const char *from,
  611. size_t fromlen,
  612. int padding, int warnOnFailure)
  613. {
  614. int outlen, r;
  615. size_t pkeylen;
  616. crypto_cipher_t *cipher = NULL;
  617. char *buf = NULL;
  618. tor_assert(fromlen < SIZE_T_CEILING);
  619. pkeylen = crypto_pk_keysize(env);
  620. if (fromlen <= pkeylen) {
  621. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  622. warnOnFailure);
  623. }
  624. buf = tor_malloc(pkeylen);
  625. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  626. warnOnFailure);
  627. if (outlen<0) {
  628. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  629. "Error decrypting public-key data");
  630. goto err;
  631. }
  632. if (outlen < CIPHER_KEY_LEN) {
  633. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  634. "No room for a symmetric key");
  635. goto err;
  636. }
  637. cipher = crypto_cipher_new(buf);
  638. if (!cipher) {
  639. goto err;
  640. }
  641. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  642. outlen -= CIPHER_KEY_LEN;
  643. tor_assert(tolen - outlen >= fromlen - pkeylen);
  644. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  645. if (r<0)
  646. goto err;
  647. memwipe(buf,0,pkeylen);
  648. tor_free(buf);
  649. crypto_cipher_free(cipher);
  650. tor_assert(outlen + fromlen < INT_MAX);
  651. return (int)(outlen + (fromlen-pkeylen));
  652. err:
  653. memwipe(buf,0,pkeylen);
  654. tor_free(buf);
  655. crypto_cipher_free(cipher);
  656. return -1;
  657. }
  658. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  659. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  660. * write the result to <b>to</b>, and return the number of bytes
  661. * written. On failure, return -1.
  662. *
  663. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  664. * at least the length of the modulus of <b>env</b>.
  665. */
  666. int
  667. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  668. const char *from, size_t fromlen, int padding)
  669. {
  670. int r;
  671. tor_assert(env);
  672. tor_assert(from);
  673. tor_assert(to);
  674. tor_assert(fromlen<INT_MAX);
  675. tor_assert(tolen >= crypto_pk_keysize(env));
  676. r = RSA_public_encrypt((int)fromlen,
  677. (unsigned char*)from, (unsigned char*)to,
  678. env->key, crypto_get_rsa_padding(padding));
  679. if (r<0) {
  680. crypto_openssl_log_errors(LOG_WARN, "performing RSA encryption");
  681. return -1;
  682. }
  683. return r;
  684. }
  685. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  686. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  687. * write the result to <b>to</b>, and return the number of bytes
  688. * written. On failure, return -1.
  689. *
  690. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  691. * at least the length of the modulus of <b>env</b>.
  692. */
  693. int
  694. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  695. size_t tolen,
  696. const char *from, size_t fromlen,
  697. int padding, int warnOnFailure)
  698. {
  699. int r;
  700. tor_assert(env);
  701. tor_assert(from);
  702. tor_assert(to);
  703. tor_assert(env->key);
  704. tor_assert(fromlen<INT_MAX);
  705. tor_assert(tolen >= crypto_pk_keysize(env));
  706. if (!crypto_pk_key_is_private(env))
  707. /* Not a private key */
  708. return -1;
  709. r = RSA_private_decrypt((int)fromlen,
  710. (unsigned char*)from, (unsigned char*)to,
  711. env->key, crypto_get_rsa_padding(padding));
  712. if (r<0) {
  713. crypto_openssl_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  714. "performing RSA decryption");
  715. return -1;
  716. }
  717. return r;
  718. }
  719. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  720. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  721. * signed data to <b>to</b>, and return the number of bytes written.
  722. * On failure, return -1.
  723. *
  724. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  725. * at least the length of the modulus of <b>env</b>.
  726. */
  727. MOCK_IMPL(int,
  728. crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
  729. size_t tolen,
  730. const char *from, size_t fromlen))
  731. {
  732. int r;
  733. tor_assert(env);
  734. tor_assert(from);
  735. tor_assert(to);
  736. tor_assert(fromlen < INT_MAX);
  737. tor_assert(tolen >= crypto_pk_keysize(env));
  738. r = RSA_public_decrypt((int)fromlen,
  739. (unsigned char*)from, (unsigned char*)to,
  740. env->key, RSA_PKCS1_PADDING);
  741. if (r<0) {
  742. crypto_openssl_log_errors(LOG_INFO, "checking RSA signature");
  743. return -1;
  744. }
  745. return r;
  746. }
  747. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  748. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  749. * <b>to</b>, and return the number of bytes written. On failure, return
  750. * -1.
  751. *
  752. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  753. * at least the length of the modulus of <b>env</b>.
  754. */
  755. int
  756. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  757. const char *from, size_t fromlen)
  758. {
  759. int r;
  760. tor_assert(env);
  761. tor_assert(from);
  762. tor_assert(to);
  763. tor_assert(fromlen < INT_MAX);
  764. tor_assert(tolen >= crypto_pk_keysize(env));
  765. if (!crypto_pk_key_is_private(env))
  766. /* Not a private key */
  767. return -1;
  768. r = RSA_private_encrypt((int)fromlen,
  769. (unsigned char*)from, (unsigned char*)to,
  770. (RSA*)env->key, RSA_PKCS1_PADDING);
  771. if (r<0) {
  772. crypto_openssl_log_errors(LOG_WARN, "generating RSA signature");
  773. return -1;
  774. }
  775. return r;
  776. }
  777. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  778. * Return -1 on error, or the number of characters used on success.
  779. */
  780. int
  781. crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
  782. {
  783. int len;
  784. unsigned char *buf = NULL;
  785. len = i2d_RSAPublicKey(pk->key, &buf);
  786. if (len < 0 || buf == NULL)
  787. return -1;
  788. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  789. OPENSSL_free(buf);
  790. return -1;
  791. }
  792. /* We don't encode directly into 'dest', because that would be illegal
  793. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  794. */
  795. memcpy(dest,buf,len);
  796. OPENSSL_free(buf);
  797. return len;
  798. }
  799. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  800. * success and NULL on failure.
  801. */
  802. crypto_pk_t *
  803. crypto_pk_asn1_decode(const char *str, size_t len)
  804. {
  805. RSA *rsa;
  806. unsigned char *buf;
  807. const unsigned char *cp;
  808. cp = buf = tor_malloc(len);
  809. memcpy(buf,str,len);
  810. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  811. tor_free(buf);
  812. if (!rsa) {
  813. crypto_openssl_log_errors(LOG_WARN,"decoding public key");
  814. return NULL;
  815. }
  816. return crypto_new_pk_from_rsa_(rsa);
  817. }
  818. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  819. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  820. * space). Return 0 on success, -1 on failure.
  821. *
  822. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  823. * of the public key, converted to hexadecimal, in upper case, with a
  824. * space after every four digits.
  825. *
  826. * If <b>add_space</b> is false, omit the spaces.
  827. */
  828. int
  829. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  830. {
  831. char digest[DIGEST_LEN];
  832. char hexdigest[HEX_DIGEST_LEN+1];
  833. if (crypto_pk_get_digest(pk, digest)) {
  834. return -1;
  835. }
  836. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  837. if (add_space) {
  838. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  839. } else {
  840. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  841. }
  842. return 0;
  843. }
  844. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  845. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  846. * bytes of space). Return 0 on success, -1 on failure.
  847. *
  848. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  849. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  850. * upper case.
  851. */
  852. int
  853. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  854. {
  855. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  856. if (crypto_pk_get_digest(pk, digest)) {
  857. return -1;
  858. }
  859. if (crypto_digest(hashed_digest, digest, DIGEST_LEN) < 0) {
  860. return -1;
  861. }
  862. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  863. return 0;
  864. }
  865. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  866. * every four characters. */
  867. void
  868. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  869. {
  870. int n = 0;
  871. char *end = out+outlen;
  872. tor_assert(outlen < SIZE_T_CEILING);
  873. while (*in && out<end) {
  874. *out++ = *in++;
  875. if (++n == 4 && *in && out<end) {
  876. n = 0;
  877. *out++ = ' ';
  878. }
  879. }
  880. tor_assert(out<end);
  881. *out = '\0';
  882. }
  883. /** Check a siglen-byte long signature at <b>sig</b> against
  884. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  885. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  886. * SHA1(data). Else return -1.
  887. */
  888. MOCK_IMPL(int,
  889. crypto_pk_public_checksig_digest,(crypto_pk_t *env, const char *data,
  890. size_t datalen, const char *sig,
  891. size_t siglen))
  892. {
  893. char digest[DIGEST_LEN];
  894. char *buf;
  895. size_t buflen;
  896. int r;
  897. tor_assert(env);
  898. tor_assert(data);
  899. tor_assert(sig);
  900. tor_assert(datalen < SIZE_T_CEILING);
  901. tor_assert(siglen < SIZE_T_CEILING);
  902. if (crypto_digest(digest,data,datalen)<0) {
  903. log_warn(LD_BUG, "couldn't compute digest");
  904. return -1;
  905. }
  906. buflen = crypto_pk_keysize(env);
  907. buf = tor_malloc(buflen);
  908. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  909. if (r != DIGEST_LEN) {
  910. log_warn(LD_CRYPTO, "Invalid signature");
  911. tor_free(buf);
  912. return -1;
  913. }
  914. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  915. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  916. tor_free(buf);
  917. return -1;
  918. }
  919. tor_free(buf);
  920. return 0;
  921. }
  922. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  923. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  924. * store it in <b>to</b>. Return the number of bytes written on
  925. * success, and -1 on failure.
  926. *
  927. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  928. * at least the length of the modulus of <b>env</b>.
  929. */
  930. int
  931. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  932. const char *from, size_t fromlen)
  933. {
  934. int r;
  935. char digest[DIGEST_LEN];
  936. if (crypto_digest(digest,from,fromlen)<0)
  937. return -1;
  938. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  939. memwipe(digest, 0, sizeof(digest));
  940. return r;
  941. }
  942. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  943. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  944. * Return 0 on success, -1 on failure.
  945. */
  946. int
  947. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  948. {
  949. char *buf;
  950. size_t buflen;
  951. int len;
  952. int rv = -1;
  953. buflen = crypto_pk_keysize(pk)*2;
  954. buf = tor_malloc(buflen);
  955. len = crypto_pk_asn1_encode(pk, buf, buflen);
  956. if (len < 0)
  957. goto done;
  958. if (crypto_digest(digest_out, buf, len) < 0)
  959. goto done;
  960. rv = 0;
  961. done:
  962. tor_free(buf);
  963. return rv;
  964. }
  965. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  966. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  967. int
  968. crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
  969. {
  970. char *buf;
  971. size_t buflen;
  972. int len;
  973. int rv = -1;
  974. buflen = crypto_pk_keysize(pk)*2;
  975. buf = tor_malloc(buflen);
  976. len = crypto_pk_asn1_encode(pk, buf, buflen);
  977. if (len < 0)
  978. goto done;
  979. if (crypto_common_digests(digests_out, (char*)buf, len) < 0)
  980. goto done;
  981. rv = 0;
  982. done:
  983. tor_free(buf);
  984. return rv;
  985. }
  986. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  987. * Base64 encoding of the DER representation of the private key as a NUL
  988. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  989. * success, -1 on failure.
  990. *
  991. * It is the caller's responsibility to sanitize and free the resulting buffer.
  992. */
  993. int
  994. crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
  995. {
  996. unsigned char *der = NULL;
  997. int der_len;
  998. int ret = -1;
  999. *priv_out = NULL;
  1000. der_len = i2d_RSAPrivateKey(pk->key, &der);
  1001. if (der_len < 0 || der == NULL)
  1002. return ret;
  1003. size_t priv_len = base64_encode_size(der_len, 0) + 1;
  1004. char *priv = tor_malloc_zero(priv_len);
  1005. if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
  1006. *priv_out = priv;
  1007. ret = 0;
  1008. } else {
  1009. tor_free(priv);
  1010. }
  1011. memwipe(der, 0, der_len);
  1012. OPENSSL_free(der);
  1013. return ret;
  1014. }
  1015. /** Given a string containing the Base64 encoded DER representation of the
  1016. * private key <b>str</b>, decode and return the result on success, or NULL
  1017. * on failure.
  1018. */
  1019. crypto_pk_t *
  1020. crypto_pk_base64_decode(const char *str, size_t len)
  1021. {
  1022. crypto_pk_t *pk = NULL;
  1023. char *der = tor_malloc_zero(len + 1);
  1024. int der_len = base64_decode(der, len, str, len);
  1025. if (der_len <= 0) {
  1026. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  1027. goto out;
  1028. }
  1029. const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
  1030. RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
  1031. if (!rsa) {
  1032. crypto_openssl_log_errors(LOG_WARN, "decoding private key");
  1033. goto out;
  1034. }
  1035. pk = crypto_new_pk_from_rsa_(rsa);
  1036. /* Make sure it's valid. */
  1037. if (crypto_pk_check_key(pk) <= 0) {
  1038. crypto_pk_free(pk);
  1039. pk = NULL;
  1040. goto out;
  1041. }
  1042. out:
  1043. memwipe(der, 0, len + 1);
  1044. tor_free(der);
  1045. return pk;
  1046. }