crypto_rsa_openssl.c 20 KB

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