crypto_rsa_openssl.c 20 KB

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