Coverage Report

Created: 2025-12-10 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/crypto/rsa/rsa_pk1.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2023 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 <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"
30
31
int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
32
    const unsigned char *from, int flen)
33
0
{
34
0
    int j;
35
0
    unsigned char *p;
36
37
0
    if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
38
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
39
0
        return 0;
40
0
    }
41
42
0
    p = (unsigned char *)to;
43
44
0
    *(p++) = 0;
45
0
    *(p++) = 1; /* Private Key BT (Block Type) */
46
47
    /* pad out with 0xff data */
48
0
    j = tlen - 3 - flen;
49
0
    memset(p, 0xff, j);
50
0
    p += j;
51
0
    *(p++) = '\0';
52
0
    memcpy(p, from, (unsigned int)flen);
53
0
    return 1;
54
0
}
55
56
int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
57
    const unsigned char *from, int flen,
58
    int num)
59
0
{
60
0
    int i, j;
61
0
    const unsigned char *p;
62
63
0
    p = from;
64
65
    /*
66
     * The format is
67
     * 00 || 01 || PS || 00 || D
68
     * PS - padding string, at least 8 bytes of FF
69
     * D  - data.
70
     */
71
72
0
    if (num < RSA_PKCS1_PADDING_SIZE)
73
0
        return -1;
74
75
    /* Accept inputs with and without the leading 0-byte. */
76
0
    if (num == flen) {
77
0
        if ((*p++) != 0x00) {
78
0
            ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
79
0
            return -1;
80
0
        }
81
0
        flen--;
82
0
    }
83
84
0
    if ((num != (flen + 1)) || (*(p++) != 0x01)) {
85
0
        ERR_raise(ERR_LIB_RSA, RSA_R_BLOCK_TYPE_IS_NOT_01);
86
0
        return -1;
87
0
    }
88
89
    /* scan over padding data */
90
0
    j = flen - 1; /* one for type. */
91
0
    for (i = 0; i < j; i++) {
92
0
        if (*p != 0xff) { /* should decrypt to 0xff */
93
0
            if (*p == 0) {
94
0
                p++;
95
0
                break;
96
0
            } else {
97
0
                ERR_raise(ERR_LIB_RSA, RSA_R_BAD_FIXED_HEADER_DECRYPT);
98
0
                return -1;
99
0
            }
100
0
        }
101
0
        p++;
102
0
    }
103
104
0
    if (i == j) {
105
0
        ERR_raise(ERR_LIB_RSA, RSA_R_NULL_BEFORE_BLOCK_MISSING);
106
0
        return -1;
107
0
    }
108
109
0
    if (i < 8) {
110
0
        ERR_raise(ERR_LIB_RSA, RSA_R_BAD_PAD_BYTE_COUNT);
111
0
        return -1;
112
0
    }
113
0
    i++; /* Skip over the '\0' */
114
0
    j -= i;
115
0
    if (j > tlen) {
116
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE);
117
0
        return -1;
118
0
    }
119
0
    memcpy(to, p, (unsigned int)j);
120
121
0
    return j;
122
0
}
123
124
int ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX *libctx, unsigned char *to,
125
    int tlen, const unsigned char *from,
126
    int flen)
127
0
{
128
0
    int i, j;
129
0
    unsigned char *p;
130
131
0
    if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
132
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
133
0
        return 0;
134
0
    } else if (flen < 0) {
135
0
        ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH);
136
0
        return 0;
137
0
    }
138
139
0
    p = (unsigned char *)to;
140
141
0
    *(p++) = 0;
142
0
    *(p++) = 2; /* Public Key BT (Block Type) */
143
144
    /* pad out with non-zero random data */
145
0
    j = tlen - 3 - flen;
146
147
0
    if (RAND_bytes_ex(libctx, p, j, 0) <= 0)
148
0
        return 0;
149
0
    for (i = 0; i < j; i++) {
150
0
        if (*p == '\0')
151
0
            do {
152
0
                if (RAND_bytes_ex(libctx, p, 1, 0) <= 0)
153
0
                    return 0;
154
0
            } while (*p == '\0');
155
0
        p++;
156
0
    }
