Coverage Report

Created: 2024-11-21 07:03

/src/openssl/crypto/rsa/rsa_pk1.c
Line
Count
Source (jump to first uncovered line)
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
32
int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
33
                                 const unsigned char *from, int flen)
34
0
{
35
0
    int j;
36
0
    unsigned char *p;
37
38
0
    if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
39
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
40
0
        return 0;
41
0
    }
42
43
0
    p = (unsigned char *)to;
44
45
0
    *(p++) = 0;
46
0
    *(p++) = 1;                 /* Private Key BT (Block Type) */
47
48
    /* pad out with 0xff data */
49
0
    j = tlen - 3 - flen;
50
0
    memset(p, 0xff, j);
51
0
    p += j;
52
0
    *(p++) = '\0';
53
0
    memcpy(p, from, (unsigned int)flen);
54
0
    return 1;
55
0
}
56
57
int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
58
                                   const unsigned char *from, int flen,
59
                                   int num)
60
0
{
61
0
    int i, j;
62
0
    const unsigned char *p;
63
64
0
    p = from;
65
66
    /*
67
     * The format is
68
     * 00 || 01 || PS || 00 || D
69
     * PS - padding string, at least 8 bytes of FF
70
     * D  - data.
71
     */
72
73
0
    if (num < RSA_PKCS1_PADDING_SIZE)
74
0
        return -1;
75
76
    /* Accept inputs with and without the leading 0-byte. */
77
0
    if (num == flen) {
78
0
        if ((*p++) != 0x00) {
79
0
            ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
80
0
            return -1;
81
0
        }
82
0
        flen--;
83
0
    }
84
85
0
    if ((num != (flen + 1)) || (*(p++) != 0x01)) {
86
0
        ERR_raise(ERR_LIB_RSA, RSA_R_BLOCK_TYPE_IS_NOT_01);
87
0
        return -1;
88
0
    }
89
90
    /* scan over padding data */
91
0
    j = flen - 1;               /* one for type. */
92
0
    for (i = 0; i < j; i++) {
93
0
        if (*p != 0xff) {       /* should decrypt to 0xff */
94
0
            if (*p == 0) {
95
0
                p++;
96
0
                break;
97
0
            } else {
98
0
                ERR_raise(ERR_LIB_RSA, RSA_R_BAD_FIXED_HEADER_DECRYPT);
99
0
                return -1;
100
0
            }
101
0
        }
102
0
        p++;
103
0
    }
104
105
0
    if (i == j) {
106
0
        ERR_raise(ERR_LIB_RSA, RSA_R_NULL_BEFORE_BLOCK_MISSING);
107
0
        return -1;
108
0
    }
109
110
0
    if (i < 8) {
111
0
        ERR_raise(ERR_LIB_RSA, RSA_R_BAD_PAD_BYTE_COUNT);
112
0
        return -1;
113
0
    }
114
0
    i++;                        /* Skip over the '\0' */
115
0
    j -= i;
116
0
    if (j > tlen) {
117
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE);
118
0
        return -1;
119
0
    }
120
0
    memcpy(to, p, (unsigned int)j);
121
122
0
    return j;
123
0
}
124
125
int ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX *libctx, unsigned char *to,
126
                                         int tlen, const unsigned char *from,
127
                                         int flen)
128
0
{
129
0
    int i, j;
130
0
    unsigned char *p;
131
132
0
    if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
133
0
        ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
134
0
        return 0;
135
0
    } else if (flen < 0) {
136
0
        ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH);
137
0
        return 0;
138
0
    }
139
140
0
    p = (unsigned char *)to;
141
142
0
    *(p++) = 0;
143
0
    *(p++) = 2;                 /* Public Key BT (Block Type) */
144
145
    /* pad out with non-zero random data */
146
0
    j = tlen - 3 - flen;
147
148
0
    if (RAND_bytes_ex(libctx, p, j, 0) <= 0)
149
0
        return 0;
150
0
    for (i = 0; i < j; i++) {
151
0
        if (*p == '\0')
152
0
            do {
153
0
                if (RAND_bytes_ex(libctx, p, 1, 0) <= 0)
154
0
                    return 0;
155
0
            } while (*p == '\0');
156
0
        p++;
157
0
    }
158
159
0
    *(p++) = '\0';
160
161
0
    memcpy(p, from, (unsigned int)flen);
162
0
    return 1;
