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