157
158
0
    *(p++) = '\0';
159
160
0
    memcpy(p, from, (unsigned int)flen);
161
0
    return 1;
162
0
}
163
164
int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
165
    const unsigned char *from, int flen)
166
0
{
167
0
    return ossl_rsa_padding_add_PKCS1_type_2_ex(NULL, to, tlen, from, flen);
168
0
}
169
170
int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
171
    const unsigned char *from, int flen,
172
    int num)
173
0
{
174
0
    int i;
175
    /* |em| is the encoded message, zero-padded to exactly |num| bytes */
176
0
    unsigned char *em = NULL;
177
0
    unsigned int good, found_zero_byte, mask;
178
0
    int zero_index = 0, msg_index, mlen = -1;
179
180
0
    if (tlen <= 0 || flen <= 0)
181
0
        return -1;
182
183
    /*
184
     * PKCS#1 v1.5 decryption. See "PKCS #1 v2.2: RSA Cryptography Standard",
185
     * section 7.2.2.
186
     */
187
188
0
    if (flen > num || num < RSA_PKCS1_PADDING_SIZE) {
189
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
190
0
        return -1;
191
0
    }
192
193
0
    em = OPENSSL_malloc(num);
194
0
    if (em == NULL)
195
0
        return -1;
196
    /*
197
     * Caller is encouraged to pass zero-padded message created with
198
     * BN_bn2binpad. Trouble is that since we can't read out of |from|'s
199
     * bounds, it's impossible to have an invariant memory access pattern
200
     * in case |from| was not zero-padded in advance.
201
     */
202
0
    for (from += flen, em += num, i = 0; i < num; i++) {
203
0
        mask = ~constant_time_is_zero(flen);
204
0
        flen -= 1 & mask;
205
0
        from -= 1 & mask;
206
0
        *--em = *from & mask;
207
0
    }
208
209
0
    good = constant_time_is_zero(em[0]);
210
0
    good &= constant_time_eq(em[1], 2);
211
212
    /* scan over padding data */
213
0
    found_zero_byte = 0;
214
0
    for (i = 2; i < num; i++) {
215
0
        unsigned int equals0 = constant_time_is_zero(em[i]);
216
217
0
        zero_index = constant_time_select_int(~found_zero_byte & equals0,
218
0
            i, zero_index);
219
0
        found_zero_byte |= equals0;
220
0
    }
221
222
    /*
223
     * PS must be at least 8 bytes long, and it starts two bytes into |em|.
224
     * If we never found a 0-byte, then |zero_index| is 0 and the check
225
     * also fails.
226
     */
227
0
    good &= constant_time_ge(zero_index, 2 + 8);
228
229
    /*
230
     * Skip the zero byte. This is incorrect if we never found a zero-byte
231
     * but in this case we also do not copy the message out.
232
     */
233
0
    msg_index = zero_index + 1;
234
0
    mlen = num - msg_index;
235
236
    /*
237
     * For good measure, do this check in constant time as well.
238
     */
239
0
    good &= constant_time_ge(tlen, mlen);
240
241
    /*
242
     * Move the result in-place by |num|-RSA_PKCS1_PADDING_SIZE-|mlen| bytes to the left.
243
     * Then if |good| move |mlen| bytes from |em|+RSA_PKCS1_PADDING_SIZE to |to|.
244
     * Otherwise leave |to| unchanged.
245
     * Copy the memory back in a way that does not reveal the size of
246
     * the data being copied via a timing side channel. This requires copying
247
     * parts of the buffer multiple times based on the bits set in the real
248
     * length. Clear bits do a non-copy with identical access pattern.
249
     * The loop below has overall complexity of O(N*log(N)).
250
     */
251
0
    tlen = constant_time_select_int(constant_time_lt(num - RSA_PKCS1_PADDING_SIZE, tlen),
252
0
        num - RSA_PKCS1_PADDING_SIZE, tlen);
253
0
    for (msg_index = 1; msg_index < num - RSA_PKCS1_PADDING_SIZE; msg_index <<= 1) {
254
0
        mask = ~constant_time_eq(msg_index & (num - RSA_PKCS1_PADDING_SIZE - mlen), 0);
255
0
        for (i = RSA_PKCS1_PADDING_SIZE; i < num - msg_index; i++)
256
0
            em[i] = constant_time_select_8(mask, em[i + msg_index], em[i]);
257
0
    }
258
0
    for (i = 0; i < tlen; i++) {
259
0
        mask = good & constant_time_lt(i, mlen);
260
0
        to[i] = constant_time_select_8(mask, em[i + RSA_PKCS1_PADDING_SIZE], to[i]);
261
0
    }
262
263
0
    OPENSSL_clear_free(em, num);
264
0
#ifndef FIPS_MODULE
265
    /*
266
     * This trick doesn't work in the FIPS provider because libcrypto manages
267
     * the error stack. Instead we opt not to put an error on the stack at all
268
     * in case of padding failure in the FIPS provider.
269
     */
270
0
    ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
271
0
    err_clear_last_constant_time(1 & good);
272
0
#endif
273
274
0
    return constant_time_select_int(good, mlen, -1);
275
0
}
276
277
static int ossl_rsa_prf(OSSL_LIB_CTX *ctx,
278
    unsigned char *to, int tlen,
279
    const char *label, int llen,
280
    const unsigned char *kdk,
281
    uint16_t bitlen)
