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