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