282
0
{
283
0
    int pos;
284
0
    int ret = -1;
285
0
    uint16_t iter = 0;
286
0
    unsigned char be_iter[sizeof(iter)];
287
0
    unsigned char be_bitlen[sizeof(bitlen)];
288
0
    HMAC_CTX *hmac = NULL;
289
0
    EVP_MD *md = NULL;
290
0
    unsigned char hmac_out[SHA256_DIGEST_LENGTH];
291
0
    unsigned int md_len;
292
293
0
    if (tlen * 8 != bitlen) {
294
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
295
0
        return ret;
296
0
    }
297
298
0
    be_bitlen[0] = (bitlen >> 8) & 0xff;
299
0
    be_bitlen[1] = bitlen & 0xff;
300
301
0
    hmac = HMAC_CTX_new();
302
0
    if (hmac == NULL) {
303
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
304
0
        goto err;
305
0
    }
306
307
    /*
308
     * we use hardcoded hash so that migrating between versions that use
309
     * different hash doesn't provide a Bleichenbacher oracle:
310
     * if the attacker can see that different versions return different
311
     * messages for the same ciphertext, they'll know that the message is
312
     * synthetically generated, which means that the padding check failed
313
     */
314
0
    md = EVP_MD_fetch(ctx, "sha256", NULL);
315
0
    if (md == NULL) {
316
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
317
0
        goto err;
318
0
    }
319
320
0
    if (HMAC_Init_ex(hmac, kdk, SHA256_DIGEST_LENGTH, md, NULL) <= 0) {
321
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
322
0
        goto err;
323
0
    }
324
325
0
    for (pos = 0; pos < tlen; pos += SHA256_DIGEST_LENGTH, iter++) {
326
0
        if (HMAC_Init_ex(hmac, NULL, 0, NULL, NULL) <= 0) {
327
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
328
0
            goto err;
329
0
        }
330
331
0
        be_iter[0] = (iter >> 8) & 0xff;
332
0
        be_iter[1] = iter & 0xff;
333
334
0
        if (HMAC_Update(hmac, be_iter, sizeof(be_iter)) <= 0) {
335
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
336
0
            goto err;
337
0
        }
338
0
        if (HMAC_Update(hmac, (unsigned char *)label, llen) <= 0) {
339
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
340
0
            goto err;
341
0
        }
342
0
        if (HMAC_Update(hmac, be_bitlen, sizeof(be_bitlen)) <= 0) {
343
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
344
0
            goto err;
345
0
        }
346
347
        /*
348
         * HMAC_Final requires the output buffer to fit the whole MAC
349
         * value, so we need to use the intermediate buffer for the last
350
         * unaligned block
351
         */
352
0
        md_len = SHA256_DIGEST_LENGTH;
353
0
        if (pos + SHA256_DIGEST_LENGTH > tlen) {
354
0
            if (HMAC_Final(hmac, hmac_out, &md_len) <= 0) {
355
0
                ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
356
0
                goto err;
357
0
            }
358
0
            memcpy(to + pos, hmac_out, tlen - pos);
359
0
        } else {
360
0
            if (HMAC_Final(hmac, to + pos, &md_len) <= 0) {
361
0
                ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
362
0
                goto err;
363
0
            }
364
0
        }
365
0
    }
366
367
0
    ret = 0;
368
369
0
err:
370
0
    HMAC_CTX_free(hmac);
371
0
    EVP_MD_free(md);
372
0
    return ret;
373
0
}
374
375
/*
376
 * ossl_rsa_padding_check_PKCS1_type_2() checks and removes the PKCS#1 type 2
377
 * padding from a decrypted RSA message. Unlike the
378
 * RSA_padding_check_PKCS1_type_2() it will not return an error in case it
379
 * detects a padding error, rather it will return a deterministically generated
380
 * random message. In other words it will perform an implicit rejection
381
 * of an invalid padding. This means that the returned value does not indicate
382
 * if the padding of the encrypted message was correct or not, making
383
 * side channel attacks like the ones described by Bleichenbacher impossible
384
 * without access to the full decrypted value and a brute-force search of
385
 * remaining padding bytes
386
 */
