crypto_rsa.c 23 KB

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