Add changes file for bug40642.
[tor.git] / src / lib / crypt_ops / crypto_rsa_openssl.c
bloba21c4a65cfd5e5e7bccf96884a3eb656f39daa30
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-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file crypto_rsa.c
9 * \brief OpenSSL implementations of our RSA code.
10 **/
12 #include "lib/crypt_ops/compat_openssl.h"
13 #include "lib/crypt_ops/crypto_rsa.h"
14 #include "lib/crypt_ops/crypto_util.h"
15 #include "lib/ctime/di_ops.h"
16 #include "lib/log/util_bug.h"
17 #include "lib/fs/files.h"
19 DISABLE_GCC_WARNING("-Wredundant-decls")
21 #include <openssl/err.h>
22 #include <openssl/rsa.h>
23 #include <openssl/pem.h>
24 #include <openssl/evp.h>
25 #include <openssl/engine.h>
26 #include <openssl/rand.h>
27 #include <openssl/bn.h>
28 #include <openssl/conf.h>
30 ENABLE_GCC_WARNING("-Wredundant-decls")
32 #include "lib/log/log.h"
33 #include "lib/encoding/binascii.h"
35 #include <string.h>
36 #include <stdbool.h>
38 /** Declaration for crypto_pk_t structure. */
39 struct crypto_pk_t
41 int refs; /**< reference count, so we don't have to copy keys */
42 RSA *key; /**< The key itself */
45 /** Return true iff <b>key</b> contains the private-key portion of the RSA
46 * key. */
47 int
48 crypto_pk_key_is_private(const crypto_pk_t *k)
50 #ifdef OPENSSL_1_1_API
51 if (!k || !k->key)
52 return 0;
54 const BIGNUM *p, *q;
55 RSA_get0_factors(k->key, &p, &q);
56 return p != NULL; /* XXX/yawning: Should we check q? */
57 #else /* !defined(OPENSSL_1_1_API) */
58 return k && k->key && k->key->p;
59 #endif /* defined(OPENSSL_1_1_API) */
62 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. Takes ownership of
63 * its argument. */
64 crypto_pk_t *
65 crypto_new_pk_from_openssl_rsa_(RSA *rsa)
67 crypto_pk_t *env;
68 tor_assert(rsa);
69 env = tor_malloc(sizeof(crypto_pk_t));
70 env->refs = 1;
71 env->key = rsa;
72 return env;
75 /** Helper, used by tor-gencert.c. Return a copy of the private RSA from a
76 * crypto_pk_t. */
77 RSA *
78 crypto_pk_get_openssl_rsa_(crypto_pk_t *env)
80 return RSAPrivateKey_dup(env->key);
83 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
84 * private is set, include the private-key portion of the key. Return a valid
85 * pointer on success, and NULL on failure. */
86 MOCK_IMPL(EVP_PKEY *,
87 crypto_pk_get_openssl_evp_pkey_,(crypto_pk_t *env, int private))
89 RSA *key = NULL;
90 EVP_PKEY *pkey = NULL;
91 tor_assert(env->key);
92 if (private) {
93 if (!(key = RSAPrivateKey_dup(env->key)))
94 goto error;
95 } else {
96 if (!(key = RSAPublicKey_dup(env->key)))
97 goto error;
99 if (!(pkey = EVP_PKEY_new()))
100 goto error;
101 if (!(EVP_PKEY_assign_RSA(pkey, key)))
102 goto error;
103 return pkey;
104 error:
105 if (pkey)
106 EVP_PKEY_free(pkey);
107 if (key)
108 RSA_free(key);
109 return NULL;
112 /** Allocate and return storage for a public key. The key itself will not yet
113 * be set.
115 MOCK_IMPL(crypto_pk_t *,
116 crypto_pk_new,(void))
118 RSA *rsa;
120 rsa = RSA_new();
121 tor_assert(rsa);
122 return crypto_new_pk_from_openssl_rsa_(rsa);
125 /** Release a reference to an asymmetric key; when all the references
126 * are released, free the key.
128 void
129 crypto_pk_free_(crypto_pk_t *env)
131 if (!env)
132 return;
134 if (--env->refs > 0)
135 return;
136 tor_assert(env->refs == 0);
138 if (env->key)
139 RSA_free(env->key);
141 tor_free(env);
144 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
145 * Return 0 on success, -1 on failure.
147 MOCK_IMPL(int,
148 crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
150 tor_assert(env);
152 if (env->key) {
153 RSA_free(env->key);
154 env->key = NULL;
158 BIGNUM *e = BN_new();
159 RSA *r = NULL;
160 if (!e)
161 goto done;
162 if (! BN_set_word(e, TOR_RSA_EXPONENT))
163 goto done;
164 r = RSA_new();
165 if (!r)
166 goto done;
167 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
168 goto done;
170 env->key = r;
171 r = NULL;
172 done:
173 if (e)
174 BN_clear_free(e);
175 if (r)
176 RSA_free(r);
179 if (!env->key) {
180 crypto_openssl_log_errors(LOG_WARN, "generating RSA key");
181 return -1;
184 return 0;
187 /** Return true if <b>env</b> has a valid key; false otherwise.
190 crypto_pk_is_valid_private_key(const crypto_pk_t *env)
192 int r;
193 tor_assert(env);
195 r = RSA_check_key(env->key);
196 if (r <= 0) {
197 crypto_openssl_log_errors(LOG_WARN,"checking RSA key");
198 return 0;
199 } else {
200 return 1;
204 /** Return true iff <b>env</b> contains a public key whose public exponent
205 * equals TOR_RSA_EXPONENT.
208 crypto_pk_public_exponent_ok(const crypto_pk_t *env)
210 tor_assert(env);
211 tor_assert(env->key);
213 const BIGNUM *e;
215 #ifdef OPENSSL_1_1_API
216 const BIGNUM *n, *d;
217 RSA_get0_key(env->key, &n, &e, &d);
218 #else
219 e = env->key->e;
220 #endif /* defined(OPENSSL_1_1_API) */
221 return BN_is_word(e, TOR_RSA_EXPONENT);
224 /** Compare the public-key components of a and b. Return less than 0
225 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
226 * considered to be less than all non-NULL keys, and equal to itself.
228 * Note that this may leak information about the keys through timing.
231 crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
233 int result;
234 char a_is_non_null = (a != NULL) && (a->key != NULL);
235 char b_is_non_null = (b != NULL) && (b->key != NULL);
236 char an_argument_is_null = !a_is_non_null | !b_is_non_null;
238 result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
239 if (an_argument_is_null)
240 return result;
242 const BIGNUM *a_n, *a_e;
243 const BIGNUM *b_n, *b_e;
245 #ifdef OPENSSL_1_1_API
246 const BIGNUM *a_d, *b_d;
247 RSA_get0_key(a->key, &a_n, &a_e, &a_d);
248 RSA_get0_key(b->key, &b_n, &b_e, &b_d);
249 #else
250 a_n = a->key->n;
251 a_e = a->key->e;
252 b_n = b->key->n;
253 b_e = b->key->e;
254 #endif /* defined(OPENSSL_1_1_API) */
256 tor_assert(a_n != NULL && a_e != NULL);
257 tor_assert(b_n != NULL && b_e != NULL);
259 result = BN_cmp(a_n, b_n);
260 if (result)
261 return result;
262 return BN_cmp(a_e, b_e);
265 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
266 size_t
267 crypto_pk_keysize(const crypto_pk_t *env)
269 tor_assert(env);
270 tor_assert(env->key);
272 return (size_t) RSA_size((RSA*)env->key);
275 /** Return the size of the public key modulus of <b>env</b>, in bits. */
277 crypto_pk_num_bits(crypto_pk_t *env)
279 tor_assert(env);
280 tor_assert(env->key);
282 #ifdef OPENSSL_1_1_API
283 /* It's so stupid that there's no other way to check that n is valid
284 * before calling RSA_bits().
286 const BIGNUM *n, *e, *d;
287 RSA_get0_key(env->key, &n, &e, &d);
288 tor_assert(n != NULL);
290 return RSA_bits(env->key);
291 #else /* !defined(OPENSSL_1_1_API) */
292 tor_assert(env->key->n);
293 return BN_num_bits(env->key->n);
294 #endif /* defined(OPENSSL_1_1_API) */
297 /** Increase the reference count of <b>env</b>, and return it.
299 crypto_pk_t *
300 crypto_pk_dup_key(crypto_pk_t *env)
302 tor_assert(env);
303 tor_assert(env->key);
305 env->refs++;
306 return env;
309 /** Replace dest with src (private key only). (Dest must have a refcount
310 * of 1)
312 void
313 crypto_pk_assign_private(crypto_pk_t *dest, const crypto_pk_t *src)
315 tor_assert(dest);
316 tor_assert(dest->refs == 1);
317 tor_assert(src);
318 RSA_free(dest->key);
319 dest->key = RSAPrivateKey_dup(src->key);
322 /** Replace dest with src (public key only). (Dest must have a refcount
323 * of 1)
325 void
326 crypto_pk_assign_public(crypto_pk_t *dest, const crypto_pk_t *src)
328 tor_assert(dest);
329 tor_assert(dest->refs == 1);
330 tor_assert(src);
331 RSA_free(dest->key);
332 dest->key = RSAPublicKey_dup(src->key);
335 /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
336 * Returns NULL on failure. */
337 crypto_pk_t *
338 crypto_pk_copy_full(crypto_pk_t *env)
340 RSA *new_key;
341 int privatekey = 0;
342 tor_assert(env);
343 tor_assert(env->key);
345 if (crypto_pk_key_is_private(env)) {
346 new_key = RSAPrivateKey_dup(env->key);
347 privatekey = 1;
348 } else {
349 new_key = RSAPublicKey_dup(env->key);
351 if (!new_key) {
352 /* LCOV_EXCL_START
354 * We can't cause RSA*Key_dup() to fail, so we can't really test this.
356 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
357 privatekey?"private":"public");
358 crypto_openssl_log_errors(LOG_ERR,
359 privatekey ? "Duplicating a private key" :
360 "Duplicating a public key");
361 tor_fragile_assert();
362 return NULL;
363 /* LCOV_EXCL_STOP */
366 return crypto_new_pk_from_openssl_rsa_(new_key);
369 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
370 * in <b>env</b>, using the padding method <b>padding</b>. On success,
371 * write the result to <b>to</b>, and return the number of bytes
372 * written. On failure, return -1.
374 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
375 * at least the length of the modulus of <b>env</b>.
378 crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
379 const char *from, size_t fromlen, int padding)
381 int r;
382 tor_assert(env);
383 tor_assert(from);
384 tor_assert(to);
385 tor_assert(fromlen<INT_MAX);
386 tor_assert(tolen >= crypto_pk_keysize(env));
388 r = RSA_public_encrypt((int)fromlen,
389 (unsigned char*)from, (unsigned char*)to,
390 env->key, crypto_get_rsa_padding(padding));
391 if (r<0) {
392 crypto_openssl_log_errors(LOG_WARN, "performing RSA encryption");
393 return -1;
395 return r;
398 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
399 * in <b>env</b>, using the padding method <b>padding</b>. On success,
400 * write the result to <b>to</b>, and return the number of bytes
401 * written. On failure, return -1.
403 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
404 * at least the length of the modulus of <b>env</b>.
407 crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
408 size_t tolen,
409 const char *from, size_t fromlen,
410 int padding, int warnOnFailure)
412 int r;
413 tor_assert(env);
414 tor_assert(from);
415 tor_assert(to);
416 tor_assert(env->key);
417 tor_assert(fromlen<INT_MAX);
418 tor_assert(tolen >= crypto_pk_keysize(env));
419 if (!crypto_pk_key_is_private(env))
420 /* Not a private key */
421 return -1;
423 r = RSA_private_decrypt((int)fromlen,
424 (unsigned char*)from, (unsigned char*)to,
425 env->key, crypto_get_rsa_padding(padding));
427 if (r<0) {
428 crypto_openssl_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
429 "performing RSA decryption");
430 return -1;
432 return r;
435 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
436 * public key in <b>env</b>, using PKCS1 padding. On success, write the
437 * signed data to <b>to</b>, and return the number of bytes written.
438 * On failure, return -1.
440 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
441 * at least the length of the modulus of <b>env</b>.
443 MOCK_IMPL(int,
444 crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
445 size_t tolen,
446 const char *from, size_t fromlen))
448 int r;
449 tor_assert(env);
450 tor_assert(from);
451 tor_assert(to);
452 tor_assert(fromlen < INT_MAX);
453 tor_assert(tolen >= crypto_pk_keysize(env));
454 r = RSA_public_decrypt((int)fromlen,
455 (unsigned char*)from, (unsigned char*)to,
456 env->key, RSA_PKCS1_PADDING);
458 if (r<0) {
459 crypto_openssl_log_errors(LOG_INFO, "checking RSA signature");
460 return -1;
462 return r;
465 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
466 * <b>env</b>, using PKCS1 padding. On success, write the signature to
467 * <b>to</b>, and return the number of bytes written. On failure, return
468 * -1.
470 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
471 * at least the length of the modulus of <b>env</b>.
474 crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
475 const char *from, size_t fromlen)
477 int r;
478 tor_assert(env);
479 tor_assert(from);
480 tor_assert(to);
481 tor_assert(fromlen < INT_MAX);
482 tor_assert(tolen >= crypto_pk_keysize(env));
483 if (!crypto_pk_key_is_private(env))
484 /* Not a private key */
485 return -1;
487 r = RSA_private_encrypt((int)fromlen,
488 (unsigned char*)from, (unsigned char*)to,
489 (RSA*)env->key, RSA_PKCS1_PADDING);
490 if (r<0) {
491 crypto_openssl_log_errors(LOG_WARN, "generating RSA signature");
492 return -1;
494 return r;
497 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
498 * Return -1 on error, or the number of characters used on success.
501 crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
503 int len;
504 unsigned char *buf = NULL;
506 len = i2d_RSAPublicKey(pk->key, &buf);
507 if (len < 0 || buf == NULL)
508 return -1;
510 if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
511 OPENSSL_free(buf);
512 return -1;
514 /* We don't encode directly into 'dest', because that would be illegal
515 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
517 memcpy(dest,buf,len);
518 OPENSSL_free(buf);
519 return len;
522 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
523 * success and NULL on failure.
525 crypto_pk_t *
526 crypto_pk_asn1_decode(const char *str, size_t len)
528 RSA *rsa;
529 unsigned char *buf;
530 const unsigned char *cp;
531 cp = buf = tor_malloc(len);
532 memcpy(buf,str,len);
533 rsa = d2i_RSAPublicKey(NULL, &cp, len);
534 tor_free(buf);
535 if (!rsa) {
536 crypto_openssl_log_errors(LOG_WARN,"decoding public key");
537 return NULL;
539 return crypto_new_pk_from_openssl_rsa_(rsa);
542 /** ASN.1-encode the private portion of <b>pk</b> into <b>dest</b>.
543 * Return -1 on error, or the number of characters used on success.
546 crypto_pk_asn1_encode_private(const crypto_pk_t *pk, char *dest,
547 size_t dest_len)
549 int len;
550 unsigned char *buf = NULL;
552 len = i2d_RSAPrivateKey(pk->key, &buf);
553 if (len < 0 || buf == NULL)
554 return -1;
556 if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
557 OPENSSL_free(buf);
558 return -1;
560 /* We don't encode directly into 'dest', because that would be illegal
561 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
563 memcpy(dest,buf,len);
564 OPENSSL_free(buf);
565 return len;
568 /** Check whether any component of a private key is too large in a way that
569 * seems likely to make verification too expensive. Return true if it's too
570 * long, and false otherwise. */
571 static bool
572 rsa_private_key_too_long(RSA *rsa, int max_bits)
574 const BIGNUM *n, *e, *p, *q, *d, *dmp1, *dmq1, *iqmp;
575 #ifdef OPENSSL_1_1_API
577 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,1)
578 n = RSA_get0_n(rsa);
579 e = RSA_get0_e(rsa);
580 p = RSA_get0_p(rsa);
581 q = RSA_get0_q(rsa);
582 d = RSA_get0_d(rsa);
583 dmp1 = RSA_get0_dmp1(rsa);
584 dmq1 = RSA_get0_dmq1(rsa);
585 iqmp = RSA_get0_iqmp(rsa);
586 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,1)) */
587 /* The accessors above did not exist in openssl 1.1.0. */
588 p = q = dmp1 = dmq1 = iqmp = NULL;
589 RSA_get0_key(rsa, &n, &e, &d);
590 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,1) */
592 if (RSA_bits(rsa) > max_bits)
593 return true;
594 #else /* !defined(OPENSSL_1_1_API) */
595 n = rsa->n;
596 e = rsa->e;
597 p = rsa->p;
598 q = rsa->q;
599 d = rsa->d;
600 dmp1 = rsa->dmp1;
601 dmq1 = rsa->dmq1;
602 iqmp = rsa->iqmp;
603 #endif /* defined(OPENSSL_1_1_API) */
605 if (n && BN_num_bits(n) > max_bits)
606 return true;
607 if (e && BN_num_bits(e) > max_bits)
608 return true;
609 if (p && BN_num_bits(p) > max_bits)
610 return true;
611 if (q && BN_num_bits(q) > max_bits)
612 return true;
613 if (d && BN_num_bits(d) > max_bits)
614 return true;
615 if (dmp1 && BN_num_bits(dmp1) > max_bits)
616 return true;
617 if (dmq1 && BN_num_bits(dmq1) > max_bits)
618 return true;
619 if (iqmp && BN_num_bits(iqmp) > max_bits)
620 return true;
622 return false;
625 /** Decode an ASN.1-encoded private key from <b>str</b>; return the result on
626 * success and NULL on failure.
628 * If <b>max_bits</b> is nonnegative, reject any key longer than max_bits
629 * without performing any expensive validation on it.
631 crypto_pk_t *
632 crypto_pk_asn1_decode_private(const char *str, size_t len, int max_bits)
634 RSA *rsa;
635 unsigned char *buf;
636 const unsigned char *cp;
637 cp = buf = tor_malloc(len);
638 memcpy(buf,str,len);
639 rsa = d2i_RSAPrivateKey(NULL, &cp, len);
640 tor_free(buf);
641 if (!rsa) {
642 crypto_openssl_log_errors(LOG_WARN,"decoding private key");
643 return NULL;
645 if (max_bits >= 0 && rsa_private_key_too_long(rsa, max_bits)) {
646 log_info(LD_CRYPTO, "Private key longer than expected.");
647 RSA_free(rsa);
648 return NULL;
650 crypto_pk_t *result = crypto_new_pk_from_openssl_rsa_(rsa);
651 if (! crypto_pk_is_valid_private_key(result)) {
652 crypto_pk_free(result);
653 return NULL;
655 return result;