387
int ossl_rsa_padding_check_PKCS1_type_2(OSSL_LIB_CTX *ctx,
388
    unsigned char *to, int tlen,
389
    const unsigned char *from, int flen,
390
    int num, unsigned char *kdk)
391
0
{
392
/*
393
 * We need to generate a random length for the synthetic message, to avoid
394
 * bias towards zero and avoid non-constant timeness of DIV, we prepare
395
 * 128 values to check if they are not too large for the used key size,
396
 * and use 0 in case none of them are small enough, as 2^-128 is a good enough
397
 * safety margin
398
 */
399
0
#define MAX_LEN_GEN_TRIES 128
400
0
    unsigned char *synthetic = NULL;
401
0
    int synthetic_length;
402
0
    uint16_t len_candidate;
403
0
    unsigned char candidate_lengths[MAX_LEN_GEN_TRIES * sizeof(len_candidate)];
404
0
    uint16_t len_mask;
405
0
    uint16_t max_sep_offset;
406
0
    int synth_msg_index = 0;
407
0
    int ret = -1;
408
0
    int i, j;
409
0
    unsigned int good, found_zero_byte;
410
0
    int zero_index = 0, msg_index;
411
412
    /*
413
     * If these checks fail then either the message in publicly invalid, or
414
     * we've been called incorrectly. We can fail immediately.
415
     * Since this code is called only internally by openssl, those are just
416
     * sanity checks
417
     */
418
0
    if (num != flen || tlen <= 0 || flen <= 0) {
419
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
420
0
        return -1;
421
0
    }
422
423
    /* Generate a random message to return in case the padding checks fail */
424
0
    synthetic = OPENSSL_malloc(flen);
425
0
    if (synthetic == NULL) {
426
0
        ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
427
0
        return -1;
428
0
    }
429
430
0
    if (ossl_rsa_prf(ctx, synthetic, flen, "message", 7, kdk, flen * 8) < 0)
431
0
        goto err;
432
433
    /* decide how long the random message should be */
434
0
    if (ossl_rsa_prf(ctx, candidate_lengths, sizeof(candidate_lengths),
435
0
            "length", 6, kdk,
436
0
            MAX_LEN_GEN_TRIES * sizeof(len_candidate) * 8)
437
0
        < 0)
438
0
        goto err;
439
440
    /*
441
     * max message size is the size of the modulus size less 2 bytes for
442
     * version and padding type and a minimum of 8 bytes padding
443
     */
444
0
    len_mask = max_sep_offset = flen - 2 - 8;
445
    /*
446
     * we want a mask so lets propagate the high bit to all positions less
447
     * significant than it
448
     */
449
0
    len_mask |= len_mask >> 1;
450
0
    len_mask |= len_mask >> 2;
451
0
    len_mask |= len_mask >> 4;
452
0
    len_mask |= len_mask >> 8;
453
454
0
    synthetic_length = 0;
455
0
    for (i = 0; i < MAX_LEN_GEN_TRIES * (int)sizeof(len_candidate);
456
0
        i += sizeof(len_candidate)) {
457
0
        len_candidate = (candidate_lengths[i] << 8) | candidate_lengths[i + 1];
458
0
        len_candidate &= len_mask;
459
460
0
        synthetic_length = constant_time_select_int(
461
0
            constant_time_lt(len_candidate, max_sep_offset),
462
0
            len_candidate, synthetic_length);
463
0
    }
464
465
0
    synth_msg_index = flen - synthetic_length;
466
467
    /* we have alternative message ready, check the real one */
468
0
    good = constant_time_is_zero(from[0]);
469
0
    good &= constant_time_eq(from[1], 2);
470
471
    /* then look for the padding|message separator (the first zero byte) */
472
0
    found_zero_byte = 0;
473
0
    for (i = 2; i < flen; i++) {
474
0
        unsigned int equals0 = constant_time_is_zero(from[i]);
475
0
        zero_index = constant_time_select_int(~found_zero_byte & equals0,
476
0
            i, zero_index);
477
0
        found_zero_byte |= equals0;
478
0
    }
479
480
    /*
481
     * padding must be at least 8 bytes long, and it starts two bytes into
482
     * |from|. If we never found a 0-byte, then |zero_index| is 0 and the check
483
     * also fails.
484
     */
485
0
    good &= constant_time_ge(zero_index, 2 + 8);
486
487
    /*
488
     * Skip the zero byte. This is incorrect if we never found a zero-byte
489
     * but in this case we also do not copy the message out.
490
     */
491
0
    msg_index = zero_index + 1;
492
493
    /*
494
     * old code returned an error in case the decrypted message wouldn't fit
495
     * into the |to|, since that would leak information, return the synthetic
496
     * message instead
497
     */
498
0
    good &= constant_time_ge(tlen, num - msg_index);
499
500
0
    msg_index = constant_time_select_int(good, msg_index, synth_msg_index);
501
502
    /*
503
     * since at this point the |msg_index| does not provide the signal
504
     * indicating if the padding check failed or not, we don't have to worry
505
     * about leaking the length of returned message, we still need to ensure
506
     * that we read contents of both buffers so that cache accesses don't leak
507
     * the value of |good|
508
     */
509
0
    for (i = msg_index, j = 0; i < flen && j < tlen; i++, j++)
510
0
        to[j] = constant_time_select_8(good, from[i], synthetic[i]);
511
0
    ret = j;
512
513
0
err:
514
    /*
515
     * the only time ret < 0 is when the ciphertext is publicly invalid
516
     * or we were called with invalid parameters, so we don't have to perform
517
     * a side-channel secure raising of the error
518
     */
519
0
    if (ret < 0)
520
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
521
0
    OPENSSL_free(synthetic);
522
0
    return ret;
523
0
}
524
525
/*
526
 * ossl_rsa_padding_check_PKCS1_type_2_TLS() checks and removes the PKCS1 type 2
527
 * padding from a decrypted RSA message in a TLS signature. The result is stored
528
 * in the buffer pointed to by |to| which should be |tlen| bytes long. |tlen|
529
 * must be at least SSL_MAX_MASTER_KEY_LENGTH. The original decrypted message
530
 * should be stored in |from| which must be |flen| bytes in length and padded
531
 * such that |flen == RSA_size()|. The TLS protocol version that the client
532
 * originally requested should be passed in |client_version|. Some buggy clients
533
 * can exist which use the negotiated version instead of the originally
534
 * requested protocol version. If it is necessary to work around this bug then
535
 * the negotiated protocol version can be passed in |alt_version|, otherwise 0
536
 * should be passed.
537
 *
538
 * If the passed message is publicly invalid or some other error that can be
539
 * treated in non-constant time occurs then -1 is returned. On success the
540
 * length of the decrypted data is returned. This will always be
541
 * SSL_MAX_MASTER_KEY_LENGTH. If an error occurs that should be treated in
542
 * constant time then this function will appear to return successfully, but the
543
 * decrypted data will be randomly generated (as per
544
 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1).
545
 */
