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