2 * Copyright 2022-2023 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
11 #include <openssl/bio.h>
12 #include <openssl/ssl.h>
13 #include <openssl/err.h>
14 #include <openssl/core_names.h>
15 #include <openssl/comp.h>
16 #include <openssl/ssl.h>
17 #include "internal/e_os.h"
18 #include "internal/packet.h"
19 #include "internal/ssl3_cbc.h"
20 #include "../../ssl_local.h"
21 #include "../record_local.h"
22 #include "recmethod_local.h"
24 static void tls_int_free(OSSL_RECORD_LAYER *rl);
26 void ossl_tls_buffer_release(TLS_BUFFER *b)
32 static void TLS_RL_RECORD_release(TLS_RL_RECORD *r, size_t num_recs)
36 for (i = 0; i < num_recs; i++) {
37 OPENSSL_free(r[i].comp);
42 void ossl_tls_rl_record_set_seq_num(TLS_RL_RECORD *r,
43 const unsigned char *seq_num)
45 memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
48 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
54 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
60 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
62 const EVP_CIPHER *ciph,
66 * Provided cipher, the TLS padding/MAC removal is performed provider
67 * side so we need to tell the ctx about our TLS version and mac size
69 OSSL_PARAM params[3], *pprm = params;
73 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
75 imacsize = EVP_MD_get_size(md);
77 macsize = (size_t)imacsize;
79 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
81 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
83 *pprm = OSSL_PARAM_construct_end();
85 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
86 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
94 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
95 * which ssl3_cbc_digest_record supports.
97 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
99 switch (EVP_MD_CTX_get_type(ctx)) {
112 #ifndef OPENSSL_NO_COMP
113 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
115 if (rl->options & SSL_OP_NO_COMPRESSION)
118 return rl->security == NULL
119 || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
123 static void tls_release_write_buffer_int(OSSL_RECORD_LAYER *rl, size_t start)
128 pipes = rl->numwpipes;
130 while (pipes > start) {
131 wb = &rl->wbuf[pipes - 1];
133 if (TLS_BUFFER_is_app_buffer(wb))
134 TLS_BUFFER_set_app_buffer(wb, 0);
136 OPENSSL_free(wb->buf);
142 int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
143 size_t firstlen, size_t nextlen)
146 size_t align = 0, headerlen;
150 size_t contenttypelen = 0;
152 if (firstlen == 0 || (numwpipes > 1 && nextlen == 0)) {
154 headerlen = DTLS1_RT_HEADER_LENGTH + 1;
156 headerlen = SSL3_RT_HEADER_LENGTH;
158 /* TLSv1.3 adds an extra content type byte after payload data */
159 if (rl->version == TLS1_3_VERSION)
162 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
163 align = SSL3_ALIGN_PAYLOAD - 1;
166 defltlen = align + headerlen + rl->eivlen + rl->max_frag_len
167 + contenttypelen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
168 #ifndef OPENSSL_NO_COMP
169 if (tls_allow_compression(rl))
170 defltlen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
173 * We don't need to add eivlen here since empty fragments only occur
174 * when we don't have an explicit IV. The contenttype byte will also
175 * always be 0 in these protocol versions
177 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0)
178 defltlen += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
182 for (currpipe = 0; currpipe < numwpipes; currpipe++) {
183 TLS_BUFFER *thiswb = &wb[currpipe];
184 size_t len = (currpipe == 0) ? firstlen : nextlen;
189 if (thiswb->len != len) {
190 OPENSSL_free(thiswb->buf);
191 thiswb->buf = NULL; /* force reallocation */
196 p = OPENSSL_malloc(len);
198 if (rl->numwpipes < currpipe)
199 rl->numwpipes = currpipe;
201 * We've got a malloc failure, and we're still initialising
202 * buffers. We assume we're so doomed that we won't even be able
205 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
209 memset(thiswb, 0, sizeof(TLS_BUFFER));
214 /* Free any previously allocated buffers that we are no longer using */
215 tls_release_write_buffer_int(rl, currpipe);
217 rl->numwpipes = numwpipes;
222 static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
224 tls_release_write_buffer_int(rl, 0);
229 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
232 size_t len, align = 0, headerlen;
238 headerlen = DTLS1_RT_HEADER_LENGTH;
240 headerlen = SSL3_RT_HEADER_LENGTH;
242 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
243 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
246 if (b->buf == NULL) {
247 len = rl->max_frag_len
248 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
249 #ifndef OPENSSL_NO_COMP
250 if (tls_allow_compression(rl))
251 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
254 /* Ensure our buffer is large enough to support all our pipelines */
255 if (rl->max_pipelines > 1)
256 len *= rl->max_pipelines;
258 if (b->default_len > len)
259 len = b->default_len;
261 if ((p = OPENSSL_malloc(len)) == NULL) {
263 * We've got a malloc failure, and we're still initialising buffers.
264 * We assume we're so doomed that we won't even be able to send an
267 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
277 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
282 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
283 OPENSSL_cleanse(b->buf, b->len);
284 OPENSSL_free(b->buf);
290 * Return values are as per SSL_read()
292 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
293 int clearold, size_t *readbytes)
296 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
297 * packet by another n bytes. The packet will be in the sub-array of
298 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
299 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
300 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
301 * packet to the start of the buffer; if clearold == 0 then leave any old
302 * packets where they were
304 size_t len, left, align = 0;
309 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
313 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
314 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
315 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
319 /* start with empty packet ... */
323 rl->packet = rb->buf + rb->offset;
324 rl->packet_length = 0;
325 /* ... now we can act as if 'extend' was set */
328 len = rl->packet_length;
329 pkt = rb->buf + align;
331 * Move any available bytes to front of buffer: 'len' bytes already
332 * pointed to by 'packet', 'left' extra ones at the end
334 if (rl->packet != pkt && clearold == 1) {
335 memmove(pkt, rl->packet, len + left);
337 rb->offset = len + align;
341 * For DTLS/UDP reads should not span multiple packets because the read
342 * operation returns the whole packet at once (as long as it fits into
346 if (left == 0 && extend) {
348 * We received a record with a header but no body data. This will
351 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
353 if (left > 0 && n > left)
357 /* if there is enough in the buffer from a previous read, take some */
359 rl->packet_length += n;
363 return OSSL_RECORD_RETURN_SUCCESS;
366 /* else we need to read more data */
368 if (n > rb->len - rb->offset) {
369 /* does not happen */
370 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
371 return OSSL_RECORD_RETURN_FATAL;
374 /* We always act like read_ahead is set for DTLS */
375 if (!rl->read_ahead && !rl->isdtls) {
376 /* ignore max parameter */
381 if (max > rb->len - rb->offset)
382 max = rb->len - rb->offset;
388 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
391 * Now we have len+left bytes at the front of rl->rbuf.buf and
392 * need to read in more until we have len + n (up to len + max if
398 ret = BIO_read(bio, pkt + len + left, max - left);
401 ret = OSSL_RECORD_RETURN_SUCCESS;
402 } else if (BIO_should_retry(bio)) {
403 if (rl->prev != NULL) {
405 * We were reading from the previous epoch. Now there is no
406 * more data, so swap to the actual transport BIO
412 ret = OSSL_RECORD_RETURN_RETRY;
413 } else if (BIO_eof(bio)) {
414 ret = OSSL_RECORD_RETURN_EOF;
416 ret = OSSL_RECORD_RETURN_FATAL;
419 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
420 ret = OSSL_RECORD_RETURN_FATAL;
423 if (ret <= OSSL_RECORD_RETURN_RETRY) {
425 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
427 tls_release_read_buffer(rl);
432 * reads should *never* span multiple packets for DTLS because the
433 * underlying transport protocol is message oriented as opposed to
434 * byte oriented as in the TLS case.
438 n = left; /* makes the while condition false */
442 /* done reading, now the book-keeping */
445 rl->packet_length += n;
447 return OSSL_RECORD_RETURN_SUCCESS;
451 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
452 * for us in the buffer.
454 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
462 p = TLS_BUFFER_get_buf(rbuf);
466 left = TLS_BUFFER_get_left(rbuf);
468 if (left < SSL3_RT_HEADER_LENGTH)
471 p += TLS_BUFFER_get_offset(rbuf);
474 * We only check the type and record length, we will sanity check version
477 if (*p != SSL3_RT_APPLICATION_DATA)
483 if (left < SSL3_RT_HEADER_LENGTH + len)
489 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
490 size_t overhead, int send)
492 uint32_t max_early_data = rl->max_early_data;
494 if (max_early_data == 0) {
495 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
496 SSL_R_TOO_MUCH_EARLY_DATA);
500 /* If we are dealing with ciphertext we need to allow for the overhead */
501 max_early_data += overhead;
503 if (rl->early_data_count + length > max_early_data) {
504 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
505 SSL_R_TOO_MUCH_EARLY_DATA);
508 rl->early_data_count += length;
514 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
515 * will be processed per call to tls_get_more_records. Without this limit an
516 * attacker could send empty records at a faster rate than we can process and
517 * cause tls_get_more_records to loop forever.
519 #define MAX_EMPTY_RECORDS 32
521 #define SSL2_RT_HEADER_LENGTH 2
524 * Call this to buffer new input records in rl->rrec.
525 * It will return a OSSL_RECORD_RETURN_* value.
526 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
527 * records have been decoded. For each record 'i':
528 * rrec[i].type - is the type of record
529 * rrec[i].data, - data
530 * rrec[i].length, - number of bytes
531 * Multiple records will only be returned if the record types are all
532 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
535 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
540 TLS_RL_RECORD *rr, *thisrr;
543 unsigned char md[EVP_MAX_MD_SIZE];
544 unsigned int version;
547 size_t num_recs = 0, max_recs, j;
548 PACKET pkt, sslv2pkt;
549 SSL_MAC_BUF *macbufs = NULL;
550 int ret = OSSL_RECORD_RETURN_FATAL;
554 if (rbuf->buf == NULL) {
555 if (!tls_setup_read_buffer(rl)) {
556 /* RLAYERfatal() already called */
557 return OSSL_RECORD_RETURN_FATAL;
561 max_recs = rl->max_pipelines;
567 thisrr = &rr[num_recs];
569 /* check if we have the header */
570 if ((rl->rstate != SSL_ST_READ_BODY) ||
571 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
575 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
576 TLS_BUFFER_get_len(rbuf), 0,
577 num_recs == 0 ? 1 : 0, &n);
579 if (rret < OSSL_RECORD_RETURN_SUCCESS)
580 return rret; /* error or non-blocking */
582 rl->rstate = SSL_ST_READ_BODY;
585 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
586 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
587 return OSSL_RECORD_RETURN_FATAL;
590 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
591 || !PACKET_get_1(&sslv2pkt, &type)) {
592 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
593 return OSSL_RECORD_RETURN_FATAL;
596 * The first record received by the server may be a V2ClientHello.
598 if (rl->role == OSSL_RECORD_ROLE_SERVER
599 && rl->is_first_record
600 && (sslv2len & 0x8000) != 0
601 && (type == SSL2_MT_CLIENT_HELLO)) {
605 * |num_recs| here will actually always be 0 because
606 * |num_recs > 0| only ever occurs when we are processing
607 * multiple app data records - which we know isn't the case here
608 * because it is an SSLv2ClientHello. We keep it using
609 * |num_recs| for the sake of consistency
611 thisrr->type = SSL3_RT_HANDSHAKE;
612 thisrr->rec_version = SSL2_VERSION;
614 thisrr->length = sslv2len & 0x7fff;
616 if (thisrr->length > TLS_BUFFER_get_len(rbuf)
617 - SSL2_RT_HEADER_LENGTH) {
618 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
619 SSL_R_PACKET_LENGTH_TOO_LONG);
620 return OSSL_RECORD_RETURN_FATAL;
623 /* SSLv3+ style record */
625 /* Pull apart the header into the TLS_RL_RECORD */
626 if (!PACKET_get_1(&pkt, &type)
627 || !PACKET_get_net_2(&pkt, &version)
628 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
629 if (rl->msg_callback != NULL)
630 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
631 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
632 return OSSL_RECORD_RETURN_FATAL;
635 thisrr->rec_version = version;
638 * When we call validate_record_header() only records actually
639 * received in SSLv2 format should have the record version set
640 * to SSL2_VERSION. This way validate_record_header() can know
641 * what format the record was in based on the version.
643 if (thisrr->rec_version == SSL2_VERSION) {
644 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
645 SSL_R_WRONG_VERSION_NUMBER);
646 return OSSL_RECORD_RETURN_FATAL;
649 if (rl->msg_callback != NULL)
650 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
653 TLS_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
654 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
655 SSL_R_PACKET_LENGTH_TOO_LONG);
656 return OSSL_RECORD_RETURN_FATAL;
660 if (!rl->funcs->validate_record_header(rl, thisrr)) {
661 /* RLAYERfatal already called */
662 return OSSL_RECORD_RETURN_FATAL;
665 /* now rl->rstate == SSL_ST_READ_BODY */
669 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
670 * how much more data we need to read for the rest of the record
672 if (thisrr->rec_version == SSL2_VERSION) {
673 more = thisrr->length + SSL2_RT_HEADER_LENGTH
674 - SSL3_RT_HEADER_LENGTH;
676 more = thisrr->length;
680 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
682 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
683 if (rret < OSSL_RECORD_RETURN_SUCCESS)
684 return rret; /* error or non-blocking io */
687 /* set state for later operations */
688 rl->rstate = SSL_ST_READ_HEADER;
691 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
692 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
693 * + thisrr->length and we have that many bytes in rl->packet
695 if (thisrr->rec_version == SSL2_VERSION)
696 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
698 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
701 * ok, we can now read from 'rl->packet' data into 'thisrr'.
702 * thisrr->input points at thisrr->length bytes, which need to be copied
703 * into thisrr->data by either the decryption or by the decompression.
704 * When the data is 'copied' into the thisrr->data buffer,
705 * thisrr->input will be updated to point at the new buffer
709 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
710 * thisrr->length bytes of encrypted compressed stuff.
713 /* decrypt in place in 'thisrr->input' */
714 thisrr->data = thisrr->input;
715 thisrr->orig_len = thisrr->length;
719 /* we have pulled in a full packet so zero things */
720 rl->packet_length = 0;
721 rl->is_first_record = 0;
722 } while (num_recs < max_recs
723 && thisrr->type == SSL3_RT_APPLICATION_DATA
724 && RLAYER_USE_EXPLICIT_IV(rl)
725 && rl->enc_ctx != NULL
726 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
727 & EVP_CIPH_FLAG_PIPELINE) != 0
728 && tls_record_app_data_waiting(rl));
731 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
732 /* The following can happen in tlsany_meth after HRR */
733 && rl->version == TLS1_3_VERSION
734 && rl->is_first_handshake) {
736 * CCS messages must be exactly 1 byte long, containing the value 0x01
738 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
739 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
740 SSL_R_INVALID_CCS_MESSAGE);
741 return OSSL_RECORD_RETURN_FATAL;
744 * CCS messages are ignored in TLSv1.3. We treat it like an empty
747 thisrr->type = SSL3_RT_HANDSHAKE;
748 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
749 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
750 SSL_R_UNEXPECTED_CCS_MESSAGE);
751 return OSSL_RECORD_RETURN_FATAL;
755 rl->num_released = 0;
757 return OSSL_RECORD_RETURN_SUCCESS;
760 if (rl->md_ctx != NULL) {
761 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
764 imac_size = EVP_MD_get_size(tmpmd);
765 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
766 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
767 return OSSL_RECORD_RETURN_FATAL;
769 mac_size = (size_t)imac_size;
774 * If in encrypt-then-mac mode calculate mac from encrypted record. All
775 * the details below are public so no timing details can leak.
777 if (rl->use_etm && rl->md_ctx != NULL) {
780 for (j = 0; j < num_recs; j++) {
783 if (thisrr->length < mac_size) {
784 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
785 return OSSL_RECORD_RETURN_FATAL;
787 thisrr->length -= mac_size;
788 mac = thisrr->data + thisrr->length;
789 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
790 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
791 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
792 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
793 return OSSL_RECORD_RETURN_FATAL;
797 * We've handled the mac now - there is no MAC inside the encrypted
804 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
805 if (macbufs == NULL) {
806 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
807 return OSSL_RECORD_RETURN_FATAL;
812 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
816 * 0: if the record is publicly invalid, or an internal error, or AEAD
817 * decryption failed, or ETM decryption failed.
818 * 1: Success or MTE decryption failed (MAC will be randomised)
821 if (rl->alert != SSL_AD_NO_ALERT) {
822 /* RLAYERfatal() already got called */
823 ERR_clear_last_mark();
827 && rl->skip_early_data != NULL
828 && rl->skip_early_data(rl->cbarg)) {
830 * Valid early_data that we cannot decrypt will fail here. We treat
831 * it like an empty record.
835 * Remove any errors from the stack. Decryption failures are normal
842 if (!rlayer_early_data_count_ok(rl, thisrr->length,
843 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
844 /* RLAYERfatal() already called */
851 rl->num_released = 0;
852 /* Reset the read sequence */
853 memset(rl->sequence, 0, sizeof(rl->sequence));
857 ERR_clear_last_mark();
858 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
859 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
862 ERR_clear_last_mark();
864 OSSL_TRACE_BEGIN(TLS) {
865 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
866 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
867 } OSSL_TRACE_END(TLS);
869 /* r->length is now the compressed data plus mac */
870 if (rl->enc_ctx != NULL
872 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
873 for (j = 0; j < num_recs; j++) {
874 SSL_MAC_BUF *thismb = &macbufs[j];
878 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
879 if (i == 0 || thismb == NULL || thismb->mac == NULL
880 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
882 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
884 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
885 if (enc_err == 0 && mac_size > 0 && thismb != NULL &&
886 thismb->mac != NULL && (md[0] ^ thismb->mac[0]) != 0xFF) {
894 if (rl->alert != SSL_AD_NO_ALERT) {
895 /* We already called RLAYERfatal() */
899 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
900 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
901 * failure is directly visible from the ciphertext anyway, we should
902 * not reveal which kind of error occurred -- this might become
903 * visible to an attacker (e.g. via a logfile)
905 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
906 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
910 for (j = 0; j < num_recs; j++) {
913 if (!rl->funcs->post_process_record(rl, thisrr)) {
914 /* RLAYERfatal already called */
919 * Record overflow checking (e.g. checking if
920 * thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH) is the responsibility of
921 * the post_process_record() function above. However we check here if
922 * the received packet overflows the current Max Fragment Length setting
924 * Note: rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH and KTLS are
925 * mutually exclusive. Also note that with KTLS thisrr->length can
926 * be > SSL3_RT_MAX_PLAIN_LENGTH (and rl->max_frag_len must be ignored)
928 if (rl->max_frag_len != SSL3_RT_MAX_PLAIN_LENGTH
929 && thisrr->length > rl->max_frag_len) {
930 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
936 * So at this point the following is true
937 * thisrr->type is the type of record
938 * thisrr->length == number of bytes in record
939 * thisrr->off == offset to first valid byte
940 * thisrr->data == where to take bytes from, increment after use :-).
943 /* just read a 0 length packet */
944 if (thisrr->length == 0) {
945 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
946 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
947 SSL_R_RECORD_TOO_SMALL);
951 rl->empty_record_count = 0;
955 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
957 if (thisrr->type == SSL3_RT_APPLICATION_DATA
958 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
959 /* RLAYERfatal already called */
964 rl->num_recs = num_recs;
966 rl->num_released = 0;
967 ret = OSSL_RECORD_RETURN_SUCCESS;
969 if (macbufs != NULL) {
970 for (j = 0; j < num_recs; j++) {
971 if (macbufs[j].alloced)
972 OPENSSL_free(macbufs[j].mac);
974 OPENSSL_free(macbufs);
979 /* Shared by ssl3_meth and tls1_meth */
980 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
982 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
984 if (rec->rec_version != rl->version) {
985 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
989 #ifndef OPENSSL_NO_COMP
991 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
992 * does not include the compression overhead anyway.
994 if (rl->compctx == NULL)
995 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
998 if (rec->length > len) {
999 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1000 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1007 int tls_do_compress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *wr)
1009 #ifndef OPENSSL_NO_COMP
1012 i = COMP_compress_block(rl->compctx, wr->data,
1013 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
1014 wr->input, (int)wr->length);
1019 wr->input = wr->data;
1026 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1028 #ifndef OPENSSL_NO_COMP
1031 if (rec->comp == NULL) {
1032 rec->comp = (unsigned char *)
1033 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
1035 if (rec->comp == NULL)
1038 i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
1039 rec->data, (int)rec->length);
1044 rec->data = rec->comp;
1051 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
1052 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1054 if (rl->compctx != NULL) {
1055 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1056 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1057 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1060 if (!tls_do_uncompress(rl, rec)) {
1061 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
1062 SSL_R_BAD_DECOMPRESSION);
1067 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1068 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1075 /* Shared by tls13_meth and ktls_meth */
1076 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
1078 if (rec->type != SSL3_RT_APPLICATION_DATA
1079 && rec->type != SSL3_RT_ALERT
1080 && rec->type != SSL3_RT_HANDSHAKE) {
1081 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1085 if (rl->msg_callback != NULL)
1086 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
1090 * TLSv1.3 alert and handshake records are required to be non-zero in
1093 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1094 && rec->length == 0) {
1095 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1102 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1103 uint8_t *type, const unsigned char **data, size_t *datalen,
1104 uint16_t *epoch, unsigned char *seq_num)
1109 * tls_get_more_records() can return success without actually reading
1110 * anything useful (i.e. if empty records are read). We loop here until
1111 * we have something useful. tls_get_more_records() will eventually fail if
1112 * too many sequential empty records are read.
1114 while (rl->curr_rec >= rl->num_recs) {
1117 if (rl->num_released != rl->num_recs) {
1118 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1119 return OSSL_RECORD_RETURN_FATAL;
1122 ret = rl->funcs->get_more_records(rl);
1124 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1129 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1130 * points to the next one to read.
1132 rec = &rl->rrec[rl->curr_rec++];
1135 *rversion = rec->rec_version;
1137 *data = rec->data + rec->off;
1138 *datalen = rec->length;
1140 *epoch = rec->epoch;
1141 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1144 return OSSL_RECORD_RETURN_SUCCESS;
1147 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length)
1149 TLS_RL_RECORD *rec = &rl->rrec[rl->num_released];
1151 if (!ossl_assert(rl->num_released < rl->curr_rec)
1152 || !ossl_assert(rechandle == rec)) {
1153 /* Should not happen */
1154 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1155 return OSSL_RECORD_RETURN_FATAL;
1158 if (rec->length < length) {
1159 /* Should not happen */
1160 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1161 return OSSL_RECORD_RETURN_FATAL;
1164 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
1165 OPENSSL_cleanse(rec->data + rec->off, length);
1168 rec->length -= length;
1170 if (rec->length > 0)
1171 return OSSL_RECORD_RETURN_SUCCESS;
1175 if (rl->curr_rec == rl->num_released
1176 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1177 && TLS_BUFFER_get_left(&rl->rbuf) == 0)
1178 tls_release_read_buffer(rl);
1180 return OSSL_RECORD_RETURN_SUCCESS;
1183 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1185 const OSSL_PARAM *p;
1187 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1188 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1189 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1193 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1194 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1195 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1199 if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
1200 p = OSSL_PARAM_locate_const(options,
1201 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1202 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1203 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1207 p = OSSL_PARAM_locate_const(options,
1208 OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
1209 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
1210 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1215 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1217 * We ignore any read_ahead setting prior to the application protection
1218 * level. Otherwise we may read ahead data in a lower protection level
1219 * that is destined for a higher protection level. To simplify the logic
1220 * we don't support that at this stage.
1222 p = OSSL_PARAM_locate_const(options,
1223 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1224 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1225 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1234 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1235 int role, int direction, int level, unsigned char *key,
1236 size_t keylen, unsigned char *iv, size_t ivlen,
1237 unsigned char *mackey, size_t mackeylen,
1238 const EVP_CIPHER *ciph, size_t taglen,
1240 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
1241 BIO *transport, BIO *next, BIO_ADDR *local,
1242 BIO_ADDR *peer, const OSSL_PARAM *settings,
1243 const OSSL_PARAM *options,
1244 const OSSL_DISPATCH *fns, void *cbarg,
1245 OSSL_RECORD_LAYER **retrl)
1247 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1248 const OSSL_PARAM *p;
1253 return OSSL_RECORD_RETURN_FATAL;
1256 * Default the value for max_frag_len. This may be overridden by the
1259 rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH;
1261 /* Loop through all the settings since they must all be understood */
1262 if (settings != NULL) {
1263 for (p = settings; p->key != NULL; p++) {
1264 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1265 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1266 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1269 } else if (strcmp(p->key,
1270 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1271 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1272 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1275 } else if (strcmp(p->key,
1276 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1277 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1278 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1281 } else if (strcmp(p->key,
1282 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1283 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1284 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1287 } else if (strcmp(p->key,
1288 OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1289 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1290 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1294 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1300 rl->libctx = libctx;
1305 rl->direction = direction;
1307 rl->taglen = taglen;
1310 rl->alert = SSL_AD_NO_ALERT;
1311 rl->rstate = SSL_ST_READ_HEADER;
1313 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1314 rl->is_first_record = 1;
1316 if (!tls_set1_bio(rl, transport))
1319 if (prev != NULL && !BIO_up_ref(prev))
1323 if (next != NULL && !BIO_up_ref(next))
1329 for (; fns->function_id != 0; fns++) {
1330 switch (fns->function_id) {
1331 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1332 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1334 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1335 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1337 case OSSL_FUNC_RLAYER_SECURITY:
1338 rl->security = OSSL_FUNC_rlayer_security(fns);
1340 case OSSL_FUNC_RLAYER_PADDING:
1341 rl->padding = OSSL_FUNC_rlayer_padding(fns);
1343 /* Just ignore anything we don't understand */
1349 if (!tls_set_options(rl, options)) {
1350 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1354 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
1355 && rl->version <= TLS1_VERSION
1356 && !EVP_CIPHER_is_a(ciph, "NULL")
1357 && !EVP_CIPHER_is_a(ciph, "RC4")) {
1359 * Enable vulnerability countermeasure for CBC ciphers with known-IV
1360 * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
1362 rl->need_empty_fragments = 1;
1366 return OSSL_RECORD_RETURN_SUCCESS;
1369 return OSSL_RECORD_RETURN_FATAL;
1373 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1374 int role, int direction, int level, uint16_t epoch,
1375 unsigned char *secret, size_t secretlen,
1376 unsigned char *key, size_t keylen, unsigned char *iv,
1377 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1378 const EVP_CIPHER *ciph, size_t taglen,
1380 const EVP_MD *md, COMP_METHOD *comp,
1381 const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
1382 BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1383 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1384 const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
1385 OSSL_RECORD_LAYER **retrl)
1389 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1390 key, keylen, iv, ivlen, mackey, mackeylen,
1391 ciph, taglen, mactype, md, comp, prev,
1392 transport, next, local, peer, settings,
1393 options, fns, cbarg, retrl);
1395 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1399 case TLS_ANY_VERSION:
1400 (*retrl)->funcs = &tls_any_funcs;
1402 case TLS1_3_VERSION:
1403 (*retrl)->funcs = &tls_1_3_funcs;
1405 case TLS1_2_VERSION:
1406 case TLS1_1_VERSION:
1408 (*retrl)->funcs = &tls_1_funcs;
1411 (*retrl)->funcs = &ssl_3_0_funcs;
1414 /* Should not happen */
1415 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1416 ret = OSSL_RECORD_RETURN_FATAL;
1420 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1421 ivlen, mackey, mackeylen, ciph,
1422 taglen, mactype, md, comp);
1425 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1426 tls_int_free(*retrl);
1432 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1437 ossl_tls_buffer_release(&rl->rbuf);
1439 tls_release_write_buffer(rl);
1441 EVP_CIPHER_CTX_free(rl->enc_ctx);
1442 EVP_MD_CTX_free(rl->md_ctx);
1443 #ifndef OPENSSL_NO_COMP
1444 COMP_CTX_free(rl->compctx);
1447 if (rl->version == SSL3_VERSION)
1448 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1450 TLS_RL_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1455 int tls_free(OSSL_RECORD_LAYER *rl)
1458 size_t left, written;
1466 left = TLS_BUFFER_get_left(rbuf);
1469 * This record layer is closing but we still have data left in our
1470 * buffer. It must be destined for the next epoch - so push it there.
1472 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1479 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1481 return TLS_BUFFER_get_left(&rl->rbuf) != 0;
1484 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1486 return rl->curr_rec < rl->num_recs;
1489 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1494 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1495 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1497 num += rl->rrec[i].length;
1502 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, uint8_t type,
1504 size_t maxfrag, size_t *preffrag)
1507 * If we have a pipeline capable cipher, and we have been configured to use
1508 * it, then return the preferred number of pipelines.
1510 if (rl->max_pipelines > 0
1511 && rl->enc_ctx != NULL
1512 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
1513 & EVP_CIPH_FLAG_PIPELINE) != 0
1514 && RLAYER_USE_EXPLICIT_IV(rl)) {
1519 pipes = ((len - 1) / *preffrag) + 1;
1521 return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
1527 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len,
1528 size_t maxfrag, size_t *preffrag)
1530 return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
1533 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
1534 OSSL_RECORD_TEMPLATE *templates,
1538 if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
1539 /* RLAYERfatal() already called */
1546 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
1547 OSSL_RECORD_TEMPLATE *templates,
1549 OSSL_RECORD_TEMPLATE *prefixtempl,
1558 for (j = 0; j < numtempl; j++) {
1562 wb->type = templates[j].type;
1564 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1565 align = (size_t)TLS_BUFFER_get_buf(wb);
1566 align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
1567 align = SSL3_ALIGN_PAYLOAD - 1
1568 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1570 TLS_BUFFER_set_offset(wb, align);
1572 if (!WPACKET_init_static_len(thispkt, TLS_BUFFER_get_buf(wb),
1573 TLS_BUFFER_get_len(wb), 0)) {
1574 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1578 if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
1579 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1587 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
1589 OSSL_RECORD_TEMPLATE *templ,
1591 unsigned char **recdata)
1597 maxcomplen = templ->buflen;
1598 if (rl->compctx != NULL)
1599 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1601 if (!WPACKET_put_bytes_u8(thispkt, rectype)
1602 || !WPACKET_put_bytes_u16(thispkt, templ->version)
1603 || !WPACKET_start_sub_packet_u16(thispkt)
1605 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
1607 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1609 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1616 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
1619 TLS_RL_RECORD *thiswr)
1622 unsigned char *recordstart;
1625 * we should still have the output to thiswr->data and the input from
1626 * wr->input. Length should be thiswr->length. thiswr->data still points
1630 if (!rl->use_etm && mac_size != 0) {
1633 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1634 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1635 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1641 * Reserve some bytes for any growth that may occur during encryption. If
1642 * we are adding the MAC independently of the cipher algorithm, then the
1643 * max encrypted overhead does not need to include an allocation for that
1646 if (!WPACKET_reserve_bytes(thispkt, SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
1649 * We also need next the amount of bytes written to this
1652 || !WPACKET_get_length(thispkt, &len)) {
1653 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1657 /* Get a pointer to the start of this record excluding header */
1658 recordstart = WPACKET_get_curr(thispkt) - len;
1659 TLS_RL_RECORD_set_data(thiswr, recordstart);
1660 TLS_RL_RECORD_reset_input(thiswr);
1661 TLS_RL_RECORD_set_length(thiswr, len);
1666 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
1668 OSSL_RECORD_TEMPLATE *thistempl,
1670 TLS_RL_RECORD *thiswr)
1672 size_t origlen, len;
1673 size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
1674 : SSL3_RT_HEADER_LENGTH;
1676 /* Allocate bytes for the encryption overhead */
1677 if (!WPACKET_get_length(thispkt, &origlen)
1678 /* Check we allowed enough room for the encryption growth */
1679 || !ossl_assert(origlen + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
1680 - mac_size >= thiswr->length)
1681 /* Encryption should never shrink the data! */
1682 || origlen > thiswr->length
1683 || (thiswr->length > origlen
1684 && !WPACKET_allocate_bytes(thispkt,
1685 thiswr->length - origlen,
1687 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1690 if (rl->use_etm && mac_size != 0) {
1693 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1694 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1695 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1699 TLS_RL_RECORD_add_length(thiswr, mac_size);
1702 if (!WPACKET_get_length(thispkt, &len)
1703 || !WPACKET_close(thispkt)) {
1704 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1708 if (rl->msg_callback != NULL) {
1709 unsigned char *recordstart;
1711 recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
1712 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1713 headerlen, rl->cbarg);
1715 if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
1716 unsigned char ctype = thistempl->type;
1718 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1719 &ctype, 1, rl->cbarg);
1723 if (!WPACKET_finish(thispkt)) {
1724 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1728 TLS_RL_RECORD_add_length(thiswr, headerlen);
1733 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
1734 OSSL_RECORD_TEMPLATE *templates,
1737 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1738 TLS_RL_RECORD wr[SSL_MAX_PIPELINES + 1];
1740 TLS_RL_RECORD *thiswr;
1741 int mac_size = 0, ret = 0;
1742 size_t wpinited = 0;
1743 size_t j, prefix = 0;
1744 OSSL_RECORD_TEMPLATE prefixtempl;
1745 OSSL_RECORD_TEMPLATE *thistempl;
1747 if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
1748 mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
1750 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1755 if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
1756 /* RLAYERfatal() already called */
1760 if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
1761 &prefixtempl, pkt, rl->wbuf,
1763 /* RLAYERfatal() already called */
1767 /* Clear our TLS_RL_RECORD structures */
1768 memset(wr, 0, sizeof(wr));
1769 for (j = 0; j < numtempl + prefix; j++) {
1770 unsigned char *compressdata = NULL;
1775 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1778 * Default to the record type as specified in the template unless the
1779 * protocol implementation says differently.
1781 if (rl->funcs->get_record_type != NULL)
1782 rectype = rl->funcs->get_record_type(rl, thistempl);
1784 rectype = thistempl->type;
1786 TLS_RL_RECORD_set_type(thiswr, rectype);
1787 TLS_RL_RECORD_set_rec_version(thiswr, thistempl->version);
1789 if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
1791 /* RLAYERfatal() already called */
1795 /* lets setup the record stuff. */
1796 TLS_RL_RECORD_set_data(thiswr, compressdata);
1797 TLS_RL_RECORD_set_length(thiswr, thistempl->buflen);
1799 TLS_RL_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1802 * we now 'read' from thiswr->input, thiswr->length bytes into
1806 /* first we compress */
1807 if (rl->compctx != NULL) {
1808 if (!tls_do_compress(rl, thiswr)
1809 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1810 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1813 } else if (compressdata != NULL) {
1814 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1815 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1818 TLS_RL_RECORD_reset_input(&wr[j]);
1821 if (rl->funcs->add_record_padding != NULL
1822 && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
1824 /* RLAYERfatal() already called */
1828 if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
1829 /* RLAYERfatal() already called */
1835 if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
1836 if (rl->alert == SSL_AD_NO_ALERT) {
1837 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1843 if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
1844 if (rl->alert == SSL_AD_NO_ALERT) {
1845 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1850 for (j = 0; j < numtempl + prefix; j++) {
1853 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1855 if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
1857 /* RLAYERfatal() already called */
1861 /* now let's set up wb */
1862 TLS_BUFFER_set_left(&rl->wbuf[j], TLS_RL_RECORD_get_length(thiswr));
1867 for (j = 0; j < wpinited; j++)
1868 WPACKET_cleanup(&pkt[j]);
1872 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1875 /* Check we don't have pending data waiting to write */
1876 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1877 || TLS_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1878 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1879 return OSSL_RECORD_RETURN_FATAL;
1882 if (!rl->funcs->write_records(rl, templates, numtempl)) {
1883 /* RLAYERfatal already called */
1884 return OSSL_RECORD_RETURN_FATAL;
1888 /* we now just need to write the buffers */
1889 return tls_retry_write_records(rl);
1892 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1898 if (rl->nextwbuf >= rl->numwpipes)
1899 return OSSL_RECORD_RETURN_SUCCESS;
1902 thiswb = &rl->wbuf[rl->nextwbuf];
1905 if (rl->bio != NULL) {
1906 if (rl->funcs->prepare_write_bio != NULL) {
1907 ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
1908 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1911 i = BIO_write(rl->bio, (char *)
1912 &(TLS_BUFFER_get_buf(thiswb)
1913 [TLS_BUFFER_get_offset(thiswb)]),
1914 (unsigned int)TLS_BUFFER_get_left(thiswb));
1917 if (i == 0 && BIO_should_retry(rl->bio))
1918 ret = OSSL_RECORD_RETURN_RETRY;
1920 ret = OSSL_RECORD_RETURN_SUCCESS;
1922 if (BIO_should_retry(rl->bio))
1923 ret = OSSL_RECORD_RETURN_RETRY;
1925 ret = OSSL_RECORD_RETURN_FATAL;
1928 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1929 ret = OSSL_RECORD_RETURN_FATAL;
1934 * When an empty fragment is sent on a connection using KTLS,
1935 * it is sent as a write of zero bytes. If this zero byte
1936 * write succeeds, i will be 0 rather than a non-zero value.
1937 * Treat i == 0 as success rather than an error for zero byte
1938 * writes to permit this case.
1940 if (i >= 0 && tmpwrit == TLS_BUFFER_get_left(thiswb)) {
1941 TLS_BUFFER_set_left(thiswb, 0);
1942 TLS_BUFFER_add_offset(thiswb, tmpwrit);
1943 if (++(rl->nextwbuf) < rl->numwpipes)
1946 if (rl->nextwbuf == rl->numwpipes
1947 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1948 tls_release_write_buffer(rl);
1949 return OSSL_RECORD_RETURN_SUCCESS;
1950 } else if (i <= 0) {
1953 * For DTLS, just drop it. That's kind of the whole point in
1954 * using a datagram service
1956 TLS_BUFFER_set_left(thiswb, 0);
1957 if (++(rl->nextwbuf) == rl->numwpipes
1958 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1959 tls_release_write_buffer(rl);
1964 TLS_BUFFER_add_offset(thiswb, tmpwrit);
1965 TLS_BUFFER_sub_left(thiswb, tmpwrit);
1969 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1974 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1976 if (bio != NULL && !BIO_up_ref(bio))
1984 /* Shared by most methods except tlsany_meth */
1985 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1987 if (rl->version != version)
1993 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1995 return rl->funcs->set_protocol_version(rl, version);
1998 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
2000 rl->allow_plain_alerts = allow;
2003 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
2005 rl->is_first_handshake = first;
2008 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
2010 rl->max_pipelines = max_pipelines;
2011 if (max_pipelines > 1)
2015 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
2016 const char **longstr)
2018 const char *shrt, *lng;
2020 switch (rl->rstate) {
2021 case SSL_ST_READ_HEADER:
2023 lng = "read header";
2025 case SSL_ST_READ_BODY:
2030 shrt = lng = "unknown";
2033 if (shortstr != NULL)
2035 if (longstr != NULL)
2039 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
2041 #ifndef OPENSSL_NO_COMP
2042 return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
2048 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
2050 rl->max_frag_len = max_frag_len;
2052 * We don't need to adjust buffer sizes. Write buffer sizes are
2053 * automatically checked anyway. We should only be changing the read buffer
2054 * size during the handshake, so we will create a new buffer when we create
2055 * the new record layer. We can't change the existing buffer because it may
2056 * already have data in it.
2060 int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
2064 /* Increment the sequence counter */
2065 for (i = SEQ_NUM_SIZE; i > 0; i--) {
2066 ++(rl->sequence[i - 1]);
2067 if (rl->sequence[i - 1] != 0)
2071 /* Sequence has wrapped */
2072 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
2078 int tls_alloc_buffers(OSSL_RECORD_LAYER *rl)
2080 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2081 /* If we have a pending write then buffers are already allocated */
2082 if (rl->nextwbuf < rl->numwpipes)
2085 * We assume 1 pipe with default sized buffer. If what we need ends up
2086 * being a different size to that then it will be reallocated on demand.
2087 * If we need more than 1 pipe then that will also be allocated on
2090 if (!tls_setup_write_buffer(rl, 1, 0, 0))
2094 * Normally when we allocate write buffers we immediately write
2095 * something into it. In this case we're not doing that so mark the
2098 TLS_BUFFER_set_left(&rl->wbuf[0], 0);
2102 /* Read direction */
2104 /* If we have pending data to be read then buffers are already allocated */
2105 if (rl->curr_rec < rl->num_recs || TLS_BUFFER_get_left(&rl->rbuf) != 0)
2107 return tls_setup_read_buffer(rl);
2110 int tls_free_buffers(OSSL_RECORD_LAYER *rl)
2112 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2113 if (rl->nextwbuf < rl->numwpipes) {
2115 * We may have pending data. If we've just got one empty buffer
2116 * allocated then it has probably just been alloc'd via
2117 * tls_alloc_buffers, and it is fine to free it. Otherwise this
2118 * looks like real pending data and it is an error.
2120 if (rl->nextwbuf != 0
2121 || rl->numwpipes != 1
2122 || TLS_BUFFER_get_left(&rl->wbuf[0]) != 0)
2125 tls_release_write_buffer(rl);
2129 /* Read direction */
2131 /* If we have pending data to be read then fail */
2132 if (rl->curr_rec < rl->num_recs || TLS_BUFFER_get_left(&rl->rbuf) != 0)
2135 return tls_release_read_buffer(rl);
2138 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2139 tls_new_record_layer,
2141 tls_unprocessed_read_pending,
2142 tls_processed_read_pending,
2143 tls_app_data_pending,
2144 tls_get_max_records,
2146 tls_retry_write_records,
2151 tls_set_protocol_version,
2152 tls_set_plain_alerts,
2153 tls_set_first_handshake,
2154 tls_set_max_pipelines,
2158 tls_get_compression,
2159 tls_set_max_frag_len,
2161 tls_increment_sequence_ctr,