546
int ossl_rsa_padding_check_PKCS1_type_2_TLS(OSSL_LIB_CTX *libctx,
547
    unsigned char *to, size_t tlen,
548
    const unsigned char *from,
549
    size_t flen, int client_version,
550
    int alt_version)
551
0
{
552
0
    unsigned int i, good, version_good;
553
0
    unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
554
555
    /*
556
     * If these checks fail then either the message in publicly invalid, or
557
     * we've been called incorrectly. We can fail immediately.
558
     */
559
0
    if (flen < RSA_PKCS1_PADDING_SIZE + SSL_MAX_MASTER_KEY_LENGTH
560
0
        || tlen < SSL_MAX_MASTER_KEY_LENGTH) {
561
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
562
0
        return -1;
563
0
    }
564
565
    /*
566
     * Generate a random premaster secret to use in the event that we fail
567
     * to decrypt.
568
     */
569
0
    if (RAND_priv_bytes_ex(libctx, rand_premaster_secret,
570
0
            sizeof(rand_premaster_secret), 0)
571
0
        <= 0) {
572
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
573
0
        return -1;
574
0
    }
575
576
0
    good = constant_time_is_zero(from[0]);
577
0
    good &= constant_time_eq(from[1], 2);
578
579
    /* Check we have the expected padding data */
580
0
    for (i = 2; i < flen - SSL_MAX_MASTER_KEY_LENGTH - 1; i++)
581
0
        good &= ~constant_time_is_zero_8(from[i]);
582
0
    good &= constant_time_is_zero_8(from[flen - SSL_MAX_MASTER_KEY_LENGTH - 1]);
583
584
    /*
585
     * If the version in the decrypted pre-master secret is correct then
586
     * version_good will be 0xff, otherwise it'll be zero. The
587
     * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
588
     * (http://eprint.iacr.org/2003/052/) exploits the version number
589
     * check as a "bad version oracle". Thus version checks are done in
590
     * constant time and are treated like any other decryption error.
591
     */
592
0
    version_good = constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
593
0
        (client_version >> 8) & 0xff);
