Coverage Report

Created: 2025-06-13 06:58

/src/openssl31/crypto/rsa/rsa_pk1.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3
 *
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
8
 */
9
10
/*
11
 * RSA low level APIs are deprecated for public use, but still ok for
12
 * internal use.
13
 */
14
#include "internal/deprecated.h"
15
16
#include "internal/constant_time.h"
17
18
#include <stdio.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 "internal/cryptlib.h"
25
#include "crypto/rsa.h"
26
#include "rsa_local.h"
27
28
int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
29
                                 const unsigned char *from, int flen)
30
2.37k
{
31
2.37k
    int j;
32
2.37k
    unsigned char *p;
33
34
2.37k
    if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
35
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
36
0
        return 0;
37
0
    }
38
39
2.37k
    p = (unsigned char *)to;
40
41
2.37k
    *(p++) = 0;
42
2.37k
    *(p++) = 1;                 /* Private Key BT (Block Type) */
43
44
    /* pad out with 0xff data */
45
2.37k
    j = tlen - 3 - flen;
46
2.37k
    memset(p, 0xff, j);
47
2.37k
    p += j;
48
2.37k
    *(p++) = '\0';
49
2.37k
    memcpy(p, from, (unsigned int)flen);
50
2.37k
    return 1;
51
2.37k
}
52
53
int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
54
                                   const unsigned char *from, int flen,
55
                                   int num)
56
2.29k
{
57
2.29k
    int i, j;
58
2.29k
    const unsigned char *p;
59
60
2.29k
    p = from;
61
62
    /*
63
     * The format is
64
     * 00 || 01 || PS || 00 || D
65
     * PS - padding string, at least 8 bytes of FF
66
     * D  - data.
67
     */
68
69
2.29k
    if (num < RSA_PKCS1_PADDING_SIZE)
70
11
        return -1;
71
72
    /* Accept inputs with and without the leading 0-byte. */
73
2.28k
    if (num == flen) {
74
2.28k
        if ((*p++) != 0x00) {
75
1.22k
            ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
76
1.22k
            return -1;
77
1.22k
        }
78
1.06k
        flen--;
79
1.06k
    }
80
81
1.06k
    if ((num != (flen + 1)) || (*(p++) != 0x01)) {
82
232
        ERR_raise(ERR_LIB_RSA, RSA_R_BLOCK_TYPE_IS_NOT_01);
83
232
        return -1;
84
232
    }
85
86
    /* scan over padding data */
87
835
    j = flen - 1;               /* one for type. */
88
119k
    for (i = 0; i < j; i++) {
89
119k
        if (*p != 0xff) {       /* should decrypt to 0xff */
90
823
            if (*p == 0) {
91
723
                p++;
92
723
                break;
93
723
            } else {
94
100
                ERR_raise(ERR_LIB_RSA, RSA_R_BAD_FIXED_HEADER_DECRYPT);
95
100
                return -1;
96
100
            }
97
823
        }
98
118k
        p++;
99
118k
    }
100
101
735
    if (i == j) {
102
12
        ERR_raise(ERR_LIB_RSA, RSA_R_NULL_BEFORE_BLOCK_MISSING);
103
12
        return -1;
104
12
    }
105
106
723
    if (i < 8) {
107
40
        ERR_raise(ERR_LIB_RSA, RSA_R_BAD_PAD_BYTE_COUNT);
108
40
        return -1;
109
40
    }
110
683
    i++;                        /* Skip over the '\0' */
111
683
    j -= i;
112
683
    if (j > tlen) {
113
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE);
114
0
        return -1;
115
0
    }
116
683
    memcpy(to, p, (unsigned int)j);
117
118
683
    return j;
119
683
}
120
121
int ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX *libctx, unsigned char *to,
122
                                         int tlen, const unsigned char *from,
123
                                         int flen)
124
1.35k
{
125
1.35k
    int i, j;
126
1.35k
    unsigned char *p;
127
128
1.35k
    if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
129
15
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
130
15
        return 0;
131
1.33k
    } else if (flen < 0) {
132
0
        ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH);
133
0
        return 0;
134
0
    }
135
136
1.33k
    p = (unsigned char *)to;
137
138
1.33k
    *(p++) = 0;
139
1.33k
    *(p++) = 2;                 /* Public Key BT (Block Type) */
140
141
    /* pad out with non-zero random data */
142
1.33k
    j = tlen - 3 - flen;
143
144
1.33k
    if (RAND_bytes_ex(libctx, p, j, 0) <= 0)
145
0
        return 0;
146
101k
    for (i = 0; i < j; i++) {
147
99.6k
        if (*p == '\0')
148
0
            do {
149
0
                if (RAND_bytes_ex(libctx, p, 1, 0) <= 0)
150
0
                    return 0;
151
0
            } while (*p == '\0');
152
99.6k
        p++;
153
99.6k
    }
154
155
1.33k
    *(p++) = '\0';
156
157
1.33k
    memcpy(p, from, (unsigned int)flen);
158
1.33k
    return 1;
159
1.33k
}
160
161
int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
162
                                 const unsigned char *from, int flen)
