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