163
0
}
164
165
int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
166
                                 const unsigned char *from, int flen)
167
0
{
168
0
    return ossl_rsa_padding_add_PKCS1_type_2_ex(NULL, to, tlen, from, flen);
169
0
}
170
171
int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
172
                                   const unsigned char *from, int flen,
173
                                   int num)
174
0
{
175
0
    int i;
176
    /* |em| is the encoded message, zero-padded to exactly |num| bytes */
177
0
    unsigned char *em = NULL;
178
0
    unsigned int good, found_zero_byte, mask;
179
0
    int zero_index = 0, msg_index, mlen = -1;
180
181
0
    if (tlen <= 0 || flen <= 0)
182
0
        return -1;
183
184
    /*
185
     * PKCS#1 v1.5 decryption. See "PKCS #1 v2.2: RSA Cryptography Standard",
186
     * section 7.2.2.
187
     */
188
189
0
    if (flen > num || num < RSA_PKCS1_PADDING_SIZE) {
190
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
191
0
        return -1;
192
0
    }
193
194
0
    em = OPENSSL_malloc(num);
195
0
    if (em == NULL)
196
0
        return -1;
197
    /*
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.
202
     */
203
0
    for (from += flen, em += num, i = 0; i < num; i++) {
204
0
        mask = ~constant_time_is_zero(flen);
205
0
        flen -= 1 & mask;
206
0
        from -= 1 & mask;
207
0
        *--em = *from & mask;
208
0
    }
209
210
0
    good = constant_time_is_zero(em[0]);
211
0
    good &= constant_time_eq(em[1], 2);
212
213
    /* scan over padding data */
214
0
    found_zero_byte = 0;
215
0
    for (i = 2; i < num; i++) {
216
0
        unsigned int equals0 = constant_time_is_zero(em[i]);
217
218
0
        zero_index = constant_time_select_int(~found_zero_byte & equals0,
219
0
                                              i, zero_index);
220
0
        found_zero_byte |= equals0;
221
0
    }
222
223
    /*
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
226
     * also fails.
227
     */
228
0
    good &= constant_time_ge(zero_index, 2 + 8);
229
230
    /*
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.
233
     */
234
0
    msg_index = zero_index + 1;
235
0
    mlen = num - msg_index;
236
237
    /*
238
     * For good measure, do this check in constant time as well.
239
     */
240
0
    good &= constant_time_ge(tlen, mlen);
241
242
    /*
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)).
251
     */
252
0
    tlen = constant_time_select_int(constant_time_lt(num - RSA_PKCS1_PADDING_SIZE, tlen),
253
0
                                    num - RSA_PKCS1_PADDING_SIZE, tlen);
254
0
    for (msg_index = 1; msg_index < num - RSA_PKCS1_PADDING_SIZE; msg_index <<= 1) {
255
0
        mask = ~constant_time_eq(msg_index & (num - RSA_PKCS1_PADDING_SIZE - mlen), 0);
256
0
        for (i = RSA_PKCS1_PADDING_SIZE; i < num - msg_index; i++)
257
0
            em[i] = constant_time_select_8(mask, em[i + msg_index], em[i]);
258
0
    }
259
0
    for (i = 0; i < tlen; i++) {
260
0
        mask = good & constant_time_lt(i, mlen);
261
0
        to[i] = constant_time_select_8(mask, em[i + RSA_PKCS1_PADDING_SIZE], to[i]);
262
0
    }
263
264
0
    OPENSSL_clear_free(em, num);
265
0
#ifndef FIPS_MODULE
266
    /*
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.
270
     */
271
0
    ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
272
0
    err_clear_last_constant_time(1 & good);
273
0
#endif
274
275
0
    return constant_time_select_int(good, mlen, -1);
276
0
}
277
278
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,
283
                        uint16_t bitlen)
