crypto_rsa.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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-2017, 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 "crypto_rsa.h"
  11. #include "crypto.h"
  12. #include "compat_openssl.h"
  13. #include "crypto_curve25519.h"
  14. #include "crypto_ed25519.h"
  15. #include "crypto_format.h"
  16. #include "crypto_digest.h"
  17. DISABLE_GCC_WARNING(redundant-decls)
  18. #include <openssl/err.h>
  19. #include <openssl/rsa.h>
  20. #include <openssl/pem.h>
  21. #include <openssl/evp.h>
  22. #include <openssl/engine.h>
  23. #include <openssl/rand.h>
  24. #include <openssl/bn.h>
  25. #include <openssl/dh.h>
  26. #include <openssl/conf.h>
  27. #include <openssl/hmac.h>
  28. ENABLE_GCC_WARNING(redundant-decls)
  29. #include "torlog.h"
  30. #include "util.h"
  31. #include "util_format.h"
  32. /** Declaration for crypto_pk_t structure. */
  33. struct crypto_pk_t
  34. {
  35. int refs; /**< reference count, so we don't have to copy keys */
  36. RSA *key; /**< The key itself */
  37. };
  38. /** Log all pending crypto errors at level <b>severity</b>. Use
  39. * <b>doing</b> to describe our current activities.
  40. */
  41. static void
  42. crypto_log_errors(int severity, const char *doing)
  43. {
  44. unsigned long err;
  45. const char *msg, *lib, *func;
  46. while ((err = ERR_get_error()) != 0) {
  47. msg = (const char*)ERR_reason_error_string(err);
  48. lib = (const char*)ERR_lib_error_string(err);
  49. func = (const char*)ERR_func_error_string(err);
  50. if (!msg) msg = "(null)";
  51. if (!lib) lib = "(null)";
  52. if (!func) func = "(null)";
  53. if (BUG(!doing)) doing = "(null)";
  54. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  55. doing, msg, lib, func);
  56. }
  57. }
  58. /** Return the number of bytes added by padding method <b>padding</b>.
  59. */
  60. int
  61. crypto_get_rsa_padding_overhead(int padding)
  62. {
  63. switch (padding)
  64. {
  65. case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
  66. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  67. }
  68. }
  69. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  70. */
  71. int
  72. crypto_get_rsa_padding(int padding)
  73. {
  74. switch (padding)
  75. {
  76. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  77. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  78. }
  79. }
  80. /** used internally: quicly validate a crypto_pk_t object as a private key.
  81. * Return 1 iff the public key is valid, 0 if obviously invalid.
  82. */
  83. static int
  84. crypto_pk_private_ok(const crypto_pk_t *k)
  85. {
  86. #ifdef OPENSSL_1_1_API
  87. if (!k || !k->key)
  88. return 0;
  89. const BIGNUM *p, *q;
  90. RSA_get0_factors(k->key, &p, &q);
  91. return p != NULL; /* XXX/yawning: Should we check q? */
  92. #else /* !(defined(OPENSSL_1_1_API)) */
  93. return k && k->key && k->key->p;
  94. #endif /* defined(OPENSSL_1_1_API) */
  95. }
  96. /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
  97. crypto_pk_t *
  98. crypto_new_pk_from_rsa_(RSA *rsa)
  99. {
  100. crypto_pk_t *env;
  101. tor_assert(rsa);
  102. env = tor_malloc(sizeof(crypto_pk_t));
  103. env->refs = 1;
  104. env->key = rsa;
  105. return env;
  106. }
  107. /** Helper, used by tor-gencert.c. Return the RSA from a
  108. * crypto_pk_t. */
  109. RSA *
  110. crypto_pk_get_rsa_(crypto_pk_t *env)
  111. {
  112. return env->key;
  113. }
  114. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
  115. * private is set, include the private-key portion of the key. Return a valid
  116. * pointer on success, and NULL on failure. */
  117. MOCK_IMPL(EVP_PKEY *,
  118. crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
  119. {
  120. RSA *key = NULL;
  121. EVP_PKEY *pkey = NULL;
  122. tor_assert(env->key);
  123. if (private) {
  124. if (!(key = RSAPrivateKey_dup(env->key)))
  125. goto error;
  126. } else {
  127. if (!(key = RSAPublicKey_dup(env->key)))
  128. goto error;
  129. }
  130. if (!(pkey = EVP_PKEY_new()))
  131. goto error;
  132. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  133. goto error;
  134. return pkey;
  135. error:
  136. if (pkey)
  137. EVP_PKEY_free(pkey);
  138. if (key)
  139. RSA_free(key);
  140. return NULL;
  141. }
  142. /** Allocate and return storage for a public key. The key itself will not yet
  143. * be set.
  144. */
  145. MOCK_IMPL(crypto_pk_t *,
  146. crypto_pk_new,(void))
  147. {
  148. RSA *rsa;
  149. rsa = RSA_new();
  150. tor_assert(rsa);
  151. return crypto_new_pk_from_rsa_(rsa);
  152. }
  153. /** Release a reference to an asymmetric key; when all the references
  154. * are released, free the key.
  155. */
  156. void
  157. crypto_pk_free_(crypto_pk_t *env)
  158. {
  159. if (!env)
  160. return;
  161. if (--env->refs > 0)
  162. return;
  163. tor_assert(env->refs == 0);
  164. if (env->key)
  165. RSA_free(env->key);
  166. tor_free(env);
  167. }
  168. /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
  169. * Return 0 on success, -1 on failure.
  170. */
  171. MOCK_IMPL(int,
  172. crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
  173. {
  174. tor_assert(env);
  175. if (env->key) {
  176. RSA_free(env->key);
  177. env->key = NULL;
  178. }
  179. {
  180. BIGNUM *e = BN_new();
  181. RSA *r = NULL;
  182. if (!e)
  183. goto done;
  184. if (! BN_set_word(e, 65537))
  185. goto done;
  186. r = RSA_new();
  187. if (!r)
  188. goto done;
  189. if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
  190. goto done;
  191. env->key = r;
  192. r = NULL;
  193. done:
  194. if (e)
  195. BN_clear_free(e);
  196. if (r)
  197. RSA_free(r);
  198. }
  199. if (!env->key) {
  200. crypto_log_errors(LOG_WARN, "generating RSA key");
  201. return -1;
  202. }
  203. return 0;
  204. }
  205. /** A PEM callback that always reports a failure to get a password */
  206. static int
  207. pem_no_password_cb(char *buf, int size, int rwflag, void *u)
  208. {
  209. (void)buf;
  210. (void)size;
  211. (void)rwflag;
  212. (void)u;
  213. return 0;
  214. }
  215. /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
  216. * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
  217. * the string is nul-terminated.
  218. */
  219. int
  220. crypto_pk_read_private_key_from_string(crypto_pk_t *env,
  221. const char *s, ssize_t len)
  222. {
  223. BIO *b;
  224. tor_assert(env);
  225. tor_assert(s);
  226. tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
  227. /* Create a read-only memory BIO, backed by the string 's' */
  228. b = BIO_new_mem_buf((char*)s, (int)len);
  229. if (!b)
  230. return -1;
  231. if (env->key)
  232. RSA_free(env->key);
  233. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,pem_no_password_cb,NULL);
  234. BIO_free(b);
  235. if (!env->key) {
  236. crypto_log_errors(LOG_WARN, "Error parsing private key");
  237. return -1;
  238. }
  239. return 0;
  240. }
  241. /** Read a PEM-encoded private key from the file named by
  242. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  243. */
  244. int
  245. crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
  246. const char *keyfile)
  247. {
  248. char *contents;
  249. int r;
  250. /* Read the file into a string. */
  251. contents = read_file_to_str(keyfile, 0, NULL);
  252. if (!contents) {
  253. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  254. return -1;
  255. }
  256. /* Try to parse it. */
  257. r = crypto_pk_read_private_key_from_string(env, contents, -1);
  258. memwipe(contents, 0, strlen(contents));
  259. tor_free(contents);
  260. if (r)
  261. return -1; /* read_private_key_from_string already warned, so we don't.*/
  262. /* Make sure it's valid. */
  263. if (crypto_pk_check_key(env) <= 0)
  264. return -1;
  265. return 0;
  266. }
  267. /** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
  268. * success, -1 on failure. */
  269. static int
  270. crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
  271. size_t *len, int is_public)
  272. {
  273. BUF_MEM *buf;
  274. BIO *b;
  275. int r;
  276. tor_assert(env);
  277. tor_assert(env->key);
  278. tor_assert(dest);
  279. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  280. if (!b)
  281. return -1;
  282. /* Now you can treat b as if it were a file. Just use the
  283. * PEM_*_bio_* functions instead of the non-bio variants.
  284. */
  285. if (is_public)
  286. r = PEM_write_bio_RSAPublicKey(b, env->key);
  287. else
  288. r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
  289. if (!r) {
  290. crypto_log_errors(LOG_WARN, "writing RSA key to string");
  291. BIO_free(b);
  292. return -1;
  293. }
  294. BIO_get_mem_ptr(b, &buf);
  295. *dest = tor_malloc(buf->length+1);
  296. memcpy(*dest, buf->data, buf->length);
  297. (*dest)[buf->length] = 0; /* nul terminate it */
  298. *len = buf->length;
  299. BIO_free(b);
  300. return 0;
  301. }
  302. /** PEM-encode the public key portion of <b>env</b> and write it to a
  303. * newly allocated string. On success, set *<b>dest</b> to the new
  304. * string, *<b>len</b> to the string's length, and return 0. On
  305. * failure, return -1.
  306. */
  307. int
  308. crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
  309. size_t *len)
  310. {
  311. return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
  312. }
  313. /** PEM-encode the private key portion of <b>env</b> and write it to a
  314. * newly allocated string. On success, set *<b>dest</b> to the new
  315. * string, *<b>len</b> to the string's length, and return 0. On
  316. * failure, return -1.
  317. */
  318. int
  319. crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
  320. size_t *len)
  321. {
  322. return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
  323. }
  324. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  325. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  326. * failure.
  327. */
  328. int
  329. crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
  330. size_t len)
  331. {
  332. BIO *b;
  333. tor_assert(env);
  334. tor_assert(src);
  335. tor_assert(len<INT_MAX);
  336. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  337. if (!b)
  338. return -1;
  339. BIO_write(b, src, (int)len);
  340. if (env->key)
  341. RSA_free(env->key);
  342. env->key = PEM_read_bio_RSAPublicKey(b, NULL, pem_no_password_cb, NULL);
  343. BIO_free(b);
  344. if (!env->key) {
  345. crypto_log_errors(LOG_WARN, "reading public key from string");
  346. return -1;
  347. }
  348. return 0;
  349. }
  350. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  351. * PEM-encoded. Return 0 on success, -1 on failure.
  352. */
  353. int
  354. crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
  355. const char *fname)
  356. {
  357. BIO *bio;
  358. char *cp;
  359. long len;
  360. char *s;
  361. int r;
  362. tor_assert(crypto_pk_private_ok(env));
  363. if (!(bio = BIO_new(BIO_s_mem())))
  364. return -1;
  365. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  366. == 0) {
  367. crypto_log_errors(LOG_WARN, "writing private key");
  368. BIO_free(bio);
  369. return -1;
  370. }
  371. len = BIO_get_mem_data(bio, &cp);
  372. tor_assert(len >= 0);
  373. s = tor_malloc(len+1);
  374. memcpy(s, cp, len);
  375. s[len]='\0';
  376. r = write_str_to_file(fname, s, 0);
  377. BIO_free(bio);
  378. memwipe(s, 0, strlen(s));
  379. tor_free(s);
  380. return r;
  381. }
  382. /** Return true iff <b>env</b> has a valid key.
  383. */
  384. int
  385. crypto_pk_check_key(crypto_pk_t *env)
  386. {
  387. int r;
  388. tor_assert(env);
  389. r = RSA_check_key(env->key);
  390. if (r <= 0)
  391. crypto_log_errors(LOG_WARN,"checking RSA key");
  392. return r;
  393. }
  394. /** Return true iff <b>key</b> contains the private-key portion of the RSA
  395. * key. */
  396. int
  397. crypto_pk_key_is_private(const crypto_pk_t *key)
  398. {
  399. tor_assert(key);
  400. return crypto_pk_private_ok(key);
  401. }
  402. /** Return true iff <b>env</b> contains a public key whose public exponent
  403. * equals 65537.
  404. */
  405. int
  406. crypto_pk_public_exponent_ok(crypto_pk_t *env)
  407. {
  408. tor_assert(env);
  409. tor_assert(env->key);
  410. const BIGNUM *e;
  411. #ifdef OPENSSL_1_1_API
  412. const BIGNUM *n, *d;
  413. RSA_get0_key(env->key, &n, &e, &d);
  414. #else
  415. e = env->key->e;
  416. #endif /* defined(OPENSSL_1_1_API) */
  417. return BN_is_word(e, 65537);
  418. }
  419. /** Compare the public-key components of a and b. Return less than 0
  420. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  421. * considered to be less than all non-NULL keys, and equal to itself.
  422. *
  423. * Note that this may leak information about the keys through timing.
  424. */
  425. int
  426. crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  427. {
  428. int result;
  429. char a_is_non_null = (a != NULL) && (a->key != NULL);
  430. char b_is_non_null = (b != NULL) && (b->key != NULL);
  431. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  432. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  433. if (an_argument_is_null)
  434. return result;
  435. const BIGNUM *a_n, *a_e;
  436. const BIGNUM *b_n, *b_e;
  437. #ifdef OPENSSL_1_1_API
  438. const BIGNUM *a_d, *b_d;
  439. RSA_get0_key(a->key, &a_n, &a_e, &a_d);
  440. RSA_get0_key(b->key, &b_n, &b_e, &b_d);
  441. #else
  442. a_n = a->key->n;
  443. a_e = a->key->e;
  444. b_n = b->key->n;
  445. b_e = b->key->e;
  446. #endif /* defined(OPENSSL_1_1_API) */
  447. tor_assert(a_n != NULL && a_e != NULL);
  448. tor_assert(b_n != NULL && b_e != NULL);
  449. result = BN_cmp(a_n, b_n);
  450. if (result)
  451. return result;
  452. return BN_cmp(a_e, b_e);
  453. }
  454. /** Compare the public-key components of a and b. Return non-zero iff
  455. * a==b. A NULL key is considered to be distinct from all non-NULL
  456. * keys, and equal to itself.
  457. *
  458. * Note that this may leak information about the keys through timing.
  459. */
  460. int
  461. crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  462. {
  463. return (crypto_pk_cmp_keys(a, b) == 0);
  464. }
  465. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  466. size_t
  467. crypto_pk_keysize(const crypto_pk_t *env)
  468. {
  469. tor_assert(env);
  470. tor_assert(env->key);
  471. return (size_t) RSA_size((RSA*)env->key);
  472. }
  473. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  474. int
  475. crypto_pk_num_bits(crypto_pk_t *env)
  476. {
  477. tor_assert(env);
  478. tor_assert(env->key);
  479. #ifdef OPENSSL_1_1_API
  480. /* It's so stupid that there's no other way to check that n is valid
  481. * before calling RSA_bits().
  482. */
  483. const BIGNUM *n, *e, *d;
  484. RSA_get0_key(env->key, &n, &e, &d);
  485. tor_assert(n != NULL);
  486. return RSA_bits(env->key);
  487. #else /* !(defined(OPENSSL_1_1_API)) */
  488. tor_assert(env->key->n);
  489. return BN_num_bits(env->key->n);
  490. #endif /* defined(OPENSSL_1_1_API) */
  491. }
  492. /** Increase the reference count of <b>env</b>, and return it.
  493. */
  494. crypto_pk_t *
  495. crypto_pk_dup_key(crypto_pk_t *env)
  496. {
  497. tor_assert(env);
  498. tor_assert(env->key);
  499. env->refs++;
  500. return env;
  501. }
  502. #ifdef TOR_UNIT_TESTS
  503. /** For testing: replace dest with src. (Dest must have a refcount
  504. * of 1) */
  505. void
  506. crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
  507. {
  508. tor_assert(dest);
  509. tor_assert(dest->refs == 1);
  510. tor_assert(src);
  511. RSA_free(dest->key);
  512. dest->key = RSAPrivateKey_dup(src->key);
  513. }
  514. #endif /* defined(TOR_UNIT_TESTS) */
  515. /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
  516. * Returns NULL on failure. */
  517. crypto_pk_t *
  518. crypto_pk_copy_full(crypto_pk_t *env)
  519. {
  520. RSA *new_key;
  521. int privatekey = 0;
  522. tor_assert(env);
  523. tor_assert(env->key);
  524. if (crypto_pk_private_ok(env)) {
  525. new_key = RSAPrivateKey_dup(env->key);
  526. privatekey = 1;
  527. } else {
  528. new_key = RSAPublicKey_dup(env->key);
  529. }
  530. if (!new_key) {
  531. /* LCOV_EXCL_START
  532. *
  533. * We can't cause RSA*Key_dup() to fail, so we can't really test this.
  534. */
  535. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  536. privatekey?"private":"public");
  537. crypto_log_errors(LOG_ERR,
  538. privatekey ? "Duplicating a private key" :
  539. "Duplicating a public key");
  540. tor_fragile_assert();
  541. return NULL;
  542. /* LCOV_EXCL_STOP */
  543. }
  544. return crypto_new_pk_from_rsa_(new_key);
  545. }
  546. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  547. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  548. * write the result to <b>to</b>, and return the number of bytes
  549. * written. On failure, return -1.
  550. *
  551. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  552. * at least the length of the modulus of <b>env</b>.
  553. */
  554. int
  555. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  556. const char *from, size_t fromlen, int padding)
  557. {
  558. int r;
  559. tor_assert(env);
  560. tor_assert(from);
  561. tor_assert(to);
  562. tor_assert(fromlen<INT_MAX);
  563. tor_assert(tolen >= crypto_pk_keysize(env));
  564. r = RSA_public_encrypt((int)fromlen,
  565. (unsigned char*)from, (unsigned char*)to,
  566. env->key, crypto_get_rsa_padding(padding));
  567. if (r<0) {
  568. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  569. return -1;
  570. }
  571. return r;
  572. }
  573. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  574. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  575. * write the result to <b>to</b>, and return the number of bytes
  576. * written. On failure, return -1.
  577. *
  578. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  579. * at least the length of the modulus of <b>env</b>.
  580. */
  581. int
  582. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  583. size_t tolen,
  584. const char *from, size_t fromlen,
  585. int padding, int warnOnFailure)
  586. {
  587. int r;
  588. tor_assert(env);
  589. tor_assert(from);
  590. tor_assert(to);
  591. tor_assert(env->key);
  592. tor_assert(fromlen<INT_MAX);
  593. tor_assert(tolen >= crypto_pk_keysize(env));
  594. if (!crypto_pk_key_is_private(env))
  595. /* Not a private key */
  596. return -1;
  597. r = RSA_private_decrypt((int)fromlen,
  598. (unsigned char*)from, (unsigned char*)to,
  599. env->key, crypto_get_rsa_padding(padding));
  600. if (r<0) {
  601. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  602. "performing RSA decryption");
  603. return -1;
  604. }
  605. return r;
  606. }
  607. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  608. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  609. * signed data to <b>to</b>, and return the number of bytes written.
  610. * On failure, return -1.
  611. *
  612. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  613. * at least the length of the modulus of <b>env</b>.
  614. */
  615. MOCK_IMPL(int,
  616. crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
  617. size_t tolen,
  618. const char *from, size_t fromlen))
  619. {
  620. int r;
  621. tor_assert(env);
  622. tor_assert(from);
  623. tor_assert(to);
  624. tor_assert(fromlen < INT_MAX);
  625. tor_assert(tolen >= crypto_pk_keysize(env));
  626. r = RSA_public_decrypt((int)fromlen,
  627. (unsigned char*)from, (unsigned char*)to,
  628. env->key, RSA_PKCS1_PADDING);
  629. if (r<0) {
  630. crypto_log_errors(LOG_INFO, "checking RSA signature");
  631. return -1;
  632. }
  633. return r;
  634. }
  635. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  636. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  637. * <b>to</b>, and return the number of bytes written. On failure, return
  638. * -1.
  639. *
  640. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  641. * at least the length of the modulus of <b>env</b>.
  642. */
  643. int
  644. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  645. const char *from, size_t fromlen)
  646. {
  647. int r;
  648. tor_assert(env);
  649. tor_assert(from);
  650. tor_assert(to);
  651. tor_assert(fromlen < INT_MAX);
  652. tor_assert(tolen >= crypto_pk_keysize(env));
  653. if (!crypto_pk_key_is_private(env))
  654. /* Not a private key */
  655. return -1;
  656. r = RSA_private_encrypt((int)fromlen,
  657. (unsigned char*)from, (unsigned char*)to,
  658. (RSA*)env->key, RSA_PKCS1_PADDING);
  659. if (r<0) {
  660. crypto_log_errors(LOG_WARN, "generating RSA signature");
  661. return -1;
  662. }
  663. return r;
  664. }
  665. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  666. * Return -1 on error, or the number of characters used on success.
  667. */
  668. int
  669. crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
  670. {
  671. int len;
  672. unsigned char *buf = NULL;
  673. len = i2d_RSAPublicKey(pk->key, &buf);
  674. if (len < 0 || buf == NULL)
  675. return -1;
  676. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  677. OPENSSL_free(buf);
  678. return -1;
  679. }
  680. /* We don't encode directly into 'dest', because that would be illegal
  681. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  682. */
  683. memcpy(dest,buf,len);
  684. OPENSSL_free(buf);
  685. return len;
  686. }
  687. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  688. * success and NULL on failure.
  689. */
  690. crypto_pk_t *
  691. crypto_pk_asn1_decode(const char *str, size_t len)
  692. {
  693. RSA *rsa;
  694. unsigned char *buf;
  695. const unsigned char *cp;
  696. cp = buf = tor_malloc(len);
  697. memcpy(buf,str,len);
  698. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  699. tor_free(buf);
  700. if (!rsa) {
  701. crypto_log_errors(LOG_WARN,"decoding public key");
  702. return NULL;
  703. }
  704. return crypto_new_pk_from_rsa_(rsa);
  705. }
  706. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  707. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  708. * space). Return 0 on success, -1 on failure.
  709. *
  710. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  711. * of the public key, converted to hexadecimal, in upper case, with a
  712. * space after every four digits.
  713. *
  714. * If <b>add_space</b> is false, omit the spaces.
  715. */
  716. int
  717. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  718. {
  719. char digest[DIGEST_LEN];
  720. char hexdigest[HEX_DIGEST_LEN+1];
  721. if (crypto_pk_get_digest(pk, digest)) {
  722. return -1;
  723. }
  724. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  725. if (add_space) {
  726. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  727. } else {
  728. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  729. }
  730. return 0;
  731. }
  732. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  733. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  734. * bytes of space). Return 0 on success, -1 on failure.
  735. *
  736. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  737. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  738. * upper case.
  739. */
  740. int
  741. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  742. {
  743. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  744. if (crypto_pk_get_digest(pk, digest)) {
  745. return -1;
  746. }
  747. if (crypto_digest(hashed_digest, digest, DIGEST_LEN) < 0) {
  748. return -1;
  749. }
  750. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  751. return 0;
  752. }
  753. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  754. * Base64 encoding of the DER representation of the private key as a NUL
  755. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  756. * sucess, -1 on failure.
  757. *
  758. * It is the caller's responsibility to sanitize and free the resulting buffer.
  759. */
  760. int
  761. crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
  762. {
  763. unsigned char *der = NULL;
  764. int der_len;
  765. int ret = -1;
  766. *priv_out = NULL;
  767. der_len = i2d_RSAPrivateKey(pk->key, &der);
  768. if (der_len < 0 || der == NULL)
  769. return ret;
  770. size_t priv_len = base64_encode_size(der_len, 0) + 1;
  771. char *priv = tor_malloc_zero(priv_len);
  772. if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
  773. *priv_out = priv;
  774. ret = 0;
  775. } else {
  776. tor_free(priv);
  777. }
  778. memwipe(der, 0, der_len);
  779. OPENSSL_free(der);
  780. return ret;
  781. }
  782. /** Given a string containing the Base64 encoded DER representation of the
  783. * private key <b>str</b>, decode and return the result on success, or NULL
  784. * on failure.
  785. */
  786. crypto_pk_t *
  787. crypto_pk_base64_decode(const char *str, size_t len)
  788. {
  789. crypto_pk_t *pk = NULL;
  790. char *der = tor_malloc_zero(len + 1);
  791. int der_len = base64_decode(der, len, str, len);
  792. if (der_len <= 0) {
  793. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  794. goto out;
  795. }
  796. const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
  797. RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
  798. if (!rsa) {
  799. crypto_log_errors(LOG_WARN, "decoding private key");
  800. goto out;
  801. }
  802. pk = crypto_new_pk_from_rsa_(rsa);
  803. /* Make sure it's valid. */
  804. if (crypto_pk_check_key(pk) <= 0) {
  805. crypto_pk_free(pk);
  806. pk = NULL;
  807. goto out;
  808. }
  809. out:
  810. memwipe(der, 0, len + 1);
  811. tor_free(der);
  812. return pk;
  813. }