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