xref: /src/crypto/openssl/crypto/rsa/rsa_pk1.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
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 
RSA_padding_add_PKCS1_type_1(unsigned char * to,int tlen,const unsigned char * from,int flen)31 int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
32     const unsigned char *from, int flen)
33 {
34     int j;
35     unsigned char *p;
36 
37     if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
38         ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
39         return 0;
40     }
41 
42     p = (unsigned char *)to;
43 
44     *(p++) = 0;
45     *(p++) = 1; /* Private Key BT (Block Type) */
46 
47     /* pad out with 0xff data */
48     j = tlen - 3 - flen;
49     memset(p, 0xff, j);
50     p += j;
51     *(p++) = '\0';
52     memcpy(p, from, (unsigned int)flen);
53     return 1;
54 }
55 
RSA_padding_check_PKCS1_type_1(unsigned char * to,int tlen,const unsigned char * from,int flen,int num)56 int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
57     const unsigned char *from, int flen,
58     int num)
59 {
60     int i, j;
61     const unsigned char *p;
62 
63     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     if (num < RSA_PKCS1_PADDING_SIZE)
73         return -1;
74 
75     /* Accept inputs with and without the leading 0-byte. */
76     if (num == flen) {
77         if ((*p++) != 0x00) {
78             ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
79             return -1;
80         }
81         flen--;
82     }
83 
84     if ((num != (flen + 1)) || (*(p++) != 0x01)) {
85         ERR_raise(ERR_LIB_RSA, RSA_R_BLOCK_TYPE_IS_NOT_01);
86         return -1;
87     }
88 
89     /* scan over padding data */
90     j = flen - 1; /* one for type. */
91     for (i = 0; i < j; i++) {
92         if (*p != 0xff) { /* should decrypt to 0xff */
93             if (*p == 0) {
94                 p++;
95                 break;
96             } else {
97                 ERR_raise(ERR_LIB_RSA, RSA_R_BAD_FIXED_HEADER_DECRYPT);
98                 return -1;
99             }
100         }
101         p++;
102     }
103 
104     if (i == j) {
105         ERR_raise(ERR_LIB_RSA, RSA_R_NULL_BEFORE_BLOCK_MISSING);
106         return -1;
107     }
108 
109     if (i < 8) {
110         ERR_raise(ERR_LIB_RSA, RSA_R_BAD_PAD_BYTE_COUNT);
111         return -1;
112     }
113     i++; /* Skip over the '\0' */
114     j -= i;
115     if (j > tlen) {
116         ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE);
117         return -1;
118     }
119     memcpy(to, p, (unsigned int)j);
120 
121     return j;
122 }
123 
ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX * libctx,unsigned char * to,int tlen,const unsigned char * from,int flen)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 {
128     int i, j;
129     unsigned char *p;
130 
131     if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
132         ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
133         return 0;
134     } else if (flen < 0) {
135         ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH);
136         return 0;
137     }
138 
139     p = (unsigned char *)to;
140 
141     *(p++) = 0;
142     *(p++) = 2; /* Public Key BT (Block Type) */
143 
144     /* pad out with non-zero random data */
145     j = tlen - 3 - flen;
146 
147     if (RAND_bytes_ex(libctx, p, j, 0) <= 0)
148         return 0;
149     for (i = 0; i < j; i++) {
150         if (*p == '\0')
151             do {
152                 if (RAND_bytes_ex(libctx, p, 1, 0) <= 0)
153                     return 0;
154             } while (*p == '\0');
155         p++;
156     }
157 
158     *(p++) = '\0';
159 
160     memcpy(p, from, (unsigned int)flen);
161     return 1;
162 }
163 
RSA_padding_add_PKCS1_type_2(unsigned char * to,int tlen,const unsigned char * from,int flen)164 int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
165     const unsigned char *from, int flen)
166 {
167     return ossl_rsa_padding_add_PKCS1_type_2_ex(NULL, to, tlen, from, flen);
168 }
169 
RSA_padding_check_PKCS1_type_2(unsigned char * to,int tlen,const unsigned char * from,int flen,int num)170 int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
171     const unsigned char *from, int flen,
172     int num)
173 {
174     int i;
175     /* |em| is the encoded message, zero-padded to exactly |num| bytes */
176     unsigned char *em = NULL;
177     unsigned int good, found_zero_byte, mask;
178     int zero_index = 0, msg_index, mlen = -1;
179 
180     if (tlen <= 0 || flen <= 0)
181         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     if (flen > num || num < RSA_PKCS1_PADDING_SIZE) {
189         ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
190         return -1;
191     }
192 
193     em = OPENSSL_malloc(num);
194     if (em == NULL)
195         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     for (from += flen, em += num, i = 0; i < num; i++) {
203         mask = ~constant_time_is_zero(flen);
204         flen -= 1 & mask;
205         from -= 1 & mask;
206         *--em = *from & mask;
207     }
208 
209     good = constant_time_is_zero(em[0]);
210     good &= constant_time_eq(em[1], 2);
211 
212     /* scan over padding data */
213     found_zero_byte = 0;
214     for (i = 2; i < num; i++) {
215         unsigned int equals0 = constant_time_is_zero(em[i]);
216 
217         zero_index = constant_time_select_int(~found_zero_byte & equals0,
218             i, zero_index);
219         found_zero_byte |= equals0;
220     }
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     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     msg_index = zero_index + 1;
234     mlen = num - msg_index;
235 
236     /*
237      * For good measure, do this check in constant time as well.
238      */
239     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     tlen = constant_time_select_int(constant_time_lt(num - RSA_PKCS1_PADDING_SIZE, tlen),
252         num - RSA_PKCS1_PADDING_SIZE, tlen);
253     for (msg_index = 1; msg_index < num - RSA_PKCS1_PADDING_SIZE; msg_index <<= 1) {
254         mask = ~constant_time_eq(msg_index & (num - RSA_PKCS1_PADDING_SIZE - mlen), 0);
255         for (i = RSA_PKCS1_PADDING_SIZE; i < num - msg_index; i++)
256             em[i] = constant_time_select_8(mask, em[i + msg_index], em[i]);
257     }
258     for (i = 0; i < tlen; i++) {
259         mask = good & constant_time_lt(i, mlen);
260         to[i] = constant_time_select_8(mask, em[i + RSA_PKCS1_PADDING_SIZE], to[i]);
261     }
262 
263     OPENSSL_clear_free(em, num);
264 #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     ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
271     err_clear_last_constant_time(1 & good);
272 #endif
273 
274     return constant_time_select_int(good, mlen, -1);
275 }
276 
ossl_rsa_prf(OSSL_LIB_CTX * ctx,unsigned char * to,int tlen,const char * label,int llen,const unsigned char * kdk,uint16_t bitlen)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 {
283     int pos;
284     int ret = -1;
285     uint16_t iter = 0;
286     unsigned char be_iter[sizeof(iter)];
287     unsigned char be_bitlen[sizeof(bitlen)];
288     HMAC_CTX *hmac = NULL;
289     EVP_MD *md = NULL;
290     unsigned char hmac_out[SHA256_DIGEST_LENGTH];
291     unsigned int md_len;
292 
293     if (tlen * 8 != bitlen) {
294         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
295         return ret;
296     }
297 
298     be_bitlen[0] = (bitlen >> 8) & 0xff;
299     be_bitlen[1] = bitlen & 0xff;
300 
301     hmac = HMAC_CTX_new();
302     if (hmac == NULL) {
303         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
304         goto err;
305     }
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     md = EVP_MD_fetch(ctx, "sha256", NULL);
315     if (md == NULL) {
316         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
317         goto err;
318     }
319 
320     if (HMAC_Init_ex(hmac, kdk, SHA256_DIGEST_LENGTH, md, NULL) <= 0) {
321         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
322         goto err;
323     }
324 
325     for (pos = 0; pos < tlen; pos += SHA256_DIGEST_LENGTH, iter++) {
326         if (HMAC_Init_ex(hmac, NULL, 0, NULL, NULL) <= 0) {
327             ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
328             goto err;
329         }
330 
331         be_iter[0] = (iter >> 8) & 0xff;
332         be_iter[1] = iter & 0xff;
333 
334         if (HMAC_Update(hmac, be_iter, sizeof(be_iter)) <= 0) {
335             ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
336             goto err;
337         }
338         if (HMAC_Update(hmac, (unsigned char *)label, llen) <= 0) {
339             ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
340             goto err;
341         }
342         if (HMAC_Update(hmac, be_bitlen, sizeof(be_bitlen)) <= 0) {
343             ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
344             goto err;
345         }
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         md_len = SHA256_DIGEST_LENGTH;
353         if (pos + SHA256_DIGEST_LENGTH > tlen) {
354             if (HMAC_Final(hmac, hmac_out, &md_len) <= 0) {
355                 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
356                 goto err;
357             }
358             memcpy(to + pos, hmac_out, tlen - pos);
359         } else {
360             if (HMAC_Final(hmac, to + pos, &md_len) <= 0) {
361                 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
362                 goto err;
363             }
364         }
365     }
366 
367     ret = 0;
368 
369 err:
370     HMAC_CTX_free(hmac);
371     EVP_MD_free(md);
372     return ret;
373 }
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  */
ossl_rsa_padding_check_PKCS1_type_2(OSSL_LIB_CTX * ctx,unsigned char * to,int tlen,const unsigned char * from,int flen,int num,unsigned char * kdk)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 {
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 #define MAX_LEN_GEN_TRIES 128
400     unsigned char *synthetic = NULL;
401     int synthetic_length;
402     uint16_t len_candidate;
403     unsigned char candidate_lengths[MAX_LEN_GEN_TRIES * sizeof(len_candidate)];
404     uint16_t len_mask;
405     uint16_t max_sep_offset;
406     int synth_msg_index = 0;
407     int ret = -1;
408     int i, j;
409     unsigned int good, found_zero_byte;
410     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     if (num != flen || tlen <= 0 || flen <= 0) {
419         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
420         return -1;
421     }
422 
423     /* Generate a random message to return in case the padding checks fail */
424     synthetic = OPENSSL_malloc(flen);
425     if (synthetic == NULL) {
426         ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
427         return -1;
428     }
429 
430     if (ossl_rsa_prf(ctx, synthetic, flen, "message", 7, kdk, flen * 8) < 0)
431         goto err;
432 
433     /* decide how long the random message should be */
434     if (ossl_rsa_prf(ctx, candidate_lengths, sizeof(candidate_lengths),
435             "length", 6, kdk,
436             MAX_LEN_GEN_TRIES * sizeof(len_candidate) * 8)
437         < 0)
438         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     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     len_mask |= len_mask >> 1;
450     len_mask |= len_mask >> 2;
451     len_mask |= len_mask >> 4;
452     len_mask |= len_mask >> 8;
453 
454     synthetic_length = 0;
455     for (i = 0; i < MAX_LEN_GEN_TRIES * (int)sizeof(len_candidate);
456         i += sizeof(len_candidate)) {
457         len_candidate = (candidate_lengths[i] << 8) | candidate_lengths[i + 1];
458         len_candidate &= len_mask;
459 
460         synthetic_length = constant_time_select_int(
461             constant_time_lt(len_candidate, max_sep_offset),
462             len_candidate, synthetic_length);
463     }
464 
465     synth_msg_index = flen - synthetic_length;
466 
467     /* we have alternative message ready, check the real one */
468     good = constant_time_is_zero(from[0]);
469     good &= constant_time_eq(from[1], 2);
470 
471     /* then look for the padding|message separator (the first zero byte) */
472     found_zero_byte = 0;
473     for (i = 2; i < flen; i++) {
474         unsigned int equals0 = constant_time_is_zero(from[i]);
475         zero_index = constant_time_select_int(~found_zero_byte & equals0,
476             i, zero_index);
477         found_zero_byte |= equals0;
478     }
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     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     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     good &= constant_time_ge(tlen, num - msg_index);
499 
500     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     for (i = msg_index, j = 0; i < flen && j < tlen; i++, j++)
510         to[j] = constant_time_select_8(good, from[i], synthetic[i]);
511     ret = j;
512 
513 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     if (ret < 0)
520         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
521     OPENSSL_free(synthetic);
522     return ret;
523 }
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  */
ossl_rsa_padding_check_PKCS1_type_2_TLS(OSSL_LIB_CTX * libctx,unsigned char * to,size_t tlen,const unsigned char * from,size_t flen,int client_version,int alt_version)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 {
552     unsigned int i, good, version_good;
553     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     if (flen < RSA_PKCS1_PADDING_SIZE + SSL_MAX_MASTER_KEY_LENGTH
560         || tlen < SSL_MAX_MASTER_KEY_LENGTH) {
561         ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
562         return -1;
563     }
564 
565     /*
566      * Generate a random premaster secret to use in the event that we fail
567      * to decrypt.
568      */
569     if (RAND_priv_bytes_ex(libctx, rand_premaster_secret,
570             sizeof(rand_premaster_secret), 0)
571         <= 0) {
572         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
573         return -1;
574     }
575 
576     good = constant_time_is_zero(from[0]);
577     good &= constant_time_eq(from[1], 2);
578 
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]);
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     version_good = constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
593         (client_version >> 8) & 0xff);
594     version_good &= constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
595         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     if (alt_version > 0) {
608         unsigned int workaround_good;
609 
610         workaround_good = constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
611             (alt_version >> 8) & 0xff);
612         workaround_good &= constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
613             alt_version & 0xff);
614         version_good |= workaround_good;
615     }
616 
617     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     for (i = 0; i < SSL_MAX_MASTER_KEY_LENGTH; i++) {
624         to[i] = constant_time_select_8(good,
625             from[flen - SSL_MAX_MASTER_KEY_LENGTH + i],
626             rand_premaster_secret[i]);
627     }
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     return SSL_MAX_MASTER_KEY_LENGTH;
639 }
640