2 * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 * RSA low level APIs are deprecated for public use, but still ok for
14 #include "internal/deprecated.h"
16 #include "internal/constant_time.h"
19 #include <openssl/bn.h>
20 #include <openssl/rsa.h>
21 #include <openssl/rand.h>
22 /* Just for the SSL_MAX_MASTER_KEY_LENGTH value */
23 #include <openssl/prov_ssl.h>
24 #include <openssl/evp.h>
25 #include <openssl/sha.h>
26 #include <openssl/hmac.h>
27 #include "internal/cryptlib.h"
28 #include "crypto/rsa.h"
29 #include "rsa_local.h"
32 int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
33 const unsigned char *from, int flen)
38 if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
39 ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
43 p = (unsigned char *)to;
46 *(p++) = 1; /* Private Key BT (Block Type) */
48 /* pad out with 0xff data */
53 memcpy(p, from, (unsigned int)flen);
57 int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
58 const unsigned char *from, int flen,
62 const unsigned char *p;
68 * 00 || 01 || PS || 00 || D
69 * PS - padding string, at least 8 bytes of FF
73 if (num < RSA_PKCS1_PADDING_SIZE)
76 /* Accept inputs with and without the leading 0-byte. */
79 ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
85 if ((num != (flen + 1)) || (*(p++) != 0x01)) {
86 ERR_raise(ERR_LIB_RSA, RSA_R_BLOCK_TYPE_IS_NOT_01);
90 /* scan over padding data */
91 j = flen - 1; /* one for type. */
92 for (i = 0; i < j; i++) {
93 if (*p != 0xff) { /* should decrypt to 0xff */
98 ERR_raise(ERR_LIB_RSA, RSA_R_BAD_FIXED_HEADER_DECRYPT);
106 ERR_raise(ERR_LIB_RSA, RSA_R_NULL_BEFORE_BLOCK_MISSING);
111 ERR_raise(ERR_LIB_RSA, RSA_R_BAD_PAD_BYTE_COUNT);
114 i++; /* Skip over the '\0' */
117 ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE);
120 memcpy(to, p, (unsigned int)j);
125 int ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX *libctx, unsigned char *to,
126 int tlen, const unsigned char *from,
132 if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
133 ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
135 } else if (flen < 0) {
136 ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH);
140 p = (unsigned char *)to;
143 *(p++) = 2; /* Public Key BT (Block Type) */
145 /* pad out with non-zero random data */
148 if (RAND_bytes_ex(libctx, p, j, 0) <= 0)
150 for (i = 0; i < j; i++) {
153 if (RAND_bytes_ex(libctx, p, 1, 0) <= 0)
155 } while (*p == '\0');
161 memcpy(p, from, (unsigned int)flen);
165 int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
166 const unsigned char *from, int flen)
168 return ossl_rsa_padding_add_PKCS1_type_2_ex(NULL, to, tlen, from, flen);
171 int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
172 const unsigned char *from, int flen,
176 /* |em| is the encoded message, zero-padded to exactly |num| bytes */
177 unsigned char *em = NULL;
178 unsigned int good, found_zero_byte, mask;
179 int zero_index = 0, msg_index, mlen = -1;
181 if (tlen <= 0 || flen <= 0)
185 * PKCS#1 v1.5 decryption. See "PKCS #1 v2.2: RSA Cryptography Standard",
189 if (flen > num || num < RSA_PKCS1_PADDING_SIZE) {
190 ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
194 em = OPENSSL_malloc(num);
198 * Caller is encouraged to pass zero-padded message created with
199 * BN_bn2binpad. Trouble is that since we can't read out of |from|'s
200 * bounds, it's impossible to have an invariant memory access pattern
201 * in case |from| was not zero-padded in advance.
203 for (from += flen, em += num, i = 0; i < num; i++) {
204 mask = ~constant_time_is_zero(flen);
207 *--em = *from & mask;
210 good = constant_time_is_zero(em[0]);
211 good &= constant_time_eq(em[1], 2);
213 /* scan over padding data */
215 for (i = 2; i < num; i++) {
216 unsigned int equals0 = constant_time_is_zero(em[i]);
218 zero_index = constant_time_select_int(~found_zero_byte & equals0,
220 found_zero_byte |= equals0;
224 * PS must be at least 8 bytes long, and it starts two bytes into |em|.
225 * If we never found a 0-byte, then |zero_index| is 0 and the check
228 good &= constant_time_ge(zero_index, 2 + 8);
231 * Skip the zero byte. This is incorrect if we never found a zero-byte
232 * but in this case we also do not copy the message out.
234 msg_index = zero_index + 1;
235 mlen = num - msg_index;
238 * For good measure, do this check in constant time as well.
240 good &= constant_time_ge(tlen, mlen);
243 * Move the result in-place by |num|-RSA_PKCS1_PADDING_SIZE-|mlen| bytes to the left.
244 * Then if |good| move |mlen| bytes from |em|+RSA_PKCS1_PADDING_SIZE to |to|.
245 * Otherwise leave |to| unchanged.
246 * Copy the memory back in a way that does not reveal the size of
247 * the data being copied via a timing side channel. This requires copying
248 * parts of the buffer multiple times based on the bits set in the real
249 * length. Clear bits do a non-copy with identical access pattern.
250 * The loop below has overall complexity of O(N*log(N)).
252 tlen = constant_time_select_int(constant_time_lt(num - RSA_PKCS1_PADDING_SIZE, tlen),
253 num - RSA_PKCS1_PADDING_SIZE, tlen);
254 for (msg_index = 1; msg_index < num - RSA_PKCS1_PADDING_SIZE; msg_index <<= 1) {
255 mask = ~constant_time_eq(msg_index & (num - RSA_PKCS1_PADDING_SIZE - mlen), 0);
256 for (i = RSA_PKCS1_PADDING_SIZE; i < num - msg_index; i++)
257 em[i] = constant_time_select_8(mask, em[i + msg_index], em[i]);
259 for (i = 0; i < tlen; i++) {
260 mask = good & constant_time_lt(i, mlen);
261 to[i] = constant_time_select_8(mask, em[i + RSA_PKCS1_PADDING_SIZE], to[i]);
264 OPENSSL_clear_free(em, num);
267 * This trick doesn't work in the FIPS provider because libcrypto manages
268 * the error stack. Instead we opt not to put an error on the stack at all
269 * in case of padding failure in the FIPS provider.
271 ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
272 err_clear_last_constant_time(1 & good);
275 return constant_time_select_int(good, mlen, -1);
279 static int ossl_rsa_prf(OSSL_LIB_CTX *ctx,
280 unsigned char *to, int tlen,
281 const char *label, int llen,
282 const unsigned char *kdk,
288 unsigned char be_iter[sizeof(iter)];
289 unsigned char be_bitlen[sizeof(bitlen)];
290 HMAC_CTX *hmac = NULL;
292 unsigned char hmac_out[SHA256_DIGEST_LENGTH];
295 if (tlen * 8 != bitlen) {
296 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
300 be_bitlen[0] = (bitlen >> 8) & 0xff;
301 be_bitlen[1] = bitlen & 0xff;
303 hmac = HMAC_CTX_new();
305 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
310 * we use hardcoded hash so that migrating between versions that use
311 * different hash doesn't provide a Bleichenbacher oracle:
312 * if the attacker can see that different versions return different
313 * messages for the same ciphertext, they'll know that the message is
314 * synthetically generated, which means that the padding check failed
316 md = EVP_MD_fetch(ctx, "sha256", NULL);
318 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
322 if (HMAC_Init_ex(hmac, kdk, SHA256_DIGEST_LENGTH, md, NULL) <= 0) {
323 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
327 for (pos = 0; pos < tlen; pos += SHA256_DIGEST_LENGTH, iter++) {
328 if (HMAC_Init_ex(hmac, NULL, 0, NULL, NULL) <= 0) {
329 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
333 be_iter[0] = (iter >> 8) & 0xff;
334 be_iter[1] = iter & 0xff;
336 if (HMAC_Update(hmac, be_iter, sizeof(be_iter)) <= 0) {
337 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
340 if (HMAC_Update(hmac, (unsigned char *)label, llen) <= 0) {
341 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
344 if (HMAC_Update(hmac, be_bitlen, sizeof(be_bitlen)) <= 0) {
345 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
350 * HMAC_Final requires the output buffer to fit the whole MAC
351 * value, so we need to use the intermediate buffer for the last
354 md_len = SHA256_DIGEST_LENGTH;
355 if (pos + SHA256_DIGEST_LENGTH > tlen) {
356 if (HMAC_Final(hmac, hmac_out, &md_len) <= 0) {
357 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
360 memcpy(to + pos, hmac_out, tlen - pos);
362 if (HMAC_Final(hmac, to + pos, &md_len) <= 0) {
363 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
378 * ossl_rsa_padding_check_PKCS1_type_2() checks and removes the PKCS#1 type 2
379 * padding from a decrypted RSA message. Unlike the
380 * RSA_padding_check_PKCS1_type_2() it will not return an error in case it
381 * detects a padding error, rather it will return a deterministically generated
382 * random message. In other words it will perform an implicit rejection
383 * of an invalid padding. This means that the returned value does not indicate
384 * if the padding of the encrypted message was correct or not, making
385 * side channel attacks like the ones described by Bleichenbacher impossible
386 * without access to the full decrypted value and a brute-force search of
387 * remaining padding bytes
389 int ossl_rsa_padding_check_PKCS1_type_2(OSSL_LIB_CTX *ctx,
390 unsigned char *to, int tlen,
391 const unsigned char *from, int flen,
392 int num, unsigned char *kdk)
395 * We need to generate a random length for the synthetic message, to avoid
396 * bias towards zero and avoid non-constant timeness of DIV, we prepare
397 * 128 values to check if they are not too large for the used key size,
398 * and use 0 in case none of them are small enough, as 2^-128 is a good enough
401 #define MAX_LEN_GEN_TRIES 128
402 unsigned char *synthetic = NULL;
403 int synthetic_length;
404 uint16_t len_candidate;
405 unsigned char candidate_lengths[MAX_LEN_GEN_TRIES * sizeof(len_candidate)];
407 uint16_t max_sep_offset;
408 int synth_msg_index = 0;
411 unsigned int good, found_zero_byte;
412 int zero_index = 0, msg_index;
415 * If these checks fail then either the message in publicly invalid, or
416 * we've been called incorrectly. We can fail immediately.
417 * Since this code is called only internally by openssl, those are just
420 if (num != flen || tlen <= 0 || flen <= 0) {
421 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
425 /* Generate a random message to return in case the padding checks fail */
426 synthetic = OPENSSL_malloc(flen);
427 if (synthetic == NULL) {
428 ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
432 if (ossl_rsa_prf(ctx, synthetic, flen, "message", 7, kdk, flen * 8) < 0)
435 /* decide how long the random message should be */
436 if (ossl_rsa_prf(ctx, candidate_lengths, sizeof(candidate_lengths),
438 MAX_LEN_GEN_TRIES * sizeof(len_candidate) * 8) < 0)
442 * max message size is the size of the modulus size less 2 bytes for
443 * version and padding type and a minimum of 8 bytes padding
445 len_mask = max_sep_offset = flen - 2 - 8;
447 * we want a mask so lets propagate the high bit to all positions less
448 * significant than it
450 len_mask |= len_mask >> 1;
451 len_mask |= len_mask >> 2;
452 len_mask |= len_mask >> 4;
453 len_mask |= len_mask >> 8;
455 synthetic_length = 0;
456 for (i = 0; i < MAX_LEN_GEN_TRIES * (int)sizeof(len_candidate);
457 i += sizeof(len_candidate)) {
458 len_candidate = (candidate_lengths[i] << 8) | candidate_lengths[i + 1];
459 len_candidate &= len_mask;
461 synthetic_length = constant_time_select_int(
462 constant_time_lt(len_candidate, max_sep_offset),
463 len_candidate, synthetic_length);
466 synth_msg_index = flen - synthetic_length;
468 /* we have alternative message ready, check the real one */
469 good = constant_time_is_zero(from[0]);
470 good &= constant_time_eq(from[1], 2);
472 /* then look for the padding|message separator (the first zero byte) */
474 for (i = 2; i < flen; i++) {
475 unsigned int equals0 = constant_time_is_zero(from[i]);
476 zero_index = constant_time_select_int(~found_zero_byte & equals0,
478 found_zero_byte |= equals0;
482 * padding must be at least 8 bytes long, and it starts two bytes into
483 * |from|. If we never found a 0-byte, then |zero_index| is 0 and the check
486 good &= constant_time_ge(zero_index, 2 + 8);
489 * Skip the zero byte. This is incorrect if we never found a zero-byte
490 * but in this case we also do not copy the message out.
492 msg_index = zero_index + 1;
495 * old code returned an error in case the decrypted message wouldn't fit
496 * into the |to|, since that would leak information, return the synthetic
499 good &= constant_time_ge(tlen, num - msg_index);
501 msg_index = constant_time_select_int(good, msg_index, synth_msg_index);
504 * since at this point the |msg_index| does not provide the signal
505 * indicating if the padding check failed or not, we don't have to worry
506 * about leaking the length of returned message, we still need to ensure
507 * that we read contents of both buffers so that cache accesses don't leak
508 * the value of |good|
510 for (i = msg_index, j = 0; i < flen && j < tlen; i++, j++)
511 to[j] = constant_time_select_8(good, from[i], synthetic[i]);
516 * the only time ret < 0 is when the ciphertext is publicly invalid
517 * or we were called with invalid parameters, so we don't have to perform
518 * a side-channel secure raising of the error
521 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
522 OPENSSL_free(synthetic);
527 * ossl_rsa_padding_check_PKCS1_type_2_TLS() checks and removes the PKCS1 type 2
528 * padding from a decrypted RSA message in a TLS signature. The result is stored
529 * in the buffer pointed to by |to| which should be |tlen| bytes long. |tlen|
530 * must be at least SSL_MAX_MASTER_KEY_LENGTH. The original decrypted message
531 * should be stored in |from| which must be |flen| bytes in length and padded
532 * such that |flen == RSA_size()|. The TLS protocol version that the client
533 * originally requested should be passed in |client_version|. Some buggy clients
534 * can exist which use the negotiated version instead of the originally
535 * requested protocol version. If it is necessary to work around this bug then
536 * the negotiated protocol version can be passed in |alt_version|, otherwise 0
539 * If the passed message is publicly invalid or some other error that can be
540 * treated in non-constant time occurs then -1 is returned. On success the
541 * length of the decrypted data is returned. This will always be
542 * SSL_MAX_MASTER_KEY_LENGTH. If an error occurs that should be treated in
543 * constant time then this function will appear to return successfully, but the
544 * decrypted data will be randomly generated (as per
545 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1).
547 int ossl_rsa_padding_check_PKCS1_type_2_TLS(OSSL_LIB_CTX *libctx,
548 unsigned char *to, size_t tlen,
549 const unsigned char *from,
550 size_t flen, int client_version,
553 unsigned int i, good, version_good;
554 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
557 * If these checks fail then either the message in publicly invalid, or
558 * we've been called incorrectly. We can fail immediately.
560 if (flen < RSA_PKCS1_PADDING_SIZE + SSL_MAX_MASTER_KEY_LENGTH
561 || tlen < SSL_MAX_MASTER_KEY_LENGTH) {
562 ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
567 * Generate a random premaster secret to use in the event that we fail
570 if (RAND_priv_bytes_ex(libctx, rand_premaster_secret,
571 sizeof(rand_premaster_secret), 0) <= 0) {
572 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
576 good = constant_time_is_zero(from[0]);
577 good &= constant_time_eq(from[1], 2);
579 /* Check we have the expected padding data */
580 for (i = 2; i < flen - SSL_MAX_MASTER_KEY_LENGTH - 1; i++)
581 good &= ~constant_time_is_zero_8(from[i]);
582 good &= constant_time_is_zero_8(from[flen - SSL_MAX_MASTER_KEY_LENGTH - 1]);
586 * If the version in the decrypted pre-master secret is correct then
587 * version_good will be 0xff, otherwise it'll be zero. The
588 * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
589 * (http://eprint.iacr.org/2003/052/) exploits the version number
590 * check as a "bad version oracle". Thus version checks are done in
591 * constant time and are treated like any other decryption error.
594 constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
595 (client_version >> 8) & 0xff);
597 constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
598 client_version & 0xff);
601 * The premaster secret must contain the same version number as the
602 * ClientHello to detect version rollback attacks (strangely, the
603 * protocol does not offer such protection for DH ciphersuites).
604 * However, buggy clients exist that send the negotiated protocol
605 * version instead if the server does not support the requested
606 * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set then we tolerate
607 * such clients. In that case alt_version will be non-zero and set to
608 * the negotiated version.
610 if (alt_version > 0) {
611 unsigned int workaround_good;
614 constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
615 (alt_version >> 8) & 0xff);
617 constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
619 version_good |= workaround_good;
622 good &= version_good;
626 * Now copy the result over to the to buffer if good, or random data if
629 for (i = 0; i < SSL_MAX_MASTER_KEY_LENGTH; i++) {
631 constant_time_select_8(good,
632 from[flen - SSL_MAX_MASTER_KEY_LENGTH + i],
633 rand_premaster_secret[i]);
637 * We must not leak whether a decryption failure occurs because of
638 * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
639 * section 7.4.7.1). The code follows that advice of the TLS RFC and
640 * generates a random premaster secret for the case that the decrypt
641 * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
642 * So, whether we actually succeeded or not, return success.
645 return SSL_MAX_MASTER_KEY_LENGTH;