crypto_rsa.c 31 KB

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