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