163
0
{
164
0
    return ossl_rsa_padding_add_PKCS1_type_2_ex(NULL, to, tlen, from, flen);
165
0
}
166
167
int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
168
                                   const unsigned char *from, int flen,
169
                                   int num)
170
0
{
171
0
    int i;
172
    /* |em| is the encoded message, zero-padded to exactly |num| bytes */
173
0
    unsigned char *em = NULL;
174
0
    unsigned int good, found_zero_byte, mask;
175
0
    int zero_index = 0, msg_index, mlen = -1;
176
177
0
    if (tlen <= 0 || flen <= 0)
178
0
        return -1;
179
180
    /*
181
     * PKCS#1 v1.5 decryption. See "PKCS #1 v2.2: RSA Cryptography Standard",
182
     * section 7.2.2.
183
     */
184
185
0
    if (flen > num || num < RSA_PKCS1_PADDING_SIZE) {
186
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
187
0
        return -1;
188
0
    }
189
190
0
    em = OPENSSL_malloc(num);
191
0
    if (em == NULL) {
192
0
        ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
193
0
        return -1;
194
0
    }
195
    /*
196
     * Caller is encouraged to pass zero-padded message created with
197
     * BN_bn2binpad. Trouble is that since we can't read out of |from|'s
198
     * bounds, it's impossible to have an invariant memory access pattern
199
     * in case |from| was not zero-padded in advance.
200
     */
201
0
    for (from += flen, em += num, i = 0; i < num; i++) {
202
0
        mask = ~constant_time_is_zero(flen);
203
0
        flen -= 1 & mask;
204
0
        from -= 1 & mask;
205
0
        *--em = *from & mask;
206
0
    }
207
208
0
    good = constant_time_is_zero(em[0]);
209
0
    good &= constant_time_eq(em[1], 2);
210
211
    /* scan over padding data */
212
0
    found_zero_byte = 0;
213
0
    for (i = 2; i < num; i++) {
214
0
        unsigned int equals0 = constant_time_is_zero(em[i]);
215
216
0
        zero_index = constant_time_select_int(~found_zero_byte & equals0,
217
0
                                              i, zero_index);
218
0
        found_zero_byte |= equals0;
219
0
    }
220
221
    /*
222
     * PS must be at least 8 bytes long, and it starts two bytes into |em|.
223
     * If we never found a 0-byte, then |zero_index| is 0 and the check
224
     * also fails.
225
     */
226
0
    good &= constant_time_ge(zero_index, 2 + 8);
227
228
    /*
229
     * Skip the zero byte. This is incorrect if we never found a zero-byte
230
     * but in this case we also do not copy the message out.
231
     */
232
0
    msg_index = zero_index + 1;
233
0
    mlen = num - msg_index;
234
235
    /*
236
     * For good measure, do this check in constant time as well.
237
     */
238
0
    good &= constant_time_ge(tlen, mlen);
239
240
    /*
241
     * Move the result in-place by |num|-RSA_PKCS1_PADDING_SIZE-|mlen| bytes to the left.
242
     * Then if |good| move |mlen| bytes from |em|+RSA_PKCS1_PADDING_SIZE to |to|.
243
     * Otherwise leave |to| unchanged.
244
     * Copy the memory back in a way that does not reveal the size of
245
     * the data being copied via a timing side channel. This requires copying
246
     * parts of the buffer multiple times based on the bits set in the real
247
     * length. Clear bits do a non-copy with identical access pattern.
248
     * The loop below has overall complexity of O(N*log(N)).
249
     */
250
0
    tlen = constant_time_select_int(constant_time_lt(num - RSA_PKCS1_PADDING_SIZE, tlen),
251
0
                                    num - RSA_PKCS1_PADDING_SIZE, tlen);
252
0
    for (msg_index = 1; msg_index < num - RSA_PKCS1_PADDING_SIZE; msg_index <<= 1) {
253
0
        mask = ~constant_time_eq(msg_index & (num - RSA_PKCS1_PADDING_SIZE - mlen), 0);
254
0
        for (i = RSA_PKCS1_PADDING_SIZE; i < num - msg_index; i++)
255
0
            em[i] = constant_time_select_8(mask, em[i + msg_index], em[i]);
256
0
    }
257
0
    for (i = 0; i < tlen; i++) {
258
0
        mask = good & constant_time_lt(i, mlen);
259
0
        to[i] = constant_time_select_8(mask, em[i + RSA_PKCS1_PADDING_SIZE], to[i]);
260
0
    }
261
262
0
    OPENSSL_clear_free(em, num);
263
0
#ifndef FIPS_MODULE
264
    /*
265
     * This trick doesn't work in the FIPS provider because libcrypto manages
266
     * the error stack. Instead we opt not to put an error on the stack at all
267
     * in case of padding failure in the FIPS provider.
268
     */
269
0
    ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
270
0
    err_clear_last_constant_time(1 & good);
271
0
#endif
272
273
0
    return constant_time_select_int(good, mlen, -1);
274
0
}
275
276
/*
277
 * ossl_rsa_padding_check_PKCS1_type_2_TLS() checks and removes the PKCS1 type 2
278
 * padding from a decrypted RSA message in a TLS signature. The result is stored
279
 * in the buffer pointed to by |to| which should be |tlen| bytes long. |tlen|
280
 * must be at least SSL_MAX_MASTER_KEY_LENGTH. The original decrypted message
281
 * should be stored in |from| which must be |flen| bytes in length and padded
282
 * such that |flen == RSA_size()|. The TLS protocol version that the client
283
 * originally requested should be passed in |client_version|. Some buggy clients
284
 * can exist which use the negotiated version instead of the originally
285
 * requested protocol version. If it is necessary to work around this bug then
286
 * the negotiated protocol version can be passed in |alt_version|, otherwise 0
287
 * should be passed.
288
 *
289
 * If the passed message is publicly invalid or some other error that can be
290
 * treated in non-constant time occurs then -1 is returned. On success the
291
 * length of the decrypted data is returned. This will always be
292
 * SSL_MAX_MASTER_KEY_LENGTH. If an error occurs that should be treated in
293
 * constant time then this function will appear to return successfully, but the
294
 * decrypted data will be randomly generated (as per
295
 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1).
296
 */
