xref: /openssl/crypto/rsa/rsa_pk1.c (revision da1c088f)
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 
RSA_padding_add_PKCS1_type_1(unsigned char * to,int tlen,const unsigned char * from,int flen)32 int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
33                                  const unsigned char *from, int flen)
34 {
35     int j;
36     unsigned char *p;
37 
38     if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
39         ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
40         return 0;
41     }
42 
43     p = (unsigned char *)to;
44 
45     *(p++) = 0;
46     *(p++) = 1;                 /* Private Key BT (Block Type) */
47 
48     /* pad out with 0xff data */
49     j = tlen - 3 - flen;
50     memset(p, 0xff, j);
51     p += j;
52     *(p++) = '\0';
53     memcpy(p, from, (unsigned int)flen);
54     return 1;
55 }
56 
RSA_padding_check_PKCS1_type_1(unsigned char * to,int tlen,const unsigned char * from,int flen,int num)57 int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
58                                    const unsigned char *from, int flen,
59                                    int num)
60 {
61     int i, j;
62     const unsigned char *p;
63 
64     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     if (num < RSA_PKCS1_PADDING_SIZE)
74         return -1;
75 
76     /* Accept inputs with and without the leading 0-byte. */
77     if (num == flen) {
78         if ((*p++) != 0x00) {
79             ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
80             return -1;
81         }
82         flen--;
83     }
84 
85     if ((num != (flen + 1)) || (*(p++) != 0x01)) {
86         ERR_raise(ERR_LIB_RSA, RSA_R_BLOCK_TYPE_IS_NOT_01);
87         return -1;
88     }
89 
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 */
94             if (*p == 0) {
95                 p++;
96                 break;
97             } else {
98                 ERR_raise(ERR_LIB_RSA, RSA_R_BAD_FIXED_HEADER_DECRYPT);
99                 return -1;
100             }
101         }
102         p++;
103     }
104 
105     if (i == j) {
106         ERR_raise(ERR_LIB_RSA, RSA_R_NULL_BEFORE_BLOCK_MISSING);
107         return -1;
108     }
109 
110     if (i < 8) {
111         ERR_raise(ERR_LIB_RSA, RSA_R_BAD_PAD_BYTE_COUNT);
112         return -1;
113     }
114     i++;                        /* Skip over the '\0' */
115     j -= i;
116     if (j > tlen) {
117         ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE);
118         return -1;
119     }
120     memcpy(to, p, (unsigned int)j);
121 
122     return j;
123 }
124 
ossl_rsa_padding_add_PKCS1_type_2_ex(OSSL_LIB_CTX * libctx,unsigned char * to,int tlen,const unsigned char * from,int flen)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 {
129     int i, j;
130     unsigned char *p;
131 
132     if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
133         ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
134         return 0;
135     } else if (flen < 0) {
136         ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_LENGTH);
137         return 0;
138     }
139 
140     p = (unsigned char *)to;
141 
142     *(p++) = 0;
143     *(p++) = 2;                 /* Public Key BT (Block Type) */
144 
145     /* pad out with non-zero random data */
146     j = tlen - 3 - flen;
147 
148     if (RAND_bytes_ex(libctx, p, j, 0) <= 0)
149         return 0;
150     for (i = 0; i < j; i++) {
151         if (*p == '\0')
152             do {
153                 if (RAND_bytes_ex(libctx, p, 1, 0) <= 0)
154                     return 0;
155             } while (*p == '\0');
156         p++;
157     }
158 
159     *(p++) = '\0';
160 
161     memcpy(p, from, (unsigned int)flen);
162     return 1;
163 }
164 
RSA_padding_add_PKCS1_type_2(unsigned char * to,int tlen,const unsigned char * from,int flen)165 int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
166                                  const unsigned char *from, int flen)
167 {
168     return ossl_rsa_padding_add_PKCS1_type_2_ex(NULL, to, tlen, from, flen);
169 }
170 
RSA_padding_check_PKCS1_type_2(unsigned char * to,int tlen,const unsigned char * from,int flen,int num)171 int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
172                                    const unsigned char *from, int flen,
173                                    int num)
174 {
175     int i;
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;
180 
181     if (tlen <= 0 || flen <= 0)
182         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     if (flen > num || num < RSA_PKCS1_PADDING_SIZE) {
190         ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
191         return -1;
192     }
193 
194     em = OPENSSL_malloc(num);
195     if (em == NULL)
196         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     for (from += flen, em += num, i = 0; i < num; i++) {
204         mask = ~constant_time_is_zero(flen);
205         flen -= 1 & mask;
206         from -= 1 & mask;
207         *--em = *from & mask;
208     }
209 
210     good = constant_time_is_zero(em[0]);
211     good &= constant_time_eq(em[1], 2);
212 
213     /* scan over padding data */
214     found_zero_byte = 0;
215     for (i = 2; i < num; i++) {
216         unsigned int equals0 = constant_time_is_zero(em[i]);
217 
218         zero_index = constant_time_select_int(~found_zero_byte & equals0,
219                                               i, zero_index);
220         found_zero_byte |= equals0;
221     }
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     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     msg_index = zero_index + 1;
235     mlen = num - msg_index;
236 
237     /*
238      * For good measure, do this check in constant time as well.
239      */
240     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     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]);
258     }
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]);
262     }
263 
264     OPENSSL_clear_free(em, num);
265 #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     ERR_raise(ERR_LIB_RSA, RSA_R_PKCS_DECODING_ERROR);
272     err_clear_last_constant_time(1 & good);
273 #endif
274 
275     return constant_time_select_int(good, mlen, -1);
276 }
277 
278 
ossl_rsa_prf(OSSL_LIB_CTX * ctx,unsigned char * to,int tlen,const char * label,int llen,const unsigned char * kdk,uint16_t bitlen)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 {
285     int pos;
286     int ret = -1;
287     uint16_t iter = 0;
288     unsigned char be_iter[sizeof(iter)];
289     unsigned char be_bitlen[sizeof(bitlen)];
290     HMAC_CTX *hmac = NULL;
291     EVP_MD *md = NULL;
292     unsigned char hmac_out[SHA256_DIGEST_LENGTH];
293     unsigned int md_len;
294 
295     if (tlen * 8 != bitlen) {
296         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
297         return ret;
298     }
299 
300     be_bitlen[0] = (bitlen >> 8) & 0xff;
301     be_bitlen[1] = bitlen & 0xff;
302 
303     hmac = HMAC_CTX_new();
304     if (hmac == NULL) {
305         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
306         goto err;
307     }
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     md = EVP_MD_fetch(ctx, "sha256", NULL);
317     if (md == NULL) {
318         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
319         goto err;
320     }
321 
322     if (HMAC_Init_ex(hmac, kdk, SHA256_DIGEST_LENGTH, md, NULL) <= 0) {
323         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
324         goto err;
325     }
326 
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);
330             goto err;
331         }
332 
333         be_iter[0] = (iter >> 8) & 0xff;
334         be_iter[1] = iter & 0xff;
335 
336         if (HMAC_Update(hmac, be_iter, sizeof(be_iter)) <= 0) {
337             ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
338             goto err;
339         }
340         if (HMAC_Update(hmac, (unsigned char *)label, llen) <= 0) {
341             ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
342             goto err;
343         }
344         if (HMAC_Update(hmac, be_bitlen, sizeof(be_bitlen)) <= 0) {
345             ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
346             goto err;
347         }
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         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);
358                 goto err;
359             }
360             memcpy(to + pos, hmac_out, tlen - pos);
361         } else {
362             if (HMAC_Final(hmac, to + pos, &md_len) <= 0) {
363                 ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
364                 goto err;
365             }
366         }
367     }
368 
369     ret = 0;
370 
371 err:
372     HMAC_CTX_free(hmac);
373     EVP_MD_free(md);
374     return ret;
375 }
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  */
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)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 {
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 #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)];
406     uint16_t len_mask;
407     uint16_t max_sep_offset;
408     int synth_msg_index = 0;
409     int ret = -1;
410     int i, j;
411     unsigned int good, found_zero_byte;
412     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     if (num != flen || tlen <= 0 || flen <= 0) {
421         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
422         return -1;
423     }
424 
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);
429         return -1;
430     }
431 
432     if (ossl_rsa_prf(ctx, synthetic, flen, "message", 7, kdk, flen * 8) < 0)
433         goto err;
434 
435     /* decide how long the random message should be */
436     if (ossl_rsa_prf(ctx, candidate_lengths, sizeof(candidate_lengths),
437                      "length", 6, kdk,
438                      MAX_LEN_GEN_TRIES * sizeof(len_candidate) * 8) < 0)
439         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     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     len_mask |= len_mask >> 1;
451     len_mask |= len_mask >> 2;
452     len_mask |= len_mask >> 4;
453     len_mask |= len_mask >> 8;
454 
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;
460 
461         synthetic_length = constant_time_select_int(
462             constant_time_lt(len_candidate, max_sep_offset),
463             len_candidate, synthetic_length);
464     }
465 
466     synth_msg_index = flen - synthetic_length;
467 
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);
471 
472     /* then look for the padding|message separator (the first zero byte) */
473     found_zero_byte = 0;
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,
477                                               i, zero_index);
478         found_zero_byte |= equals0;
479     }
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     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     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     good &= constant_time_ge(tlen, num - msg_index);
500 
501     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     for (i = msg_index, j = 0; i < flen && j < tlen; i++, j++)
511         to[j] = constant_time_select_8(good, from[i], synthetic[i]);
512     ret = j;
513 
514 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     if (ret < 0)
521         ERR_raise(ERR_LIB_RSA, ERR_R_INTERNAL_ERROR);
522     OPENSSL_free(synthetic);
523     return ret;
524 }
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  */
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)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 {
553     unsigned int i, good, version_good;
554     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     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);
563         return -1;
564     }
565 
566     /*
567      * Generate a random premaster secret to use in the event that we fail
568      * to decrypt.
569      */
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);
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     /*
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     version_good =
594         constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
595                          (client_version >> 8) & 0xff);
596     version_good &=
597         constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
598                          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     if (alt_version > 0) {
611         unsigned int workaround_good;
612 
613         workaround_good =
614             constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH],
615                              (alt_version >> 8) & 0xff);
616         workaround_good &=
617             constant_time_eq(from[flen - SSL_MAX_MASTER_KEY_LENGTH + 1],
618                              alt_version & 0xff);
619         version_good |= workaround_good;
620     }
621 
622     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     for (i = 0; i < SSL_MAX_MASTER_KEY_LENGTH; i++) {
630         to[i] =
631             constant_time_select_8(good,
632                                    from[flen - SSL_MAX_MASTER_KEY_LENGTH + i],
633                                    rand_premaster_secret[i]);
634     }
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     return SSL_MAX_MASTER_KEY_LENGTH;
646 }
647