crypto_rsa.c 22 KB

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