crypto_rsa.c 31 KB

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