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