crypto_rsa.c 30 KB

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