2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include <openssl/bio.h>
11 #include <openssl/ssl.h>
12 #include <openssl/err.h>
13 #include <openssl/core_names.h>
14 #include "internal/e_os.h"
15 #include "internal/packet.h"
16 #include "../../ssl_local.h"
17 #include "../record_local.h"
18 #include "recmethod_local.h"
20 static void tls_int_free(OSSL_RECORD_LAYER *rl);
22 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
28 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
34 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
36 const EVP_CIPHER *ciph,
40 * Provided cipher, the TLS padding/MAC removal is performed provider
41 * side so we need to tell the ctx about our TLS version and mac size
43 OSSL_PARAM params[3], *pprm = params;
47 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
49 imacsize = EVP_MD_get_size(md);
51 macsize = (size_t)imacsize;
53 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
55 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
57 *pprm = OSSL_PARAM_construct_end();
59 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
60 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
68 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
69 * which ssl3_cbc_digest_record supports.
71 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
73 switch (EVP_MD_CTX_get_type(ctx)) {
86 #ifndef OPENSSL_NO_COMP
87 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
89 if (rl->options & SSL_OP_NO_COMPRESSION)
92 return rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
96 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
99 size_t len, align = 0, headerlen;
105 headerlen = DTLS1_RT_HEADER_LENGTH;
107 headerlen = SSL3_RT_HEADER_LENGTH;
109 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
110 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
113 if (b->buf == NULL) {
114 len = SSL3_RT_MAX_PLAIN_LENGTH
115 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
116 #ifndef OPENSSL_NO_COMP
117 if (tls_allow_compression(rl))
118 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
120 if (b->default_len > len)
121 len = b->default_len;
122 if ((p = OPENSSL_malloc(len)) == NULL) {
124 * We've got a malloc failure, and we're still initialising buffers.
125 * We assume we're so doomed that we won't even be able to send an
128 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
138 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
143 if (rl->options & SSL_OP_CLEANSE_PLAINTEXT)
144 OPENSSL_cleanse(b->buf, b->len);
145 OPENSSL_free(b->buf);
151 * Return values are as per SSL_read()
153 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
154 int clearold, size_t *readbytes)
157 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
158 * packet by another n bytes. The packet will be in the sub-array of
159 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
160 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
161 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
162 * packet to the start of the buffer; if clearold == 0 then leave any old
163 * packets where they were
165 size_t len, left, align = 0;
170 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
174 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
175 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
176 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
180 /* start with empty packet ... */
183 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
185 * check if next packet length is large enough to justify payload
188 pkt = rb->buf + rb->offset;
189 if (pkt[0] == SSL3_RT_APPLICATION_DATA
190 && (pkt[3] << 8 | pkt[4]) >= 128) {
192 * Note that even if packet is corrupted and its length field
193 * is insane, we can only be led to wrong decision about
194 * whether memmove will occur or not. Header values has no
195 * effect on memmove arguments and therefore no buffer
196 * overrun can be triggered.
198 memmove(rb->buf + align, pkt, left);
202 rl->packet = rb->buf + rb->offset;
203 rl->packet_length = 0;
204 /* ... now we can act as if 'extend' was set */
207 len = rl->packet_length;
208 pkt = rb->buf + align;
210 * Move any available bytes to front of buffer: 'len' bytes already
211 * pointed to by 'packet', 'left' extra ones at the end
213 if (rl->packet != pkt && clearold == 1) {
214 memmove(pkt, rl->packet, len + left);
216 rb->offset = len + align;
220 * For DTLS/UDP reads should not span multiple packets because the read
221 * operation returns the whole packet at once (as long as it fits into
225 if (left == 0 && extend)
227 if (left > 0 && n > left)
231 /* if there is enough in the buffer from a previous read, take some */
233 rl->packet_length += n;
237 return OSSL_RECORD_RETURN_SUCCESS;
240 /* else we need to read more data */
242 if (n > rb->len - rb->offset) {
243 /* does not happen */
244 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
245 return OSSL_RECORD_RETURN_FATAL;
248 /* We always act like read_ahead is set for DTLS */
249 if (!rl->read_ahead && !rl->isdtls) {
250 /* ignore max parameter */
255 if (max > rb->len - rb->offset)
256 max = rb->len - rb->offset;
262 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
265 * Now we have len+left bytes at the front of s->s3.rbuf.buf and
266 * need to read in more until we have len+n (up to len+max if
272 ret = BIO_read(bio, pkt + len + left, max - left);
275 ret = OSSL_RECORD_RETURN_SUCCESS;
276 } else if (BIO_should_retry(bio)) {
277 if (rl->prev != NULL) {
279 * We were reading from the previous epoch. Now there is no
280 * more data, so swap to the actual transport BIO
286 ret = OSSL_RECORD_RETURN_RETRY;
287 } else if (BIO_eof(bio)) {
288 ret = OSSL_RECORD_RETURN_EOF;
290 ret = OSSL_RECORD_RETURN_FATAL;
293 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
294 ret = OSSL_RECORD_RETURN_FATAL;
297 if (ret <= OSSL_RECORD_RETURN_RETRY) {
299 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
301 tls_release_read_buffer(rl);
306 * reads should *never* span multiple packets for DTLS because the
307 * underlying transport protocol is message oriented as opposed to
308 * byte oriented as in the TLS case.
312 n = left; /* makes the while condition false */
316 /* done reading, now the book-keeping */
319 rl->packet_length += n;
321 return OSSL_RECORD_RETURN_SUCCESS;
325 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
326 * for us in the buffer.
328 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
336 p = SSL3_BUFFER_get_buf(rbuf);
340 left = SSL3_BUFFER_get_left(rbuf);
342 if (left < SSL3_RT_HEADER_LENGTH)
345 p += SSL3_BUFFER_get_offset(rbuf);
348 * We only check the type and record length, we will sanity check version
351 if (*p != SSL3_RT_APPLICATION_DATA)
357 if (left < SSL3_RT_HEADER_LENGTH + len)
363 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
364 size_t overhead, int send)
366 uint32_t max_early_data = rl->max_early_data;
368 if (max_early_data == 0) {
369 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
370 SSL_R_TOO_MUCH_EARLY_DATA);
374 /* If we are dealing with ciphertext we need to allow for the overhead */
375 max_early_data += overhead;
377 if (rl->early_data_count + length > max_early_data) {
378 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
379 SSL_R_TOO_MUCH_EARLY_DATA);
382 rl->early_data_count += length;
388 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
389 * will be processed per call to ssl3_get_record. Without this limit an
390 * attacker could send empty records at a faster rate than we can process and
391 * cause ssl3_get_record to loop forever.
393 #define MAX_EMPTY_RECORDS 32
395 #define SSL2_RT_HEADER_LENGTH 2
398 * Call this to buffer new input records in rl->rrec.
399 * It will return a OSSL_RECORD_RETURN_* value.
400 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
401 * records have been decoded. For each record 'i':
402 * rrec[i].type - is the type of record
403 * rrec[i].data, - data
404 * rrec[i].length, - number of bytes
405 * Multiple records will only be returned if the record types are all
406 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
409 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
414 SSL3_RECORD *rr, *thisrr;
417 unsigned char md[EVP_MAX_MD_SIZE];
418 unsigned int version;
421 size_t num_recs = 0, max_recs, j;
422 PACKET pkt, sslv2pkt;
423 SSL_MAC_BUF *macbufs = NULL;
424 int ret = OSSL_RECORD_RETURN_FATAL;
428 if (rbuf->buf == NULL) {
429 if (!tls_setup_read_buffer(rl)) {
430 /* RLAYERfatal() already called */
431 return OSSL_RECORD_RETURN_FATAL;
435 max_recs = rl->max_pipelines;
441 thisrr = &rr[num_recs];
443 /* check if we have the header */
444 if ((rl->rstate != SSL_ST_READ_BODY) ||
445 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
449 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
450 SSL3_BUFFER_get_len(rbuf), 0,
451 num_recs == 0 ? 1 : 0, &n);
453 if (rret < OSSL_RECORD_RETURN_SUCCESS)
454 return rret; /* error or non-blocking */
456 rl->rstate = SSL_ST_READ_BODY;
459 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
460 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
461 return OSSL_RECORD_RETURN_FATAL;
464 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
465 || !PACKET_get_1(&sslv2pkt, &type)) {
466 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
467 return OSSL_RECORD_RETURN_FATAL;
470 * The first record received by the server may be a V2ClientHello.
472 if (rl->role == OSSL_RECORD_ROLE_SERVER
473 && rl->is_first_record
474 && (sslv2len & 0x8000) != 0
475 && (type == SSL2_MT_CLIENT_HELLO)) {
479 * |num_recs| here will actually always be 0 because
480 * |num_recs > 0| only ever occurs when we are processing
481 * multiple app data records - which we know isn't the case here
482 * because it is an SSLv2ClientHello. We keep it using
483 * |num_recs| for the sake of consistency
485 thisrr->type = SSL3_RT_HANDSHAKE;
486 thisrr->rec_version = SSL2_VERSION;
488 thisrr->length = sslv2len & 0x7fff;
490 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
491 - SSL2_RT_HEADER_LENGTH) {
492 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
493 SSL_R_PACKET_LENGTH_TOO_LONG);
494 return OSSL_RECORD_RETURN_FATAL;
497 /* SSLv3+ style record */
499 /* Pull apart the header into the SSL3_RECORD */
500 if (!PACKET_get_1(&pkt, &type)
501 || !PACKET_get_net_2(&pkt, &version)
502 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
503 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
504 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
505 return OSSL_RECORD_RETURN_FATAL;
508 thisrr->rec_version = version;
511 * When we call validate_record_header() only records actually
512 * received in SSLv2 format should have the record version set
513 * to SSL2_VERSION. This way validate_record_header() can know
514 * what format the record was in based on the version.
516 if (thisrr->rec_version == SSL2_VERSION) {
517 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
518 SSL_R_WRONG_VERSION_NUMBER);
519 return OSSL_RECORD_RETURN_FATAL;
522 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
525 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
526 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
527 SSL_R_PACKET_LENGTH_TOO_LONG);
528 return OSSL_RECORD_RETURN_FATAL;
532 if (!rl->funcs->validate_record_header(rl, thisrr)) {
533 /* RLAYERfatal already called */
534 return OSSL_RECORD_RETURN_FATAL;
537 /* now rl->rstate == SSL_ST_READ_BODY */
541 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
542 * how much more data we need to read for the rest of the record
544 if (thisrr->rec_version == SSL2_VERSION) {
545 more = thisrr->length + SSL2_RT_HEADER_LENGTH
546 - SSL3_RT_HEADER_LENGTH;
548 more = thisrr->length;
552 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
554 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
555 if (rret < OSSL_RECORD_RETURN_SUCCESS)
556 return rret; /* error or non-blocking io */
559 /* set state for later operations */
560 rl->rstate = SSL_ST_READ_HEADER;
563 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
564 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
565 * + thisrr->length and we have that many bytes in rl->packet
567 if (thisrr->rec_version == SSL2_VERSION)
568 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
570 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
573 * ok, we can now read from 'rl->packet' data into 'thisrr'.
574 * thisrr->input points at thisrr->length bytes, which need to be copied
575 * into thisrr->data by either the decryption or by the decompression.
576 * When the data is 'copied' into the thisrr->data buffer,
577 * thisrr->input will be updated to point at the new buffer
581 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
582 * thisrr->length bytes of encrypted compressed stuff.
585 /* decrypt in place in 'thisrr->input' */
586 thisrr->data = thisrr->input;
587 thisrr->orig_len = thisrr->length;
591 /* we have pulled in a full packet so zero things */
592 rl->packet_length = 0;
593 rl->is_first_record = 0;
594 } while (num_recs < max_recs
595 && thisrr->type == SSL3_RT_APPLICATION_DATA
596 && RLAYER_USE_EXPLICIT_IV(rl)
597 && rl->enc_ctx != NULL
598 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
599 & EVP_CIPH_FLAG_PIPELINE) != 0
600 && tls_record_app_data_waiting(rl));
603 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
604 /* The following can happen in tlsany_meth after HRR */
605 && rl->version == TLS1_3_VERSION
606 && rl->is_first_handshake) {
608 * CCS messages must be exactly 1 byte long, containing the value 0x01
610 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
611 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
612 SSL_R_INVALID_CCS_MESSAGE);
613 return OSSL_RECORD_RETURN_FATAL;
616 * CCS messages are ignored in TLSv1.3. We treat it like an empty
619 thisrr->type = SSL3_RT_HANDSHAKE;
620 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
621 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
622 SSL_R_UNEXPECTED_CCS_MESSAGE);
623 return OSSL_RECORD_RETURN_FATAL;
627 rl->num_released = 0;
629 return OSSL_RECORD_RETURN_SUCCESS;
632 if (rl->md_ctx != NULL) {
633 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
636 imac_size = EVP_MD_get_size(tmpmd);
637 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
638 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
639 return OSSL_RECORD_RETURN_FATAL;
641 mac_size = (size_t)imac_size;
646 * If in encrypt-then-mac mode calculate mac from encrypted record. All
647 * the details below are public so no timing details can leak.
649 if (rl->use_etm && rl->md_ctx) {
652 for (j = 0; j < num_recs; j++) {
655 if (thisrr->length < mac_size) {
656 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
657 return OSSL_RECORD_RETURN_FATAL;
659 thisrr->length -= mac_size;
660 mac = thisrr->data + thisrr->length;
661 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
662 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
663 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
664 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
665 return OSSL_RECORD_RETURN_FATAL;
669 * We've handled the mac now - there is no MAC inside the encrypted
676 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
677 if (macbufs == NULL) {
678 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
679 return OSSL_RECORD_RETURN_FATAL;
683 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
687 * 0: if the record is publicly invalid, or an internal error, or AEAD
688 * decryption failed, or ETM decryption failed.
689 * 1: Success or MTE decryption failed (MAC will be randomised)
692 if (rl->alert != SSL_AD_NO_ALERT) {
693 /* RLAYERfatal() already got called */
696 if (num_recs == 1 && rl->skip_early_data(rl->cbarg)) {
698 * Valid early_data that we cannot decrypt will fail here. We treat
699 * it like an empty record.
704 if (!rlayer_early_data_count_ok(rl, thisrr->length,
705 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
706 /* RLAYERfatal() already called */
713 rl->num_released = 0;
714 /* Reset the read sequence */
715 memset(rl->sequence, 0, sizeof(rl->sequence));
719 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
720 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
723 OSSL_TRACE_BEGIN(TLS) {
724 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
725 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
726 } OSSL_TRACE_END(TLS);
728 /* r->length is now the compressed data plus mac */
729 if (rl->enc_ctx != NULL
731 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
732 /* rl->md_ctx != NULL => mac_size != -1 */
734 for (j = 0; j < num_recs; j++) {
735 SSL_MAC_BUF *thismb = &macbufs[j];
738 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
739 if (i == 0 || thismb == NULL || thismb->mac == NULL
740 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
742 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
748 if (rl->alert != SSL_AD_NO_ALERT) {
749 /* We already called RLAYERfatal() */
753 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
754 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
755 * failure is directly visible from the ciphertext anyway, we should
756 * not reveal which kind of error occurred -- this might become
757 * visible to an attacker (e.g. via a logfile)
759 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
760 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
764 for (j = 0; j < num_recs; j++) {
767 if (!rl->funcs->post_process_record(rl, thisrr)) {
768 /* RLAYERfatal already called */
773 * Check if the received packet overflows the current
774 * Max Fragment Length setting.
775 * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
777 if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
778 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
784 * So at this point the following is true
785 * thisrr->type is the type of record
786 * thisrr->length == number of bytes in record
787 * thisrr->off == offset to first valid byte
788 * thisrr->data == where to take bytes from, increment after use :-).
791 /* just read a 0 length packet */
792 if (thisrr->length == 0) {
793 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
794 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL);
798 rl->empty_record_count = 0;
802 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
804 if (thisrr->type == SSL3_RT_APPLICATION_DATA
805 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
806 /* RLAYERfatal already called */
811 rl->num_recs = num_recs;
813 rl->num_released = 0;
814 ret = OSSL_RECORD_RETURN_SUCCESS;
816 if (macbufs != NULL) {
817 for (j = 0; j < num_recs; j++) {
818 if (macbufs[j].alloced)
819 OPENSSL_free(macbufs[j].mac);
821 OPENSSL_free(macbufs);
826 /* Shared by ssl3_meth and tls1_meth */
827 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
829 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
831 if (rec->rec_version != rl->version) {
832 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
836 #ifndef OPENSSL_NO_COMP
838 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
839 * does not include the compression overhead anyway.
841 if (rl->expand == NULL)
842 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
845 if (rec->length > len) {
846 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
847 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
854 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
856 #ifndef OPENSSL_NO_COMP
859 if (rec->comp == NULL) {
860 rec->comp = (unsigned char *)
861 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
863 if (rec->comp == NULL)
866 i = COMP_expand_block(rl->expand, rec->comp,
867 SSL3_RT_MAX_PLAIN_LENGTH, rec->data, (int)rec->length);
872 rec->data = rec->comp;
879 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
880 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
882 if (rl->expand != NULL) {
883 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
884 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
885 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
888 if (!tls_do_uncompress(rl, rec)) {
889 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
890 SSL_R_BAD_DECOMPRESSION);
895 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
896 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
903 /* Shared by tls13_meth and ktls_meth */
904 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
906 if (rec->type != SSL3_RT_APPLICATION_DATA
907 && rec->type != SSL3_RT_ALERT
908 && rec->type != SSL3_RT_HANDSHAKE) {
909 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
913 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
917 * TLSv1.3 alert and handshake records are required to be non-zero in
920 if ((rec->type == SSL3_RT_HANDSHAKE
921 || rec->type == SSL3_RT_ALERT)
922 && rec->length == 0) {
923 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
930 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
931 int *type, unsigned char **data, size_t *datalen,
932 uint16_t *epoch, unsigned char *seq_num)
937 * tls_get_more_records() can return success without actually reading
938 * anything useful (i.e. if empty records are read). We loop here until
939 * we have something useful. tls_get_more_records() will eventually fail if
940 * too many sequential empty records are read.
942 while (rl->curr_rec >= rl->num_recs) {
945 if (rl->num_released != rl->num_recs) {
946 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
947 return OSSL_RECORD_RETURN_FATAL;
950 ret = rl->funcs->get_more_records(rl);
952 if (ret != OSSL_RECORD_RETURN_SUCCESS)
957 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
958 * points to the next one to read.
960 rec = &rl->rrec[rl->curr_rec++];
963 *rversion = rec->rec_version;
965 *data = rec->data + rec->off;
966 *datalen = rec->length;
969 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
972 return OSSL_RECORD_RETURN_SUCCESS;
975 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
977 if (!ossl_assert(rl->num_released < rl->curr_rec)
978 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
979 /* Should not happen */
980 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
981 return OSSL_RECORD_RETURN_FATAL;
986 if (rl->curr_rec == rl->num_released
987 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
988 && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
989 tls_release_read_buffer(rl);
991 return OSSL_RECORD_RETURN_SUCCESS;
994 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
998 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
999 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1000 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1004 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1005 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1006 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1010 p = OSSL_PARAM_locate_const(options,
1011 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1012 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1013 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1017 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1019 * We ignore any read_ahead setting prior to the application protection
1020 * level. Otherwise we may read ahead data in a lower protection level
1021 * that is destined for a higher protection level. To simplify the logic
1022 * we don't support that at this stage.
1024 p = OSSL_PARAM_locate_const(options,
1025 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1026 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1027 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1036 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1037 int role, int direction, int level, unsigned char *key,
1038 size_t keylen, unsigned char *iv, size_t ivlen,
1039 unsigned char *mackey, size_t mackeylen,
1040 const EVP_CIPHER *ciph, size_t taglen,
1042 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1043 BIO *transport, BIO *next, BIO_ADDR *local,
1044 BIO_ADDR *peer, const OSSL_PARAM *settings,
1045 const OSSL_PARAM *options,
1046 const OSSL_DISPATCH *fns, void *cbarg,
1047 OSSL_RECORD_LAYER **retrl)
1049 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1050 const OSSL_PARAM *p;
1055 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1056 return OSSL_RECORD_RETURN_FATAL;
1059 /* Loop through all the settings since they must all be understood */
1060 if (settings != NULL) {
1061 for (p = settings; p->key != NULL; p++) {
1062 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1063 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1064 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1065 SSL_R_FAILED_TO_GET_PARAMETER);
1068 } else if (strcmp(p->key,
1069 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1070 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1071 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1072 SSL_R_FAILED_TO_GET_PARAMETER);
1075 } else if (strcmp(p->key,
1076 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1077 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1078 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1079 SSL_R_FAILED_TO_GET_PARAMETER);
1082 } else if (strcmp(p->key,
1083 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1084 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1085 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1086 SSL_R_FAILED_TO_GET_PARAMETER);
1089 } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1090 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1091 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1092 SSL_R_FAILED_TO_GET_PARAMETER);
1096 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1097 SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1103 rl->libctx = libctx;
1108 rl->direction = direction;
1111 rl->alert = SSL_AD_NO_ALERT;
1113 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1114 rl->is_first_record = 1;
1116 if (!tls_set1_bio(rl, transport))
1119 if (prev != NULL && !BIO_up_ref(prev))
1123 if (next != NULL && !BIO_up_ref(next))
1129 for (; fns->function_id != 0; fns++) {
1130 switch (fns->function_id) {
1131 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1132 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1134 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1135 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1137 case OSSL_FUNC_RLAYER_SECURITY:
1138 rl->security = OSSL_FUNC_rlayer_security(fns);
1141 /* Just ignore anything we don't understand */
1147 if (!tls_set_options(rl, options)) {
1148 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1153 return OSSL_RECORD_RETURN_SUCCESS;
1156 return OSSL_RECORD_RETURN_FATAL;
1160 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1161 int role, int direction, int level, uint16_t epoch,
1162 unsigned char *key, size_t keylen, unsigned char *iv,
1163 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1164 const EVP_CIPHER *ciph, size_t taglen,
1166 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1167 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1168 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1169 const OSSL_DISPATCH *fns, void *cbarg,
1170 OSSL_RECORD_LAYER **retrl)
1174 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1175 key, keylen, iv, ivlen, mackey, mackeylen,
1176 ciph, taglen, mactype, md, comp, prev,
1177 transport, next, local, peer, settings,
1178 options, fns, cbarg, retrl);
1180 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1184 case TLS_ANY_VERSION:
1185 (*retrl)->funcs = &tls_any_funcs;
1187 case TLS1_3_VERSION:
1188 (*retrl)->funcs = &tls_1_3_funcs;
1190 case TLS1_2_VERSION:
1191 case TLS1_1_VERSION:
1193 (*retrl)->funcs = &tls_1_funcs;
1196 (*retrl)->funcs = &ssl_3_0_funcs;
1199 /* Should not happen */
1200 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1201 ret = OSSL_RECORD_RETURN_FATAL;
1205 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1206 ivlen, mackey, mackeylen, ciph,
1207 taglen, mactype, md, comp);
1210 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1211 OPENSSL_free(*retrl);
1217 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1222 SSL3_BUFFER_release(&rl->rbuf);
1224 EVP_CIPHER_CTX_free(rl->enc_ctx);
1225 EVP_MD_CTX_free(rl->md_ctx);
1226 #ifndef OPENSSL_NO_COMP
1227 COMP_CTX_free(rl->expand);
1230 if (rl->version == SSL3_VERSION)
1231 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1236 int tls_free(OSSL_RECORD_LAYER *rl)
1239 size_t left, written;
1244 left = SSL3_BUFFER_get_left(rbuf);
1247 * This record layer is closing but we still have data left in our
1248 * buffer. It must be destined for the next epoch - so push it there.
1250 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1258 int tls_reset(OSSL_RECORD_LAYER *rl)
1260 memset(rl, 0, sizeof(*rl));
1264 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1266 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1269 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1271 return rl->curr_rec < rl->num_recs;
1274 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1279 for (i = rl->curr_rec; i <rl->num_recs; i++) {
1280 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1282 num += rl->rrec[i].length;
1287 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1292 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1297 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1302 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE **templates,
1303 size_t numtempl, size_t allowance, size_t *sent)
1308 int tls_retry_write_records(OSSL_RECORD_LAYER *rl, size_t allowance,
1315 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1320 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1322 if (bio != NULL && !BIO_up_ref(bio))
1330 /* Shared by most methods except tlsany_meth */
1331 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1333 if (rl->version != version)
1339 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1341 return rl->funcs->set_protocol_version(rl, version);
1344 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1346 rl->allow_plain_alerts = allow;
1349 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1351 rl->is_first_handshake = first;
1354 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1356 rl->max_pipelines = max_pipelines;
1357 if (max_pipelines > 1)
1361 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1362 const char **longstr)
1364 const char *shrt, *lng;
1365 switch (rl->rstate) {
1366 case SSL_ST_READ_HEADER:
1368 lng = "read header";
1370 case SSL_ST_READ_BODY:
1375 shrt = lng = "unknown";
1378 if (shortstr != NULL)
1380 if (longstr != NULL)
1384 const OSSL_RECORD_METHOD ossl_tls_record_method = {
1385 tls_new_record_layer,
1388 tls_unprocessed_read_pending,
1389 tls_processed_read_pending,
1390 tls_app_data_pending,
1392 tls_get_max_record_len,
1393 tls_get_max_records,
1395 tls_retry_write_records,
1400 tls_set_protocol_version,
1401 tls_set_plain_alerts,
1402 tls_set_first_handshake,
1403 tls_set_max_pipelines,