Avoid possible divide by zero
[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 /*
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     enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0, macbufs, mac_size);
580
581     /*-
582      * enc_err is:
583      *    0: if the record is publicly invalid, or an internal error, or AEAD
584      *       decryption failed, or ETM decryption failed.
585      *    1: Success or MTE decryption failed (MAC will be randomised)
586      */
587     if (enc_err == 0) {
588         if (ossl_statem_in_error(s)) {
589             /* SSLfatal() already got called */
590             goto end;
591         }
592         if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
593             /*
594              * Valid early_data that we cannot decrypt will fail here. We treat
595              * it like an empty record.
596              */
597
598             thisrr = &rr[0];
599
600             if (!early_data_count_ok(s, thisrr->length,
601                                      EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
602                 /* SSLfatal() already called */
603                 goto end;
604             }
605
606             thisrr->length = 0;
607             thisrr->read = 1;
608             RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
609             RECORD_LAYER_reset_read_sequence(&s->rlayer);
610             ret = 1;
611             goto end;
612         }
613         SSLfatal(s, SSL_AD_BAD_RECORD_MAC,
614                  SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
615         goto end;
616     }
617     OSSL_TRACE_BEGIN(TLS) {
618         BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
619         BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
620     } OSSL_TRACE_END(TLS);
621
622     /* r->length is now the compressed data plus mac */
623     if ((sess != NULL)
624             && (s->enc_read_ctx != NULL)
625             && (!SSL_READ_ETM(s) && EVP_MD_CTX_get0_md(s->read_hash) != NULL)) {
626         /* s->read_hash != NULL => mac_size != -1 */
627
628         for (j = 0; j < num_recs; j++) {
629             SSL_MAC_BUF *thismb = &macbufs[j];
630             thisrr = &rr[j];
631
632             i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
633             if (i == 0 || thismb == NULL || thismb->mac == NULL
634                 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
635                 enc_err = 0;
636             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
637                 enc_err = 0;
638         }
639     }
640
641     if (enc_err == 0) {
642         if (ossl_statem_in_error(s)) {
643             /* We already called SSLfatal() */
644             goto end;
645         }
646         /*
647          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
648          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
649          * failure is directly visible from the ciphertext anyway, we should
650          * not reveal which kind of error occurred -- this might become
651          * visible to an attacker (e.g. via a logfile)
652          */
653         SSLfatal(s, SSL_AD_BAD_RECORD_MAC,
654                  SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
655         goto end;
656     }
657
658  skip_decryption:
659
660     for (j = 0; j < num_recs; j++) {
661         thisrr = &rr[j];
662
663         /* thisrr->length is now just compressed */
664         if (s->expand != NULL) {
665             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
666                 SSLfatal(s, SSL_AD_RECORD_OVERFLOW,
667                          SSL_R_COMPRESSED_LENGTH_TOO_LONG);
668                 goto end;
669             }
670             if (!ssl3_do_uncompress(s, thisrr)) {
671                 SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE,
672                          SSL_R_BAD_DECOMPRESSION);
673                 goto end;
674             }
675         }
676
677         if (SSL_IS_TLS13(s)
678                 && s->enc_read_ctx != NULL
679                 && thisrr->type != SSL3_RT_ALERT) {
680             size_t end;
681
682             if (thisrr->length == 0
683                     || thisrr->type != SSL3_RT_APPLICATION_DATA) {
684                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
685                 goto end;
686             }
687
688             /* Strip trailing padding */
689             for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
690                  end--)
691                 continue;
692
693             thisrr->length = end;
694             thisrr->type = thisrr->data[end];
695             if (thisrr->type != SSL3_RT_APPLICATION_DATA
696                     && thisrr->type != SSL3_RT_ALERT
697                     && thisrr->type != SSL3_RT_HANDSHAKE) {
698                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
699                 goto end;
700             }
701             if (s->msg_callback)
702                 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
703                                 &thisrr->data[end], 1, s, s->msg_callback_arg);
704         }
705
706         /*
707          * TLSv1.3 alert and handshake records are required to be non-zero in
708          * length.
709          */
710         if (SSL_IS_TLS13(s)
711                 && (thisrr->type == SSL3_RT_HANDSHAKE
712                     || thisrr->type == SSL3_RT_ALERT)
713                 && thisrr->length == 0) {
714             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
715             goto end;
716         }
717
718         /*
719          * Usually thisrr->length is the length of a single record, but when
720          * KTLS handles the decryption, thisrr->length may be larger than
721          * SSL3_RT_MAX_PLAIN_LENGTH because the kernel may have coalesced
722          * multiple records.
723          * Therefore we have to rely on KTLS to check the plaintext length
724          * limit in the kernel.
725          */
726         if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH
727                 && (!BIO_get_ktls_recv(s->rbio) || is_ktls_left)) {
728             SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
729             goto end;
730         }
731
732         /*
733          * Check if the received packet overflows the current
734          * Max Fragment Length setting.
735          * Note: USE_MAX_FRAGMENT_LENGTH_EXT and KTLS are mutually exclusive.
736          */
737         if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
738                 && thisrr->length > GET_MAX_FRAGMENT_LENGTH(s->session)) {
739             SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
740             goto end;
741         }
742
743         thisrr->off = 0;
744         /*-
745          * So at this point the following is true
746          * thisrr->type   is the type of record
747          * thisrr->length == number of bytes in record
748          * thisrr->off    == offset to first valid byte
749          * thisrr->data   == where to take bytes from, increment after use :-).
750          */
751
752         /* just read a 0 length packet */
753         if (thisrr->length == 0) {
754             RECORD_LAYER_inc_empty_record_count(&s->rlayer);
755             if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
756                 > MAX_EMPTY_RECORDS) {
757                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL);
758                 goto end;
759             }
760         } else {
761             RECORD_LAYER_reset_empty_record_count(&s->rlayer);
762         }
763     }
764
765     if (s->early_data_state == SSL_EARLY_DATA_READING) {
766         thisrr = &rr[0];
767         if (thisrr->type == SSL3_RT_APPLICATION_DATA
768                 && !early_data_count_ok(s, thisrr->length, 0, 0)) {
769             /* SSLfatal already called */
770             goto end;
771         }
772     }
773
774     RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
775     ret = 1;
776  end:
777     if (macbufs != NULL) {
778         for (j = 0; j < num_recs; j++) {
779             if (macbufs[j].alloced)
780                 OPENSSL_free(macbufs[j].mac);
781         }
782         OPENSSL_free(macbufs);
783     }
784     return ret;
785 }
786
787 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
788 {
789 #ifndef OPENSSL_NO_COMP
790     int i;
791
792     if (rr->comp == NULL) {
793         rr->comp = (unsigned char *)
794             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
795     }
796     if (rr->comp == NULL)
797         return 0;
798
799     i = COMP_expand_block(ssl->expand, rr->comp,
800                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
801     if (i < 0)
802         return 0;
803     else
804         rr->length = i;
805     rr->data = rr->comp;
806 #endif
807     return 1;
808 }
809
810 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
811 {
812 #ifndef OPENSSL_NO_COMP
813     int i;
814
815     i = COMP_compress_block(ssl->compress, wr->data,
816                             (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
817                             wr->input, (int)wr->length);
818     if (i < 0)
819         return 0;
820     else
821         wr->length = i;
822
823     wr->input = wr->data;
824 #endif
825     return 1;
826 }
827
828 /*-
829  * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|. Calls SSLfatal on
830  * internal error, but not otherwise. It is the responsibility of the caller to
831  * report a bad_record_mac
832  *
833  * Returns:
834  *    0: if the record is publicly invalid, or an internal error
835  *    1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
836  */
837 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending,
838              SSL_MAC_BUF *mac, size_t macsize)
839 {
840     SSL3_RECORD *rec;
841     EVP_CIPHER_CTX *ds;
842     size_t l, i;
843     size_t bs;
844     const EVP_CIPHER *enc;
845
846     rec = inrecs;
847     /*
848      * We shouldn't ever be called with more than one record in the SSLv3 case
849      */
850     if (n_recs != 1)
851         return 0;
852     if (sending) {
853         ds = s->enc_write_ctx;
854         if (s->enc_write_ctx == NULL)
855             enc = NULL;
856         else
857             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx);
858     } else {
859         ds = s->enc_read_ctx;
860         if (s->enc_read_ctx == NULL)
861             enc = NULL;
862         else
863             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_read_ctx);
864     }
865
866     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
867         memmove(rec->data, rec->input, rec->length);
868         rec->input = rec->data;
869     } else {
870         int provided = (EVP_CIPHER_get0_provider(enc) != NULL);
871
872         l = rec->length;
873         bs = EVP_CIPHER_CTX_get_block_size(ds);
874
875         /* COMPRESS */
876
877         if ((bs != 1) && sending && !provided) {
878             /*
879              * We only do this for legacy ciphers. Provided ciphers add the
880              * padding on the provider side.
881              */
882             i = bs - (l % bs);
883
884             /* we need to add 'i-1' padding bytes */
885             l += i;
886             /*
887              * the last of these zero bytes will be overwritten with the
888              * padding length.
889              */
890             memset(&rec->input[rec->length], 0, i);
891             rec->length += i;
892             rec->input[l - 1] = (unsigned char)(i - 1);
893         }
894
895         if (!sending) {
896             if (l == 0 || l % bs != 0) {
897                 /* Publicly invalid */
898                 return 0;
899             }
900             /* otherwise, rec->length >= bs */
901         }
902
903         if (EVP_CIPHER_get0_provider(enc) != NULL) {
904             int outlen;
905
906             if (!EVP_CipherUpdate(ds, rec->data, &outlen, rec->input,
907                                   (unsigned int)l))
908                 return 0;
909             rec->length = outlen;
910
911             if (!sending && mac != NULL) {
912                 /* Now get a pointer to the MAC */
913                 OSSL_PARAM params[2], *p = params;
914
915                 /* Get the MAC */
916                 mac->alloced = 0;
917
918                 *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
919                                                       (void **)&mac->mac,
920                                                       macsize);
921                 *p = OSSL_PARAM_construct_end();
922
923                 if (!EVP_CIPHER_CTX_get_params(ds, params)) {
924                     /* Shouldn't normally happen */
925                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
926                     return 0;
927                 }
928             }
929         } else {
930             if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1) {
931                 /* Shouldn't happen */
932                 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, ERR_R_INTERNAL_ERROR);
933                 return 0;
934             }
935
936             if (!sending)
937                 return ssl3_cbc_remove_padding_and_mac(&rec->length,
938                                            rec->orig_len,
939                                            rec->data,
940                                            (mac != NULL) ? &mac->mac : NULL,
941                                            (mac != NULL) ? &mac->alloced : NULL,
942                                            bs,
943                                            macsize,
944                                            s->ctx->libctx);
945         }
946     }
947     return 1;
948 }
949
950 #define MAX_PADDING 256
951 /*-
952  * tls1_enc encrypts/decrypts |n_recs| in |recs|. Calls SSLfatal on internal
953  * error, but not otherwise. It is the responsibility of the caller to report
954  * a bad_record_mac - if appropriate (DTLS just drops the record).
955  *
956  * Returns:
957  *    0: if the record is publicly invalid, or an internal error, or AEAD
958  *       decryption failed, or Encrypt-then-mac decryption failed.
959  *    1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
960  */
961 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending,
962              SSL_MAC_BUF *macs, size_t macsize)
963 {
964     EVP_CIPHER_CTX *ds;
965     size_t reclen[SSL_MAX_PIPELINES];
966     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
967     int i, pad = 0, tmpr;
968     size_t bs, ctr, padnum, loop;
969     unsigned char padval;
970     const EVP_CIPHER *enc;
971     int tlstree_enc = sending ? (s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
972                               : (s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
973
974     if (n_recs == 0) {
975         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
976         return 0;
977     }
978
979     if (sending) {
980         if (EVP_MD_CTX_get0_md(s->write_hash)) {
981             int n = EVP_MD_CTX_get_size(s->write_hash);
982             if (!ossl_assert(n >= 0)) {
983                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
984                 return 0;
985             }
986         }
987         ds = s->enc_write_ctx;
988         if (s->enc_write_ctx == NULL)
989             enc = NULL;
990         else {
991             int ivlen;
992
993             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx);
994             /* For TLSv1.1 and later explicit IV */
995             if (SSL_USE_EXPLICIT_IV(s)
996                 && EVP_CIPHER_get_mode(enc) == EVP_CIPH_CBC_MODE)
997                 ivlen = EVP_CIPHER_get_iv_length(enc);
998             else
999                 ivlen = 0;
1000             if (ivlen > 1) {
1001                 for (ctr = 0; ctr < n_recs; ctr++) {
1002                     if (recs[ctr].data != recs[ctr].input) {
1003                         /*
1004                          * we can't write into the input stream: Can this ever
1005                          * happen?? (steve)
1006                          */
1007                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1008                         return 0;
1009                     } else if (RAND_bytes_ex(s->ctx->libctx, recs[ctr].input,
1010                                              ivlen, 0) <= 0) {
1011                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1012                         return 0;
1013                     }
1014                 }
1015             }
1016         }
1017     } else {
1018         if (EVP_MD_CTX_get0_md(s->read_hash)) {
1019             int n = EVP_MD_CTX_get_size(s->read_hash);
1020             if (!ossl_assert(n >= 0)) {
1021                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1022                 return 0;
1023             }
1024         }
1025         ds = s->enc_read_ctx;
1026         if (s->enc_read_ctx == NULL)
1027             enc = NULL;
1028         else
1029             enc = EVP_CIPHER_CTX_get0_cipher(s->enc_read_ctx);
1030     }
1031
1032     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
1033         for (ctr = 0; ctr < n_recs; ctr++) {
1034             memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
1035             recs[ctr].input = recs[ctr].data;
1036         }
1037     } else {
1038         int provided = (EVP_CIPHER_get0_provider(enc) != NULL);
1039
1040         bs = EVP_CIPHER_get_block_size(EVP_CIPHER_CTX_get0_cipher(ds));
1041
1042         if (n_recs > 1) {
1043             if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
1044                   & EVP_CIPH_FLAG_PIPELINE) == 0) {
1045                 /*
1046                  * We shouldn't have been called with pipeline data if the
1047                  * cipher doesn't support pipelining
1048                  */
1049                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
1050                 return 0;
1051             }
1052         }
1053         for (ctr = 0; ctr < n_recs; ctr++) {
1054             reclen[ctr] = recs[ctr].length;
1055
1056             if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
1057                         & EVP_CIPH_FLAG_AEAD_CIPHER) != 0) {
1058                 unsigned char *seq;
1059
1060                 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
1061                     : RECORD_LAYER_get_read_sequence(&s->rlayer);
1062
1063                 if (SSL_IS_DTLS(s)) {
1064                     /* DTLS does not support pipelining */
1065                     unsigned char dtlsseq[8], *p = dtlsseq;
1066
1067                     s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
1068                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
1069                     memcpy(p, &seq[2], 6);
1070                     memcpy(buf[ctr], dtlsseq, 8);
1071                 } else {
1072                     memcpy(buf[ctr], seq, 8);
1073                     for (i = 7; i >= 0; i--) { /* increment */
1074                         ++seq[i];
1075                         if (seq[i] != 0)
1076                             break;
1077                     }
1078                 }
1079
1080                 buf[ctr][8] = recs[ctr].type;
1081                 buf[ctr][9] = (unsigned char)(s->version >> 8);
1082                 buf[ctr][10] = (unsigned char)(s->version);
1083                 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
1084                 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
1085                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
1086                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
1087                 if (pad <= 0) {
1088                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1089                     return 0;
1090                 }
1091
1092                 if (sending) {
1093                     reclen[ctr] += pad;
1094                     recs[ctr].length += pad;
1095                 }
1096
1097             } else if ((bs != 1) && sending && !provided) {
1098                 /*
1099                  * We only do this for legacy ciphers. Provided ciphers add the
1100                  * padding on the provider side.
1101                  */
1102                 padnum = bs - (reclen[ctr] % bs);
1103
1104                 /* Add weird padding of up to 256 bytes */
1105
1106                 if (padnum > MAX_PADDING) {
1107                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1108                     return 0;
1109                 }
1110                 /* we need to add 'padnum' padding bytes of value padval */
1111                 padval = (unsigned char)(padnum - 1);
1112                 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
1113                     recs[ctr].input[loop] = padval;
1114                 reclen[ctr] += padnum;
1115                 recs[ctr].length += padnum;
1116             }
1117
1118             if (!sending) {
1119                 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0) {
1120                     /* Publicly invalid */
1121                     return 0;
1122                 }
1123             }
1124         }
1125         if (n_recs > 1) {
1126             unsigned char *data[SSL_MAX_PIPELINES];
1127
1128             /* Set the output buffers */
1129             for (ctr = 0; ctr < n_recs; ctr++) {
1130                 data[ctr] = recs[ctr].data;
1131             }
1132             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
1133                                     (int)n_recs, data) <= 0) {
1134                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
1135                 return 0;
1136             }
1137             /* Set the input buffers */
1138             for (ctr = 0; ctr < n_recs; ctr++) {
1139                 data[ctr] = recs[ctr].input;
1140             }
1141             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
1142                                     (int)n_recs, data) <= 0
1143                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
1144                                        (int)n_recs, reclen) <= 0) {
1145                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
1146                 return 0;
1147             }
1148         }
1149
1150         if (!SSL_IS_DTLS(s) && tlstree_enc) {
1151             unsigned char *seq;
1152             int decrement_seq = 0;
1153
1154             /*
1155              * When sending, seq is incremented after MAC calculation.
1156              * So if we are in ETM mode, we use seq 'as is' in the ctrl-function.
1157              * Otherwise we have to decrease it in the implementation
1158              */
1159             if (sending && !SSL_WRITE_ETM(s))
1160                 decrement_seq = 1;
1161
1162             seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
1163                           : RECORD_LAYER_get_read_sequence(&s->rlayer);
1164             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_TLSTREE, decrement_seq, seq) <= 0) {
1165                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1166                 return 0;
1167             }
1168         }
1169
1170         if (provided) {
1171             int outlen;
1172
1173             /* Provided cipher - we do not support pipelining on this path */
1174             if (n_recs > 1)  {
1175                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1176                 return 0;
1177             }
1178
1179             if (!EVP_CipherUpdate(ds, recs[0].data, &outlen, recs[0].input,
1180                                   (unsigned int)reclen[0]))
1181                 return 0;
1182             recs[0].length = outlen;
1183
1184             /*
1185              * The length returned from EVP_CipherUpdate above is the actual
1186              * payload length. We need to adjust the data/input ptr to skip over
1187              * any explicit IV
1188              */
1189             if (!sending) {
1190                 if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
1191                         recs[0].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1192                         recs[0].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1193                 } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
1194                         recs[0].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1195                         recs[0].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1196                 } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
1197                     recs[0].data += bs;
1198                     recs[0].input += bs;
1199                     recs[0].orig_len -= bs;
1200                 }
1201
1202                 /* Now get a pointer to the MAC (if applicable) */
1203                 if (macs != NULL) {
1204                     OSSL_PARAM params[2], *p = params;
1205
1206                     /* Get the MAC */
1207                     macs[0].alloced = 0;
1208
1209                     *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
1210                                                           (void **)&macs[0].mac,
1211                                                           macsize);
1212                     *p = OSSL_PARAM_construct_end();
1213
1214                     if (!EVP_CIPHER_CTX_get_params(ds, params)) {
1215                         /* Shouldn't normally happen */
1216                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1217                                  ERR_R_INTERNAL_ERROR);
1218                         return 0;
1219                     }
1220                 }
1221             }
1222         } else {
1223             /* Legacy cipher */
1224
1225             tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
1226                               (unsigned int)reclen[0]);
1227             if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
1228                  & EVP_CIPH_FLAG_CUSTOM_CIPHER) != 0
1229                 ? (tmpr < 0)
1230                 : (tmpr == 0)) {
1231                 /* AEAD can fail to verify MAC */
1232                 return 0;
1233             }
1234
1235             if (!sending) {
1236                 for (ctr = 0; ctr < n_recs; ctr++) {
1237                     /* Adjust the record to remove the explicit IV/MAC/Tag */
1238                     if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
1239                         recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1240                         recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1241                         recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1242                     } else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
1243                         recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1244                         recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1245                         recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1246                     } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
1247                         if (recs[ctr].length < bs)
1248                             return 0;
1249                         recs[ctr].data += bs;
1250                         recs[ctr].input += bs;
1251                         recs[ctr].length -= bs;
1252                         recs[ctr].orig_len -= bs;
1253                     }
1254
1255                     /*
1256                      * If using Mac-then-encrypt, then this will succeed but
1257                      * with a random MAC if padding is invalid
1258                      */
1259                     if (!tls1_cbc_remove_padding_and_mac(&recs[ctr].length,
1260                                          recs[ctr].orig_len,
1261                                          recs[ctr].data,
1262                                          (macs != NULL) ? &macs[ctr].mac : NULL,
1263                                          (macs != NULL) ? &macs[ctr].alloced
1264                                                         : NULL,
1265                                          bs,
1266                                          pad ? (size_t)pad : macsize,
1267                                          (EVP_CIPHER_get_flags(enc)
1268                                          & EVP_CIPH_FLAG_AEAD_CIPHER) != 0,
1269                                          s->ctx->libctx))
1270                         return 0;
1271                 }
1272             }
1273         }
1274     }
1275     return 1;
1276 }
1277
1278 /*
1279  * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
1280  * which ssl3_cbc_digest_record supports.
1281  */
1282 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
1283 {
1284     switch (EVP_MD_CTX_get_type(ctx)) {
1285     case NID_md5:
1286     case NID_sha1:
1287     case NID_sha224:
1288     case NID_sha256:
1289     case NID_sha384:
1290     case NID_sha512:
1291         return 1;
1292     default:
1293         return 0;
1294     }
1295 }
1296
1297 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1298 {
1299     unsigned char *mac_sec, *seq;
1300     const EVP_MD_CTX *hash;
1301     unsigned char *p, rec_char;
1302     size_t md_size;
1303     size_t npad;
1304     int t;
1305
1306     if (sending) {
1307         mac_sec = &(ssl->s3.write_mac_secret[0]);
1308         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1309         hash = ssl->write_hash;
1310     } else {
1311         mac_sec = &(ssl->s3.read_mac_secret[0]);
1312         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1313         hash = ssl->read_hash;
1314     }
1315
1316     t = EVP_MD_CTX_get_size(hash);
1317     if (t <= 0)
1318         return 0;
1319     md_size = t;
1320     npad = (48 / md_size) * md_size;
1321
1322     if (!sending
1323         && EVP_CIPHER_CTX_get_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE
1324         && ssl3_cbc_record_digest_supported(hash)) {
1325 #ifdef OPENSSL_NO_DEPRECATED_3_0
1326         return 0;
1327 #else
1328         /*
1329          * This is a CBC-encrypted record. We must avoid leaking any
1330          * timing-side channel information about how many blocks of data we
1331          * are hashing because that gives an attacker a timing-oracle.
1332          */
1333
1334         /*-
1335          * npad is, at most, 48 bytes and that's with MD5:
1336          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1337          *
1338          * With SHA-1 (the largest hash speced for SSLv3) the hash size
1339          * goes up 4, but npad goes down by 8, resulting in a smaller
1340          * total size.
1341          */
1342         unsigned char header[75];
1343         size_t j = 0;
1344         memcpy(header + j, mac_sec, md_size);
1345         j += md_size;
1346         memcpy(header + j, ssl3_pad_1, npad);
1347         j += npad;
1348         memcpy(header + j, seq, 8);
1349         j += 8;
1350         header[j++] = rec->type;
1351         header[j++] = (unsigned char)(rec->length >> 8);
1352         header[j++] = (unsigned char)(rec->length & 0xff);
1353
1354         /* Final param == is SSLv3 */
1355         if (ssl3_cbc_digest_record(EVP_MD_CTX_get0_md(hash),
1356                                    md, &md_size,
1357                                    header, rec->input,
1358                                    rec->length, rec->orig_len,
1359                                    mac_sec, md_size, 1) <= 0)
1360             return 0;
1361 #endif
1362     } else {
1363         unsigned int md_size_u;
1364         /* Chop the digest off the end :-) */
1365         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1366
1367         if (md_ctx == NULL)
1368             return 0;
1369
1370         rec_char = rec->type;
1371         p = md;
1372         s2n(rec->length, p);
1373         if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1374             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1375             || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1376             || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1377             || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1378             || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1379             || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1380             || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1381             || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1382             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1383             || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1384             || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1385             || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1386             EVP_MD_CTX_free(md_ctx);
1387             return 0;
1388         }
1389
1390         EVP_MD_CTX_free(md_ctx);
1391     }
1392
1393     ssl3_record_sequence_update(seq);
1394     return 1;
1395 }
1396
1397 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1398 {
1399     unsigned char *seq;
1400     EVP_MD_CTX *hash;
1401     size_t md_size;
1402     int i;
1403     EVP_MD_CTX *hmac = NULL, *mac_ctx;
1404     unsigned char header[13];
1405     int stream_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1406                              : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM);
1407     int tlstree_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
1408                               : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
1409     int t;
1410     int ret = 0;
1411
1412     if (sending) {
1413         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1414         hash = ssl->write_hash;
1415     } else {
1416         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1417         hash = ssl->read_hash;
1418     }
1419
1420     t = EVP_MD_CTX_get_size(hash);
1421     if (!ossl_assert(t >= 0))
1422         return 0;
1423     md_size = t;
1424
1425     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1426     if (stream_mac) {
1427         mac_ctx = hash;
1428     } else {
1429         hmac = EVP_MD_CTX_new();
1430         if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash)) {
1431             goto end;
1432         }
1433         mac_ctx = hmac;
1434     }
1435
1436     if (!SSL_IS_DTLS(ssl) && tlstree_mac && EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_TLSTREE, 0, seq) <= 0) {
1437         goto end;
1438     }
1439
1440     if (SSL_IS_DTLS(ssl)) {
1441         unsigned char dtlsseq[8], *p = dtlsseq;
1442
1443         s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1444             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1445         memcpy(p, &seq[2], 6);
1446
1447         memcpy(header, dtlsseq, 8);
1448     } else
1449         memcpy(header, seq, 8);
1450
1451     header[8] = rec->type;
1452     header[9] = (unsigned char)(ssl->version >> 8);
1453     header[10] = (unsigned char)(ssl->version);
1454     header[11] = (unsigned char)(rec->length >> 8);
1455     header[12] = (unsigned char)(rec->length & 0xff);
1456
1457     if (!sending && !SSL_READ_ETM(ssl)
1458         && EVP_CIPHER_CTX_get_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE
1459         && ssl3_cbc_record_digest_supported(mac_ctx)) {
1460         OSSL_PARAM tls_hmac_params[2], *p = tls_hmac_params;
1461
1462         *p++ = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_TLS_DATA_SIZE,
1463                                            &rec->orig_len);
1464         *p++ = OSSL_PARAM_construct_end();
1465
1466         if (!EVP_PKEY_CTX_set_params(EVP_MD_CTX_get_pkey_ctx(mac_ctx),
1467                                      tls_hmac_params)) {
1468             goto end;
1469         }
1470     }
1471
1472     if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1473         || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1474         || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1475         goto end;
1476     }
1477
1478     OSSL_TRACE_BEGIN(TLS) {
1479         BIO_printf(trc_out, "seq:\n");
1480         BIO_dump_indent(trc_out, seq, 8, 4);
1481         BIO_printf(trc_out, "rec:\n");
1482         BIO_dump_indent(trc_out, rec->data, rec->length, 4);
1483     } OSSL_TRACE_END(TLS);
1484
1485     if (!SSL_IS_DTLS(ssl)) {
1486         for (i = 7; i >= 0; i--) {
1487             ++seq[i];
1488             if (seq[i] != 0)
1489                 break;
1490         }
1491     }
1492     OSSL_TRACE_BEGIN(TLS) {
1493         BIO_printf(trc_out, "md:\n");
1494         BIO_dump_indent(trc_out, md, md_size, 4);
1495     } OSSL_TRACE_END(TLS);
1496     ret = 1;
1497  end:
1498     EVP_MD_CTX_free(hmac);
1499     return ret;
1500 }
1501
1502 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1503 {
1504     int i;
1505     int enc_err;
1506     SSL_SESSION *sess;
1507     SSL3_RECORD *rr;
1508     int imac_size;
1509     size_t mac_size = 0;
1510     unsigned char md[EVP_MAX_MD_SIZE];
1511     size_t max_plain_length = SSL3_RT_MAX_PLAIN_LENGTH;
1512     SSL_MAC_BUF macbuf = { NULL, 0 };
1513     int ret = 0;
1514
1515     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1516     sess = s->session;
1517
1518     /*
1519      * At this point, s->rlayer.packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1520      * and we have that many bytes in s->rlayer.packet
1521      */
1522     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1523
1524     /*
1525      * ok, we can now read from 's->rlayer.packet' data into 'rr'. rr->input
1526      * points at rr->length bytes, which need to be copied into rr->data by
1527      * either the decryption or by the decompression. When the data is 'copied'
1528      * into the rr->data buffer, rr->input will be pointed at the new buffer
1529      */
1530
1531     /*
1532      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1533      * bytes of encrypted compressed stuff.
1534      */
1535
1536     /* check is not needed I believe */
1537     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1538         SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1539         return 0;
1540     }
1541
1542     /* decrypt in place in 'rr->input' */
1543     rr->data = rr->input;
1544     rr->orig_len = rr->length;
1545
1546     if (s->read_hash != NULL) {
1547         const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(s->read_hash);
1548
1549         if (tmpmd != NULL) {
1550             imac_size = EVP_MD_get_size(tmpmd);
1551             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
1552                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
1553                     return 0;
1554             }
1555             mac_size = (size_t)imac_size;
1556         }
1557     }
1558
1559     if (SSL_READ_ETM(s) && s->read_hash) {
1560         unsigned char *mac;
1561
1562         if (rr->orig_len < mac_size) {
1563             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1564             return 0;
1565         }
1566         rr->length -= mac_size;
1567         mac = rr->data + rr->length;
1568         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1569         if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1570             SSLfatal(s, SSL_AD_BAD_RECORD_MAC,
1571                      SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1572             return 0;
1573         }
1574         /*
1575          * We've handled the mac now - there is no MAC inside the encrypted
1576          * record
1577          */
1578         mac_size = 0;
1579     }
1580
1581     /*
1582      * Set a mark around the packet decryption attempt.  This is DTLS, so
1583      * bad packets are just ignored, and we don't want to leave stray
1584      * errors in the queue from processing bogus junk that we ignored.
1585      */
1586     ERR_set_mark();
1587     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0, &macbuf, mac_size);
1588
1589     /*-
1590      * enc_err is:
1591      *    0: if the record is publicly invalid, or an internal error, or AEAD
1592      *       decryption failed, or ETM decryption failed.
1593      *    1: Success or MTE decryption failed (MAC will be randomised)
1594      */
1595     if (enc_err == 0) {
1596         ERR_pop_to_mark();
1597         if (ossl_statem_in_error(s)) {
1598             /* SSLfatal() got called */
1599             goto end;
1600         }
1601         /* For DTLS we simply ignore bad packets. */
1602         rr->length = 0;
1603         RECORD_LAYER_reset_packet_length(&s->rlayer);
1604         goto end;
1605     }
1606     ERR_clear_last_mark();
1607     OSSL_TRACE_BEGIN(TLS) {
1608         BIO_printf(trc_out, "dec %zd\n", rr->length);
1609         BIO_dump_indent(trc_out, rr->data, rr->length, 4);
1610     } OSSL_TRACE_END(TLS);
1611
1612     /* r->length is now the compressed data plus mac */
1613     if ((sess != NULL)
1614             && !SSL_READ_ETM(s)
1615             && (s->enc_read_ctx != NULL)
1616             && (EVP_MD_CTX_get0_md(s->read_hash) != NULL)) {
1617         /* s->read_hash != NULL => mac_size != -1 */
1618
1619         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1620         if (i == 0 || macbuf.mac == NULL
1621             || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
1622             enc_err = 0;
1623         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1624             enc_err = 0;
1625     }
1626
1627     if (enc_err == 0) {
1628         /* decryption failed, silently discard message */
1629         rr->length = 0;
1630         RECORD_LAYER_reset_packet_length(&s->rlayer);
1631         goto end;
1632     }
1633
1634     /* r->length is now just compressed */
1635     if (s->expand != NULL) {
1636         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1637             SSLfatal(s, SSL_AD_RECORD_OVERFLOW,
1638                      SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1639             goto end;
1640         }
1641         if (!ssl3_do_uncompress(s, rr)) {
1642             SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE, SSL_R_BAD_DECOMPRESSION);
1643             goto end;
1644         }
1645     }
1646
1647     /* use current Max Fragment Length setting if applicable */
1648     if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1649         max_plain_length = GET_MAX_FRAGMENT_LENGTH(s->session);
1650
1651     /* send overflow if the plaintext is too long now it has passed MAC */
1652     if (rr->length > max_plain_length) {
1653         SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1654         goto end;
1655     }
1656
1657     rr->off = 0;
1658     /*-
1659      * So at this point the following is true
1660      * ssl->s3.rrec.type   is the type of record
1661      * ssl->s3.rrec.length == number of bytes in record
1662      * ssl->s3.rrec.off    == offset to first valid byte
1663      * ssl->s3.rrec.data   == where to take bytes from, increment
1664      *                        after use :-).
1665      */
1666
1667     /* we have pulled in a full packet so zero things */
1668     RECORD_LAYER_reset_packet_length(&s->rlayer);
1669
1670     /* Mark receipt of record. */
1671     dtls1_record_bitmap_update(s, bitmap);
1672
1673     ret = 1;
1674  end:
1675     if (macbuf.alloced)
1676         OPENSSL_free(macbuf.mac);
1677     return ret;
1678 }
1679
1680 /*
1681  * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1682  */
1683 #define dtls1_get_processed_record(s) \
1684                    dtls1_retrieve_buffered_record((s), \
1685                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1686
1687 /*-
1688  * Call this to get a new input record.
1689  * It will return <= 0 if more data is needed, normally due to an error
1690  * or non-blocking IO.
1691  * When it finishes, one packet has been decoded and can be found in
1692  * ssl->s3.rrec.type    - is the type of record
1693  * ssl->s3.rrec.data    - data
1694  * ssl->s3.rrec.length  - number of bytes
1695  */
1696 /* used only by dtls1_read_bytes */
1697 int dtls1_get_record(SSL *s)
1698 {
1699     int ssl_major, ssl_minor;
1700     int rret;
1701     size_t more, n;
1702     SSL3_RECORD *rr;
1703     unsigned char *p = NULL;
1704     unsigned short version;
1705     DTLS1_BITMAP *bitmap;
1706     unsigned int is_next_epoch;
1707
1708     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1709
1710  again:
1711     /*
1712      * The epoch may have changed.  If so, process all the pending records.
1713      * This is a non-blocking operation.
1714      */
1715     if (!dtls1_process_buffered_records(s)) {
1716         /* SSLfatal() already called */
1717         return -1;
1718     }
1719
1720     /* if we're renegotiating, then there may be buffered records */
1721     if (dtls1_get_processed_record(s))
1722         return 1;
1723
1724     /* get something from the wire */
1725
1726     /* check if we have the header */
1727     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1728         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1729         rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1730                            SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1731         /* read timeout is handled by dtls1_read_bytes */
1732         if (rret <= 0) {
1733             /* SSLfatal() already called if appropriate */
1734             return rret;         /* error or non-blocking */
1735         }
1736
1737         /* this packet contained a partial record, dump it */
1738         if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1739             DTLS1_RT_HEADER_LENGTH) {
1740             RECORD_LAYER_reset_packet_length(&s->rlayer);
1741             goto again;
1742         }
1743
1744         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1745
1746         p = RECORD_LAYER_get_packet(&s->rlayer);
1747
1748         if (s->msg_callback)
1749             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1750                             s, s->msg_callback_arg);
1751
1752         /* Pull apart the header into the DTLS1_RECORD */
1753         rr->type = *(p++);
1754         ssl_major = *(p++);
1755         ssl_minor = *(p++);
1756         version = (ssl_major << 8) | ssl_minor;
1757
1758         /* sequence number is 64 bits, with top 2 bytes = epoch */
1759         n2s(p, rr->epoch);
1760
1761         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1762         p += 6;
1763
1764         n2s(p, rr->length);
1765         rr->read = 0;
1766
1767         /*
1768          * Lets check the version. We tolerate alerts that don't have the exact
1769          * version number (e.g. because of protocol version errors)
1770          */
1771         if (!s->first_packet && rr->type != SSL3_RT_ALERT) {
1772             if (version != s->version) {
1773                 /* unexpected version, silently discard */
1774                 rr->length = 0;
1775                 rr->read = 1;
1776                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1777                 goto again;
1778             }
1779         }
1780
1781         if ((version & 0xff00) != (s->version & 0xff00)) {
1782             /* wrong version, silently discard record */
1783             rr->length = 0;
1784             rr->read = 1;
1785             RECORD_LAYER_reset_packet_length(&s->rlayer);
1786             goto again;
1787         }
1788
1789         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1790             /* record too long, silently discard it */
1791             rr->length = 0;
1792             rr->read = 1;
1793             RECORD_LAYER_reset_packet_length(&s->rlayer);
1794             goto again;
1795         }
1796
1797         /* If received packet overflows own-client Max Fragment Length setting */
1798         if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1799                 && rr->length > GET_MAX_FRAGMENT_LENGTH(s->session) + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
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         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1808     }
1809
1810     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1811
1812     if (rr->length >
1813         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1814         /* now s->rlayer.packet_length == DTLS1_RT_HEADER_LENGTH */
1815         more = rr->length;
1816         rret = ssl3_read_n(s, more, more, 1, 1, &n);
1817         /* this packet contained a partial record, dump it */
1818         if (rret <= 0 || n != more) {
1819             if (ossl_statem_in_error(s)) {
1820                 /* ssl3_read_n() called SSLfatal() */
1821                 return -1;
1822             }
1823             rr->length = 0;
1824             rr->read = 1;
1825             RECORD_LAYER_reset_packet_length(&s->rlayer);
1826             goto again;
1827         }
1828
1829         /*
1830          * now n == rr->length, and s->rlayer.packet_length ==
1831          * DTLS1_RT_HEADER_LENGTH + rr->length
1832          */
1833     }
1834     /* set state for later operations */
1835     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1836
1837     /* match epochs.  NULL means the packet is dropped on the floor */
1838     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1839     if (bitmap == NULL) {
1840         rr->length = 0;
1841         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1842         goto again;             /* get another record */
1843     }
1844 #ifndef OPENSSL_NO_SCTP
1845     /* Only do replay check if no SCTP bio */
1846     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1847 #endif
1848         /* Check whether this is a repeat, or aged record. */
1849         if (!dtls1_record_replay_check(s, bitmap)) {
1850             rr->length = 0;
1851             rr->read = 1;
1852             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1853             goto again;         /* get another record */
1854         }
1855 #ifndef OPENSSL_NO_SCTP
1856     }
1857 #endif
1858
1859     /* just read a 0 length packet */
1860     if (rr->length == 0) {
1861         rr->read = 1;
1862         goto again;
1863     }
1864
1865     /*
1866      * If this record is from the next epoch (either HM or ALERT), and a
1867      * handshake is currently in progress, buffer it since it cannot be
1868      * processed at this time.
1869      */
1870     if (is_next_epoch) {
1871         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1872             if (dtls1_buffer_record (s,
1873                     &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1874                     rr->seq_num) < 0) {
1875                 /* SSLfatal() already called */
1876                 return -1;
1877             }
1878         }
1879         rr->length = 0;
1880         rr->read = 1;
1881         RECORD_LAYER_reset_packet_length(&s->rlayer);
1882         goto again;
1883     }
1884
1885     if (!dtls1_process_record(s, bitmap)) {
1886         if (ossl_statem_in_error(s)) {
1887             /* dtls1_process_record() called SSLfatal */
1888             return -1;
1889         }
1890         rr->length = 0;
1891         rr->read = 1;
1892         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1893         goto again;             /* get another record */
1894     }
1895
1896     return 1;
1897
1898 }
1899
1900 int dtls_buffer_listen_record(SSL *s, size_t len, unsigned char *seq, size_t off)
1901 {
1902     SSL3_RECORD *rr;
1903
1904     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1905     memset(rr, 0, sizeof(SSL3_RECORD));
1906
1907     rr->length = len;
1908     rr->type = SSL3_RT_HANDSHAKE;
1909     memcpy(rr->seq_num, seq, sizeof(rr->seq_num));
1910     rr->off = off;
1911
1912     s->rlayer.packet = RECORD_LAYER_get_rbuf(&s->rlayer)->buf;
1913     s->rlayer.packet_length = DTLS1_RT_HEADER_LENGTH + len;
1914     rr->data = s->rlayer.packet + DTLS1_RT_HEADER_LENGTH;
1915
1916     if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
1917                             SSL3_RECORD_get_seq_num(s->rlayer.rrec)) <= 0) {
1918         /* SSLfatal() already called */
1919         return 0;
1920     }
1921
1922     return 1;
1923 }