284
0
{
285
0
    int pos;
286
0
    int ret = -1;
287
0
    uint16_t iter = 0;
288
0
    unsigned char be_iter[sizeof(iter)];
289
0
    unsigned char be_bitlen[sizeof(bitlen)];
290
0
    HMAC_CTX *hmac = NULL;
291
0
    EVP_MD *md = NULL;
292
0
    unsigned char hmac_out[SHA256_DIGEST_LENGTH];
293
0
    unsigned int md_len;
294
295
0
    if (tlen * 8 != bitlen) {
296
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
297
0
        return ret;
298
0
    }
299
300
0
    be_bitlen[0] = (bitlen >> 8) & 0xff;
301
0
    be_bitlen[1] = bitlen & 0xff;
302
303
0
    hmac = HMAC_CTX_new();
304
0
    if (hmac == NULL) {
305
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
306
0
        goto err;
307
0
    }
308
309
    /*
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
315
     */
316
0
    md = EVP_MD_fetch(ctx, "sha256", NULL);
317
0
    if (md == NULL) {
318
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
319
0
        goto err;
320
0
    }
321
322
0
    if (HMAC_Init_ex(hmac, kdk, SHA256_DIGEST_LENGTH, md, NULL) <= 0) {
323
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
324
0
        goto err;
325
0
    }
326
327
0
    for (pos = 0; pos < tlen; pos += SHA256_DIGEST_LENGTH, iter++) {
328
0
        if (HMAC_Init_ex(hmac, NULL, 0, NULL, NULL) <= 0) {
329
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
330
0
            goto err;
331
0
        }
332
333
0
        be_iter[0] = (iter >> 8) & 0xff;
334
0
        be_iter[1] = iter & 0xff;
335
336
0
        if (HMAC_Update(hmac, be_iter, sizeof(be_iter)) <= 0) {
337
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
338
0
            goto err;
339
0
        }
340
0
        if (HMAC_Update(hmac, (unsigned char *)label, llen) <= 0) {
341
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
342
0
            goto err;
343
0
        }
344
0
        if (HMAC_Update(hmac, be_bitlen, sizeof(be_bitlen)) <= 0) {
345
0
            ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
346
0
            goto err;
347
0
        }
348
349
        /*
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
352
         * unaligned block
353
         */
354
0
        md_len = SHA256_DIGEST_LENGTH;
355
0
        if (pos + SHA256_DIGEST_LENGTH > tlen) {
356
0
            if (HMAC_Final(hmac, hmac_out, &md_len) <= 0) {
357
0
                ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
358
0
                goto err;
359
0
            }
360
0
            memcpy(to + pos, hmac_out, tlen - pos);
361
0
        } else {
362
0
            if (HMAC_Final(hmac, to + pos, &md_len) <= 0) {
363
0
                ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
364
0
                goto err;
365
0
            }
366
0
        }
367
0
    }
368
369
0
    ret = 0;
370
371
0
err:
372
0
    HMAC_CTX_free(hmac);
373
0
    EVP_MD_free(md);
374
0
    return ret;
375
0
}
376
377
/*
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
388
 */
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)
393
0
{
394
/*
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
399
 * safety margin
400
 */
401
0
#define MAX_LEN_GEN_TRIES 128
402
0
    unsigned char *synthetic = NULL;
403
0
    int synthetic_length;
404
0
    uint16_t len_candidate;
405
0
    unsigned char candidate_lengths[MAX_LEN_GEN_TRIES * sizeof(len_candidate)];
406
0
    uint16_t len_mask;
407
0
    uint16_t max_sep_offset;
408
0
    int synth_msg_index = 0;
409
0
    int ret = -1;
410
0
    int i, j;
411
0
    unsigned int good, found_zero_byte;
412
0
    int zero_index = 0, msg_index;
413
414
    /*
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
418
     * sanity checks
419
     */
420
0
    if (num != flen || tlen <= 0 || flen <= 0) {
421
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
422
0
        return -1;
423
0
    }
424
425
    /* Generate a random message to return in case the padding checks fail */
426
0
    synthetic = OPENSSL_malloc(flen);
427
0
    if (synthetic == NULL) {
428
0
        ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
429
0
        return -1;
430
0
    }
431
432
0
    if (ossl_rsa_prf(ctx, synthetic, flen, "message", 7, kdk, flen * 8) < 0)
433
0
        goto err;
434
435
    /* decide how long the random message should be */
436
0
    if (ossl_rsa_prf(ctx, candidate_lengths, sizeof(candidate_lengths),
437
0
                     "length", 6, kdk,
438
0
                     MAX_LEN_GEN_TRIES * sizeof(len_candidate) * 8) < 0)
439
0
        goto err;
440
441
    /*
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
444
     */
445
0
    len_mask = max_sep_offset = flen - 2 - 8;
446
    /*
447
     * we want a mask so lets propagate the high bit to all positions less
448
     * significant than it
449
     */
450
0
    len_mask |= len_mask >> 1;
451
0
    len_mask |= len_mask >> 2;
452
0
    len_mask |= len_mask >> 4;
453
0
    len_mask |= len_mask >> 8;
454
455
0
    synthetic_length = 0;
456
0
    for (i = 0; i < MAX_LEN_GEN_TRIES * (int)sizeof(len_candidate);
457
0
            i += sizeof(len_candidate)) {
458
0
        len_candidate = (candidate_lengths[i] << 8) | candidate_lengths[i + 1];
459
0
        len_candidate &= len_mask;
460
461
0
        synthetic_length = constant_time_select_int(
462
0
            constant_time_lt(len_candidate, max_sep_offset),
463
0
            len_candidate, synthetic_length);
464
0
    }
465
466
0
    synth_msg_index = flen - synthetic_length;
467
468
    /* we have alternative message ready, check the real one */
469
0
    good = constant_time_is_zero(from[0]);
470
0
    good &= constant_time_eq(from[1], 2);
471
472
    /* then look for the padding|message separator (the first zero byte) */
473
0
    found_zero_byte = 0;
474
0
    for (i = 2; i < flen; i++) {
475
0
        unsigned int equals0 = constant_time_is_zero(from[i]);
476
0
        zero_index = constant_time_select_int(~found_zero_byte & equals0,
477
0
                                              i, zero_index);
478
0
        found_zero_byte |= equals0;
479
0
    }
480
481
    /*
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
484
     * also fails.
485
     */
486
0
    good &= constant_time_ge(zero_index, 2 + 8);
487
488
    /*
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.
491
     */
492
0
    msg_index = zero_index + 1;
493
494
    /*
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
497
     * message instead
498
     */
499
0
    good &= constant_time_ge(tlen, num - msg_index);
500
501
0
    msg_index = constant_time_select_int(good, msg_index, synth_msg_index);
502
503
    /*
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|
509
     */
510
0
    for (i = msg_index, j = 0; i < flen && j < tlen; i++, j++)
511
0
        to[j] = constant_time_select_8(good, from[i], synthetic[i]);
512
0
    ret = j;
513
514
0
err:
515
    /*
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
519
     */
520
0
    if (ret < 0)
521
0
        ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
522
0
    OPENSSL_free(synthetic);
523
0
    return ret;
524
0
}
525
526
/*
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
537
 * should be passed.
538
 *
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).
546
 */
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,
551
                                            int alt_version)
