Try to be more consistent about the alerts we send
[openssl.git] / ssl / record / ssl3_record.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <assert.h>
11 #include "../ssl_locl.h"
12 #include "internal/constant_time_locl.h"
13 #include <openssl/rand.h>
14 #include "record_locl.h"
15
16 static const unsigned char ssl3_pad_1[48] = {
17     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
18     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
19     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
20     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
21     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
22     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
23 };
24
25 static const unsigned char ssl3_pad_2[48] = {
26     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
27     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
28     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
29     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
30     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
31     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
32 };
33
34 /*
35  * Clear the contents of an SSL3_RECORD but retain any memory allocated
36  */
37 void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
38 {
39     unsigned char *comp;
40     size_t i;
41
42     for (i = 0; i < num_recs; i++) {
43         comp = r[i].comp;
44
45         memset(&r[i], 0, sizeof(*r));
46         r[i].comp = comp;
47     }
48 }
49
50 void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
51 {
52     size_t i;
53
54     for (i = 0; i < num_recs; i++) {
55         OPENSSL_free(r[i].comp);
56         r[i].comp = NULL;
57     }
58 }
59
60 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
61 {
62     memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
63 }
64
65 /*
66  * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
67  * for us in the buffer.
68  */
69 static int ssl3_record_app_data_waiting(SSL *s)
70 {
71     SSL3_BUFFER *rbuf;
72     size_t left, len;
73     unsigned char *p;
74
75     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
76
77     p = SSL3_BUFFER_get_buf(rbuf);
78     if (p == NULL)
79         return 0;
80
81     left = SSL3_BUFFER_get_left(rbuf);
82
83     if (left < SSL3_RT_HEADER_LENGTH)
84         return 0;
85
86     p += SSL3_BUFFER_get_offset(rbuf);
87
88     /*
89      * We only check the type and record length, we will sanity check version
90      * etc later
91      */
92     if (*p != SSL3_RT_APPLICATION_DATA)
93         return 0;
94
95     p += 3;
96     n2s(p, len);
97
98     if (left < SSL3_RT_HEADER_LENGTH + len)
99         return 0;
100
101     return 1;
102 }
103
104 int early_data_count_ok(SSL *s, size_t length, size_t overhead, int *al)
105 {
106     uint32_t max_early_data = s->max_early_data;
107
108     /*
109      * If we are a client then we always use the max_early_data from the
110      * session. Otherwise we go with the lowest out of the max early data set in
111      * the session and the configured max_early_data.
112      */
113     if (!s->server || (s->hit
114                        && s->session->ext.max_early_data < s->max_early_data))
115         max_early_data = s->session->ext.max_early_data;
116
117     if (max_early_data == 0) {
118         if (al != NULL)
119             *al = SSL_AD_UNEXPECTED_MESSAGE;
120         SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
121         return 0;
122     }
123
124     /* If we are dealing with ciphertext we need to allow for the overhead */
125     max_early_data += overhead;
126
127     if (s->early_data_count + length > max_early_data) {
128         if (al != NULL)
129             *al = SSL_AD_UNEXPECTED_MESSAGE;
130         SSLerr(SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
131         return 0;
132     }
133     s->early_data_count += length;
134
135     return 1;
136 }
137
138 /*
139  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
140  * will be processed per call to ssl3_get_record. Without this limit an
141  * attacker could send empty records at a faster rate than we can process and
142  * cause ssl3_get_record to loop forever.
143  */
144 #define MAX_EMPTY_RECORDS 32
145
146 #define SSL2_RT_HEADER_LENGTH   2
147 /*-
148  * Call this to get new input records.
149  * It will return <= 0 if more data is needed, normally due to an error
150  * or non-blocking IO.
151  * When it finishes, |numrpipes| records have been decoded. For each record 'i':
152  * rr[i].type    - is the type of record
153  * rr[i].data,   - data
154  * rr[i].length, - number of bytes
155  * Multiple records will only be returned if the record types are all
156  * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
157  * |max_pipelines|
158  */
159 /* used only by ssl3_read_bytes */
160 int ssl3_get_record(SSL *s)
161 {
162     int al;
163     int enc_err, rret, ret = -1;
164     int i;
165     size_t more, n;
166     SSL3_RECORD *rr, *thisrr;
167     SSL3_BUFFER *rbuf;
168     SSL_SESSION *sess;
169     unsigned char *p;
170     unsigned char md[EVP_MAX_MD_SIZE];
171     unsigned int version;
172     size_t mac_size;
173     int imac_size;
174     size_t num_recs = 0, max_recs, j;
175     PACKET pkt, sslv2pkt;
176     size_t first_rec_len;
177
178     rr = RECORD_LAYER_get_rrec(&s->rlayer);
179     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
180     max_recs = s->max_pipelines;
181     if (max_recs == 0)
182         max_recs = 1;
183     sess = s->session;
184
185     do {
186         thisrr = &rr[num_recs];
187
188         /* check if we have the header */
189         if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
190             (RECORD_LAYER_get_packet_length(&s->rlayer)
191              < SSL3_RT_HEADER_LENGTH)) {
192             size_t sslv2len;
193             unsigned int type;
194
195             rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
196                                SSL3_BUFFER_get_len(rbuf), 0,
197                                num_recs == 0 ? 1 : 0, &n);
198             if (rret <= 0)
199                 return rret;     /* error or non-blocking */
200             RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
201
202             p = RECORD_LAYER_get_packet(&s->rlayer);
203             if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
204                                  RECORD_LAYER_get_packet_length(&s->rlayer))) {
205                 al = SSL_AD_INTERNAL_ERROR;
206                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
207                 goto f_err;
208             }
209             sslv2pkt = pkt;
210             if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
211                     || !PACKET_get_1(&sslv2pkt, &type)) {
212                 al = SSL_AD_DECODE_ERROR;
213                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
214                 goto f_err;
215             }
216             /*
217              * The first record received by the server may be a V2ClientHello.
218              */
219             if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
220                     && (sslv2len & 0x8000) != 0
221                     && (type == SSL2_MT_CLIENT_HELLO)) {
222                 /*
223                  *  SSLv2 style record
224                  *
225                  * |num_recs| here will actually always be 0 because
226                  * |num_recs > 0| only ever occurs when we are processing
227                  * multiple app data records - which we know isn't the case here
228                  * because it is an SSLv2ClientHello. We keep it using
229                  * |num_recs| for the sake of consistency
230                  */
231                 thisrr->type = SSL3_RT_HANDSHAKE;
232                 thisrr->rec_version = SSL2_VERSION;
233
234                 thisrr->length = sslv2len & 0x7fff;
235
236                 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
237                     - SSL2_RT_HEADER_LENGTH) {
238                     al = SSL_AD_RECORD_OVERFLOW;
239                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
240                     goto f_err;
241                 }
242
243                 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
244                     al = SSL_AD_DECODE_ERROR;
245                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
246                     goto f_err;
247                 }
248             } else {
249                 /* SSLv3+ style record */
250                 if (s->msg_callback)
251                     s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
252                                     s->msg_callback_arg);
253
254                 /* Pull apart the header into the SSL3_RECORD */
255                 if (!PACKET_get_1(&pkt, &type)
256                         || !PACKET_get_net_2(&pkt, &version)
257                         || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
258                     al = SSL_AD_DECODE_ERROR;
259                     SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
260                     goto f_err;
261                 }
262                 thisrr->type = type;
263                 thisrr->rec_version = version;
264
265                 /* Lets check version. In TLSv1.3 we ignore this field */
266                 if (!s->first_packet && !SSL_IS_TLS13(s)
267                         && version != (unsigned int)s->version) {
268                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
269                     if ((s->version & 0xFF00) == (version & 0xFF00)
270                         && !s->enc_write_ctx && !s->write_hash) {
271                         if (thisrr->type == SSL3_RT_ALERT) {
272                             /*
273                              * The record is using an incorrect version number,
274                              * but what we've got appears to be an alert. We
275                              * haven't read the body yet to check whether its a
276                              * fatal or not - but chances are it is. We probably
277                              * shouldn't send a fatal alert back. We'll just
278                              * end.
279                              */
280                             goto err;
281                         }
282                         /*
283                          * Send back error using their minor version number :-)
284                          */
285                         s->version = (unsigned short)version;
286                     }
287                     al = SSL_AD_PROTOCOL_VERSION;
288                     goto f_err;
289                 }
290
291                 if ((version >> 8) != SSL3_VERSION_MAJOR) {
292                     if (RECORD_LAYER_is_first_record(&s->rlayer)) {
293                         /* Go back to start of packet, look at the five bytes
294                          * that we have. */
295                         p = RECORD_LAYER_get_packet(&s->rlayer);
296                         if (strncmp((char *)p, "GET ", 4) == 0 ||
297                             strncmp((char *)p, "POST ", 5) == 0 ||
298                             strncmp((char *)p, "HEAD ", 5) == 0 ||
299                             strncmp((char *)p, "PUT ", 4) == 0) {
300                             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
301                             goto err;
302                         } else if (strncmp((char *)p, "CONNE", 5) == 0) {
303                             SSLerr(SSL_F_SSL3_GET_RECORD,
304                                    SSL_R_HTTPS_PROXY_REQUEST);
305                             goto err;
306                         }
307
308                         /* Doesn't look like TLS - don't send an alert */
309                         SSLerr(SSL_F_SSL3_GET_RECORD,
310                                SSL_R_WRONG_VERSION_NUMBER);
311                         goto err;
312                     } else {
313                         SSLerr(SSL_F_SSL3_GET_RECORD,
314                                SSL_R_WRONG_VERSION_NUMBER);
315                         al = SSL_AD_PROTOCOL_VERSION;
316                         goto f_err;
317                     }
318                 }
319
320                 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL
321                         && thisrr->type != SSL3_RT_APPLICATION_DATA) {
322                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
323                     al = SSL_AD_UNEXPECTED_MESSAGE;
324                     goto f_err;
325                 }
326
327                 if (thisrr->length >
328                     SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
329                     al = SSL_AD_RECORD_OVERFLOW;
330                     SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
331                     goto f_err;
332                 }
333             }
334
335             /* now s->rlayer.rstate == SSL_ST_READ_BODY */
336         }
337
338         if (SSL_IS_TLS13(s)) {
339             if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
340                 al = SSL_AD_RECORD_OVERFLOW;
341                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
342                 goto f_err;
343             }
344         } else {
345             size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
346
347 #ifndef OPENSSL_NO_COMP
348             /*
349              * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
350              * does not include the compression overhead anyway.
351              */
352             if (s->expand == NULL)
353                 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
354 #endif
355
356             if (thisrr->length > len) {
357                 al = SSL_AD_RECORD_OVERFLOW;
358                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
359                 goto f_err;
360             }
361         }
362
363         /*
364          * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
365          * Calculate how much more data we need to read for the rest of the
366          * record
367          */
368         if (thisrr->rec_version == SSL2_VERSION) {
369             more = thisrr->length + SSL2_RT_HEADER_LENGTH
370                 - SSL3_RT_HEADER_LENGTH;
371         } else {
372             more = thisrr->length;
373         }
374         if (more > 0) {
375             /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
376
377             rret = ssl3_read_n(s, more, more, 1, 0, &n);
378             if (rret <= 0)
379                 return rret;     /* error or non-blocking io */
380         }
381
382         /* set state for later operations */
383         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
384
385         /*
386          * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
387          * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
388          * + thisrr->length and we have that many bytes in s->packet
389          */
390         if (thisrr->rec_version == SSL2_VERSION) {
391             thisrr->input =
392                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
393         } else {
394             thisrr->input =
395                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
396         }
397
398         /*
399          * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
400          * points at thisrr->length bytes, which need to be copied into
401          * thisrr->data by either the decryption or by the decompression When
402          * the data is 'copied' into the thisrr->data buffer, thisrr->input will
403          * be pointed at the new buffer
404          */
405
406         /*
407          * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
408          * thisrr->length bytes of encrypted compressed stuff.
409          */
410
411         /* decrypt in place in 'thisrr->input' */
412         thisrr->data = thisrr->input;
413         thisrr->orig_len = thisrr->length;
414
415         /* Mark this record as not read by upper layers yet */
416         thisrr->read = 0;
417
418         num_recs++;
419
420         /* we have pulled in a full packet so zero things */
421         RECORD_LAYER_reset_packet_length(&s->rlayer);
422         RECORD_LAYER_clear_first_record(&s->rlayer);
423     } while (num_recs < max_recs
424              && thisrr->type == SSL3_RT_APPLICATION_DATA
425              && SSL_USE_EXPLICIT_IV(s)
426              && s->enc_read_ctx != NULL
427              && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
428                  & EVP_CIPH_FLAG_PIPELINE)
429              && ssl3_record_app_data_waiting(s));
430
431     /*
432      * If in encrypt-then-mac mode calculate mac from encrypted record. All
433      * the details below are public so no timing details can leak.
434      */
435     if (SSL_READ_ETM(s) && s->read_hash) {
436         unsigned char *mac;
437         /* TODO(size_t): convert this to do size_t properly */
438         imac_size = EVP_MD_CTX_size(s->read_hash);
439         assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE);
440         if (imac_size < 0 || imac_size > EVP_MAX_MD_SIZE) {
441                 al = SSL_AD_INTERNAL_ERROR;
442                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_LIB_EVP);
443                 goto f_err;
444         }
445         mac_size = (size_t)imac_size;
446         for (j = 0; j < num_recs; j++) {
447             thisrr = &rr[j];
448
449             if (thisrr->length < mac_size) {
450                 al = SSL_AD_DECODE_ERROR;
451                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
452                 goto f_err;
453             }
454             thisrr->length -= mac_size;
455             mac = thisrr->data + thisrr->length;
456             i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
457             if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
458                 al = SSL_AD_BAD_RECORD_MAC;
459                 SSLerr(SSL_F_SSL3_GET_RECORD,
460                        SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
461                 goto f_err;
462             }
463         }
464     }
465
466     first_rec_len = rr[0].length;
467
468     enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
469
470     /*-
471      * enc_err is:
472      *    0: (in non-constant time) if the record is publicly invalid.
473      *    1: if the padding is valid
474      *    -1: if the padding is invalid
475      */
476     if (enc_err == 0) {
477         if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
478             /*
479              * Valid early_data that we cannot decrypt might fail here as
480              * publicly invalid. We treat it like an empty record.
481              */
482
483             thisrr = &rr[0];
484
485             if (!early_data_count_ok(s, thisrr->length,
486                                      EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
487                 goto f_err;
488
489             thisrr->length = 0;
490             thisrr->read = 1;
491             RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
492             RECORD_LAYER_reset_read_sequence(&s->rlayer);
493             return 1;
494         }
495         al = SSL_AD_DECRYPTION_FAILED;
496         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
497         goto f_err;
498     }
499 #ifdef SSL_DEBUG
500     printf("dec %"OSSLzu"\n", rr[0].length);
501     {
502         size_t z;
503         for (z = 0; z < rr[0].length; z++)
504             printf("%02X%c", rr[0].data[z], ((z + 1) % 16) ? ' ' : '\n');
505     }
506     printf("\n");
507 #endif
508
509     /* r->length is now the compressed data plus mac */
510     if ((sess != NULL) &&
511         (s->enc_read_ctx != NULL) &&
512         (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
513         /* s->read_hash != NULL => mac_size != -1 */
514         unsigned char *mac = NULL;
515         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
516
517         mac_size = EVP_MD_CTX_size(s->read_hash);
518         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
519
520         for (j = 0; j < num_recs; j++) {
521             thisrr = &rr[j];
522             /*
523              * orig_len is the length of the record before any padding was
524              * removed. This is public information, as is the MAC in use,
525              * therefore we can safely process the record in a different amount
526              * of time if it's too short to possibly contain a MAC.
527              */
528             if (thisrr->orig_len < mac_size ||
529                 /* CBC records must have a padding length byte too. */
530                 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
531                  thisrr->orig_len < mac_size + 1)) {
532                 al = SSL_AD_DECODE_ERROR;
533                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
534                 goto f_err;
535             }
536
537             if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
538                 /*
539                  * We update the length so that the TLS header bytes can be
540                  * constructed correctly but we need to extract the MAC in
541                  * constant time from within the record, without leaking the
542                  * contents of the padding bytes.
543                  */
544                 mac = mac_tmp;
545                 ssl3_cbc_copy_mac(mac_tmp, thisrr, mac_size);
546                 thisrr->length -= mac_size;
547             } else {
548                 /*
549                  * In this case there's no padding, so |rec->orig_len| equals
550                  * |rec->length| and we checked that there's enough bytes for
551                  * |mac_size| above.
552                  */
553                 thisrr->length -= mac_size;
554                 mac = &thisrr->data[thisrr->length];
555             }
556
557             i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
558             if (i == 0 || mac == NULL
559                 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
560                 enc_err = -1;
561             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
562                 enc_err = -1;
563         }
564     }
565
566     if (enc_err < 0) {
567         if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
568             /*
569              * We assume this is unreadable early_data - we treat it like an
570              * empty record
571              */
572
573             /*
574              * The record length may have been modified by the mac check above
575              * so we use the previously saved value
576              */
577             if (!early_data_count_ok(s, first_rec_len,
578                                      EARLY_DATA_CIPHERTEXT_OVERHEAD, &al))
579                 goto f_err;
580
581             thisrr = &rr[0];
582             thisrr->length = 0;
583             thisrr->read = 1;
584             RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
585             RECORD_LAYER_reset_read_sequence(&s->rlayer);
586             return 1;
587         }
588         /*
589          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
590          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
591          * failure is directly visible from the ciphertext anyway, we should
592          * not reveal which kind of error occurred -- this might become
593          * visible to an attacker (e.g. via a logfile)
594          */
595         al = SSL_AD_BAD_RECORD_MAC;
596         SSLerr(SSL_F_SSL3_GET_RECORD,
597                SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
598         goto f_err;
599     }
600
601     for (j = 0; j < num_recs; j++) {
602         thisrr = &rr[j];
603
604         /* thisrr->length is now just compressed */
605         if (s->expand != NULL) {
606             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
607                 al = SSL_AD_RECORD_OVERFLOW;
608                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
609                 goto f_err;
610             }
611             if (!ssl3_do_uncompress(s, thisrr)) {
612                 al = SSL_AD_DECOMPRESSION_FAILURE;
613                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
614                 goto f_err;
615             }
616         }
617
618         if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
619             size_t end;
620
621             if (thisrr->length == 0
622                     || thisrr->type != SSL3_RT_APPLICATION_DATA) {
623                 al = SSL_AD_UNEXPECTED_MESSAGE;
624                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
625                 goto f_err;
626             }
627
628             /* Strip trailing padding */
629             for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
630                  end--)
631                 continue;
632
633             thisrr->length = end;
634             thisrr->type = thisrr->data[end];
635             if (thisrr->type != SSL3_RT_APPLICATION_DATA
636                     && thisrr->type != SSL3_RT_ALERT
637                     && thisrr->type != SSL3_RT_HANDSHAKE) {
638                 al = SSL_AD_UNEXPECTED_MESSAGE;
639                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
640                 goto f_err;
641             }
642             if (s->msg_callback)
643                 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
644                                 &thisrr->data[end], 1, s, s->msg_callback_arg);
645         }
646
647         /*
648          * TLSv1.3 alert and handshake records are required to be non-zero in
649          * length.
650          */
651         if (SSL_IS_TLS13(s)
652                 && (thisrr->type == SSL3_RT_HANDSHAKE
653                     || thisrr->type == SSL3_RT_ALERT)
654                 && thisrr->length == 0) {
655             al = SSL_AD_UNEXPECTED_MESSAGE;
656             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_LENGTH);
657             goto f_err;
658         }
659
660         if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
661             al = SSL_AD_RECORD_OVERFLOW;
662             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
663             goto f_err;
664         }
665
666         thisrr->off = 0;
667         /*-
668          * So at this point the following is true
669          * thisrr->type   is the type of record
670          * thisrr->length == number of bytes in record
671          * thisrr->off    == offset to first valid byte
672          * thisrr->data   == where to take bytes from, increment after use :-).
673          */
674
675         /* just read a 0 length packet */
676         if (thisrr->length == 0) {
677             RECORD_LAYER_inc_empty_record_count(&s->rlayer);
678             if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
679                 > MAX_EMPTY_RECORDS) {
680                 al = SSL_AD_UNEXPECTED_MESSAGE;
681                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
682                 goto f_err;
683             }
684         } else {
685             RECORD_LAYER_reset_empty_record_count(&s->rlayer);
686         }
687     }
688
689     if (s->early_data_state == SSL_EARLY_DATA_READING) {
690         thisrr = &rr[0];
691         if (thisrr->type == SSL3_RT_APPLICATION_DATA
692                 && !early_data_count_ok(s, thisrr->length, 0, &al))
693             goto f_err;
694     }
695
696     RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
697     return 1;
698
699  f_err:
700     ssl3_send_alert(s, SSL3_AL_FATAL, al);
701  err:
702     return ret;
703 }
704
705 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
706 {
707 #ifndef OPENSSL_NO_COMP
708     int i;
709
710     if (rr->comp == NULL) {
711         rr->comp = (unsigned char *)
712             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
713     }
714     if (rr->comp == NULL)
715         return 0;
716
717     /* TODO(size_t): Convert this call */
718     i = COMP_expand_block(ssl->expand, rr->comp,
719                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
720     if (i < 0)
721         return 0;
722     else
723         rr->length = i;
724     rr->data = rr->comp;
725 #endif
726     return 1;
727 }
728
729 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
730 {
731 #ifndef OPENSSL_NO_COMP
732     int i;
733
734     /* TODO(size_t): Convert this call */
735     i = COMP_compress_block(ssl->compress, wr->data,
736                             (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
737                             wr->input, (int)wr->length);
738     if (i < 0)
739         return (0);
740     else
741         wr->length = i;
742
743     wr->input = wr->data;
744 #endif
745     return (1);
746 }
747
748 /*-
749  * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
750  *
751  * Returns:
752  *   0: (in non-constant time) if the record is publically invalid (i.e. too
753  *       short etc).
754  *   1: if the record's padding is valid / the encryption was successful.
755  *   -1: if the record's padding is invalid or, if sending, an internal error
756  *       occurred.
757  */
758 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending)
759 {
760     SSL3_RECORD *rec;
761     EVP_CIPHER_CTX *ds;
762     size_t l, i;
763     size_t bs, mac_size = 0;
764     int imac_size;
765     const EVP_CIPHER *enc;
766
767     rec = inrecs;
768     /*
769      * We shouldn't ever be called with more than one record in the SSLv3 case
770      */
771     if (n_recs != 1)
772         return 0;
773     if (sending) {
774         ds = s->enc_write_ctx;
775         if (s->enc_write_ctx == NULL)
776             enc = NULL;
777         else
778             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
779     } else {
780         ds = s->enc_read_ctx;
781         if (s->enc_read_ctx == NULL)
782             enc = NULL;
783         else
784             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
785     }
786
787     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
788         memmove(rec->data, rec->input, rec->length);
789         rec->input = rec->data;
790     } else {
791         l = rec->length;
792         /* TODO(size_t): Convert this call */
793         bs = EVP_CIPHER_CTX_block_size(ds);
794
795         /* COMPRESS */
796
797         if ((bs != 1) && sending) {
798             i = bs - (l % bs);
799
800             /* we need to add 'i-1' padding bytes */
801             l += i;
802             /*
803              * the last of these zero bytes will be overwritten with the
804              * padding length.
805              */
806             memset(&rec->input[rec->length], 0, i);
807             rec->length += i;
808             rec->input[l - 1] = (unsigned char)(i - 1);
809         }
810
811         if (!sending) {
812             if (l == 0 || l % bs != 0)
813                 return 0;
814             /* otherwise, rec->length >= bs */
815         }
816
817         /* TODO(size_t): Convert this call */
818         if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1)
819             return -1;
820
821         if (EVP_MD_CTX_md(s->read_hash) != NULL) {
822             /* TODO(size_t): convert me */
823             imac_size = EVP_MD_CTX_size(s->read_hash);
824             if (imac_size < 0)
825                 return -1;
826             mac_size = (size_t)imac_size;
827         }
828         if ((bs != 1) && !sending)
829             return ssl3_cbc_remove_padding(rec, bs, mac_size);
830     }
831     return (1);
832 }
833
834 #define MAX_PADDING 256
835 /*-
836  * tls1_enc encrypts/decrypts |n_recs| in |recs|.
837  *
838  * Returns:
839  *   0: (in non-constant time) if the record is publically invalid (i.e. too
840  *       short etc).
841  *   1: if the record's padding is valid / the encryption was successful.
842  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
843  *       an internal error occurred.
844  */
845 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending)
846 {
847     EVP_CIPHER_CTX *ds;
848     size_t reclen[SSL_MAX_PIPELINES];
849     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
850     int i, pad = 0, ret, tmpr;
851     size_t bs, mac_size = 0, ctr, padnum, loop;
852     unsigned char padval;
853     int imac_size;
854     const EVP_CIPHER *enc;
855
856     if (n_recs == 0)
857         return 0;
858
859     if (sending) {
860         if (EVP_MD_CTX_md(s->write_hash)) {
861             int n = EVP_MD_CTX_size(s->write_hash);
862             OPENSSL_assert(n >= 0);
863         }
864         ds = s->enc_write_ctx;
865         if (s->enc_write_ctx == NULL)
866             enc = NULL;
867         else {
868             int ivlen;
869             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
870             /* For TLSv1.1 and later explicit IV */
871             if (SSL_USE_EXPLICIT_IV(s)
872                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
873                 ivlen = EVP_CIPHER_iv_length(enc);
874             else
875                 ivlen = 0;
876             if (ivlen > 1) {
877                 for (ctr = 0; ctr < n_recs; ctr++) {
878                     if (recs[ctr].data != recs[ctr].input) {
879                         /*
880                          * we can't write into the input stream: Can this ever
881                          * happen?? (steve)
882                          */
883                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
884                         return -1;
885                     } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
886                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
887                         return -1;
888                     }
889                 }
890             }
891         }
892     } else {
893         if (EVP_MD_CTX_md(s->read_hash)) {
894             int n = EVP_MD_CTX_size(s->read_hash);
895             OPENSSL_assert(n >= 0);
896         }
897         ds = s->enc_read_ctx;
898         if (s->enc_read_ctx == NULL)
899             enc = NULL;
900         else
901             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
902     }
903
904     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
905         for (ctr = 0; ctr < n_recs; ctr++) {
906             memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
907             recs[ctr].input = recs[ctr].data;
908         }
909         ret = 1;
910     } else {
911         bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
912
913         if (n_recs > 1) {
914             if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
915                   & EVP_CIPH_FLAG_PIPELINE)) {
916                 /*
917                  * We shouldn't have been called with pipeline data if the
918                  * cipher doesn't support pipelining
919                  */
920                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
921                 return -1;
922             }
923         }
924         for (ctr = 0; ctr < n_recs; ctr++) {
925             reclen[ctr] = recs[ctr].length;
926
927             if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
928                 & EVP_CIPH_FLAG_AEAD_CIPHER) {
929                 unsigned char *seq;
930
931                 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
932                     : RECORD_LAYER_get_read_sequence(&s->rlayer);
933
934                 if (SSL_IS_DTLS(s)) {
935                     /* DTLS does not support pipelining */
936                     unsigned char dtlsseq[9], *p = dtlsseq;
937
938                     s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
939                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
940                     memcpy(p, &seq[2], 6);
941                     memcpy(buf[ctr], dtlsseq, 8);
942                 } else {
943                     memcpy(buf[ctr], seq, 8);
944                     for (i = 7; i >= 0; i--) { /* increment */
945                         ++seq[i];
946                         if (seq[i] != 0)
947                             break;
948                     }
949                 }
950
951                 buf[ctr][8] = recs[ctr].type;
952                 buf[ctr][9] = (unsigned char)(s->version >> 8);
953                 buf[ctr][10] = (unsigned char)(s->version);
954                 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
955                 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
956                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
957                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
958                 if (pad <= 0)
959                     return -1;
960
961                 if (sending) {
962                     reclen[ctr] += pad;
963                     recs[ctr].length += pad;
964                 }
965
966             } else if ((bs != 1) && sending) {
967                 padnum = bs - (reclen[ctr] % bs);
968
969                 /* Add weird padding of upto 256 bytes */
970
971                 if (padnum > MAX_PADDING)
972                     return -1;
973                 /* we need to add 'padnum' padding bytes of value padval */
974                 padval = (unsigned char)(padnum - 1);
975                 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
976                     recs[ctr].input[loop] = padval;
977                 reclen[ctr] += padnum;
978                 recs[ctr].length += padnum;
979             }
980
981             if (!sending) {
982                 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
983                     return 0;
984             }
985         }
986         if (n_recs > 1) {
987             unsigned char *data[SSL_MAX_PIPELINES];
988
989             /* Set the output buffers */
990             for (ctr = 0; ctr < n_recs; ctr++) {
991                 data[ctr] = recs[ctr].data;
992             }
993             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
994                                     (int)n_recs, data) <= 0) {
995                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
996             }
997             /* Set the input buffers */
998             for (ctr = 0; ctr < n_recs; ctr++) {
999                 data[ctr] = recs[ctr].input;
1000             }
1001             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
1002                                     (int)n_recs, data) <= 0
1003                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
1004                                        (int)n_recs, reclen) <= 0) {
1005                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
1006                 return -1;
1007             }
1008         }
1009
1010         /* TODO(size_t): Convert this call */
1011         tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
1012                           (unsigned int)reclen[0]);
1013         if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1014              & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1015             ? (tmpr < 0)
1016             : (tmpr == 0))
1017             return -1;          /* AEAD can fail to verify MAC */
1018         if (sending == 0) {
1019             if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1020                 for (ctr = 0; ctr < n_recs; ctr++) {
1021                     recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1022                     recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1023                     recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1024                 }
1025             } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1026                 for (ctr = 0; ctr < n_recs; ctr++) {
1027                     recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1028                     recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1029                     recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1030                 }
1031             }
1032         }
1033
1034         ret = 1;
1035         if (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL) {
1036             imac_size = EVP_MD_CTX_size(s->read_hash);
1037             if (imac_size < 0)
1038                 return -1;
1039             mac_size = (size_t)imac_size;
1040         }
1041         if ((bs != 1) && !sending) {
1042             int tmpret;
1043             for (ctr = 0; ctr < n_recs; ctr++) {
1044                 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
1045                 /*
1046                  * If tmpret == 0 then this means publicly invalid so we can
1047                  * short circuit things here. Otherwise we must respect constant
1048                  * time behaviour.
1049                  */
1050                 if (tmpret == 0)
1051                     return 0;
1052                 ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
1053                                                ret, -1);
1054             }
1055         }
1056         if (pad && !sending) {
1057             for (ctr = 0; ctr < n_recs; ctr++) {
1058                 recs[ctr].length -= pad;
1059             }
1060         }
1061     }
1062     return ret;
1063 }
1064
1065 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1066 {
1067     unsigned char *mac_sec, *seq;
1068     const EVP_MD_CTX *hash;
1069     unsigned char *p, rec_char;
1070     size_t md_size;
1071     size_t npad;
1072     int t;
1073
1074     if (sending) {
1075         mac_sec = &(ssl->s3->write_mac_secret[0]);
1076         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1077         hash = ssl->write_hash;
1078     } else {
1079         mac_sec = &(ssl->s3->read_mac_secret[0]);
1080         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1081         hash = ssl->read_hash;
1082     }
1083
1084     t = EVP_MD_CTX_size(hash);
1085     if (t < 0)
1086         return 0;
1087     md_size = t;
1088     npad = (48 / md_size) * md_size;
1089
1090     if (!sending &&
1091         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1092         ssl3_cbc_record_digest_supported(hash)) {
1093         /*
1094          * This is a CBC-encrypted record. We must avoid leaking any
1095          * timing-side channel information about how many blocks of data we
1096          * are hashing because that gives an attacker a timing-oracle.
1097          */
1098
1099         /*-
1100          * npad is, at most, 48 bytes and that's with MD5:
1101          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1102          *
1103          * With SHA-1 (the largest hash speced for SSLv3) the hash size
1104          * goes up 4, but npad goes down by 8, resulting in a smaller
1105          * total size.
1106          */
1107         unsigned char header[75];
1108         size_t j = 0;
1109         memcpy(header + j, mac_sec, md_size);
1110         j += md_size;
1111         memcpy(header + j, ssl3_pad_1, npad);
1112         j += npad;
1113         memcpy(header + j, seq, 8);
1114         j += 8;
1115         header[j++] = rec->type;
1116         header[j++] = (unsigned char)(rec->length >> 8);
1117         header[j++] = (unsigned char)(rec->length & 0xff);
1118
1119         /* Final param == is SSLv3 */
1120         if (ssl3_cbc_digest_record(hash,
1121                                    md, &md_size,
1122                                    header, rec->input,
1123                                    rec->length + md_size, rec->orig_len,
1124                                    mac_sec, md_size, 1) <= 0)
1125             return 0;
1126     } else {
1127         unsigned int md_size_u;
1128         /* Chop the digest off the end :-) */
1129         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1130
1131         if (md_ctx == NULL)
1132             return 0;
1133
1134         rec_char = rec->type;
1135         p = md;
1136         s2n(rec->length, p);
1137         if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1138             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1139             || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1140             || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1141             || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1142             || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1143             || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1144             || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1145             || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1146             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1147             || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1148             || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1149             || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1150             EVP_MD_CTX_reset(md_ctx);
1151             return 0;
1152         }
1153
1154         EVP_MD_CTX_free(md_ctx);
1155     }
1156
1157     ssl3_record_sequence_update(seq);
1158     return 1;
1159 }
1160
1161 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1162 {
1163     unsigned char *seq;
1164     EVP_MD_CTX *hash;
1165     size_t md_size;
1166     int i;
1167     EVP_MD_CTX *hmac = NULL, *mac_ctx;
1168     unsigned char header[13];
1169     int stream_mac = (sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1170                       : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1171     int t;
1172
1173     if (sending) {
1174         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1175         hash = ssl->write_hash;
1176     } else {
1177         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1178         hash = ssl->read_hash;
1179     }
1180
1181     t = EVP_MD_CTX_size(hash);
1182     OPENSSL_assert(t >= 0);
1183     md_size = t;
1184
1185     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1186     if (stream_mac) {
1187         mac_ctx = hash;
1188     } else {
1189         hmac = EVP_MD_CTX_new();
1190         if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
1191             return 0;
1192         mac_ctx = hmac;
1193     }
1194
1195     if (SSL_IS_DTLS(ssl)) {
1196         unsigned char dtlsseq[8], *p = dtlsseq;
1197
1198         s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1199             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1200         memcpy(p, &seq[2], 6);
1201
1202         memcpy(header, dtlsseq, 8);
1203     } else
1204         memcpy(header, seq, 8);
1205
1206     header[8] = rec->type;
1207     header[9] = (unsigned char)(ssl->version >> 8);
1208     header[10] = (unsigned char)(ssl->version);
1209     header[11] = (unsigned char)(rec->length >> 8);
1210     header[12] = (unsigned char)(rec->length & 0xff);
1211
1212     if (!sending && !SSL_READ_ETM(ssl) &&
1213         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1214         ssl3_cbc_record_digest_supported(mac_ctx)) {
1215         /*
1216          * This is a CBC-encrypted record. We must avoid leaking any
1217          * timing-side channel information about how many blocks of data we
1218          * are hashing because that gives an attacker a timing-oracle.
1219          */
1220         /* Final param == not SSLv3 */
1221         if (ssl3_cbc_digest_record(mac_ctx,
1222                                    md, &md_size,
1223                                    header, rec->input,
1224                                    rec->length + md_size, rec->orig_len,
1225                                    ssl->s3->read_mac_secret,
1226                                    ssl->s3->read_mac_secret_size, 0) <= 0) {
1227             EVP_MD_CTX_free(hmac);
1228             return -1;
1229         }
1230     } else {
1231         /* TODO(size_t): Convert these calls */
1232         if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1233             || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1234             || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1235             EVP_MD_CTX_free(hmac);
1236             return 0;
1237         }
1238     }
1239
1240     EVP_MD_CTX_free(hmac);
1241
1242 #ifdef SSL_DEBUG
1243     fprintf(stderr, "seq=");
1244     {
1245         int z;
1246         for (z = 0; z < 8; z++)
1247             fprintf(stderr, "%02X ", seq[z]);
1248         fprintf(stderr, "\n");
1249     }
1250     fprintf(stderr, "rec=");
1251     {
1252         size_t z;
1253         for (z = 0; z < rec->length; z++)
1254             fprintf(stderr, "%02X ", rec->data[z]);
1255         fprintf(stderr, "\n");
1256     }
1257 #endif
1258
1259     if (!SSL_IS_DTLS(ssl)) {
1260         for (i = 7; i >= 0; i--) {
1261             ++seq[i];
1262             if (seq[i] != 0)
1263                 break;
1264         }
1265     }
1266 #ifdef SSL_DEBUG
1267     {
1268         unsigned int z;
1269         for (z = 0; z < md_size; z++)
1270             fprintf(stderr, "%02X ", md[z]);
1271         fprintf(stderr, "\n");
1272     }
1273 #endif
1274     return 1;
1275 }
1276
1277 /*-
1278  * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1279  * record in |rec| by updating |rec->length| in constant time.
1280  *
1281  * block_size: the block size of the cipher used to encrypt the record.
1282  * returns:
1283  *   0: (in non-constant time) if the record is publicly invalid.
1284  *   1: if the padding was valid
1285  *  -1: otherwise.
1286  */
1287 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1288                             size_t block_size, size_t mac_size)
1289 {
1290     size_t padding_length;
1291     size_t good;
1292     const size_t overhead = 1 /* padding length byte */  + mac_size;
1293
1294     /*
1295      * These lengths are all public so we can test them in non-constant time.
1296      */
1297     if (overhead > rec->length)
1298         return 0;
1299
1300     padding_length = rec->data[rec->length - 1];
1301     good = constant_time_ge_s(rec->length, padding_length + overhead);
1302     /* SSLv3 requires that the padding is minimal. */
1303     good &= constant_time_ge_s(block_size, padding_length + 1);
1304     rec->length -= good & (padding_length + 1);
1305     return constant_time_select_int_s(good, 1, -1);
1306 }
1307
1308 /*-
1309  * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1310  * record in |rec| in constant time and returns 1 if the padding is valid and
1311  * -1 otherwise. It also removes any explicit IV from the start of the record
1312  * without leaking any timing about whether there was enough space after the
1313  * padding was removed.
1314  *
1315  * block_size: the block size of the cipher used to encrypt the record.
1316  * returns:
1317  *   0: (in non-constant time) if the record is publicly invalid.
1318  *   1: if the padding was valid
1319  *  -1: otherwise.
1320  */
1321 int tls1_cbc_remove_padding(const SSL *s,
1322                             SSL3_RECORD *rec,
1323                             size_t block_size, size_t mac_size)
1324 {
1325     size_t good;
1326     size_t padding_length, to_check, i;
1327     const size_t overhead = 1 /* padding length byte */  + mac_size;
1328     /* Check if version requires explicit IV */
1329     if (SSL_USE_EXPLICIT_IV(s)) {
1330         /*
1331          * These lengths are all public so we can test them in non-constant
1332          * time.
1333          */
1334         if (overhead + block_size > rec->length)
1335             return 0;
1336         /* We can now safely skip explicit IV */
1337         rec->data += block_size;
1338         rec->input += block_size;
1339         rec->length -= block_size;
1340         rec->orig_len -= block_size;
1341     } else if (overhead > rec->length)
1342         return 0;
1343
1344     padding_length = rec->data[rec->length - 1];
1345
1346     if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
1347         EVP_CIPH_FLAG_AEAD_CIPHER) {
1348         /* padding is already verified */
1349         rec->length -= padding_length + 1;
1350         return 1;
1351     }
1352
1353     good = constant_time_ge_s(rec->length, overhead + padding_length);
1354     /*
1355      * The padding consists of a length byte at the end of the record and
1356      * then that many bytes of padding, all with the same value as the length
1357      * byte. Thus, with the length byte included, there are i+1 bytes of
1358      * padding. We can't check just |padding_length+1| bytes because that
1359      * leaks decrypted information. Therefore we always have to check the
1360      * maximum amount of padding possible. (Again, the length of the record
1361      * is public information so we can use it.)
1362      */
1363     to_check = 256;            /* maximum amount of padding, inc length byte. */
1364     if (to_check > rec->length)
1365         to_check = rec->length;
1366
1367     for (i = 0; i < to_check; i++) {
1368         unsigned char mask = constant_time_ge_8_s(padding_length, i);
1369         unsigned char b = rec->data[rec->length - 1 - i];
1370         /*
1371          * The final |padding_length+1| bytes should all have the value
1372          * |padding_length|. Therefore the XOR should be zero.
1373          */
1374         good &= ~(mask & (padding_length ^ b));
1375     }
1376
1377     /*
1378      * If any of the final |padding_length+1| bytes had the wrong value, one
1379      * or more of the lower eight bits of |good| will be cleared.
1380      */
1381     good = constant_time_eq_s(0xff, good & 0xff);
1382     rec->length -= good & (padding_length + 1);
1383
1384     return constant_time_select_int_s(good, 1, -1);
1385 }
1386
1387 /*-
1388  * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1389  * constant time (independent of the concrete value of rec->length, which may
1390  * vary within a 256-byte window).
1391  *
1392  * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1393  * this function.
1394  *
1395  * On entry:
1396  *   rec->orig_len >= md_size
1397  *   md_size <= EVP_MAX_MD_SIZE
1398  *
1399  * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1400  * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1401  * a single or pair of cache-lines, then the variable memory accesses don't
1402  * actually affect the timing. CPUs with smaller cache-lines [if any] are
1403  * not multi-core and are not considered vulnerable to cache-timing attacks.
1404  */
1405 #define CBC_MAC_ROTATE_IN_PLACE
1406
1407 void ssl3_cbc_copy_mac(unsigned char *out,
1408                        const SSL3_RECORD *rec, size_t md_size)
1409 {
1410 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1411     unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1412     unsigned char *rotated_mac;
1413 #else
1414     unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1415 #endif
1416
1417     /*
1418      * mac_end is the index of |rec->data| just after the end of the MAC.
1419      */
1420     size_t mac_end = rec->length;
1421     size_t mac_start = mac_end - md_size;
1422     size_t in_mac;
1423     /*
1424      * scan_start contains the number of bytes that we can ignore because the
1425      * MAC's position can only vary by 255 bytes.
1426      */
1427     size_t scan_start = 0;
1428     size_t i, j;
1429     size_t rotate_offset;
1430
1431     OPENSSL_assert(rec->orig_len >= md_size);
1432     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1433
1434 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1435     rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1436 #endif
1437
1438     /* This information is public so it's safe to branch based on it. */
1439     if (rec->orig_len > md_size + 255 + 1)
1440         scan_start = rec->orig_len - (md_size + 255 + 1);
1441
1442     in_mac = 0;
1443     rotate_offset = 0;
1444     memset(rotated_mac, 0, md_size);
1445     for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1446         size_t mac_started = constant_time_eq_s(i, mac_start);
1447         size_t mac_ended = constant_time_lt_s(i, mac_end);
1448         unsigned char b = rec->data[i];
1449
1450         in_mac |= mac_started;
1451         in_mac &= mac_ended;
1452         rotate_offset |= j & mac_started;
1453         rotated_mac[j++] |= b & in_mac;
1454         j &= constant_time_lt_s(j, md_size);
1455     }
1456
1457     /* Now rotate the MAC */
1458 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1459     j = 0;
1460     for (i = 0; i < md_size; i++) {
1461         /* in case cache-line is 32 bytes, touch second line */
1462         ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1463         out[j++] = rotated_mac[rotate_offset++];
1464         rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1465     }
1466 #else
1467     memset(out, 0, md_size);
1468     rotate_offset = md_size - rotate_offset;
1469     rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1470     for (i = 0; i < md_size; i++) {
1471         for (j = 0; j < md_size; j++)
1472             out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
1473         rotate_offset++;
1474         rotate_offset &= constant_time_lt_s(rotate_offset, md_size);
1475     }
1476 #endif
1477 }
1478
1479 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1480 {
1481     int i, al;
1482     int enc_err;
1483     SSL_SESSION *sess;
1484     SSL3_RECORD *rr;
1485     int imac_size;
1486     size_t mac_size;
1487     unsigned char md[EVP_MAX_MD_SIZE];
1488
1489     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1490     sess = s->session;
1491
1492     /*
1493      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1494      * and we have that many bytes in s->packet
1495      */
1496     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1497
1498     /*
1499      * ok, we can now read from 's->packet' data into 'rr' rr->input points
1500      * at rr->length bytes, which need to be copied into rr->data by either
1501      * the decryption or by the decompression When the data is 'copied' into
1502      * the rr->data buffer, rr->input will be pointed at the new buffer
1503      */
1504
1505     /*
1506      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1507      * bytes of encrypted compressed stuff.
1508      */
1509
1510     /* check is not needed I believe */
1511     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1512         al = SSL_AD_RECORD_OVERFLOW;
1513         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1514         goto f_err;
1515     }
1516
1517     /* decrypt in place in 'rr->input' */
1518     rr->data = rr->input;
1519     rr->orig_len = rr->length;
1520
1521     if (SSL_READ_ETM(s) && s->read_hash) {
1522         unsigned char *mac;
1523         mac_size = EVP_MD_CTX_size(s->read_hash);
1524         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1525         if (rr->orig_len < mac_size) {
1526             al = SSL_AD_DECODE_ERROR;
1527             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1528             goto f_err;
1529         }
1530         rr->length -= mac_size;
1531         mac = rr->data + rr->length;
1532         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1533         if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1534             al = SSL_AD_BAD_RECORD_MAC;
1535             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1536                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1537             goto f_err;
1538         }
1539     }
1540
1541     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1542     /*-
1543      * enc_err is:
1544      *    0: (in non-constant time) if the record is publically invalid.
1545      *    1: if the padding is valid
1546      *   -1: if the padding is invalid
1547      */
1548     if (enc_err == 0) {
1549         /* For DTLS we simply ignore bad packets. */
1550         rr->length = 0;
1551         RECORD_LAYER_reset_packet_length(&s->rlayer);
1552         goto err;
1553     }
1554 #ifdef SSL_DEBUG
1555     printf("dec %ld\n", rr->length);
1556     {
1557         size_t z;
1558         for (z = 0; z < rr->length; z++)
1559             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1560     }
1561     printf("\n");
1562 #endif
1563
1564     /* r->length is now the compressed data plus mac */
1565     if ((sess != NULL) && !SSL_READ_ETM(s) &&
1566         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1567         /* s->read_hash != NULL => mac_size != -1 */
1568         unsigned char *mac = NULL;
1569         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1570
1571         /* TODO(size_t): Convert this to do size_t properly */
1572         imac_size = EVP_MD_CTX_size(s->read_hash);
1573         if (imac_size < 0) {
1574             al = SSL_AD_INTERNAL_ERROR;
1575             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, ERR_LIB_EVP);
1576             goto f_err;
1577         }
1578         mac_size = (size_t)imac_size;
1579         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1580
1581         /*
1582          * orig_len is the length of the record before any padding was
1583          * removed. This is public information, as is the MAC in use,
1584          * therefore we can safely process the record in a different amount
1585          * of time if it's too short to possibly contain a MAC.
1586          */
1587         if (rr->orig_len < mac_size ||
1588             /* CBC records must have a padding length byte too. */
1589             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1590              rr->orig_len < mac_size + 1)) {
1591             al = SSL_AD_DECODE_ERROR;
1592             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1593             goto f_err;
1594         }
1595
1596         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1597             /*
1598              * We update the length so that the TLS header bytes can be
1599              * constructed correctly but we need to extract the MAC in
1600              * constant time from within the record, without leaking the
1601              * contents of the padding bytes.
1602              */
1603             mac = mac_tmp;
1604             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1605             rr->length -= mac_size;
1606         } else {
1607             /*
1608              * In this case there's no padding, so |rec->orig_len| equals
1609              * |rec->length| and we checked that there's enough bytes for
1610              * |mac_size| above.
1611              */
1612             rr->length -= mac_size;
1613             mac = &rr->data[rr->length];
1614         }
1615
1616         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1617         if (i == 0 || mac == NULL
1618             || CRYPTO_memcmp(md, mac, mac_size) != 0)
1619             enc_err = -1;
1620         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1621             enc_err = -1;
1622     }
1623
1624     if (enc_err < 0) {
1625         /* decryption failed, silently discard message */
1626         rr->length = 0;
1627         RECORD_LAYER_reset_packet_length(&s->rlayer);
1628         goto err;
1629     }
1630
1631     /* r->length is now just compressed */
1632     if (s->expand != NULL) {
1633         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1634             al = SSL_AD_RECORD_OVERFLOW;
1635             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1636                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1637             goto f_err;
1638         }
1639         if (!ssl3_do_uncompress(s, rr)) {
1640             al = SSL_AD_DECOMPRESSION_FAILURE;
1641             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1642             goto f_err;
1643         }
1644     }
1645
1646     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1647         al = SSL_AD_RECORD_OVERFLOW;
1648         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1649         goto f_err;
1650     }
1651
1652     rr->off = 0;
1653     /*-
1654      * So at this point the following is true
1655      * ssl->s3->rrec.type   is the type of record
1656      * ssl->s3->rrec.length == number of bytes in record
1657      * ssl->s3->rrec.off    == offset to first valid byte
1658      * ssl->s3->rrec.data   == where to take bytes from, increment
1659      *                         after use :-).
1660      */
1661
1662     /* we have pulled in a full packet so zero things */
1663     RECORD_LAYER_reset_packet_length(&s->rlayer);
1664
1665     /* Mark receipt of record. */
1666     dtls1_record_bitmap_update(s, bitmap);
1667
1668     return (1);
1669
1670  f_err:
1671     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1672  err:
1673     return (0);
1674 }
1675
1676 /*
1677  * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1678  */
1679 #define dtls1_get_processed_record(s) \
1680                    dtls1_retrieve_buffered_record((s), \
1681                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1682
1683 /*-
1684  * Call this to get a new input record.
1685  * It will return <= 0 if more data is needed, normally due to an error
1686  * or non-blocking IO.
1687  * When it finishes, one packet has been decoded and can be found in
1688  * ssl->s3->rrec.type    - is the type of record
1689  * ssl->s3->rrec.data,   - data
1690  * ssl->s3->rrec.length, - number of bytes
1691  */
1692 /* used only by dtls1_read_bytes */
1693 int dtls1_get_record(SSL *s)
1694 {
1695     int ssl_major, ssl_minor;
1696     int rret;
1697     size_t more, n;
1698     SSL3_RECORD *rr;
1699     unsigned char *p = NULL;
1700     unsigned short version;
1701     DTLS1_BITMAP *bitmap;
1702     unsigned int is_next_epoch;
1703
1704     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1705
1706  again:
1707     /*
1708      * The epoch may have changed.  If so, process all the pending records.
1709      * This is a non-blocking operation.
1710      */
1711     if (!dtls1_process_buffered_records(s))
1712         return -1;
1713
1714     /* if we're renegotiating, then there may be buffered records */
1715     if (dtls1_get_processed_record(s))
1716         return 1;
1717
1718     /* get something from the wire */
1719
1720     /* check if we have the header */
1721     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1722         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1723         rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1724                            SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1725         /* read timeout is handled by dtls1_read_bytes */
1726         if (rret <= 0)
1727             return rret;         /* error or non-blocking */
1728
1729         /* this packet contained a partial record, dump it */
1730         if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1731             DTLS1_RT_HEADER_LENGTH) {
1732             RECORD_LAYER_reset_packet_length(&s->rlayer);
1733             goto again;
1734         }
1735
1736         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1737
1738         p = RECORD_LAYER_get_packet(&s->rlayer);
1739
1740         if (s->msg_callback)
1741             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1742                             s, s->msg_callback_arg);
1743
1744         /* Pull apart the header into the DTLS1_RECORD */
1745         rr->type = *(p++);
1746         ssl_major = *(p++);
1747         ssl_minor = *(p++);
1748         version = (ssl_major << 8) | ssl_minor;
1749
1750         /* sequence number is 64 bits, with top 2 bytes = epoch */
1751         n2s(p, rr->epoch);
1752
1753         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1754         p += 6;
1755
1756         n2s(p, rr->length);
1757
1758         /* Lets check version */
1759         if (!s->first_packet) {
1760             if (version != s->version) {
1761                 /* unexpected version, silently discard */
1762                 rr->length = 0;
1763                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1764                 goto again;
1765             }
1766         }
1767
1768         if ((version & 0xff00) != (s->version & 0xff00)) {
1769             /* wrong version, silently discard record */
1770             rr->length = 0;
1771             RECORD_LAYER_reset_packet_length(&s->rlayer);
1772             goto again;
1773         }
1774
1775         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1776             /* record too long, silently discard it */
1777             rr->length = 0;
1778             RECORD_LAYER_reset_packet_length(&s->rlayer);
1779             goto again;
1780         }
1781
1782         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1783     }
1784
1785     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1786
1787     if (rr->length >
1788         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1789         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1790         more = rr->length;
1791         rret = ssl3_read_n(s, more, more, 1, 1, &n);
1792         /* this packet contained a partial record, dump it */
1793         if (rret <= 0 || n != more) {
1794             rr->length = 0;
1795             RECORD_LAYER_reset_packet_length(&s->rlayer);
1796             goto again;
1797         }
1798
1799         /*
1800          * now n == rr->length, and s->packet_length ==
1801          * DTLS1_RT_HEADER_LENGTH + rr->length
1802          */
1803     }
1804     /* set state for later operations */
1805     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1806
1807     /* match epochs.  NULL means the packet is dropped on the floor */
1808     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1809     if (bitmap == NULL) {
1810         rr->length = 0;
1811         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1812         goto again;             /* get another record */
1813     }
1814 #ifndef OPENSSL_NO_SCTP
1815     /* Only do replay check if no SCTP bio */
1816     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1817 #endif
1818         /* Check whether this is a repeat, or aged record. */
1819         /*
1820          * TODO: Does it make sense to have replay protection in epoch 0 where
1821          * we have no integrity negotiated yet?
1822          */
1823         if (!dtls1_record_replay_check(s, bitmap)) {
1824             rr->length = 0;
1825             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1826             goto again;         /* get another record */
1827         }
1828 #ifndef OPENSSL_NO_SCTP
1829     }
1830 #endif
1831
1832     /* just read a 0 length packet */
1833     if (rr->length == 0)
1834         goto again;
1835
1836     /*
1837      * If this record is from the next epoch (either HM or ALERT), and a
1838      * handshake is currently in progress, buffer it since it cannot be
1839      * processed at this time.
1840      */
1841     if (is_next_epoch) {
1842         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1843             if (dtls1_buffer_record
1844                 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1845                  rr->seq_num) < 0)
1846                 return -1;
1847         }
1848         rr->length = 0;
1849         RECORD_LAYER_reset_packet_length(&s->rlayer);
1850         goto again;
1851     }
1852
1853     if (!dtls1_process_record(s, bitmap)) {
1854         rr->length = 0;
1855         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1856         goto again;             /* get another record */
1857     }
1858
1859     return (1);
1860
1861 }