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