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