Move the TLS1.0/1.1/1.2 record crypto code into the new record layer
[openssl.git] / ssl / record / ssl3_record.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 "../ssl_local.h"
11 #include <openssl/trace.h>
12 #include <openssl/rand.h>
13 #include <openssl/core_names.h>
14 #include "record_local.h"
15 #include "internal/cryptlib.h"
16
17 static const unsigned char ssl3_pad_1[48] = {
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     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
24 };
25
26 static const unsigned char ssl3_pad_2[48] = {
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     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
33 };
34
35 /*
36  * Clear the contents of an SSL3_RECORD but retain any memory allocated
37  */
38 void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
39 {
40     unsigned char *comp;
41     size_t i;
42
43     for (i = 0; i < num_recs; i++) {
44         comp = r[i].comp;
45
46         memset(&r[i], 0, sizeof(*r));
47         r[i].comp = comp;
48     }
49 }
50
51 void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
52 {
53     size_t i;
54
55     for (i = 0; i < num_recs; i++) {
56         OPENSSL_free(r[i].comp);
57         r[i].comp = NULL;
58     }
59 }
60
61 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
62 {
63     memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
64 }
65
66 int ossl_early_data_count_ok(SSL_CONNECTION *s, size_t length,
67                              size_t overhead, int send)
68 {
69     uint32_t max_early_data;
70     SSL_SESSION *sess = s->session;
71
72     /*
73      * If we are a client then we always use the max_early_data from the
74      * session/psksession. Otherwise we go with the lowest out of the max early
75      * data set in the session and the configured max_early_data.
76      */
77     if (!s->server && sess->ext.max_early_data == 0) {
78         if (!ossl_assert(s->psksession != NULL
79                          && s->psksession->ext.max_early_data > 0)) {
80             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
81             return 0;
82         }
83         sess = s->psksession;
84     }
85
86     if (!s->server)
87         max_early_data = sess->ext.max_early_data;
88     else if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
89         max_early_data = s->recv_max_early_data;
90     else
91         max_early_data = s->recv_max_early_data < sess->ext.max_early_data
92                          ? s->recv_max_early_data : sess->ext.max_early_data;
93
94     if (max_early_data == 0) {
95         SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
96                  SSL_R_TOO_MUCH_EARLY_DATA);
97         return 0;
98     }
99
100     /* If we are dealing with ciphertext we need to allow for the overhead */
101     max_early_data += overhead;
102
103     if (s->early_data_count + length > max_early_data) {
104         SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
105                  SSL_R_TOO_MUCH_EARLY_DATA);
106         return 0;
107     }
108     s->early_data_count += length;
109
110     return 1;
111 }
112
113
114 int ssl3_do_uncompress(SSL_CONNECTION *sc, SSL3_RECORD *rr)
115 {
116 #ifndef OPENSSL_NO_COMP
117     int i;
118
119     if (rr->comp == NULL) {
120         rr->comp = (unsigned char *)
121             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
122     }
123     if (rr->comp == NULL)
124         return 0;
125
126     i = COMP_expand_block(sc->expand, rr->comp,
127                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
128     if (i < 0)
129         return 0;
130     else
131         rr->length = i;
132     rr->data = rr->comp;
133 #endif
134     return 1;
135 }
136
137 int ssl3_do_compress(SSL_CONNECTION *sc, SSL3_RECORD *wr)
138 {
139 #ifndef OPENSSL_NO_COMP
140     int i;
141
142     i = COMP_compress_block(sc->compress, wr->data,
143                             (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
144                             wr->input, (int)wr->length);
145     if (i < 0)
146         return 0;
147     else
148         wr->length = i;
149
150     wr->input = wr->data;
151 #endif
152     return 1;
153 }
154
155 /*-
156  * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|. Calls SSLfatal on
157  * internal error, but not otherwise. It is the responsibility of the caller to
158  * report a bad_record_mac
159  *
160  * Returns:
161  *    0: if the record is publicly invalid, or an internal error
162  *    1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
163  */
164 int ssl3_enc(SSL_CONNECTION *s, SSL3_RECORD *inrecs, size_t n_recs, int sending,
165              SSL_MAC_BUF *mac, size_t macsize)
166 {
167     SSL3_RECORD *rec;
168     EVP_CIPHER_CTX *ds;
169     size_t l, i;
170     size_t bs;
171     const EVP_CIPHER *enc;
172
173     rec = inrecs;
174     /*
175      * We shouldn't ever be called with more than one record in the SSLv3 case
176      */
177     if (n_recs != 1)
178         return 0;
179     if (sending) {
180         ds = s->enc_write_ctx;
181         if (s->enc_write_ctx == NULL)
182             enc = NULL;
183         else
184             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx);
185     } else {
186         ds = s->enc_read_ctx;
187         if (s->enc_read_ctx == NULL)
188             enc = NULL;
189         else
190             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_read_ctx);
191     }
192
193     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
194         memmove(rec->data, rec->input, rec->length);
195         rec->input = rec->data;
196     } else {
197         int provided = (EVP_CIPHER_get0_provider(enc) != NULL);
198
199         l = rec->length;
200         bs = EVP_CIPHER_CTX_get_block_size(ds);
201
202         /* COMPRESS */
203
204         if ((bs != 1) && sending && !provided) {
205             /*
206              * We only do this for legacy ciphers. Provided ciphers add the
207              * padding on the provider side.
208              */
209             i = bs - (l % bs);
210
211             /* we need to add 'i-1' padding bytes */
212             l += i;
213             /*
214              * the last of these zero bytes will be overwritten with the
215              * padding length.
216              */
217             memset(&rec->input[rec->length], 0, i);
218             rec->length += i;
219             rec->input[l - 1] = (unsigned char)(i - 1);
220         }
221
222         if (!sending) {
223             if (l == 0 || l % bs != 0) {
224                 /* Publicly invalid */
225                 return 0;
226             }
227             /* otherwise, rec->length >= bs */
228         }
229
230         if (EVP_CIPHER_get0_provider(enc) != NULL) {
231             int outlen;
232
233             if (!EVP_CipherUpdate(ds, rec->data, &outlen, rec->input,
234                                   (unsigned int)l))
235                 return 0;
236             rec->length = outlen;
237
238             if (!sending && mac != NULL) {
239                 /* Now get a pointer to the MAC */
240                 OSSL_PARAM params[2], *p = params;
241
242                 /* Get the MAC */
243                 mac->alloced = 0;
244
245                 *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
246                                                       (void **)&mac->mac,
247                                                       macsize);
248                 *p = OSSL_PARAM_construct_end();
249
250                 if (!EVP_CIPHER_CTX_get_params(ds, params)) {
251                     /* Shouldn't normally happen */
252                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
253                     return 0;
254                 }
255             }
256         } else {
257             if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1) {
258                 /* Shouldn't happen */
259                 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, ERR_R_INTERNAL_ERROR);
260                 return 0;
261             }
262
263             if (!sending)
264                 return ssl3_cbc_remove_padding_and_mac(&rec->length,
265                                            rec->orig_len,
266                                            rec->data,
267                                            (mac != NULL) ? &mac->mac : NULL,
268                                            (mac != NULL) ? &mac->alloced : NULL,
269                                            bs,
270                                            macsize,
271                                            SSL_CONNECTION_GET_CTX(s)->libctx);
272         }
273     }
274     return 1;
275 }
276
277 #define MAX_PADDING 256
278 /*-
279  * tls1_enc encrypts/decrypts |n_recs| in |recs|. Calls SSLfatal on internal
280  * error, but not otherwise. It is the responsibility of the caller to report
281  * a bad_record_mac - if appropriate (DTLS just drops the record).
282  *
283  * Returns:
284  *    0: if the record is publicly invalid, or an internal error, or AEAD
285  *       decryption failed, or Encrypt-then-mac decryption failed.
286  *    1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
287  */
288 int tls1_enc(SSL_CONNECTION *s, SSL3_RECORD *recs, size_t n_recs, int sending,
289              SSL_MAC_BUF *macs, size_t macsize)
290 {
291     EVP_CIPHER_CTX *ds;
292     size_t reclen[SSL_MAX_PIPELINES];
293     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
294     int i, pad = 0, tmpr;
295     size_t bs, ctr, padnum, loop;
296     unsigned char padval;
297     const EVP_CIPHER *enc;
298     int tlstree_enc = sending ? (s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
299                               : (s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
300
301     if (n_recs == 0) {
302         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
303         return 0;
304     }
305
306     if (sending) {
307         if (EVP_MD_CTX_get0_md(s->write_hash)) {
308             int n = EVP_MD_CTX_get_size(s->write_hash);
309             if (!ossl_assert(n >= 0)) {
310                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
311                 return 0;
312             }
313         }
314         ds = s->enc_write_ctx;
315         if (s->enc_write_ctx == NULL)
316             enc = NULL;
317         else {
318             int ivlen;
319
320             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx);
321             /* For TLSv1.1 and later explicit IV */
322             if (SSL_USE_EXPLICIT_IV(s)
323                 && EVP_CIPHER_get_mode(enc) == EVP_CIPH_CBC_MODE)
324                 ivlen = EVP_CIPHER_get_iv_length(enc);
325             else
326                 ivlen = 0;
327             if (ivlen > 1) {
328                 for (ctr = 0; ctr < n_recs; ctr++) {
329                     if (recs[ctr].data != recs[ctr].input) {
330                         /*
331                          * we can't write into the input stream: Can this ever
332                          * happen?? (steve)
333                          */
334                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
335                         return 0;
336                     } else if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
337                                              recs[ctr].input,
338                                              ivlen, 0) <= 0) {
339                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
340                         return 0;
341                     }
342                 }
343             }
344         }
345     } else {
346         if (EVP_MD_CTX_get0_md(s->read_hash)) {
347             int n = EVP_MD_CTX_get_size(s->read_hash);
348             if (!ossl_assert(n >= 0)) {
349                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
350                 return 0;
351             }
352         }
353         ds = s->enc_read_ctx;
354         if (s->enc_read_ctx == NULL)
355             enc = NULL;
356         else
357             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_read_ctx);
358     }
359
360     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
361         for (ctr = 0; ctr < n_recs; ctr++) {
362             memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
363             recs[ctr].input = recs[ctr].data;
364         }
365     } else {
366         int provided = (EVP_CIPHER_get0_provider(enc) != NULL);
367
368         bs = EVP_CIPHER_get_block_size(EVP_CIPHER_CTX_get0_cipher(ds));
369
370         if (n_recs > 1) {
371             if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
372                   & EVP_CIPH_FLAG_PIPELINE) == 0) {
373                 /*
374                  * We shouldn't have been called with pipeline data if the
375                  * cipher doesn't support pipelining
376                  */
377                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
378                 return 0;
379             }
380         }
381         for (ctr = 0; ctr < n_recs; ctr++) {
382             reclen[ctr] = recs[ctr].length;
383
384             if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
385                         & EVP_CIPH_FLAG_AEAD_CIPHER) != 0) {
386                 unsigned char *seq;
387
388                 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
389                     : RECORD_LAYER_get_read_sequence(&s->rlayer);
390
391                 if (SSL_CONNECTION_IS_DTLS(s)) {
392                     /* DTLS does not support pipelining */
393                     unsigned char dtlsseq[8], *p = dtlsseq;
394
395                     s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
396                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
397                     memcpy(p, &seq[2], 6);
398                     memcpy(buf[ctr], dtlsseq, 8);
399                 } else {
400                     memcpy(buf[ctr], seq, 8);
401                     for (i = 7; i >= 0; i--) { /* increment */
402                         ++seq[i];
403                         if (seq[i] != 0)
404                             break;
405                     }
406                 }
407
408                 buf[ctr][8] = recs[ctr].type;
409                 buf[ctr][9] = (unsigned char)(s->version >> 8);
410                 buf[ctr][10] = (unsigned char)(s->version);
411                 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
412                 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
413                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
414                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
415                 if (pad <= 0) {
416                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
417                     return 0;
418                 }
419
420                 if (sending) {
421                     reclen[ctr] += pad;
422                     recs[ctr].length += pad;
423                 }
424
425             } else if ((bs != 1) && sending && !provided) {
426                 /*
427                  * We only do this for legacy ciphers. Provided ciphers add the
428                  * padding on the provider side.
429                  */
430                 padnum = bs - (reclen[ctr] % bs);
431
432                 /* Add weird padding of up to 256 bytes */
433
434                 if (padnum > MAX_PADDING) {
435                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
436                     return 0;
437                 }
438                 /* we need to add 'padnum' padding bytes of value padval */
439                 padval = (unsigned char)(padnum - 1);
440                 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
441                     recs[ctr].input[loop] = padval;
442                 reclen[ctr] += padnum;
443                 recs[ctr].length += padnum;
444             }
445
446             if (!sending) {
447                 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0) {
448                     /* Publicly invalid */
449                     return 0;
450                 }
451             }
452         }
453         if (n_recs > 1) {
454             unsigned char *data[SSL_MAX_PIPELINES];
455
456             /* Set the output buffers */
457             for (ctr = 0; ctr < n_recs; ctr++) {
458                 data[ctr] = recs[ctr].data;
459             }
460             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
461                                     (int)n_recs, data) <= 0) {
462                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
463                 return 0;
464             }
465             /* Set the input buffers */
466             for (ctr = 0; ctr < n_recs; ctr++) {
467                 data[ctr] = recs[ctr].input;
468             }
469             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
470                                     (int)n_recs, data) <= 0
471                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
472                                        (int)n_recs, reclen) <= 0) {
473                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
474                 return 0;
475             }
476         }
477
478         if (!SSL_CONNECTION_IS_DTLS(s) && tlstree_enc) {
479             unsigned char *seq;
480             int decrement_seq = 0;
481
482             /*
483              * When sending, seq is incremented after MAC calculation.
484              * So if we are in ETM mode, we use seq 'as is' in the ctrl-function.
485              * Otherwise we have to decrease it in the implementation
486              */
487             if (sending && !SSL_WRITE_ETM(s))
488                 decrement_seq = 1;
489
490             seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
491                           : RECORD_LAYER_get_read_sequence(&s->rlayer);
492             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_TLSTREE, decrement_seq, seq) <= 0) {
493                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
494                 return 0;
495             }
496         }
497
498         if (provided) {
499             int outlen;
500
501             /* Provided cipher - we do not support pipelining on this path */
502             if (n_recs > 1)  {
503                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
504                 return 0;
505             }
506
507             if (!EVP_CipherUpdate(ds, recs[0].data, &outlen, recs[0].input,
508                                   (unsigned int)reclen[0]))
509                 return 0;
510             recs[0].length = outlen;
511
512             /*
513              * The length returned from EVP_CipherUpdate above is the actual
514              * payload length. We need to adjust the data/input ptr to skip over
515              * any explicit IV
516              */
517             if (!sending) {
518                 if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
519                         recs[0].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
520                         recs[0].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
521                 } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
522                         recs[0].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
523                         recs[0].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
524                 } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
525                     recs[0].data += bs;
526                     recs[0].input += bs;
527                     recs[0].orig_len -= bs;
528                 }
529
530                 /* Now get a pointer to the MAC (if applicable) */
531                 if (macs != NULL) {
532                     OSSL_PARAM params[2], *p = params;
533
534                     /* Get the MAC */
535                     macs[0].alloced = 0;
536
537                     *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
538                                                           (void **)&macs[0].mac,
539                                                           macsize);
540                     *p = OSSL_PARAM_construct_end();
541
542                     if (!EVP_CIPHER_CTX_get_params(ds, params)) {
543                         /* Shouldn't normally happen */
544                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
545                                  ERR_R_INTERNAL_ERROR);
546                         return 0;
547                     }
548                 }
549             }
550         } else {
551             /* Legacy cipher */
552
553             tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
554                               (unsigned int)reclen[0]);
555             if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
556                  & EVP_CIPH_FLAG_CUSTOM_CIPHER) != 0
557                 ? (tmpr < 0)
558                 : (tmpr == 0)) {
559                 /* AEAD can fail to verify MAC */
560                 return 0;
561             }
562
563             if (!sending) {
564                 for (ctr = 0; ctr < n_recs; ctr++) {
565                     /* Adjust the record to remove the explicit IV/MAC/Tag */
566                     if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
567                         recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
568                         recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
569                         recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
570                     } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
571                         recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
572                         recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
573                         recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
574                     } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
575                         if (recs[ctr].length < bs)
576                             return 0;
577                         recs[ctr].data += bs;
578                         recs[ctr].input += bs;
579                         recs[ctr].length -= bs;
580                         recs[ctr].orig_len -= bs;
581                     }
582
583                     /*
584                      * If using Mac-then-encrypt, then this will succeed but
585                      * with a random MAC if padding is invalid
586                      */
587                     if (!tls1_cbc_remove_padding_and_mac(&recs[ctr].length,
588                                          recs[ctr].orig_len,
589                                          recs[ctr].data,
590                                          (macs != NULL) ? &macs[ctr].mac : NULL,
591                                          (macs != NULL) ? &macs[ctr].alloced
592                                                         : NULL,
593                                          bs,
594                                          pad ? (size_t)pad : macsize,
595                                          (EVP_CIPHER_get_flags(enc)
596                                          & EVP_CIPH_FLAG_AEAD_CIPHER) != 0,
597                                          SSL_CONNECTION_GET_CTX(s)->libctx))
598                         return 0;
599                 }
600             }
601         }
602     }
603     return 1;
604 }
605
606 /*
607  * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
608  * which ssl3_cbc_digest_record supports.
609  */
610 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
611 {
612     switch (EVP_MD_CTX_get_type(ctx)) {
613     case NID_md5:
614     case NID_sha1:
615     case NID_sha224:
616     case NID_sha256:
617     case NID_sha384:
618     case NID_sha512:
619         return 1;
620     default:
621         return 0;
622     }
623 }
624
625 int n_ssl3_mac(SSL_CONNECTION *sc, SSL3_RECORD *rec, unsigned char *md,
626                int sending)
627 {
628     unsigned char *mac_sec, *seq;
629     const EVP_MD_CTX *hash;
630     unsigned char *p, rec_char;
631     size_t md_size;
632     size_t npad;
633     int t;
634
635     if (sending) {
636         mac_sec = &(sc->s3.write_mac_secret[0]);
637         seq = RECORD_LAYER_get_write_sequence(&sc->rlayer);
638         hash = sc->write_hash;
639     } else {
640         mac_sec = &(sc->s3.read_mac_secret[0]);
641         seq = RECORD_LAYER_get_read_sequence(&sc->rlayer);
642         hash = sc->read_hash;
643     }
644
645     t = EVP_MD_CTX_get_size(hash);
646     if (t < 0)
647         return 0;
648     md_size = t;
649     npad = (48 / md_size) * md_size;
650
651     if (!sending
652         && EVP_CIPHER_CTX_get_mode(sc->enc_read_ctx) == EVP_CIPH_CBC_MODE
653         && ssl3_cbc_record_digest_supported(hash)) {
654 #ifdef OPENSSL_NO_DEPRECATED_3_0
655         return 0;
656 #else
657         /*
658          * This is a CBC-encrypted record. We must avoid leaking any
659          * timing-side channel information about how many blocks of data we
660          * are hashing because that gives an attacker a timing-oracle.
661          */
662
663         /*-
664          * npad is, at most, 48 bytes and that's with MD5:
665          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
666          *
667          * With SHA-1 (the largest hash speced for SSLv3) the hash size
668          * goes up 4, but npad goes down by 8, resulting in a smaller
669          * total size.
670          */
671         unsigned char header[75];
672         size_t j = 0;
673         memcpy(header + j, mac_sec, md_size);
674         j += md_size;
675         memcpy(header + j, ssl3_pad_1, npad);
676         j += npad;
677         memcpy(header + j, seq, 8);
678         j += 8;
679         header[j++] = rec->type;
680         header[j++] = (unsigned char)(rec->length >> 8);
681         header[j++] = (unsigned char)(rec->length & 0xff);
682
683         /* Final param == is SSLv3 */
684         if (ssl3_cbc_digest_record(EVP_MD_CTX_get0_md(hash),
685                                    md, &md_size,
686                                    header, rec->input,
687                                    rec->length, rec->orig_len,
688                                    mac_sec, md_size, 1) <= 0)
689             return 0;
690 #endif
691     } else {
692         unsigned int md_size_u;
693         /* Chop the digest off the end :-) */
694         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
695
696         if (md_ctx == NULL)
697             return 0;
698
699         rec_char = rec->type;
700         p = md;
701         s2n(rec->length, p);
702         if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
703             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
704             || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
705             || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
706             || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
707             || EVP_DigestUpdate(md_ctx, md, 2) <= 0
708             || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
709             || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
710             || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
711             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
712             || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
713             || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
714             || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
715             EVP_MD_CTX_free(md_ctx);
716             return 0;
717         }
718
719         EVP_MD_CTX_free(md_ctx);
720     }
721
722     ssl3_record_sequence_update(seq);
723     return 1;
724 }
725
726 int tls1_mac_old(SSL_CONNECTION *sc, SSL3_RECORD *rec, unsigned char *md,
727                  int sending)
728 {
729     unsigned char *seq;
730     EVP_MD_CTX *hash;
731     size_t md_size;
732     int i;
733     EVP_MD_CTX *hmac = NULL, *mac_ctx;
734     unsigned char header[13];
735     int stream_mac = sending ? (sc->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
736                              : (sc->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM);
737     int tlstree_mac = sending ? (sc->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
738                               : (sc->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
739     int t;
740     int ret = 0;
741
742     if (sending) {
743         seq = RECORD_LAYER_get_write_sequence(&sc->rlayer);
744         hash = sc->write_hash;
745     } else {
746         seq = RECORD_LAYER_get_read_sequence(&sc->rlayer);
747         hash = sc->read_hash;
748     }
749
750     t = EVP_MD_CTX_get_size(hash);
751     if (!ossl_assert(t >= 0))
752         return 0;
753     md_size = t;
754
755     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
756     if (stream_mac) {
757         mac_ctx = hash;
758     } else {
759         hmac = EVP_MD_CTX_new();
760         if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash)) {
761             goto end;
762         }
763         mac_ctx = hmac;
764     }
765
766     if (!SSL_CONNECTION_IS_DTLS(sc) && tlstree_mac
767         && EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_TLSTREE, 0, seq) <= 0) {
768         goto end;
769     }
770
771     if (SSL_CONNECTION_IS_DTLS(sc)) {
772         unsigned char dtlsseq[8], *p = dtlsseq;
773
774         s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&sc->rlayer) :
775             DTLS_RECORD_LAYER_get_r_epoch(&sc->rlayer), p);
776         memcpy(p, &seq[2], 6);
777
778         memcpy(header, dtlsseq, 8);
779     } else
780         memcpy(header, seq, 8);
781
782     header[8] = rec->type;
783     header[9] = (unsigned char)(sc->version >> 8);
784     header[10] = (unsigned char)(sc->version);
785     header[11] = (unsigned char)(rec->length >> 8);
786     header[12] = (unsigned char)(rec->length & 0xff);
787
788     if (!sending && !SSL_READ_ETM(sc)
789         && EVP_CIPHER_CTX_get_mode(sc->enc_read_ctx) == EVP_CIPH_CBC_MODE
790         && ssl3_cbc_record_digest_supported(mac_ctx)) {
791         OSSL_PARAM tls_hmac_params[2], *p = tls_hmac_params;
792
793         *p++ = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_TLS_DATA_SIZE,
794                                            &rec->orig_len);
795         *p++ = OSSL_PARAM_construct_end();
796
797         if (!EVP_PKEY_CTX_set_params(EVP_MD_CTX_get_pkey_ctx(mac_ctx),
798                                      tls_hmac_params)) {
799             goto end;
800         }
801     }
802
803     if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
804         || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
805         || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
806         goto end;
807     }
808
809     OSSL_TRACE_BEGIN(TLS) {
810         BIO_printf(trc_out, "seq:\n");
811         BIO_dump_indent(trc_out, seq, 8, 4);
812         BIO_printf(trc_out, "rec:\n");
813         BIO_dump_indent(trc_out, rec->data, rec->length, 4);
814     } OSSL_TRACE_END(TLS);
815
816     if (!SSL_CONNECTION_IS_DTLS(sc)) {
817         for (i = 7; i >= 0; i--) {
818             ++seq[i];
819             if (seq[i] != 0)
820                 break;
821         }
822     }
823     OSSL_TRACE_BEGIN(TLS) {
824         BIO_printf(trc_out, "md:\n");
825         BIO_dump_indent(trc_out, md, md_size, 4);
826     } OSSL_TRACE_END(TLS);
827     ret = 1;
828  end:
829     EVP_MD_CTX_free(hmac);
830     return ret;
831 }
832
833 int dtls1_process_record(SSL_CONNECTION *s, DTLS1_BITMAP *bitmap)
834 {
835     int i;
836     int enc_err;
837     SSL_SESSION *sess;
838     SSL3_RECORD *rr;
839     int imac_size;
840     size_t mac_size = 0;
841     unsigned char md[EVP_MAX_MD_SIZE];
842     size_t max_plain_length = SSL3_RT_MAX_PLAIN_LENGTH;
843     SSL_MAC_BUF macbuf = { NULL, 0 };
844     int ret = 0;
845     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
846
847     rr = RECORD_LAYER_get_rrec(&s->rlayer);
848     sess = s->session;
849
850     /*
851      * At this point, s->rlayer.packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
852      * and we have that many bytes in s->rlayer.packet
853      */
854     rr->input = &(s->rrlmethod->get0_packet(s->rrl)[DTLS1_RT_HEADER_LENGTH]);
855
856     /*
857      * ok, we can now read from 's->rlayer.packet' data into 'rr'. rr->input
858      * points at rr->length bytes, which need to be copied into rr->data by
859      * either the decryption or by the decompression. When the data is 'copied'
860      * into the rr->data buffer, rr->input will be pointed at the new buffer
861      */
862
863     /*
864      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
865      * bytes of encrypted compressed stuff.
866      */
867
868     /* check is not needed I believe */
869     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
870         SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
871         return 0;
872     }
873
874     /* decrypt in place in 'rr->input' */
875     rr->data = rr->input;
876     rr->orig_len = rr->length;
877
878     if (s->read_hash != NULL) {
879         const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(s->read_hash);
880
881         if (tmpmd != NULL) {
882             imac_size = EVP_MD_get_size(tmpmd);
883             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
884                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
885                     return 0;
886             }
887             mac_size = (size_t)imac_size;
888         }
889     }
890
891     if (SSL_READ_ETM(s) && s->read_hash) {
892         unsigned char *mac;
893
894         if (rr->orig_len < mac_size) {
895             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
896             return 0;
897         }
898         rr->length -= mac_size;
899         mac = rr->data + rr->length;
900         i = ssl->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
901         if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
902             SSLfatal(s, SSL_AD_BAD_RECORD_MAC,
903                      SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
904             return 0;
905         }
906         /*
907          * We've handled the mac now - there is no MAC inside the encrypted
908          * record
909          */
910         mac_size = 0;
911     }
912
913     /*
914      * Set a mark around the packet decryption attempt.  This is DTLS, so
915      * bad packets are just ignored, and we don't want to leave stray
916      * errors in the queue from processing bogus junk that we ignored.
917      */
918     ERR_set_mark();
919     enc_err = ssl->method->ssl3_enc->enc(s, rr, 1, 0, &macbuf, mac_size);
920
921     /*-
922      * enc_err is:
923      *    0: if the record is publicly invalid, or an internal error, or AEAD
924      *       decryption failed, or ETM decryption failed.
925      *    1: Success or MTE decryption failed (MAC will be randomised)
926      */
927     if (enc_err == 0) {
928         ERR_pop_to_mark();
929         if (ossl_statem_in_error(s)) {
930             /* SSLfatal() got called */
931             goto end;
932         }
933         /* For DTLS we simply ignore bad packets. */
934         rr->length = 0;
935         s->rrlmethod->reset_packet_length(s->rrl);
936         goto end;
937     }
938     ERR_clear_last_mark();
939     OSSL_TRACE_BEGIN(TLS) {
940         BIO_printf(trc_out, "dec %zd\n", rr->length);
941         BIO_dump_indent(trc_out, rr->data, rr->length, 4);
942     } OSSL_TRACE_END(TLS);
943
944     /* r->length is now the compressed data plus mac */
945     if ((sess != NULL)
946             && !SSL_READ_ETM(s)
947             && (s->enc_read_ctx != NULL)
948             && (EVP_MD_CTX_get0_md(s->read_hash) != NULL)) {
949         /* s->read_hash != NULL => mac_size != -1 */
950
951         i = ssl->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
952         if (i == 0 || macbuf.mac == NULL
953             || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
954             enc_err = 0;
955         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
956             enc_err = 0;
957     }
958
959     if (enc_err == 0) {
960         /* decryption failed, silently discard message */
961         rr->length = 0;
962         s->rrlmethod->reset_packet_length(s->rrl);
963         goto end;
964     }
965
966     /* r->length is now just compressed */
967     if (s->expand != NULL) {
968         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
969             SSLfatal(s, SSL_AD_RECORD_OVERFLOW,
970                      SSL_R_COMPRESSED_LENGTH_TOO_LONG);
971             goto end;
972         }
973         if (!ssl3_do_uncompress(s, rr)) {
974             SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION);
975             goto end;
976         }
977     }
978
979     /* use current Max Fragment Length setting if applicable */
980     if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
981         max_plain_length = GET_MAX_FRAGMENT_LENGTH(s->session);
982
983     /* send overflow if the plaintext is too long now it has passed MAC */
984     if (rr->length > max_plain_length) {
985         SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
986         goto end;
987     }
988
989     rr->off = 0;
990     /*-
991      * So at this point the following is true
992      * ssl->s3.rrec.type   is the type of record
993      * ssl->s3.rrec.length == number of bytes in record
994      * ssl->s3.rrec.off    == offset to first valid byte
995      * ssl->s3.rrec.data   == where to take bytes from, increment
996      *                        after use :-).
997      */
998
999     /* we have pulled in a full packet so zero things */
1000     s->rrlmethod->reset_packet_length(s->rrl);
1001
1002     /* Mark receipt of record. */
1003     dtls1_record_bitmap_update(s, bitmap);
1004
1005     ret = 1;
1006  end:
1007     if (macbuf.alloced)
1008         OPENSSL_free(macbuf.mac);
1009     return ret;
1010 }
1011
1012 /*
1013  * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1014  */
1015 #define dtls1_get_processed_record(s) \
1016                    dtls1_retrieve_buffered_record((s), \
1017                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1018
1019 /*-
1020  * Call this to get a new input record.
1021  * It will return <= 0 if more data is needed, normally due to an error
1022  * or non-blocking IO.
1023  * When it finishes, one packet has been decoded and can be found in
1024  * ssl->s3.rrec.type    - is the type of record
1025  * ssl->s3.rrec.data    - data
1026  * ssl->s3.rrec.length  - number of bytes
1027  */
1028 /* used only by dtls1_read_bytes */
1029 int dtls1_get_record(SSL_CONNECTION *s)
1030 {
1031     int ssl_major, ssl_minor;
1032     int rret;
1033     size_t more, n;
1034     SSL3_RECORD *rr;
1035     unsigned char *p = NULL;
1036     unsigned short version;
1037     DTLS1_BITMAP *bitmap;
1038     unsigned int is_next_epoch;
1039     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1040
1041     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1042
1043  again:
1044     /*
1045      * The epoch may have changed.  If so, process all the pending records.
1046      * This is a non-blocking operation.
1047      */
1048     if (!dtls1_process_buffered_records(s)) {
1049         /* SSLfatal() already called */
1050         return -1;
1051     }
1052
1053     /* if we're renegotiating, then there may be buffered records */
1054     if (dtls1_get_processed_record(s))
1055         return 1;
1056
1057     /* get something from the wire */
1058
1059     /* check if we have the header */
1060     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1061         (s->rrlmethod->get_packet_length(s->rrl) < DTLS1_RT_HEADER_LENGTH)) {
1062         rret = HANDLE_RLAYER_RETURN(s,
1063             s->rrlmethod->read_n(s->rrl, DTLS1_RT_HEADER_LENGTH,
1064                                  SSL3_BUFFER_get_len(s->rrlmethod->get0_rbuf(s->rrl)), 0, 1, &n));
1065         /* read timeout is handled by dtls1_read_bytes */
1066         if (rret <= 0) {
1067             /* SSLfatal() already called if appropriate */
1068             return rret;         /* error or non-blocking */
1069         }
1070
1071         /* this packet contained a partial record, dump it */
1072         if (s->rrlmethod->get_packet_length(s->rrl) != DTLS1_RT_HEADER_LENGTH) {
1073             s->rrlmethod->reset_packet_length(s->rrl);
1074             goto again;
1075         }
1076
1077         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1078
1079         p = s->rrlmethod->get0_packet(s->rrl);
1080
1081         if (s->msg_callback)
1082             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1083                             ssl, s->msg_callback_arg);
1084
1085         /* Pull apart the header into the DTLS1_RECORD */
1086         rr->type = *(p++);
1087         ssl_major = *(p++);
1088         ssl_minor = *(p++);
1089         version = (ssl_major << 8) | ssl_minor;
1090
1091         /* sequence number is 64 bits, with top 2 bytes = epoch */
1092         n2s(p, rr->epoch);
1093
1094         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1095         p += 6;
1096
1097         n2s(p, rr->length);
1098         rr->read = 0;
1099
1100         /*
1101          * Lets check the version. We tolerate alerts that don't have the exact
1102          * version number (e.g. because of protocol version errors)
1103          */
1104         if (!s->first_packet && rr->type != SSL3_RT_ALERT) {
1105             if (version != s->version) {
1106                 /* unexpected version, silently discard */
1107                 rr->length = 0;
1108                 rr->read = 1;
1109                 s->rrlmethod->reset_packet_length(s->rrl);
1110                 goto again;
1111             }
1112         }
1113
1114         if ((version & 0xff00) != (s->version & 0xff00)) {
1115             /* wrong version, silently discard record */
1116             rr->length = 0;
1117             rr->read = 1;
1118             s->rrlmethod->reset_packet_length(s->rrl);
1119             goto again;
1120         }
1121
1122         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1123             /* record too long, silently discard it */
1124             rr->length = 0;
1125             rr->read = 1;
1126             s->rrlmethod->reset_packet_length(s->rrl);
1127             goto again;
1128         }
1129
1130         /* If received packet overflows own-client Max Fragment Length setting */
1131         if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1132                 && rr->length > GET_MAX_FRAGMENT_LENGTH(s->session) + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
1133             /* record too long, silently discard it */
1134             rr->length = 0;
1135             rr->read = 1;
1136             s->rrlmethod->reset_packet_length(s->rrl);
1137             goto again;
1138         }
1139
1140         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1141     }
1142
1143     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1144
1145     if (rr->length >
1146         s->rrlmethod->get_packet_length(s->rrl) - DTLS1_RT_HEADER_LENGTH) {
1147         /* now s->rlayer.packet_length == DTLS1_RT_HEADER_LENGTH */
1148         more = rr->length;
1149         rret = HANDLE_RLAYER_RETURN(s,
1150             s->rrlmethod->read_n(s->rrl, more, more, 1, 1, &n));
1151         /* this packet contained a partial record, dump it */
1152         if (rret <= 0 || n != more) {
1153             if (ossl_statem_in_error(s)) {
1154                 /* read_n() called SSLfatal() */
1155                 return -1;
1156             }
1157             rr->length = 0;
1158             rr->read = 1;
1159             s->rrlmethod->reset_packet_length(s->rrl);
1160             goto again;
1161         }
1162
1163         /*
1164          * now n == rr->length, and s->rlayer.packet_length ==
1165          * DTLS1_RT_HEADER_LENGTH + rr->length
1166          */
1167     }
1168     /* set state for later operations */
1169     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1170
1171     /* match epochs.  NULL means the packet is dropped on the floor */
1172     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1173     if (bitmap == NULL) {
1174         rr->length = 0;
1175         s->rrlmethod->reset_packet_length(s->rrl); /* dump this record */
1176         goto again;             /* get another record */
1177     }
1178 #ifndef OPENSSL_NO_SCTP
1179     /* Only do replay check if no SCTP bio */
1180     if (!BIO_dgram_is_sctp(SSL_get_rbio(ssl))) {
1181 #endif
1182         /* Check whether this is a repeat, or aged record. */
1183         if (!dtls1_record_replay_check(s, bitmap)) {
1184             rr->length = 0;
1185             rr->read = 1;
1186             s->rrlmethod->reset_packet_length(s->rrl); /* dump this record */
1187             goto again;         /* get another record */
1188         }
1189 #ifndef OPENSSL_NO_SCTP
1190     }
1191 #endif
1192
1193     /* just read a 0 length packet */
1194     if (rr->length == 0) {
1195         rr->read = 1;
1196         goto again;
1197     }
1198
1199     /*
1200      * If this record is from the next epoch (either HM or ALERT), and a
1201      * handshake is currently in progress, buffer it since it cannot be
1202      * processed at this time.
1203      */
1204     if (is_next_epoch) {
1205         if ((SSL_in_init(ssl) || ossl_statem_get_in_handshake(s))) {
1206             if (dtls1_buffer_record (s,
1207                     &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1208                     rr->seq_num) < 0) {
1209                 /* SSLfatal() already called */
1210                 return -1;
1211             }
1212         }
1213         rr->length = 0;
1214         rr->read = 1;
1215         s->rrlmethod->reset_packet_length(s->rrl);
1216         goto again;
1217     }
1218
1219     if (!dtls1_process_record(s, bitmap)) {
1220         if (ossl_statem_in_error(s)) {
1221             /* dtls1_process_record() called SSLfatal */
1222             return -1;
1223         }
1224         rr->length = 0;
1225         rr->read = 1;
1226         s->rrlmethod->reset_packet_length(s->rrl); /* dump this record */
1227         goto again;             /* get another record */
1228     }
1229
1230     return 1;
1231
1232 }
1233
1234 int dtls_buffer_listen_record(SSL_CONNECTION *s, size_t len, unsigned char *seq,
1235                               size_t off)
1236 {
1237     SSL3_RECORD *rr;
1238
1239     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1240     memset(rr, 0, sizeof(SSL3_RECORD));
1241
1242     rr->length = len;
1243     rr->type = SSL3_RT_HANDSHAKE;
1244     memcpy(rr->seq_num, seq, sizeof(rr->seq_num));
1245     rr->off = off;
1246
1247     s->rrlmethod->set0_packet(s->rrl, s->rrlmethod->get0_rbuf(s->rrl)->buf,
1248                               DTLS1_RT_HEADER_LENGTH + len);
1249     rr->data = s->rrlmethod->get0_packet(s->rrl) + DTLS1_RT_HEADER_LENGTH;
1250
1251     if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
1252                             SSL3_RECORD_get_seq_num(s->rlayer.rrec)) <= 0) {
1253         /* SSLfatal() already called */
1254         return 0;
1255     }
1256
1257     return 1;
1258 }