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