ff09f0b16ae197394ba38b54a7dff0128cef90cf
[openssl.git] / ssl / record / ssl3_record.c
1 /* ssl/record/ssl3_record.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2015 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include "../ssl_locl.h"
113 #include "internal/constant_time_locl.h"
114 #include <openssl/rand.h>
115 #include "record_locl.h"
116
117 static const unsigned char ssl3_pad_1[48] = {
118     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
119     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
120     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
121     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
122     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
123     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
124 };
125
126 static const unsigned char ssl3_pad_2[48] = {
127     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
128     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
129     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
130     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
131     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
132     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
133 };
134
135 void SSL3_RECORD_clear(SSL3_RECORD *r)
136 {
137     memset(r->seq_num, 0, sizeof(r->seq_num));
138 }
139
140 void SSL3_RECORD_release(SSL3_RECORD *r)
141 {
142     OPENSSL_free(r->comp);
143     r->comp = NULL;
144 }
145
146 int SSL3_RECORD_setup(SSL3_RECORD *r)
147 {
148     if (r->comp == NULL)
149         r->comp = (unsigned char *)
150             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
151     if (r->comp == NULL)
152         return 0;
153     return 1;
154 }
155
156 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
157 {
158     memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
159 }
160
161 /*
162  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
163  * will be processed per call to ssl3_get_record. Without this limit an
164  * attacker could send empty records at a faster rate than we can process and
165  * cause ssl3_get_record to loop forever.
166  */
167 #define MAX_EMPTY_RECORDS 32
168
169 #define SSL2_RT_HEADER_LENGTH   2
170 /*-
171  * Call this to get a new input record.
172  * It will return <= 0 if more data is needed, normally due to an error
173  * or non-blocking IO.
174  * When it finishes, one packet has been decoded and can be found in
175  * ssl->s3->rrec.type    - is the type of record
176  * ssl->s3->rrec.data,   - data
177  * ssl->s3->rrec.length, - number of bytes
178  */
179 /* used only by ssl3_read_bytes */
180 int ssl3_get_record(SSL *s)
181 {
182     int ssl_major, ssl_minor, al;
183     int enc_err, n, i, ret = -1;
184     SSL3_RECORD *rr;
185     SSL_SESSION *sess;
186     unsigned char *p;
187     unsigned char md[EVP_MAX_MD_SIZE];
188     short version;
189     unsigned mac_size;
190     size_t extra;
191     unsigned empty_record_count = 0;
192
193     rr = RECORD_LAYER_get_rrec(&s->rlayer);
194     sess = s->session;
195
196     if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
197         extra = SSL3_RT_MAX_EXTRA;
198     else
199         extra = 0;
200     if (extra && !s->s3->init_extra) {
201         /*
202          * An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
203          * ssl3_setup_buffers() was done
204          */
205         SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
206         return -1;
207     }
208
209  again:
210     /* check if we have the header */
211     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
212         (RECORD_LAYER_get_packet_length(&s->rlayer) < SSL3_RT_HEADER_LENGTH)) {
213         n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
214             SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0);
215         if (n <= 0)
216             return (n);         /* error or non-blocking */
217         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
218
219         p = RECORD_LAYER_get_packet(&s->rlayer);
220
221         /*
222          * Check whether this is a regular record or an SSLv2 style record. The
223          * latter is only used in an initial ClientHello for old clients.
224          */
225         if (s->first_packet && s->server && !s->read_hash && !s->enc_read_ctx
226                 && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
227             /* SSLv2 style record */
228             if (s->msg_callback)
229                 s->msg_callback(0, SSL2_VERSION, 0,  p + 2,
230                                 RECORD_LAYER_get_packet_length(&s->rlayer) - 2,
231                                 s, s->msg_callback_arg);
232
233             rr->type = SSL3_RT_HANDSHAKE;
234             rr->rec_version = SSL2_VERSION;
235
236             rr->length = ((p[0] & 0x7f) << 8) | p[1];
237
238             if (rr->length > SSL3_BUFFER_get_len(&s->rlayer.rbuf)
239                                     - SSL2_RT_HEADER_LENGTH) {
240                 al = SSL_AD_RECORD_OVERFLOW;
241                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
242                 goto f_err;
243             }
244
245             if (rr->length < MIN_SSL2_RECORD_LEN) {
246                 al = SSL_AD_HANDSHAKE_FAILURE;
247                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
248                 goto f_err;
249             }
250         } else {
251             /* SSLv3+ style record */
252             if (s->msg_callback)
253                 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
254                                 s->msg_callback_arg);
255
256             /* Pull apart the header into the SSL3_RECORD */
257             rr->type = *(p++);
258             ssl_major = *(p++);
259             ssl_minor = *(p++);
260             version = (ssl_major << 8) | ssl_minor;
261             rr->rec_version = version;
262             n2s(p, rr->length);
263
264             /* Lets check version */
265             if (!s->first_packet) {
266                 if (version != s->version
267                         && s->method->version != TLS_ANY_VERSION) {
268                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
269                     if ((s->version & 0xFF00) == (version & 0xFF00)
270                         && !s->enc_write_ctx && !s->write_hash)
271                         /*
272                          * Send back error using their minor version number :-)
273                          */
274                         s->version = (unsigned short)version;
275                     al = SSL_AD_PROTOCOL_VERSION;
276                     goto f_err;
277                 }
278             }
279
280             if ((version >> 8) != SSL3_VERSION_MAJOR) {
281                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
282                 goto err;
283             }
284
285             if (rr->length >
286                     SSL3_BUFFER_get_len(&s->rlayer.rbuf)
287                     - SSL3_RT_HEADER_LENGTH) {
288                 al = SSL_AD_RECORD_OVERFLOW;
289                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
290                 goto f_err;
291             }
292         }
293
294         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
295     }
296
297     /*
298      * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
299      * Calculate how much more data we need to read for the rest of the record
300      */
301     if (rr->rec_version == SSL2_VERSION) {
302         i = rr->length + SSL2_RT_HEADER_LENGTH - SSL3_RT_HEADER_LENGTH;
303     } else {
304         i = rr->length;
305     }
306     if (i > 0) {
307         /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
308
309         n = ssl3_read_n(s, i, i, 1);
310         if (n <= 0)
311             return (n);         /* error or non-blocking io */
312         /*
313          * now n == rr->length, and
314          * s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length
315          * or
316          * s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
317          * (if SSLv2 packet)
318          */
319     } else {
320         n = 0;
321     }
322
323     /* set state for later operations */
324     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
325
326     /*
327      * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length,
328      * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
329      * and we have that many bytes in s->packet
330      */
331     if(rr->rec_version == SSL2_VERSION) {
332         rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
333     } else {
334         rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
335     }
336
337     /*
338      * ok, we can now read from 's->packet' data into 'rr' rr->input points
339      * at rr->length bytes, which need to be copied into rr->data by either
340      * the decryption or by the decompression When the data is 'copied' into
341      * the rr->data buffer, rr->input will be pointed at the new buffer
342      */
343
344     /*
345      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
346      * bytes of encrypted compressed stuff.
347      */
348
349     /* check is not needed I believe */
350     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
351         al = SSL_AD_RECORD_OVERFLOW;
352         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
353         goto f_err;
354     }
355
356     /* decrypt in place in 'rr->input' */
357     rr->data = rr->input;
358     rr->orig_len = rr->length;
359     /*
360      * If in encrypt-then-mac mode calculate mac from encrypted record. All
361      * the details below are public so no timing details can leak.
362      */
363     if (SSL_USE_ETM(s) && s->read_hash) {
364         unsigned char *mac;
365         mac_size = EVP_MD_CTX_size(s->read_hash);
366         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
367         if (rr->length < mac_size) {
368             al = SSL_AD_DECODE_ERROR;
369             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
370             goto f_err;
371         }
372         rr->length -= mac_size;
373         mac = rr->data + rr->length;
374         i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
375         if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
376             al = SSL_AD_BAD_RECORD_MAC;
377             SSLerr(SSL_F_SSL3_GET_RECORD,
378                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
379             goto f_err;
380         }
381     }
382
383     enc_err = s->method->ssl3_enc->enc(s, 0);
384     /*-
385      * enc_err is:
386      *    0: (in non-constant time) if the record is publically invalid.
387      *    1: if the padding is valid
388      *    -1: if the padding is invalid
389      */
390     if (enc_err == 0) {
391         al = SSL_AD_DECRYPTION_FAILED;
392         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
393         goto f_err;
394     }
395 #ifdef TLS_DEBUG
396     printf("dec %d\n", rr->length);
397     {
398         unsigned int z;
399         for (z = 0; z < rr->length; z++)
400             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
401     }
402     printf("\n");
403 #endif
404
405     /* r->length is now the compressed data plus mac */
406     if ((sess != NULL) &&
407         (s->enc_read_ctx != NULL) &&
408         (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
409         /* s->read_hash != NULL => mac_size != -1 */
410         unsigned char *mac = NULL;
411         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
412         mac_size = EVP_MD_CTX_size(s->read_hash);
413         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
414
415         /*
416          * orig_len is the length of the record before any padding was
417          * removed. This is public information, as is the MAC in use,
418          * therefore we can safely process the record in a different amount
419          * of time if it's too short to possibly contain a MAC.
420          */
421         if (rr->orig_len < mac_size ||
422             /* CBC records must have a padding length byte too. */
423             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
424              rr->orig_len < mac_size + 1)) {
425             al = SSL_AD_DECODE_ERROR;
426             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
427             goto f_err;
428         }
429
430         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
431             /*
432              * We update the length so that the TLS header bytes can be
433              * constructed correctly but we need to extract the MAC in
434              * constant time from within the record, without leaking the
435              * contents of the padding bytes.
436              */
437             mac = mac_tmp;
438             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
439             rr->length -= mac_size;
440         } else {
441             /*
442              * In this case there's no padding, so |rec->orig_len| equals
443              * |rec->length| and we checked that there's enough bytes for
444              * |mac_size| above.
445              */
446             rr->length -= mac_size;
447             mac = &rr->data[rr->length];
448         }
449
450         i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
451         if (i < 0 || mac == NULL
452             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
453             enc_err = -1;
454         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
455             enc_err = -1;
456     }
457
458     if (enc_err < 0) {
459         /*
460          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
461          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
462          * failure is directly visible from the ciphertext anyway, we should
463          * not reveal which kind of error occurred -- this might become
464          * visible to an attacker (e.g. via a logfile)
465          */
466         al = SSL_AD_BAD_RECORD_MAC;
467         SSLerr(SSL_F_SSL3_GET_RECORD,
468                SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
469         goto f_err;
470     }
471
472     /* r->length is now just compressed */
473     if (s->expand != NULL) {
474         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
475             al = SSL_AD_RECORD_OVERFLOW;
476             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
477             goto f_err;
478         }
479         if (!ssl3_do_uncompress(s)) {
480             al = SSL_AD_DECOMPRESSION_FAILURE;
481             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
482             goto f_err;
483         }
484     }
485
486     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
487         al = SSL_AD_RECORD_OVERFLOW;
488         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
489         goto f_err;
490     }
491
492     rr->off = 0;
493     /*-
494      * So at this point the following is true
495      * ssl->s3->rrec.type   is the type of record
496      * ssl->s3->rrec.length == number of bytes in record
497      * ssl->s3->rrec.off    == offset to first valid byte
498      * ssl->s3->rrec.data   == where to take bytes from, increment
499      *                         after use :-).
500      */
501
502     /* we have pulled in a full packet so zero things */
503     RECORD_LAYER_reset_packet_length(&s->rlayer);
504
505     /* just read a 0 length packet */
506     if (rr->length == 0) {
507         empty_record_count++;
508         if (empty_record_count > MAX_EMPTY_RECORDS) {
509             al = SSL_AD_UNEXPECTED_MESSAGE;
510             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
511             goto f_err;
512         }
513         goto again;
514     }
515
516     return (1);
517
518  f_err:
519     ssl3_send_alert(s, SSL3_AL_FATAL, al);
520  err:
521     return (ret);
522 }
523
524 int ssl3_do_uncompress(SSL *ssl)
525 {
526 #ifndef OPENSSL_NO_COMP
527     int i;
528     SSL3_RECORD *rr;
529
530     rr = RECORD_LAYER_get_rrec(&ssl->rlayer);
531     i = COMP_expand_block(ssl->expand, rr->comp,
532                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
533                           (int)rr->length);
534     if (i < 0)
535         return (0);
536     else
537         rr->length = i;
538     rr->data = rr->comp;
539 #endif
540     return (1);
541 }
542
543 int ssl3_do_compress(SSL *ssl)
544 {
545 #ifndef OPENSSL_NO_COMP
546     int i;
547     SSL3_RECORD *wr;
548
549     wr = RECORD_LAYER_get_wrec(&ssl->rlayer);
550     i = COMP_compress_block(ssl->compress, wr->data,
551                             SSL3_RT_MAX_COMPRESSED_LENGTH,
552                             wr->input, (int)wr->length);
553     if (i < 0)
554         return (0);
555     else
556         wr->length = i;
557
558     wr->input = wr->data;
559 #endif
560     return (1);
561 }
562
563 /*-
564  * ssl3_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
565  *
566  * Returns:
567  *   0: (in non-constant time) if the record is publically invalid (i.e. too
568  *       short etc).
569  *   1: if the record's padding is valid / the encryption was successful.
570  *   -1: if the record's padding is invalid or, if sending, an internal error
571  *       occurred.
572  */
573 int ssl3_enc(SSL *s, int send)
574 {
575     SSL3_RECORD *rec;
576     EVP_CIPHER_CTX *ds;
577     unsigned long l;
578     int bs, i, mac_size = 0;
579     const EVP_CIPHER *enc;
580
581     if (send) {
582         ds = s->enc_write_ctx;
583         rec = RECORD_LAYER_get_wrec(&s->rlayer);
584         if (s->enc_write_ctx == NULL)
585             enc = NULL;
586         else
587             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
588     } else {
589         ds = s->enc_read_ctx;
590         rec = RECORD_LAYER_get_rrec(&s->rlayer);
591         if (s->enc_read_ctx == NULL)
592             enc = NULL;
593         else
594             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
595     }
596
597     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
598         memmove(rec->data, rec->input, rec->length);
599         rec->input = rec->data;
600     } else {
601         l = rec->length;
602         bs = EVP_CIPHER_block_size(ds->cipher);
603
604         /* COMPRESS */
605
606         if ((bs != 1) && send) {
607             i = bs - ((int)l % bs);
608
609             /* we need to add 'i-1' padding bytes */
610             l += i;
611             /*
612              * the last of these zero bytes will be overwritten with the
613              * padding length.
614              */
615             memset(&rec->input[rec->length], 0, i);
616             rec->length += i;
617             rec->input[l - 1] = (i - 1);
618         }
619
620         if (!send) {
621             if (l == 0 || l % bs != 0)
622                 return 0;
623             /* otherwise, rec->length >= bs */
624         }
625
626         if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
627             return -1;
628
629         if (EVP_MD_CTX_md(s->read_hash) != NULL)
630             mac_size = EVP_MD_CTX_size(s->read_hash);
631         if ((bs != 1) && !send)
632             return ssl3_cbc_remove_padding(s, rec, bs, mac_size);
633     }
634     return (1);
635 }
636
637 /*-
638  * tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
639  *
640  * Returns:
641  *   0: (in non-constant time) if the record is publically invalid (i.e. too
642  *       short etc).
643  *   1: if the record's padding is valid / the encryption was successful.
644  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
645  *       an internal error occurred.
646  */
647 int tls1_enc(SSL *s, int send)
648 {
649     SSL3_RECORD *rec;
650     EVP_CIPHER_CTX *ds;
651     unsigned long l;
652     int bs, i, j, k, pad = 0, ret, mac_size = 0;
653     const EVP_CIPHER *enc;
654
655     if (send) {
656         if (EVP_MD_CTX_md(s->write_hash)) {
657             int n = EVP_MD_CTX_size(s->write_hash);
658             OPENSSL_assert(n >= 0);
659         }
660         ds = s->enc_write_ctx;
661         rec = RECORD_LAYER_get_wrec(&s->rlayer);
662         if (s->enc_write_ctx == NULL)
663             enc = NULL;
664         else {
665             int ivlen;
666             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
667             /* For TLSv1.1 and later explicit IV */
668             if (SSL_USE_EXPLICIT_IV(s)
669                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
670                 ivlen = EVP_CIPHER_iv_length(enc);
671             else
672                 ivlen = 0;
673             if (ivlen > 1) {
674                 if (rec->data != rec->input)
675                     /*
676                      * we can't write into the input stream: Can this ever
677                      * happen?? (steve)
678                      */
679                     fprintf(stderr,
680                             "%s:%d: rec->data != rec->input\n",
681                             __FILE__, __LINE__);
682                 else if (RAND_bytes(rec->input, ivlen) <= 0)
683                     return -1;
684             }
685         }
686     } else {
687         if (EVP_MD_CTX_md(s->read_hash)) {
688             int n = EVP_MD_CTX_size(s->read_hash);
689             OPENSSL_assert(n >= 0);
690         }
691         ds = s->enc_read_ctx;
692         rec = RECORD_LAYER_get_rrec(&s->rlayer);
693         if (s->enc_read_ctx == NULL)
694             enc = NULL;
695         else
696             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
697     }
698
699     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
700         memmove(rec->data, rec->input, rec->length);
701         rec->input = rec->data;
702         ret = 1;
703     } else {
704         l = rec->length;
705         bs = EVP_CIPHER_block_size(ds->cipher);
706
707         if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
708             unsigned char buf[EVP_AEAD_TLS1_AAD_LEN], *seq;
709
710             seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
711                 : RECORD_LAYER_get_read_sequence(&s->rlayer);
712
713             if (SSL_IS_DTLS(s)) {
714                 unsigned char dtlsseq[9], *p = dtlsseq;
715
716                 s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
717                     DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
718                 memcpy(p, &seq[2], 6);
719                 memcpy(buf, dtlsseq, 8);
720             } else {
721                 memcpy(buf, seq, 8);
722                 for (i = 7; i >= 0; i--) { /* increment */
723                     ++seq[i];
724                     if (seq[i] != 0)
725                         break;
726                 }
727             }
728
729             buf[8] = rec->type;
730             buf[9] = (unsigned char)(s->version >> 8);
731             buf[10] = (unsigned char)(s->version);
732             buf[11] = rec->length >> 8;
733             buf[12] = rec->length & 0xff;
734             pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
735                                       EVP_AEAD_TLS1_AAD_LEN, buf);
736             if (pad <= 0)
737                 return -1;
738             if (send) {
739                 l += pad;
740                 rec->length += pad;
741             }
742         } else if ((bs != 1) && send) {
743             i = bs - ((int)l % bs);
744
745             /* Add weird padding of upto 256 bytes */
746
747             /* we need to add 'i' padding bytes of value j */
748             j = i - 1;
749             if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) {
750                 if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
751                     j++;
752             }
753             for (k = (int)l; k < (int)(l + i); k++)
754                 rec->input[k] = j;
755             l += i;
756             rec->length += i;
757         }
758
759         if (!send) {
760             if (l == 0 || l % bs != 0)
761                 return 0;
762         }
763
764         i = EVP_Cipher(ds, rec->data, rec->input, l);
765         if ((EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_CUSTOM_CIPHER)
766             ? (i < 0)
767             : (i == 0))
768             return -1;          /* AEAD can fail to verify MAC */
769         if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
770             rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
771             rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
772             rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
773         }
774
775         ret = 1;
776         if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
777             mac_size = EVP_MD_CTX_size(s->read_hash);
778         if ((bs != 1) && !send)
779             ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
780         if (pad && !send)
781             rec->length -= pad;
782     }
783     return ret;
784 }
785
786 int n_ssl3_mac(SSL *ssl, unsigned char *md, int send)
787 {
788     SSL3_RECORD *rec;
789     unsigned char *mac_sec, *seq;
790     EVP_MD_CTX md_ctx;
791     const EVP_MD_CTX *hash;
792     unsigned char *p, rec_char;
793     size_t md_size;
794     int npad;
795     int t;
796
797     if (send) {
798         rec = RECORD_LAYER_get_wrec(&ssl->rlayer);
799         mac_sec = &(ssl->s3->write_mac_secret[0]);
800         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
801         hash = ssl->write_hash;
802     } else {
803         rec = RECORD_LAYER_get_rrec(&ssl->rlayer);
804         mac_sec = &(ssl->s3->read_mac_secret[0]);
805         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
806         hash = ssl->read_hash;
807     }
808
809     t = EVP_MD_CTX_size(hash);
810     if (t < 0)
811         return -1;
812     md_size = t;
813     npad = (48 / md_size) * md_size;
814
815     if (!send &&
816         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
817         ssl3_cbc_record_digest_supported(hash)) {
818         /*
819          * This is a CBC-encrypted record. We must avoid leaking any
820          * timing-side channel information about how many blocks of data we
821          * are hashing because that gives an attacker a timing-oracle.
822          */
823
824         /*-
825          * npad is, at most, 48 bytes and that's with MD5:
826          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
827          *
828          * With SHA-1 (the largest hash speced for SSLv3) the hash size
829          * goes up 4, but npad goes down by 8, resulting in a smaller
830          * total size.
831          */
832         unsigned char header[75];
833         unsigned j = 0;
834         memcpy(header + j, mac_sec, md_size);
835         j += md_size;
836         memcpy(header + j, ssl3_pad_1, npad);
837         j += npad;
838         memcpy(header + j, seq, 8);
839         j += 8;
840         header[j++] = rec->type;
841         header[j++] = rec->length >> 8;
842         header[j++] = rec->length & 0xff;
843
844         /* Final param == is SSLv3 */
845         ssl3_cbc_digest_record(hash,
846                                md, &md_size,
847                                header, rec->input,
848                                rec->length + md_size, rec->orig_len,
849                                mac_sec, md_size, 1);
850     } else {
851         unsigned int md_size_u;
852         /* Chop the digest off the end :-) */
853         EVP_MD_CTX_init(&md_ctx);
854
855         EVP_MD_CTX_copy_ex(&md_ctx, hash);
856         EVP_DigestUpdate(&md_ctx, mac_sec, md_size);
857         EVP_DigestUpdate(&md_ctx, ssl3_pad_1, npad);
858         EVP_DigestUpdate(&md_ctx, seq, 8);
859         rec_char = rec->type;
860         EVP_DigestUpdate(&md_ctx, &rec_char, 1);
861         p = md;
862         s2n(rec->length, p);
863         EVP_DigestUpdate(&md_ctx, md, 2);
864         EVP_DigestUpdate(&md_ctx, rec->input, rec->length);
865         EVP_DigestFinal_ex(&md_ctx, md, NULL);
866
867         EVP_MD_CTX_copy_ex(&md_ctx, hash);
868         EVP_DigestUpdate(&md_ctx, mac_sec, md_size);
869         EVP_DigestUpdate(&md_ctx, ssl3_pad_2, npad);
870         EVP_DigestUpdate(&md_ctx, md, md_size);
871         EVP_DigestFinal_ex(&md_ctx, md, &md_size_u);
872         md_size = md_size_u;
873
874         EVP_MD_CTX_cleanup(&md_ctx);
875     }
876
877     ssl3_record_sequence_update(seq);
878     return (md_size);
879 }
880
881 int tls1_mac(SSL *ssl, unsigned char *md, int send)
882 {
883     SSL3_RECORD *rec;
884     unsigned char *seq;
885     EVP_MD_CTX *hash;
886     size_t md_size;
887     int i;
888     EVP_MD_CTX hmac, *mac_ctx;
889     unsigned char header[13];
890     int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
891                       : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
892     int t;
893
894     if (send) {
895         rec = RECORD_LAYER_get_wrec(&ssl->rlayer);
896         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
897         hash = ssl->write_hash;
898     } else {
899         rec = RECORD_LAYER_get_rrec(&ssl->rlayer);
900         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
901         hash = ssl->read_hash;
902     }
903
904     t = EVP_MD_CTX_size(hash);
905     OPENSSL_assert(t >= 0);
906     md_size = t;
907
908     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
909     if (stream_mac) {
910         mac_ctx = hash;
911     } else {
912         if (!EVP_MD_CTX_copy(&hmac, hash))
913             return -1;
914         mac_ctx = &hmac;
915     }
916
917     if (SSL_IS_DTLS(ssl)) {
918         unsigned char dtlsseq[8], *p = dtlsseq;
919
920         s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
921             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
922         memcpy(p, &seq[2], 6);
923
924         memcpy(header, dtlsseq, 8);
925     } else
926         memcpy(header, seq, 8);
927
928     header[8] = rec->type;
929     header[9] = (unsigned char)(ssl->version >> 8);
930     header[10] = (unsigned char)(ssl->version);
931     header[11] = (rec->length) >> 8;
932     header[12] = (rec->length) & 0xff;
933
934     if (!send && !SSL_USE_ETM(ssl) &&
935         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
936         ssl3_cbc_record_digest_supported(mac_ctx)) {
937         /*
938          * This is a CBC-encrypted record. We must avoid leaking any
939          * timing-side channel information about how many blocks of data we
940          * are hashing because that gives an attacker a timing-oracle.
941          */
942         /* Final param == not SSLv3 */
943         ssl3_cbc_digest_record(mac_ctx,
944                                md, &md_size,
945                                header, rec->input,
946                                rec->length + md_size, rec->orig_len,
947                                ssl->s3->read_mac_secret,
948                                ssl->s3->read_mac_secret_size, 0);
949     } else {
950         EVP_DigestSignUpdate(mac_ctx, header, sizeof(header));
951         EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length);
952         t = EVP_DigestSignFinal(mac_ctx, md, &md_size);
953         OPENSSL_assert(t > 0);
954         if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
955             tls_fips_digest_extra(ssl->enc_read_ctx,
956                                   mac_ctx, rec->input,
957                                   rec->length, rec->orig_len);
958     }
959
960     if (!stream_mac)
961         EVP_MD_CTX_cleanup(&hmac);
962 #ifdef TLS_DEBUG
963     fprintf(stderr, "seq=");
964     {
965         int z;
966         for (z = 0; z < 8; z++)
967             fprintf(stderr, "%02X ", seq[z]);
968         fprintf(stderr, "\n");
969     }
970     fprintf(stderr, "rec=");
971     {
972         unsigned int z;
973         for (z = 0; z < rec->length; z++)
974             fprintf(stderr, "%02X ", rec->data[z]);
975         fprintf(stderr, "\n");
976     }
977 #endif
978
979     if (!SSL_IS_DTLS(ssl)) {
980         for (i = 7; i >= 0; i--) {
981             ++seq[i];
982             if (seq[i] != 0)
983                 break;
984         }
985     }
986 #ifdef TLS_DEBUG
987     {
988         unsigned int z;
989         for (z = 0; z < md_size; z++)
990             fprintf(stderr, "%02X ", md[z]);
991         fprintf(stderr, "\n");
992     }
993 #endif
994     return (md_size);
995 }
996
997 /*-
998  * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
999  * record in |rec| by updating |rec->length| in constant time.
1000  *
1001  * block_size: the block size of the cipher used to encrypt the record.
1002  * returns:
1003  *   0: (in non-constant time) if the record is publicly invalid.
1004  *   1: if the padding was valid
1005  *  -1: otherwise.
1006  */
1007 int ssl3_cbc_remove_padding(const SSL *s,
1008                             SSL3_RECORD *rec,
1009                             unsigned block_size, unsigned mac_size)
1010 {
1011     unsigned padding_length, good;
1012     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1013
1014     /*
1015      * These lengths are all public so we can test them in non-constant time.
1016      */
1017     if (overhead > rec->length)
1018         return 0;
1019
1020     padding_length = rec->data[rec->length - 1];
1021     good = constant_time_ge(rec->length, padding_length + overhead);
1022     /* SSLv3 requires that the padding is minimal. */
1023     good &= constant_time_ge(block_size, padding_length + 1);
1024     rec->length -= good & (padding_length + 1);
1025     return constant_time_select_int(good, 1, -1);
1026 }
1027
1028 /*-
1029  * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1030  * record in |rec| in constant time and returns 1 if the padding is valid and
1031  * -1 otherwise. It also removes any explicit IV from the start of the record
1032  * without leaking any timing about whether there was enough space after the
1033  * padding was removed.
1034  *
1035  * block_size: the block size of the cipher used to encrypt the record.
1036  * returns:
1037  *   0: (in non-constant time) if the record is publicly invalid.
1038  *   1: if the padding was valid
1039  *  -1: otherwise.
1040  */
1041 int tls1_cbc_remove_padding(const SSL *s,
1042                             SSL3_RECORD *rec,
1043                             unsigned block_size, unsigned mac_size)
1044 {
1045     unsigned padding_length, good, to_check, i;
1046     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1047     /* Check if version requires explicit IV */
1048     if (SSL_USE_EXPLICIT_IV(s)) {
1049         /*
1050          * These lengths are all public so we can test them in non-constant
1051          * time.
1052          */
1053         if (overhead + block_size > rec->length)
1054             return 0;
1055         /* We can now safely skip explicit IV */
1056         rec->data += block_size;
1057         rec->input += block_size;
1058         rec->length -= block_size;
1059         rec->orig_len -= block_size;
1060     } else if (overhead > rec->length)
1061         return 0;
1062
1063     padding_length = rec->data[rec->length - 1];
1064
1065     /*
1066      * NB: if compression is in operation the first packet may not be of even
1067      * length so the padding bug check cannot be performed. This bug
1068      * workaround has been around since SSLeay so hopefully it is either
1069      * fixed now or no buggy implementation supports compression [steve]
1070      */
1071     if ((s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) && !s->expand) {
1072         /* First packet is even in size, so check */
1073         if ((memcmp(RECORD_LAYER_get_read_sequence(&s->rlayer),
1074                 "\0\0\0\0\0\0\0\0", 8) == 0) &&
1075             !(padding_length & 1)) {
1076             s->s3->flags |= TLS1_FLAGS_TLS_PADDING_BUG;
1077         }
1078         if ((s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) && padding_length > 0) {
1079             padding_length--;
1080         }
1081     }
1082
1083     if (EVP_CIPHER_flags(s->enc_read_ctx->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1084         /* padding is already verified */
1085         rec->length -= padding_length + 1;
1086         return 1;
1087     }
1088
1089     good = constant_time_ge(rec->length, overhead + padding_length);
1090     /*
1091      * The padding consists of a length byte at the end of the record and
1092      * then that many bytes of padding, all with the same value as the length
1093      * byte. Thus, with the length byte included, there are i+1 bytes of
1094      * padding. We can't check just |padding_length+1| bytes because that
1095      * leaks decrypted information. Therefore we always have to check the
1096      * maximum amount of padding possible. (Again, the length of the record
1097      * is public information so we can use it.)
1098      */
1099     to_check = 255;             /* maximum amount of padding. */
1100     if (to_check > rec->length - 1)
1101         to_check = rec->length - 1;
1102
1103     for (i = 0; i < to_check; i++) {
1104         unsigned char mask = constant_time_ge_8(padding_length, i);
1105         unsigned char b = rec->data[rec->length - 1 - i];
1106         /*
1107          * The final |padding_length+1| bytes should all have the value
1108          * |padding_length|. Therefore the XOR should be zero.
1109          */
1110         good &= ~(mask & (padding_length ^ b));
1111     }
1112
1113     /*
1114      * If any of the final |padding_length+1| bytes had the wrong value, one
1115      * or more of the lower eight bits of |good| will be cleared.
1116      */
1117     good = constant_time_eq(0xff, good & 0xff);
1118     rec->length -= good & (padding_length + 1);
1119
1120     return constant_time_select_int(good, 1, -1);
1121 }
1122
1123 /*-
1124  * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1125  * constant time (independent of the concrete value of rec->length, which may
1126  * vary within a 256-byte window).
1127  *
1128  * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1129  * this function.
1130  *
1131  * On entry:
1132  *   rec->orig_len >= md_size
1133  *   md_size <= EVP_MAX_MD_SIZE
1134  *
1135  * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1136  * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1137  * a single or pair of cache-lines, then the variable memory accesses don't
1138  * actually affect the timing. CPUs with smaller cache-lines [if any] are
1139  * not multi-core and are not considered vulnerable to cache-timing attacks.
1140  */
1141 #define CBC_MAC_ROTATE_IN_PLACE
1142
1143 void ssl3_cbc_copy_mac(unsigned char *out,
1144                        const SSL3_RECORD *rec, unsigned md_size)
1145 {
1146 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1147     unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1148     unsigned char *rotated_mac;
1149 #else
1150     unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1151 #endif
1152
1153     /*
1154      * mac_end is the index of |rec->data| just after the end of the MAC.
1155      */
1156     unsigned mac_end = rec->length;
1157     unsigned mac_start = mac_end - md_size;
1158     /*
1159      * scan_start contains the number of bytes that we can ignore because the
1160      * MAC's position can only vary by 255 bytes.
1161      */
1162     unsigned scan_start = 0;
1163     unsigned i, j;
1164     unsigned div_spoiler;
1165     unsigned rotate_offset;
1166
1167     OPENSSL_assert(rec->orig_len >= md_size);
1168     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1169
1170 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1171     rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1172 #endif
1173
1174     /* This information is public so it's safe to branch based on it. */
1175     if (rec->orig_len > md_size + 255 + 1)
1176         scan_start = rec->orig_len - (md_size + 255 + 1);
1177     /*
1178      * div_spoiler contains a multiple of md_size that is used to cause the
1179      * modulo operation to be constant time. Without this, the time varies
1180      * based on the amount of padding when running on Intel chips at least.
1181      * The aim of right-shifting md_size is so that the compiler doesn't
1182      * figure out that it can remove div_spoiler as that would require it to
1183      * prove that md_size is always even, which I hope is beyond it.
1184      */
1185     div_spoiler = md_size >> 1;
1186     div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1187     rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1188
1189     memset(rotated_mac, 0, md_size);
1190     for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1191         unsigned char mac_started = constant_time_ge_8(i, mac_start);
1192         unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1193         unsigned char b = rec->data[i];
1194         rotated_mac[j++] |= b & mac_started & ~mac_ended;
1195         j &= constant_time_lt(j, md_size);
1196     }
1197
1198     /* Now rotate the MAC */
1199 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1200     j = 0;
1201     for (i = 0; i < md_size; i++) {
1202         /* in case cache-line is 32 bytes, touch second line */
1203         ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1204         out[j++] = rotated_mac[rotate_offset++];
1205         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1206     }
1207 #else
1208     memset(out, 0, md_size);
1209     rotate_offset = md_size - rotate_offset;
1210     rotate_offset &= constant_time_lt(rotate_offset, md_size);
1211     for (i = 0; i < md_size; i++) {
1212         for (j = 0; j < md_size; j++)
1213             out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1214         rotate_offset++;
1215         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1216     }
1217 #endif
1218 }
1219
1220 int dtls1_process_record(SSL *s)
1221 {
1222     int i, al;
1223     int enc_err;
1224     SSL_SESSION *sess;
1225     SSL3_RECORD *rr;
1226     unsigned int mac_size;
1227     unsigned char md[EVP_MAX_MD_SIZE];
1228
1229     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1230     sess = s->session;
1231
1232     /*
1233      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1234      * and we have that many bytes in s->packet
1235      */
1236     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1237
1238     /*
1239      * ok, we can now read from 's->packet' data into 'rr' rr->input points
1240      * at rr->length bytes, which need to be copied into rr->data by either
1241      * the decryption or by the decompression When the data is 'copied' into
1242      * the rr->data buffer, rr->input will be pointed at the new buffer
1243      */
1244
1245     /*
1246      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1247      * bytes of encrypted compressed stuff.
1248      */
1249
1250     /* check is not needed I believe */
1251     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1252         al = SSL_AD_RECORD_OVERFLOW;
1253         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1254         goto f_err;
1255     }
1256
1257     /* decrypt in place in 'rr->input' */
1258     rr->data = rr->input;
1259     rr->orig_len = rr->length;
1260
1261     enc_err = s->method->ssl3_enc->enc(s, 0);
1262     /*-
1263      * enc_err is:
1264      *    0: (in non-constant time) if the record is publically invalid.
1265      *    1: if the padding is valid
1266      *   -1: if the padding is invalid
1267      */
1268     if (enc_err == 0) {
1269         /* For DTLS we simply ignore bad packets. */
1270         rr->length = 0;
1271         RECORD_LAYER_reset_packet_length(&s->rlayer);
1272         goto err;
1273     }
1274 #ifdef TLS_DEBUG
1275     printf("dec %d\n", rr->length);
1276     {
1277         unsigned int z;
1278         for (z = 0; z < rr->length; z++)
1279             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1280     }
1281     printf("\n");
1282 #endif
1283
1284     /* r->length is now the compressed data plus mac */
1285     if ((sess != NULL) &&
1286         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1287         /* s->read_hash != NULL => mac_size != -1 */
1288         unsigned char *mac = NULL;
1289         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1290         mac_size = EVP_MD_CTX_size(s->read_hash);
1291         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1292
1293         /*
1294          * orig_len is the length of the record before any padding was
1295          * removed. This is public information, as is the MAC in use,
1296          * therefore we can safely process the record in a different amount
1297          * of time if it's too short to possibly contain a MAC.
1298          */
1299         if (rr->orig_len < mac_size ||
1300             /* CBC records must have a padding length byte too. */
1301             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1302              rr->orig_len < mac_size + 1)) {
1303             al = SSL_AD_DECODE_ERROR;
1304             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1305             goto f_err;
1306         }
1307
1308         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1309             /*
1310              * We update the length so that the TLS header bytes can be
1311              * constructed correctly but we need to extract the MAC in
1312              * constant time from within the record, without leaking the
1313              * contents of the padding bytes.
1314              */
1315             mac = mac_tmp;
1316             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1317             rr->length -= mac_size;
1318         } else {
1319             /*
1320              * In this case there's no padding, so |rec->orig_len| equals
1321              * |rec->length| and we checked that there's enough bytes for
1322              * |mac_size| above.
1323              */
1324             rr->length -= mac_size;
1325             mac = &rr->data[rr->length];
1326         }
1327
1328         i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
1329         if (i < 0 || mac == NULL
1330             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1331             enc_err = -1;
1332         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1333             enc_err = -1;
1334     }
1335
1336     if (enc_err < 0) {
1337         /* decryption failed, silently discard message */
1338         rr->length = 0;
1339         RECORD_LAYER_reset_packet_length(&s->rlayer);
1340         goto err;
1341     }
1342
1343     /* r->length is now just compressed */
1344     if (s->expand != NULL) {
1345         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1346             al = SSL_AD_RECORD_OVERFLOW;
1347             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1348                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1349             goto f_err;
1350         }
1351         if (!ssl3_do_uncompress(s)) {
1352             al = SSL_AD_DECOMPRESSION_FAILURE;
1353             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1354             goto f_err;
1355         }
1356     }
1357
1358     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1359         al = SSL_AD_RECORD_OVERFLOW;
1360         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1361         goto f_err;
1362     }
1363
1364     rr->off = 0;
1365     /*-
1366      * So at this point the following is true
1367      * ssl->s3->rrec.type   is the type of record
1368      * ssl->s3->rrec.length == number of bytes in record
1369      * ssl->s3->rrec.off    == offset to first valid byte
1370      * ssl->s3->rrec.data   == where to take bytes from, increment
1371      *                         after use :-).
1372      */
1373
1374     /* we have pulled in a full packet so zero things */
1375     RECORD_LAYER_reset_packet_length(&s->rlayer);
1376     return (1);
1377
1378  f_err:
1379     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1380  err:
1381     return (0);
1382 }
1383
1384
1385 /*
1386  * retrieve a buffered record that belongs to the current epoch, ie,
1387  * processed
1388  */
1389 #define dtls1_get_processed_record(s) \
1390                    dtls1_retrieve_buffered_record((s), \
1391                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1392
1393 /*-
1394  * Call this to get a new input record.
1395  * It will return <= 0 if more data is needed, normally due to an error
1396  * or non-blocking IO.
1397  * When it finishes, one packet has been decoded and can be found in
1398  * ssl->s3->rrec.type    - is the type of record
1399  * ssl->s3->rrec.data,   - data
1400  * ssl->s3->rrec.length, - number of bytes
1401  */
1402 /* used only by dtls1_read_bytes */
1403 int dtls1_get_record(SSL *s)
1404 {
1405     int ssl_major, ssl_minor;
1406     int i, n;
1407     SSL3_RECORD *rr;
1408     unsigned char *p = NULL;
1409     unsigned short version;
1410     DTLS1_BITMAP *bitmap;
1411     unsigned int is_next_epoch;
1412
1413     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1414
1415     /*
1416      * The epoch may have changed.  If so, process all the pending records.
1417      * This is a non-blocking operation.
1418      */
1419     if (dtls1_process_buffered_records(s) < 0)
1420         return -1;
1421
1422     /* if we're renegotiating, then there may be buffered records */
1423     if (dtls1_get_processed_record(s))
1424         return 1;
1425
1426     /* get something from the wire */
1427  again:
1428     /* check if we have the header */
1429     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1430         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1431         n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1432             SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0);
1433         /* read timeout is handled by dtls1_read_bytes */
1434         if (n <= 0)
1435             return (n);         /* error or non-blocking */
1436
1437         /* this packet contained a partial record, dump it */
1438         if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1439             RECORD_LAYER_reset_packet_length(&s->rlayer);
1440             goto again;
1441         }
1442
1443         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1444
1445         p = RECORD_LAYER_get_packet(&s->rlayer);
1446
1447         if (s->msg_callback)
1448             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1449                             s, s->msg_callback_arg);
1450
1451         /* Pull apart the header into the DTLS1_RECORD */
1452         rr->type = *(p++);
1453         ssl_major = *(p++);
1454         ssl_minor = *(p++);
1455         version = (ssl_major << 8) | ssl_minor;
1456
1457         /* sequence number is 64 bits, with top 2 bytes = epoch */
1458         n2s(p, rr->epoch);
1459
1460         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1461         p += 6;
1462
1463         n2s(p, rr->length);
1464
1465         /* Lets check version */
1466         if (!s->first_packet) {
1467             if (version != s->version) {
1468                 /* unexpected version, silently discard */
1469                 rr->length = 0;
1470                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1471                 goto again;
1472             }
1473         }
1474
1475         if ((version & 0xff00) != (s->version & 0xff00)) {
1476             /* wrong version, silently discard record */
1477             rr->length = 0;
1478             RECORD_LAYER_reset_packet_length(&s->rlayer);
1479             goto again;
1480         }
1481
1482         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1483             /* record too long, silently discard it */
1484             rr->length = 0;
1485             RECORD_LAYER_reset_packet_length(&s->rlayer);
1486             goto again;
1487         }
1488
1489         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1490     }
1491
1492     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1493
1494     if (rr->length >
1495         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1496         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1497         i = rr->length;
1498         n = ssl3_read_n(s, i, i, 1);
1499         /* this packet contained a partial record, dump it */
1500         if (n != i) {
1501             rr->length = 0;
1502             RECORD_LAYER_reset_packet_length(&s->rlayer);
1503             goto again;
1504         }
1505
1506         /*
1507          * now n == rr->length, and s->packet_length ==
1508          * DTLS1_RT_HEADER_LENGTH + rr->length
1509          */
1510     }
1511     /* set state for later operations */
1512     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1513
1514     /* match epochs.  NULL means the packet is dropped on the floor */
1515     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1516     if (bitmap == NULL) {
1517         rr->length = 0;
1518         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1519         goto again;             /* get another record */
1520     }
1521 #ifndef OPENSSL_NO_SCTP
1522     /* Only do replay check if no SCTP bio */
1523     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1524 #endif
1525         /*
1526          * Check whether this is a repeat, or aged record. Don't check if
1527          * we're listening and this message is a ClientHello. They can look
1528          * as if they're replayed, since they arrive from different
1529          * connections and would be dropped unnecessarily.
1530          */
1531         if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
1532               RECORD_LAYER_get_packet_length(&s->rlayer)
1533                   > DTLS1_RT_HEADER_LENGTH &&
1534               RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]
1535                   == SSL3_MT_CLIENT_HELLO) &&
1536             !dtls1_record_replay_check(s, bitmap)) {
1537             rr->length = 0;
1538             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1539             goto again;         /* get another record */
1540         }
1541 #ifndef OPENSSL_NO_SCTP
1542     }
1543 #endif
1544
1545     /* just read a 0 length packet */
1546     if (rr->length == 0)
1547         goto again;
1548
1549     /*
1550      * If this record is from the next epoch (either HM or ALERT), and a
1551      * handshake is currently in progress, buffer it since it cannot be
1552      * processed at this time. However, do not buffer anything while
1553      * listening.
1554      */
1555     if (is_next_epoch) {
1556         if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
1557             if (dtls1_buffer_record
1558                 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1559                 rr->seq_num) < 0)
1560                 return -1;
1561             /* Mark receipt of record. */
1562             dtls1_record_bitmap_update(s, bitmap);
1563         }
1564         rr->length = 0;
1565         RECORD_LAYER_reset_packet_length(&s->rlayer);
1566         goto again;
1567     }
1568
1569     if (!dtls1_process_record(s)) {
1570         rr->length = 0;
1571         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1572         goto again;             /* get another record */
1573     }
1574     dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
1575
1576     return (1);
1577
1578 }
1579