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