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