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