crypto_rsa.c 30 KB

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