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