594
0
    version_good &= constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
595
0
        client_version & 0xff);
596
597
    /*
598
     * The premaster secret must contain the same version number as the
599
     * ClientHello to detect version rollback attacks (strangely, the
600
     * protocol does not offer such protection for DH ciphersuites).
601
     * However, buggy clients exist that send the negotiated protocol
602
     * version instead if the server does not support the requested
603
     * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set then we tolerate
604
     * such clients. In that case alt_version will be non-zero and set to
605
     * the negotiated version.
606
     */
607
0
    if (alt_version > 0) {
608
0
        unsigned int workaround_good;
609
610
0
        workaround_good = constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
611
0
            (alt_version >> 8) & 0xff);
612
0
        workaround_good &= constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
613
0
            alt_version & 0xff);
614
0
        version_good |= workaround_good;
615
0
    }
616
617
0
    good &= version_good;
618
619
    /*
620
     * Now copy the result over to the to buffer if good, or random data if
621
     * not good.
622
     */
623
0
    for (i = 0; i < SSL_MAX_MASTER_KEY_LENGTH; i++) {
624
0
        to[i] = constant_time_select_8(good,
625
0
            from[flen - SSL_MAX_MASTER_KEY_LENGTH + i],
626
0
            rand_premaster_secret[i]);
627
0
    }
628
629
    /*
630
     * We must not leak whether a decryption failure occurs because of
631
     * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
632
     * section 7.4.7.1). The code follows that advice of the TLS RFC and
633
     * generates a random premaster secret for the case that the decrypt
634
     * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
635
     * So, whether we actually succeeded or not, return success.
636
     */
637
638
0
    return SSL_MAX_MASTER_KEY_LENGTH;
639
0
}