552
0
{
553
0
    unsigned int i, good, version_good;
554
0
    unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
555
556
    /*
557
     * If these checks fail then either the message in publicly invalid, or
558
     * we've been called incorrectly. We can fail immediately.
559
     */
560
0
    if (flen < RSA_PKCS1_PADDING_SIZE + SSL_MAX_MASTER_KEY_LENGTH
561
0
            || tlen < SSL_MAX_MASTER_KEY_LENGTH) {
562
0
        ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
563
0
        return -1;
564
0
    }
565
566
    /*
567
     * Generate a random premaster secret to use in the event that we fail
568
     * to decrypt.
569
     */
570
0
    if (RAND_priv_bytes_ex(libctx, rand_premaster_secret,
571
0
                           sizeof(rand_premaster_secret), 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
    /*
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.
592
     */
593
0
    version_good =
594
0
        constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
595
0
                         (client_version >> 8) & 0xff);
596
0
    version_good &=
597
0
        constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
598
0
                         client_version & 0xff);
599
600
    /*
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.
609
     */
610
0
    if (alt_version > 0) {
611
0
        unsigned int workaround_good;
612
613
0
        workaround_good =
614
0
            constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
615
0
                             (alt_version >> 8) & 0xff);
616
0
        workaround_good &=
617
0
            constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
618
0
                             alt_version & 0xff);
619
0
        version_good |= workaround_good;
620
0
    }
621
622
0
    good &= version_good;
623
624
625
    /*
626
     * Now copy the result over to the to buffer if good, or random data if
627
     * not good.
628
     */
629
0
    for (i = 0; i < SSL_MAX_MASTER_KEY_LENGTH; i++) {
630
0
        to[i] =
631
0
            constant_time_select_8(good,
632
0
                                   from[flen - SSL_MAX_MASTER_KEY_LENGTH + i],
633
0
                                   rand_premaster_secret[i]);
634
0
    }
635
636
    /*
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.
643
     */
644
645
0
    return SSL_MAX_MASTER_KEY_LENGTH;
646
0
}