crypto_rsa_openssl.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 OpenSSL implementations of our RSA code.
  9. **/
  10. #include "lib/crypt_ops/compat_openssl.h"
  11. #include "lib/crypt_ops/crypto_rsa.h"
  12. #include "lib/crypt_ops/crypto_util.h"
  13. #include "lib/ctime/di_ops.h"
  14. #include "lib/log/util_bug.h"
  15. #include "lib/fs/files.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/conf.h>
  25. ENABLE_GCC_WARNING(redundant-decls)
  26. #include "lib/log/log.h"
  27. #include "lib/encoding/binascii.h"
  28. #include <string.h>
  29. /** Declaration for crypto_pk_t structure. */
  30. struct crypto_pk_t
  31. {
  32. int refs; /**< reference count, so we don't have to copy keys */
  33. RSA *key; /**< The key itself */
  34. };
  35. /** Return true iff <b>key</b> contains the private-key portion of the RSA
  36. * key. */
  37. int
  38. crypto_pk_key_is_private(const crypto_pk_t *k)
  39. {
  40. #ifdef OPENSSL_1_1_API
  41. if (!k || !k->key)
  42. return 0;
  43. const BIGNUM *p, *q;
  44. RSA_get0_factors(k->key, &p, &q);
  45. return p != NULL; /* XXX/yawning: Should we check q? */
  46. #else /* !(defined(OPENSSL_1_1_API)) */
  47. return k && k->key && k->key->p;
  48. #endif /* defined(OPENSSL_1_1_API) */
  49. }
  50. /** used by tortls.c: wrap an RSA* in a crypto_pk_t. Takes ownership of
  51. * its argument. */
  52. crypto_pk_t *
  53. crypto_new_pk_from_openssl_rsa_(RSA *rsa)
  54. {
  55. crypto_pk_t *env;
  56. tor_assert(rsa);
  57. env = tor_malloc(sizeof(crypto_pk_t));
  58. env->refs = 1;
  59. env->key = rsa;
  60. return env;
  61. }
  62. /** Helper, used by tor-gencert.c. Return a copy of the private RSA from a
  63. * crypto_pk_t. */
  64. RSA *
  65. crypto_pk_get_openssl_rsa_(crypto_pk_t *env)
  66. {
  67. return RSA_PrivateKeyDup(env->key);
  68. }
  69. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
  70. * private is set, include the private-key portion of the key. Return a valid
  71. * pointer on success, and NULL on failure. */
  72. MOCK_IMPL(EVP_PKEY *,
  73. crypto_pk_get_openssl_evp_pkey_,(crypto_pk_t *env, int private))
  74. {
  75. RSA *key = NULL;
  76. EVP_PKEY *pkey = NULL;
  77. tor_assert(env->key);
  78. if (private) {
  79. if (!(key = RSAPrivateKey_dup(env->key)))
  80. goto error;
  81. } else {
  82. if (!(key = RSAPublicKey_dup(env->key)))
  83. goto error;
  84. }
  85. if (!(pkey = EVP_PKEY_new()))
  86. goto error;
  87. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  88. goto error;
  89. return pkey;
  90. error:
  91. if (pkey)
  92. EVP_PKEY_free(pkey);
  93. if (key)
  94. RSA_free(key);
  95. return NULL;
  96. }
  97. /** Allocate and return storage for a public key. The key itself will not yet
  98. * be set.
  99. */
  100. MOCK_IMPL(crypto_pk_t *,
  101. crypto_pk_new,(void))
  102. {
  103. RSA *rsa;
  104. rsa = RSA_new();
  105. tor_assert(rsa);
  106. return crypto_new_pk_from_openssl_rsa_(rsa);
  107. }
  108. /** Release a reference to an asymmetric key; when all the references
  109. * are released, free the key.
  110. */
  111. void
  112. crypto_pk_free_(crypto_pk_t *env)
  113. {
  114. if (!env)
  115. return;
  116. if (--env->refs > 0)
  117. return;
  118. tor_assert(env->refs == 0);
  119. if (env->key)
  120. RSA_free(env->key);
  121. tor_free(env);
  122. }
  123. /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
  124. * Return 0 on success, -1 on failure.
  125. */
  126. MOCK_IMPL(int,
  127. crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
  128. {
  129. tor_assert(env);
  130. if (env->key) {
  131. RSA_free(env->key);
  132. env->key = NULL;
  133. }
  134. {
  135. BIGNUM *e = BN_new();
  136. RSA *r = NULL;
  137. if (!e)
  138. goto done;
  139. if (! BN_set_word(e, TOR_RSA_EXPONENT))
  140. goto done;
  141. r = RSA_new();
  142. if (!r)
  143. goto done;
  144. if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
  145. goto done;
  146. env->key = r;
  147. r = NULL;
  148. done:
  149. if (e)
  150. BN_clear_free(e);
  151. if (r)
  152. RSA_free(r);
  153. }
  154. if (!env->key) {
  155. crypto_openssl_log_errors(LOG_WARN, "generating RSA key");
  156. return -1;
  157. }
  158. return 0;
  159. }
  160. /** Return true iff <b>env</b> has a valid key.
  161. */
  162. int
  163. crypto_pk_check_key(crypto_pk_t *env)
  164. {
  165. int r;
  166. tor_assert(env);
  167. r = RSA_check_key(env->key);
  168. if (r <= 0)
  169. crypto_openssl_log_errors(LOG_WARN,"checking RSA key");
  170. return r;
  171. }
  172. /** Return true iff <b>env</b> contains a public key whose public exponent
  173. * equals TOR_RSA_EXPONENT.
  174. */
  175. int
  176. crypto_pk_public_exponent_ok(crypto_pk_t *env)
  177. {
  178. tor_assert(env);
  179. tor_assert(env->key);
  180. const BIGNUM *e;
  181. #ifdef OPENSSL_1_1_API
  182. const BIGNUM *n, *d;
  183. RSA_get0_key(env->key, &n, &e, &d);
  184. #else
  185. e = env->key->e;
  186. #endif /* defined(OPENSSL_1_1_API) */
  187. return BN_is_word(e, TOR_RSA_EXPONENT);
  188. }
  189. /** Compare the public-key components of a and b. Return less than 0
  190. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  191. * considered to be less than all non-NULL keys, and equal to itself.
  192. *
  193. * Note that this may leak information about the keys through timing.
  194. */
  195. int
  196. crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  197. {
  198. int result;
  199. char a_is_non_null = (a != NULL) && (a->key != NULL);
  200. char b_is_non_null = (b != NULL) && (b->key != NULL);
  201. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  202. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  203. if (an_argument_is_null)
  204. return result;
  205. const BIGNUM *a_n, *a_e;
  206. const BIGNUM *b_n, *b_e;
  207. #ifdef OPENSSL_1_1_API
  208. const BIGNUM *a_d, *b_d;
  209. RSA_get0_key(a->key, &a_n, &a_e, &a_d);
  210. RSA_get0_key(b->key, &b_n, &b_e, &b_d);
  211. #else
  212. a_n = a->key->n;
  213. a_e = a->key->e;
  214. b_n = b->key->n;
  215. b_e = b->key->e;
  216. #endif /* defined(OPENSSL_1_1_API) */
  217. tor_assert(a_n != NULL && a_e != NULL);
  218. tor_assert(b_n != NULL && b_e != NULL);
  219. result = BN_cmp(a_n, b_n);
  220. if (result)
  221. return result;
  222. return BN_cmp(a_e, b_e);
  223. }
  224. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  225. size_t
  226. crypto_pk_keysize(const crypto_pk_t *env)
  227. {
  228. tor_assert(env);
  229. tor_assert(env->key);
  230. return (size_t) RSA_size((RSA*)env->key);
  231. }
  232. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  233. int
  234. crypto_pk_num_bits(crypto_pk_t *env)
  235. {
  236. tor_assert(env);
  237. tor_assert(env->key);
  238. #ifdef OPENSSL_1_1_API
  239. /* It's so stupid that there's no other way to check that n is valid
  240. * before calling RSA_bits().
  241. */
  242. const BIGNUM *n, *e, *d;
  243. RSA_get0_key(env->key, &n, &e, &d);
  244. tor_assert(n != NULL);
  245. return RSA_bits(env->key);
  246. #else /* !(defined(OPENSSL_1_1_API)) */
  247. tor_assert(env->key->n);
  248. return BN_num_bits(env->key->n);
  249. #endif /* defined(OPENSSL_1_1_API) */
  250. }
  251. /** Increase the reference count of <b>env</b>, and return it.
  252. */
  253. crypto_pk_t *
  254. crypto_pk_dup_key(crypto_pk_t *env)
  255. {
  256. tor_assert(env);
  257. tor_assert(env->key);
  258. env->refs++;
  259. return env;
  260. }
  261. /** Replace dest with src (private key only). (Dest must have a refcount
  262. * of 1)
  263. */
  264. void
  265. crypto_pk_assign_private(crypto_pk_t *dest, const crypto_pk_t *src)
  266. {
  267. tor_assert(dest);
  268. tor_assert(dest->refs == 1);
  269. tor_assert(src);
  270. RSA_free(dest->key);
  271. dest->key = RSAPrivateKey_dup(src->key);
  272. }
  273. /** Replace dest with src (public key only). (Dest must have a refcount
  274. * of 1)
  275. */
  276. void
  277. crypto_pk_assign_public(crypto_pk_t *dest, const crypto_pk_t *src)
  278. {
  279. tor_assert(dest);
  280. tor_assert(dest->refs == 1);
  281. tor_assert(src);
  282. RSA_free(dest->key);
  283. dest->key = RSAPublicKey_dup(src->key);
  284. }
  285. /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
  286. * Returns NULL on failure. */
  287. crypto_pk_t *
  288. crypto_pk_copy_full(crypto_pk_t *env)
  289. {
  290. RSA *new_key;
  291. int privatekey = 0;
  292. tor_assert(env);
  293. tor_assert(env->key);
  294. if (crypto_pk_key_is_private(env)) {
  295. new_key = RSAPrivateKey_dup(env->key);
  296. privatekey = 1;
  297. } else {
  298. new_key = RSAPublicKey_dup(env->key);
  299. }
  300. if (!new_key) {
  301. /* LCOV_EXCL_START
  302. *
  303. * We can't cause RSA*Key_dup() to fail, so we can't really test this.
  304. */
  305. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  306. privatekey?"private":"public");
  307. crypto_openssl_log_errors(LOG_ERR,
  308. privatekey ? "Duplicating a private key" :
  309. "Duplicating a public key");
  310. tor_fragile_assert();
  311. return NULL;
  312. /* LCOV_EXCL_STOP */
  313. }
  314. return crypto_new_pk_from_openssl_rsa_(new_key);
  315. }
  316. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  317. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  318. * write the result to <b>to</b>, and return the number of bytes
  319. * written. On failure, return -1.
  320. *
  321. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  322. * at least the length of the modulus of <b>env</b>.
  323. */
  324. int
  325. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  326. const char *from, size_t fromlen, int padding)
  327. {
  328. int r;
  329. tor_assert(env);
  330. tor_assert(from);
  331. tor_assert(to);
  332. tor_assert(fromlen<INT_MAX);
  333. tor_assert(tolen >= crypto_pk_keysize(env));
  334. r = RSA_public_encrypt((int)fromlen,
  335. (unsigned char*)from, (unsigned char*)to,
  336. env->key, crypto_get_rsa_padding(padding));
  337. if (r<0) {
  338. crypto_openssl_log_errors(LOG_WARN, "performing RSA encryption");
  339. return -1;
  340. }
  341. return r;
  342. }
  343. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  344. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  345. * write the result to <b>to</b>, and return the number of bytes
  346. * written. On failure, return -1.
  347. *
  348. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  349. * at least the length of the modulus of <b>env</b>.
  350. */
  351. int
  352. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  353. size_t tolen,
  354. const char *from, size_t fromlen,
  355. int padding, int warnOnFailure)
  356. {
  357. int r;
  358. tor_assert(env);
  359. tor_assert(from);
  360. tor_assert(to);
  361. tor_assert(env->key);
  362. tor_assert(fromlen<INT_MAX);
  363. tor_assert(tolen >= crypto_pk_keysize(env));
  364. if (!crypto_pk_key_is_private(env))
  365. /* Not a private key */
  366. return -1;
  367. r = RSA_private_decrypt((int)fromlen,
  368. (unsigned char*)from, (unsigned char*)to,
  369. env->key, crypto_get_rsa_padding(padding));
  370. if (r<0) {
  371. crypto_openssl_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  372. "performing RSA decryption");
  373. return -1;
  374. }
  375. return r;
  376. }
  377. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  378. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  379. * signed data to <b>to</b>, and return the number of bytes written.
  380. * On failure, return -1.
  381. *
  382. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  383. * at least the length of the modulus of <b>env</b>.
  384. */
  385. MOCK_IMPL(int,
  386. crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
  387. size_t tolen,
  388. const char *from, size_t fromlen))
  389. {
  390. int r;
  391. tor_assert(env);
  392. tor_assert(from);
  393. tor_assert(to);
  394. tor_assert(fromlen < INT_MAX);
  395. tor_assert(tolen >= crypto_pk_keysize(env));
  396. r = RSA_public_decrypt((int)fromlen,
  397. (unsigned char*)from, (unsigned char*)to,
  398. env->key, RSA_PKCS1_PADDING);
  399. if (r<0) {
  400. crypto_openssl_log_errors(LOG_INFO, "checking RSA signature");
  401. return -1;
  402. }
  403. return r;
  404. }
  405. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  406. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  407. * <b>to</b>, and return the number of bytes written. On failure, return
  408. * -1.
  409. *
  410. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  411. * at least the length of the modulus of <b>env</b>.
  412. */
  413. int
  414. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  415. const char *from, size_t fromlen)
  416. {
  417. int r;
  418. tor_assert(env);
  419. tor_assert(from);
  420. tor_assert(to);
  421. tor_assert(fromlen < INT_MAX);
  422. tor_assert(tolen >= crypto_pk_keysize(env));
  423. if (!crypto_pk_key_is_private(env))
  424. /* Not a private key */
  425. return -1;
  426. r = RSA_private_encrypt((int)fromlen,
  427. (unsigned char*)from, (unsigned char*)to,
  428. (RSA*)env->key, RSA_PKCS1_PADDING);
  429. if (r<0) {
  430. crypto_openssl_log_errors(LOG_WARN, "generating RSA signature");
  431. return -1;
  432. }
  433. return r;
  434. }
  435. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  436. * Return -1 on error, or the number of characters used on success.
  437. */
  438. int
  439. crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
  440. {
  441. int len;
  442. unsigned char *buf = NULL;
  443. len = i2d_RSAPublicKey(pk->key, &buf);
  444. if (len < 0 || buf == NULL)
  445. return -1;
  446. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  447. OPENSSL_free(buf);
  448. return -1;
  449. }
  450. /* We don't encode directly into 'dest', because that would be illegal
  451. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  452. */
  453. memcpy(dest,buf,len);
  454. OPENSSL_free(buf);
  455. return len;
  456. }
  457. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  458. * success and NULL on failure.
  459. */
  460. crypto_pk_t *
  461. crypto_pk_asn1_decode(const char *str, size_t len)
  462. {
  463. RSA *rsa;
  464. unsigned char *buf;
  465. const unsigned char *cp;
  466. cp = buf = tor_malloc(len);
  467. memcpy(buf,str,len);
  468. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  469. tor_free(buf);
  470. if (!rsa) {
  471. crypto_openssl_log_errors(LOG_WARN,"decoding public key");
  472. return NULL;
  473. }
  474. return crypto_new_pk_from_openssl_rsa_(rsa);
  475. }
  476. /** ASN.1-encode the private portion of <b>pk</b> into <b>dest</b>.
  477. * Return -1 on error, or the number of characters used on success.
  478. */
  479. int
  480. crypto_pk_asn1_encode_private(const crypto_pk_t *pk, char *dest,
  481. size_t dest_len)
  482. {
  483. int len;
  484. unsigned char *buf = NULL;
  485. len = i2d_RSAPrivateKey(pk->key, &buf);
  486. if (len < 0 || buf == NULL)
  487. return -1;
  488. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  489. OPENSSL_free(buf);
  490. return -1;
  491. }
  492. /* We don't encode directly into 'dest', because that would be illegal
  493. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  494. */
  495. memcpy(dest,buf,len);
  496. OPENSSL_free(buf);
  497. return len;
  498. }
  499. /** Decode an ASN.1-encoded private key from <b>str</b>; return the result on
  500. * success and NULL on failure.
  501. */
  502. crypto_pk_t *
  503. crypto_pk_asn1_decode_private(const char *str, size_t len)
  504. {
  505. RSA *rsa;
  506. unsigned char *buf;
  507. const unsigned char *cp;
  508. cp = buf = tor_malloc(len);
  509. memcpy(buf,str,len);
  510. rsa = d2i_RSAPrivateKey(NULL, &cp, len);
  511. tor_free(buf);
  512. if (!rsa) {
  513. crypto_openssl_log_errors(LOG_WARN,"decoding public key");
  514. return NULL;
  515. }
  516. return crypto_new_pk_from_openssl_rsa_(rsa);
  517. }