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 */
9 * \brief OpenSSL implementations of our RSA code.
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"
38 /** Declaration for crypto_pk_t structure. */
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
48 crypto_pk_key_is_private(const crypto_pk_t
*k
)
50 #ifdef OPENSSL_1_1_API
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
65 crypto_new_pk_from_openssl_rsa_(RSA
*rsa
)
69 env
= tor_malloc(sizeof(crypto_pk_t
));
75 /** Helper, used by tor-gencert.c. Return a copy of the private RSA from a
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. */
87 crypto_pk_get_openssl_evp_pkey_
,(crypto_pk_t
*env
, int private))
90 EVP_PKEY
*pkey
= NULL
;
93 if (!(key
= RSAPrivateKey_dup(env
->key
)))
96 if (!(key
= RSAPublicKey_dup(env
->key
)))
99 if (!(pkey
= EVP_PKEY_new()))
101 if (!(EVP_PKEY_assign_RSA(pkey
, key
)))
112 /** Allocate and return storage for a public key. The key itself will not yet
115 MOCK_IMPL(crypto_pk_t
*,
116 crypto_pk_new
,(void))
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.
129 crypto_pk_free_(crypto_pk_t
*env
)
136 tor_assert(env
->refs
== 0);
144 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
145 * Return 0 on success, -1 on failure.
148 crypto_pk_generate_key_with_bits
,(crypto_pk_t
*env
, int bits
))
158 BIGNUM
*e
= BN_new();
162 if (! BN_set_word(e
, TOR_RSA_EXPONENT
))
167 if (RSA_generate_key_ex(r
, bits
, e
, NULL
) == -1)
180 crypto_openssl_log_errors(LOG_WARN
, "generating RSA key");
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
)
195 r
= RSA_check_key(env
->key
);
197 crypto_openssl_log_errors(LOG_WARN
,"checking RSA key");
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
)
211 tor_assert(env
->key
);
215 #ifdef OPENSSL_1_1_API
217 RSA_get0_key(env
->key
, &n
, &e
, &d
);
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
)
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
)
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
);
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
);
262 return BN_cmp(a_e
, b_e
);
265 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
267 crypto_pk_keysize(const crypto_pk_t
*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
)
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.
300 crypto_pk_dup_key(crypto_pk_t
*env
)
303 tor_assert(env
->key
);
309 /** Replace dest with src (private key only). (Dest must have a refcount
313 crypto_pk_assign_private(crypto_pk_t
*dest
, const crypto_pk_t
*src
)
316 tor_assert(dest
->refs
== 1);
319 dest
->key
= RSAPrivateKey_dup(src
->key
);
322 /** Replace dest with src (public key only). (Dest must have a refcount
326 crypto_pk_assign_public(crypto_pk_t
*dest
, const crypto_pk_t
*src
)
329 tor_assert(dest
->refs
== 1);
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. */
338 crypto_pk_copy_full(crypto_pk_t
*env
)
343 tor_assert(env
->key
);
345 if (crypto_pk_key_is_private(env
)) {
346 new_key
= RSAPrivateKey_dup(env
->key
);
349 new_key
= RSAPublicKey_dup(env
->key
);
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();
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
)
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
));
392 crypto_openssl_log_errors(LOG_WARN
, "performing RSA encryption");
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
,
409 const char *from
, size_t fromlen
,
410 int padding
, int warnOnFailure
)
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 */
423 r
= RSA_private_decrypt((int)fromlen
,
424 (unsigned char*)from
, (unsigned char*)to
,
425 env
->key
, crypto_get_rsa_padding(padding
));
428 crypto_openssl_log_errors(warnOnFailure
?LOG_WARN
:LOG_DEBUG
,
429 "performing RSA decryption");
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>.
444 crypto_pk_public_checksig
,(const crypto_pk_t
*env
, char *to
,
446 const char *from
, size_t fromlen
))
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
);
459 crypto_openssl_log_errors(LOG_INFO
, "checking RSA signature");
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
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
)
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 */
487 r
= RSA_private_encrypt((int)fromlen
,
488 (unsigned char*)from
, (unsigned char*)to
,
489 (RSA
*)env
->key
, RSA_PKCS1_PADDING
);
491 crypto_openssl_log_errors(LOG_WARN
, "generating RSA signature");
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
)
504 unsigned char *buf
= NULL
;
506 len
= i2d_RSAPublicKey(pk
->key
, &buf
);
507 if (len
< 0 || buf
== NULL
)
510 if ((size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
) {
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
);
522 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
523 * success and NULL on failure.
526 crypto_pk_asn1_decode(const char *str
, size_t len
)
530 const unsigned char *cp
;
531 cp
= buf
= tor_malloc(len
);
533 rsa
= d2i_RSAPublicKey(NULL
, &cp
, len
);
536 crypto_openssl_log_errors(LOG_WARN
,"decoding public key");
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
,
550 unsigned char *buf
= NULL
;
552 len
= i2d_RSAPrivateKey(pk
->key
, &buf
);
553 if (len
< 0 || buf
== NULL
)
556 if ((size_t)len
> dest_len
|| dest_len
> SIZE_T_CEILING
) {
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
);
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. */
572 rsa_private_key_too_long(RSA
*rsa
, int max_bits
)
574 const BIGNUM
*n
, *e
, *p
, *q
, *d
, *dmp1
, *dmq1
, *iqmp
;
575 #if defined(OPENSSL_1_1_API) && \
576 (!defined(LIBRESSL_VERSION_NUMBER) || \
577 LIBRESSL_VERSION_NUMBER >= OPENSSL_V_SERIES(3,5,0))
579 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,1)
585 dmp1
= RSA_get0_dmp1(rsa
);
586 dmq1
= RSA_get0_dmq1(rsa
);
587 iqmp
= RSA_get0_iqmp(rsa
);
588 #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,1)) */
589 /* The accessors above did not exist in openssl 1.1.0. */
590 p
= q
= dmp1
= dmq1
= iqmp
= NULL
;
591 RSA_get0_key(rsa
, &n
, &e
, &d
);
592 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,1) */
594 if (RSA_bits(rsa
) > max_bits
)
596 #else /* !defined(OPENSSL_1_1_API) && ... */
605 #endif /* defined(OPENSSL_1_1_API) && ... */
607 if (n
&& BN_num_bits(n
) > max_bits
)
609 if (e
&& BN_num_bits(e
) > max_bits
)
611 if (p
&& BN_num_bits(p
) > max_bits
)
613 if (q
&& BN_num_bits(q
) > max_bits
)
615 if (d
&& BN_num_bits(d
) > max_bits
)
617 if (dmp1
&& BN_num_bits(dmp1
) > max_bits
)
619 if (dmq1
&& BN_num_bits(dmq1
) > max_bits
)
621 if (iqmp
&& BN_num_bits(iqmp
) > max_bits
)
627 /** Decode an ASN.1-encoded private key from <b>str</b>; return the result on
628 * success and NULL on failure.
630 * If <b>max_bits</b> is nonnegative, reject any key longer than max_bits
631 * without performing any expensive validation on it.
634 crypto_pk_asn1_decode_private(const char *str
, size_t len
, int max_bits
)
638 const unsigned char *cp
;
639 cp
= buf
= tor_malloc(len
);
641 rsa
= d2i_RSAPrivateKey(NULL
, &cp
, len
);
644 crypto_openssl_log_errors(LOG_WARN
,"decoding private key");
647 if (max_bits
>= 0 && rsa_private_key_too_long(rsa
, max_bits
)) {
648 log_info(LD_CRYPTO
, "Private key longer than expected.");
652 crypto_pk_t
*result
= crypto_new_pk_from_openssl_rsa_(rsa
);
653 if (! crypto_pk_is_valid_private_key(result
)) {
654 crypto_pk_free(result
);