crypto_rsa_openssl.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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-2019, 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 RSAPrivateKey_dup(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 if <b>env</b> has a valid key; false otherwise.
  161. */
  162. int
  163. crypto_pk_is_valid_private_key(const 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 0;
  171. } else {
  172. return 1;
  173. }
  174. }
  175. /** Return true iff <b>env</b> contains a public key whose public exponent
  176. * equals TOR_RSA_EXPONENT.
  177. */
  178. int
  179. crypto_pk_public_exponent_ok(const crypto_pk_t *env)
  180. {
  181. tor_assert(env);
  182. tor_assert(env->key);
  183. const BIGNUM *e;
  184. #ifdef OPENSSL_1_1_API
  185. const BIGNUM *n, *d;
  186. RSA_get0_key(env->key, &n, &e, &d);
  187. #else
  188. e = env->key->e;
  189. #endif /* defined(OPENSSL_1_1_API) */
  190. return BN_is_word(e, TOR_RSA_EXPONENT);
  191. }
  192. /** Compare the public-key components of a and b. Return less than 0
  193. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  194. * considered to be less than all non-NULL keys, and equal to itself.
  195. *
  196. * Note that this may leak information about the keys through timing.
  197. */
  198. int
  199. crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  200. {
  201. int result;
  202. char a_is_non_null = (a != NULL) && (a->key != NULL);
  203. char b_is_non_null = (b != NULL) && (b->key != NULL);
  204. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  205. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  206. if (an_argument_is_null)
  207. return result;
  208. const BIGNUM *a_n, *a_e;
  209. const BIGNUM *b_n, *b_e;
  210. #ifdef OPENSSL_1_1_API
  211. const BIGNUM *a_d, *b_d;
  212. RSA_get0_key(a->key, &a_n, &a_e, &a_d);
  213. RSA_get0_key(b->key, &b_n, &b_e, &b_d);
  214. #else
  215. a_n = a->key->n;
  216. a_e = a->key->e;
  217. b_n = b->key->n;
  218. b_e = b->key->e;
  219. #endif /* defined(OPENSSL_1_1_API) */
  220. tor_assert(a_n != NULL && a_e != NULL);
  221. tor_assert(b_n != NULL && b_e != NULL);
  222. result = BN_cmp(a_n, b_n);
  223. if (result)
  224. return result;
  225. return BN_cmp(a_e, b_e);
  226. }
  227. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  228. size_t
  229. crypto_pk_keysize(const crypto_pk_t *env)
  230. {
  231. tor_assert(env);
  232. tor_assert(env->key);
  233. return (size_t) RSA_size((RSA*)env->key);
  234. }
  235. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  236. int
  237. crypto_pk_num_bits(crypto_pk_t *env)
  238. {
  239. tor_assert(env);
  240. tor_assert(env->key);
  241. #ifdef OPENSSL_1_1_API
  242. /* It's so stupid that there's no other way to check that n is valid
  243. * before calling RSA_bits().
  244. */
  245. const BIGNUM *n, *e, *d;
  246. RSA_get0_key(env->key, &n, &e, &d);
  247. tor_assert(n != NULL);
  248. return RSA_bits(env->key);
  249. #else /* !(defined(OPENSSL_1_1_API)) */
  250. tor_assert(env->key->n);
  251. return BN_num_bits(env->key->n);
  252. #endif /* defined(OPENSSL_1_1_API) */
  253. }
  254. /** Increase the reference count of <b>env</b>, and return it.
  255. */
  256. crypto_pk_t *
  257. crypto_pk_dup_key(crypto_pk_t *env)
  258. {
  259. tor_assert(env);
  260. tor_assert(env->key);
  261. env->refs++;
  262. return env;
  263. }
  264. /** Replace dest with src (private key only). (Dest must have a refcount
  265. * of 1)
  266. */
  267. void
  268. crypto_pk_assign_private(crypto_pk_t *dest, const crypto_pk_t *src)
  269. {
  270. tor_assert(dest);
  271. tor_assert(dest->refs == 1);
  272. tor_assert(src);
  273. RSA_free(dest->key);
  274. dest->key = RSAPrivateKey_dup(src->key);
  275. }
  276. /** Replace dest with src (public key only). (Dest must have a refcount
  277. * of 1)
  278. */
  279. void
  280. crypto_pk_assign_public(crypto_pk_t *dest, const crypto_pk_t *src)
  281. {
  282. tor_assert(dest);
  283. tor_assert(dest->refs == 1);
  284. tor_assert(src);
  285. RSA_free(dest->key);
  286. dest->key = RSAPublicKey_dup(src->key);
  287. }
  288. /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
  289. * Returns NULL on failure. */
  290. crypto_pk_t *
  291. crypto_pk_copy_full(crypto_pk_t *env)
  292. {
  293. RSA *new_key;
  294. int privatekey = 0;
  295. tor_assert(env);
  296. tor_assert(env->key);
  297. if (crypto_pk_key_is_private(env)) {
  298. new_key = RSAPrivateKey_dup(env->key);
  299. privatekey = 1;
  300. } else {
  301. new_key = RSAPublicKey_dup(env->key);
  302. }
  303. if (!new_key) {
  304. /* LCOV_EXCL_START
  305. *
  306. * We can't cause RSA*Key_dup() to fail, so we can't really test this.
  307. */
  308. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  309. privatekey?"private":"public");
  310. crypto_openssl_log_errors(LOG_ERR,
  311. privatekey ? "Duplicating a private key" :
  312. "Duplicating a public key");
  313. tor_fragile_assert();
  314. return NULL;
  315. /* LCOV_EXCL_STOP */
  316. }
  317. return crypto_new_pk_from_openssl_rsa_(new_key);
  318. }
  319. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  320. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  321. * write the result to <b>to</b>, and return the number of bytes
  322. * written. On failure, return -1.
  323. *
  324. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  325. * at least the length of the modulus of <b>env</b>.
  326. */
  327. int
  328. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  329. const char *from, size_t fromlen, int padding)
  330. {
  331. int r;
  332. tor_assert(env);
  333. tor_assert(from);
  334. tor_assert(to);
  335. tor_assert(fromlen<INT_MAX);
  336. tor_assert(tolen >= crypto_pk_keysize(env));
  337. r = RSA_public_encrypt((int)fromlen,
  338. (unsigned char*)from, (unsigned char*)to,
  339. env->key, crypto_get_rsa_padding(padding));
  340. if (r<0) {
  341. crypto_openssl_log_errors(LOG_WARN, "performing RSA encryption");
  342. return -1;
  343. }
  344. return r;
  345. }
  346. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  347. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  348. * write the result to <b>to</b>, and return the number of bytes
  349. * written. On failure, return -1.
  350. *
  351. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  352. * at least the length of the modulus of <b>env</b>.
  353. */
  354. int
  355. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  356. size_t tolen,
  357. const char *from, size_t fromlen,
  358. int padding, int warnOnFailure)
  359. {
  360. int r;
  361. tor_assert(env);
  362. tor_assert(from);
  363. tor_assert(to);
  364. tor_assert(env->key);
  365. tor_assert(fromlen<INT_MAX);
  366. tor_assert(tolen >= crypto_pk_keysize(env));
  367. if (!crypto_pk_key_is_private(env))
  368. /* Not a private key */
  369. return -1;
  370. r = RSA_private_decrypt((int)fromlen,
  371. (unsigned char*)from, (unsigned char*)to,
  372. env->key, crypto_get_rsa_padding(padding));
  373. if (r<0) {
  374. crypto_openssl_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  375. "performing RSA decryption");
  376. return -1;
  377. }
  378. return r;
  379. }
  380. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  381. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  382. * signed data to <b>to</b>, and return the number of bytes written.
  383. * On failure, return -1.
  384. *
  385. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  386. * at least the length of the modulus of <b>env</b>.
  387. */
  388. MOCK_IMPL(int,
  389. crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
  390. size_t tolen,
  391. const char *from, size_t fromlen))
  392. {
  393. int r;
  394. tor_assert(env);
  395. tor_assert(from);
  396. tor_assert(to);
  397. tor_assert(fromlen < INT_MAX);
  398. tor_assert(tolen >= crypto_pk_keysize(env));
  399. r = RSA_public_decrypt((int)fromlen,
  400. (unsigned char*)from, (unsigned char*)to,
  401. env->key, RSA_PKCS1_PADDING);
  402. if (r<0) {
  403. crypto_openssl_log_errors(LOG_INFO, "checking RSA signature");
  404. return -1;
  405. }
  406. return r;
  407. }
  408. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  409. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  410. * <b>to</b>, and return the number of bytes written. On failure, return
  411. * -1.
  412. *
  413. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  414. * at least the length of the modulus of <b>env</b>.
  415. */
  416. int
  417. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  418. const char *from, size_t fromlen)
  419. {
  420. int r;
  421. tor_assert(env);
  422. tor_assert(from);
  423. tor_assert(to);
  424. tor_assert(fromlen < INT_MAX);
  425. tor_assert(tolen >= crypto_pk_keysize(env));
  426. if (!crypto_pk_key_is_private(env))
  427. /* Not a private key */
  428. return -1;
  429. r = RSA_private_encrypt((int)fromlen,
  430. (unsigned char*)from, (unsigned char*)to,
  431. (RSA*)env->key, RSA_PKCS1_PADDING);
  432. if (r<0) {
  433. crypto_openssl_log_errors(LOG_WARN, "generating RSA signature");
  434. return -1;
  435. }
  436. return r;
  437. }
  438. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  439. * Return -1 on error, or the number of characters used on success.
  440. */
  441. int
  442. crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
  443. {
  444. int len;
  445. unsigned char *buf = NULL;
  446. len = i2d_RSAPublicKey(pk->key, &buf);
  447. if (len < 0 || buf == NULL)
  448. return -1;
  449. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  450. OPENSSL_free(buf);
  451. return -1;
  452. }
  453. /* We don't encode directly into 'dest', because that would be illegal
  454. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  455. */
  456. memcpy(dest,buf,len);
  457. OPENSSL_free(buf);
  458. return len;
  459. }
  460. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  461. * success and NULL on failure.
  462. */
  463. crypto_pk_t *
  464. crypto_pk_asn1_decode(const char *str, size_t len)
  465. {
  466. RSA *rsa;
  467. unsigned char *buf;
  468. const unsigned char *cp;
  469. cp = buf = tor_malloc(len);
  470. memcpy(buf,str,len);
  471. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  472. tor_free(buf);
  473. if (!rsa) {
  474. crypto_openssl_log_errors(LOG_WARN,"decoding public key");
  475. return NULL;
  476. }
  477. return crypto_new_pk_from_openssl_rsa_(rsa);
  478. }
  479. /** ASN.1-encode the private portion of <b>pk</b> into <b>dest</b>.
  480. * Return -1 on error, or the number of characters used on success.
  481. */
  482. int
  483. crypto_pk_asn1_encode_private(const crypto_pk_t *pk, char *dest,
  484. size_t dest_len)
  485. {
  486. int len;
  487. unsigned char *buf = NULL;
  488. len = i2d_RSAPrivateKey(pk->key, &buf);
  489. if (len < 0 || buf == NULL)
  490. return -1;
  491. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  492. OPENSSL_free(buf);
  493. return -1;
  494. }
  495. /* We don't encode directly into 'dest', because that would be illegal
  496. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  497. */
  498. memcpy(dest,buf,len);
  499. OPENSSL_free(buf);
  500. return len;
  501. }
  502. /** Decode an ASN.1-encoded private key from <b>str</b>; return the result on
  503. * success and NULL on failure.
  504. */
  505. crypto_pk_t *
  506. crypto_pk_asn1_decode_private(const char *str, size_t len)
  507. {
  508. RSA *rsa;
  509. unsigned char *buf;
  510. const unsigned char *cp;
  511. cp = buf = tor_malloc(len);
  512. memcpy(buf,str,len);
  513. rsa = d2i_RSAPrivateKey(NULL, &cp, len);
  514. tor_free(buf);
  515. if (!rsa) {
  516. crypto_openssl_log_errors(LOG_WARN,"decoding public key");
  517. return NULL;
  518. }
  519. crypto_pk_t *result = crypto_new_pk_from_openssl_rsa_(rsa);
  520. if (! crypto_pk_is_valid_private_key(result)) {
  521. crypto_pk_free(result);
  522. return NULL;
  523. }
  524. return result;
  525. }