297
int ossl_rsa_padding_check_PKCS1_type_2_TLS(OSSL_LIB_CTX *libctx,
298
                                            unsigned char *to, size_t tlen,
299
                                            const unsigned char *from,
300
                                            size_t flen, int client_version,
301
                                            int alt_version)
302
5.57k
{
303
5.57k
    unsigned int i, good, version_good;
304
5.57k
    unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
305
306
    /*
307
     * If these checks fail then either the message in publicly invalid, or
308
     * we've been called incorrectly. We can fail immediately.
309
     */
310
5.57k
    if (flen < RSA_PKCS1_PADDING_SIZE + SSL_MAX_MASTER_KEY_LENGTH
311
5.57k
            || tlen < SSL_MAX_MASTER_KEY_LENGTH) {
312
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
313
0
        return -1;
314
0
    }
315
316
    /*
317
     * Generate a random premaster secret to use in the event that we fail
318
     * to decrypt.
319
     */
320
5.57k
    if (RAND_priv_bytes_ex(libctx, rand_premaster_secret,
321
5.57k
                           sizeof(rand_premaster_secret), 0) <= 0) {
322
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
323
0
        return -1;
324
0
    }
325
326
5.57k
    good = constant_time_is_zero(from[0]);
327
5.57k
    good &= constant_time_eq(from[1], 2);
328
329
    /* Check we have the expected padding data */
330
1.14M
    for (i = 2; i < flen - SSL_MAX_MASTER_KEY_LENGTH - 1; i++)
331
1.14M
        good &= ~constant_time_is_zero_8(from[i]);
332
5.57k
    good &= constant_time_is_zero_8(from[flen - SSL_MAX_MASTER_KEY_LENGTH - 1]);
333
334
335
    /*
336
     * If the version in the decrypted pre-master secret is correct then
337
     * version_good will be 0xff, otherwise it'll be zero. The
338
     * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
339
     * (http://eprint.iacr.org/2003/052/) exploits the version number
340
     * check as a "bad version oracle". Thus version checks are done in
341
     * constant time and are treated like any other decryption error.
342
     */
343
5.57k
    version_good =
344
5.57k
        constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
345
5.57k
                         (client_version >> 8) & 0xff);
346
5.57k
    version_good &=
347
5.57k
        constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
348
5.57k
                         client_version & 0xff);
349
350
    /*
351
     * The premaster secret must contain the same version number as the
352
     * ClientHello to detect version rollback attacks (strangely, the
353
     * protocol does not offer such protection for DH ciphersuites).
354
     * However, buggy clients exist that send the negotiated protocol
355
     * version instead if the server does not support the requested
356
     * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set then we tolerate
357
     * such clients. In that case alt_version will be non-zero and set to
358
     * the negotiated version.
359
     */
360
5.57k
    if (alt_version > 0) {
361
0
        unsigned int workaround_good;
362
363
0
        workaround_good =
364
0
            constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
365
0
                             (alt_version >> 8) & 0xff);
366
0
        workaround_good &=
367
0
            constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
368
0
                             alt_version & 0xff);
369
0
        version_good |= workaround_good;
370
0
    }
371
372
5.57k
    good &= version_good;
373
374
375
    /*
376
     * Now copy the result over to the to buffer if good, or random data if
377
     * not good.
378
     */
379
273k
    for (i = 0; i < SSL_MAX_MASTER_KEY_LENGTH; i++) {
380
267k
        to[i] =
381
267k
            constant_time_select_8(good,
382
267k
                                   from[flen - SSL_MAX_MASTER_KEY_LENGTH + i],
383
267k
                                   rand_premaster_secret[i]);
384
267k
    }
385
386
    /*
387
     * We must not leak whether a decryption failure occurs because of
388
     * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
389
     * section 7.4.7.1). The code follows that advice of the TLS RFC and
390
     * generates a random premaster secret for the case that the decrypt
391
     * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
392
     * So, whether we actually succeeded or not, return success.
393
     */
394
395
5.57k
    return SSL_MAX_MASTER_KEY_LENGTH;
396
5.57k
}