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
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 "../../ssl_local.h"
20 #include "../record_local.h"
21 #include "recmethod_local.h"
23 static void tls_int_free(OSSL_RECORD_LAYER *rl);
25 void SSL3_BUFFER_release(SSL3_BUFFER *b)
31 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
37 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
43 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
45 const EVP_CIPHER *ciph,
49 * Provided cipher, the TLS padding/MAC removal is performed provider
50 * side so we need to tell the ctx about our TLS version and mac size
52 OSSL_PARAM params[3], *pprm = params;
56 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
58 imacsize = EVP_MD_get_size(md);
60 macsize = (size_t)imacsize;
62 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
64 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
66 *pprm = OSSL_PARAM_construct_end();
68 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
69 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
77 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
78 * which ssl3_cbc_digest_record supports.
80 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
82 switch (EVP_MD_CTX_get_type(ctx)) {
95 #ifndef OPENSSL_NO_COMP
96 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
98 if (rl->options & SSL_OP_NO_COMPRESSION)
101 return rl->security == NULL
102 || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
106 static void tls_release_write_buffer_int(OSSL_RECORD_LAYER *rl, size_t start)
111 pipes = rl->numwpipes;
113 while (pipes > start) {
114 wb = &rl->wbuf[pipes - 1];
116 if (SSL3_BUFFER_is_app_buffer(wb))
117 SSL3_BUFFER_set_app_buffer(wb, 0);
119 OPENSSL_free(wb->buf);
125 int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
126 size_t firstlen, size_t nextlen)
129 size_t align = 0, headerlen;
134 if (firstlen == 0 || (numwpipes > 1 && nextlen == 0)) {
136 headerlen = DTLS1_RT_HEADER_LENGTH + 1;
138 headerlen = SSL3_RT_HEADER_LENGTH;
140 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
141 align = SSL3_ALIGN_PAYLOAD - 1;
144 defltlen = rl->max_frag_len + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
146 #ifndef OPENSSL_NO_COMP
147 if (tls_allow_compression(rl))
148 defltlen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
150 if (!(rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
151 defltlen += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
155 for (currpipe = 0; currpipe < numwpipes; currpipe++) {
156 SSL3_BUFFER *thiswb = &wb[currpipe];
157 size_t len = (currpipe == 0) ? firstlen : nextlen;
162 if (thiswb->len != len) {
163 OPENSSL_free(thiswb->buf);
164 thiswb->buf = NULL; /* force reallocation */
169 p = OPENSSL_malloc(len);
171 if (rl->numwpipes < currpipe)
172 rl->numwpipes = currpipe;
174 * We've got a malloc failure, and we're still initialising
175 * buffers. We assume we're so doomed that we won't even be able
178 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
182 memset(thiswb, 0, sizeof(SSL3_BUFFER));
187 /* Free any previously allocated buffers that we are no longer using */
188 tls_release_write_buffer_int(rl, currpipe);
190 rl->numwpipes = numwpipes;
195 static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
197 tls_release_write_buffer_int(rl, 0);
202 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
205 size_t len, align = 0, headerlen;
211 headerlen = DTLS1_RT_HEADER_LENGTH;
213 headerlen = SSL3_RT_HEADER_LENGTH;
215 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
216 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
219 if (b->buf == NULL) {
220 len = rl->max_frag_len
221 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
222 #ifndef OPENSSL_NO_COMP
223 if (tls_allow_compression(rl))
224 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
226 if (b->default_len > len)
227 len = b->default_len;
228 if ((p = OPENSSL_malloc(len)) == NULL) {
230 * We've got a malloc failure, and we're still initialising buffers.
231 * We assume we're so doomed that we won't even be able to send an
234 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
244 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
249 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
250 OPENSSL_cleanse(b->buf, b->len);
251 OPENSSL_free(b->buf);
257 * Return values are as per SSL_read()
259 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
260 int clearold, size_t *readbytes)
263 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
264 * packet by another n bytes. The packet will be in the sub-array of
265 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
266 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
267 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
268 * packet to the start of the buffer; if clearold == 0 then leave any old
269 * packets where they were
271 size_t len, left, align = 0;
276 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
280 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
281 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
282 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
286 /* start with empty packet ... */
289 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
291 * check if next packet length is large enough to justify payload
294 pkt = rb->buf + rb->offset;
295 if (pkt[0] == SSL3_RT_APPLICATION_DATA
296 && (pkt[3] << 8 | pkt[4]) >= 128) {
298 * Note that even if packet is corrupted and its length field
299 * is insane, we can only be led to wrong decision about
300 * whether memmove will occur or not. Header values has no
301 * effect on memmove arguments and therefore no buffer
302 * overrun can be triggered.
304 memmove(rb->buf + align, pkt, left);
308 rl->packet = rb->buf + rb->offset;
309 rl->packet_length = 0;
310 /* ... now we can act as if 'extend' was set */
313 len = rl->packet_length;
314 pkt = rb->buf + align;
316 * Move any available bytes to front of buffer: 'len' bytes already
317 * pointed to by 'packet', 'left' extra ones at the end
319 if (rl->packet != pkt && clearold == 1) {
320 memmove(pkt, rl->packet, len + left);
322 rb->offset = len + align;
326 * For DTLS/UDP reads should not span multiple packets because the read
327 * operation returns the whole packet at once (as long as it fits into
331 if (left == 0 && extend) {
333 * We received a record with a header but no body data. This will
336 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
338 if (left > 0 && n > left)
342 /* if there is enough in the buffer from a previous read, take some */
344 rl->packet_length += n;
348 return OSSL_RECORD_RETURN_SUCCESS;
351 /* else we need to read more data */
353 if (n > rb->len - rb->offset) {
354 /* does not happen */
355 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
356 return OSSL_RECORD_RETURN_FATAL;
359 /* We always act like read_ahead is set for DTLS */
360 if (!rl->read_ahead && !rl->isdtls) {
361 /* ignore max parameter */
366 if (max > rb->len - rb->offset)
367 max = rb->len - rb->offset;
373 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
376 * Now we have len+left bytes at the front of rl->rbuf.buf and
377 * need to read in more until we have len + n (up to len + max if
383 ret = BIO_read(bio, pkt + len + left, max - left);
386 ret = OSSL_RECORD_RETURN_SUCCESS;
387 } else if (BIO_should_retry(bio)) {
388 if (rl->prev != NULL) {
390 * We were reading from the previous epoch. Now there is no
391 * more data, so swap to the actual transport BIO
397 ret = OSSL_RECORD_RETURN_RETRY;
398 } else if (BIO_eof(bio)) {
399 ret = OSSL_RECORD_RETURN_EOF;
401 ret = OSSL_RECORD_RETURN_FATAL;
404 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
405 ret = OSSL_RECORD_RETURN_FATAL;
408 if (ret <= OSSL_RECORD_RETURN_RETRY) {
410 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
412 tls_release_read_buffer(rl);
417 * reads should *never* span multiple packets for DTLS because the
418 * underlying transport protocol is message oriented as opposed to
419 * byte oriented as in the TLS case.
423 n = left; /* makes the while condition false */
427 /* done reading, now the book-keeping */
430 rl->packet_length += n;
432 return OSSL_RECORD_RETURN_SUCCESS;
436 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
437 * for us in the buffer.
439 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
447 p = SSL3_BUFFER_get_buf(rbuf);
451 left = SSL3_BUFFER_get_left(rbuf);
453 if (left < SSL3_RT_HEADER_LENGTH)
456 p += SSL3_BUFFER_get_offset(rbuf);
459 * We only check the type and record length, we will sanity check version
462 if (*p != SSL3_RT_APPLICATION_DATA)
468 if (left < SSL3_RT_HEADER_LENGTH + len)
474 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
475 size_t overhead, int send)
477 uint32_t max_early_data = rl->max_early_data;
479 if (max_early_data == 0) {
480 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
481 SSL_R_TOO_MUCH_EARLY_DATA);
485 /* If we are dealing with ciphertext we need to allow for the overhead */
486 max_early_data += overhead;
488 if (rl->early_data_count + length > max_early_data) {
489 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
490 SSL_R_TOO_MUCH_EARLY_DATA);
493 rl->early_data_count += length;
499 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
500 * will be processed per call to tls_get_more_records. Without this limit an
501 * attacker could send empty records at a faster rate than we can process and
502 * cause tls_get_more_records to loop forever.
504 #define MAX_EMPTY_RECORDS 32
506 #define SSL2_RT_HEADER_LENGTH 2
509 * Call this to buffer new input records in rl->rrec.
510 * It will return a OSSL_RECORD_RETURN_* value.
511 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
512 * records have been decoded. For each record 'i':
513 * rrec[i].type - is the type of record
514 * rrec[i].data, - data
515 * rrec[i].length, - number of bytes
516 * Multiple records will only be returned if the record types are all
517 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
520 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
525 SSL3_RECORD *rr, *thisrr;
528 unsigned char md[EVP_MAX_MD_SIZE];
529 unsigned int version;
532 size_t num_recs = 0, max_recs, j;
533 PACKET pkt, sslv2pkt;
534 SSL_MAC_BUF *macbufs = NULL;
535 int ret = OSSL_RECORD_RETURN_FATAL;
539 if (rbuf->buf == NULL) {
540 if (!tls_setup_read_buffer(rl)) {
541 /* RLAYERfatal() already called */
542 return OSSL_RECORD_RETURN_FATAL;
546 max_recs = rl->max_pipelines;
552 thisrr = &rr[num_recs];
554 /* check if we have the header */
555 if ((rl->rstate != SSL_ST_READ_BODY) ||
556 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
560 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
561 SSL3_BUFFER_get_len(rbuf), 0,
562 num_recs == 0 ? 1 : 0, &n);
564 if (rret < OSSL_RECORD_RETURN_SUCCESS)
565 return rret; /* error or non-blocking */
567 rl->rstate = SSL_ST_READ_BODY;
570 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
571 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
572 return OSSL_RECORD_RETURN_FATAL;
575 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
576 || !PACKET_get_1(&sslv2pkt, &type)) {
577 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
578 return OSSL_RECORD_RETURN_FATAL;
581 * The first record received by the server may be a V2ClientHello.
583 if (rl->role == OSSL_RECORD_ROLE_SERVER
584 && rl->is_first_record
585 && (sslv2len & 0x8000) != 0
586 && (type == SSL2_MT_CLIENT_HELLO)) {
590 * |num_recs| here will actually always be 0 because
591 * |num_recs > 0| only ever occurs when we are processing
592 * multiple app data records - which we know isn't the case here
593 * because it is an SSLv2ClientHello. We keep it using
594 * |num_recs| for the sake of consistency
596 thisrr->type = SSL3_RT_HANDSHAKE;
597 thisrr->rec_version = SSL2_VERSION;
599 thisrr->length = sslv2len & 0x7fff;
601 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
602 - SSL2_RT_HEADER_LENGTH) {
603 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
604 SSL_R_PACKET_LENGTH_TOO_LONG);
605 return OSSL_RECORD_RETURN_FATAL;
608 /* SSLv3+ style record */
610 /* Pull apart the header into the SSL3_RECORD */
611 if (!PACKET_get_1(&pkt, &type)
612 || !PACKET_get_net_2(&pkt, &version)
613 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
614 if (rl->msg_callback != NULL)
615 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
616 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
617 return OSSL_RECORD_RETURN_FATAL;
620 thisrr->rec_version = version;
623 * When we call validate_record_header() only records actually
624 * received in SSLv2 format should have the record version set
625 * to SSL2_VERSION. This way validate_record_header() can know
626 * what format the record was in based on the version.
628 if (thisrr->rec_version == SSL2_VERSION) {
629 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
630 SSL_R_WRONG_VERSION_NUMBER);
631 return OSSL_RECORD_RETURN_FATAL;
634 if (rl->msg_callback != NULL)
635 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
638 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
639 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
640 SSL_R_PACKET_LENGTH_TOO_LONG);
641 return OSSL_RECORD_RETURN_FATAL;
645 if (!rl->funcs->validate_record_header(rl, thisrr)) {
646 /* RLAYERfatal already called */
647 return OSSL_RECORD_RETURN_FATAL;
650 /* now rl->rstate == SSL_ST_READ_BODY */
654 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
655 * how much more data we need to read for the rest of the record
657 if (thisrr->rec_version == SSL2_VERSION) {
658 more = thisrr->length + SSL2_RT_HEADER_LENGTH
659 - SSL3_RT_HEADER_LENGTH;
661 more = thisrr->length;
665 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
667 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
668 if (rret < OSSL_RECORD_RETURN_SUCCESS)
669 return rret; /* error or non-blocking io */
672 /* set state for later operations */
673 rl->rstate = SSL_ST_READ_HEADER;
676 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
677 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
678 * + thisrr->length and we have that many bytes in rl->packet
680 if (thisrr->rec_version == SSL2_VERSION)
681 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
683 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
686 * ok, we can now read from 'rl->packet' data into 'thisrr'.
687 * thisrr->input points at thisrr->length bytes, which need to be copied
688 * into thisrr->data by either the decryption or by the decompression.
689 * When the data is 'copied' into the thisrr->data buffer,
690 * thisrr->input will be updated to point at the new buffer
694 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
695 * thisrr->length bytes of encrypted compressed stuff.
698 /* decrypt in place in 'thisrr->input' */
699 thisrr->data = thisrr->input;
700 thisrr->orig_len = thisrr->length;
704 /* we have pulled in a full packet so zero things */
705 rl->packet_length = 0;
706 rl->is_first_record = 0;
707 } while (num_recs < max_recs
708 && thisrr->type == SSL3_RT_APPLICATION_DATA
709 && RLAYER_USE_EXPLICIT_IV(rl)
710 && rl->enc_ctx != NULL
711 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
712 & EVP_CIPH_FLAG_PIPELINE) != 0
713 && tls_record_app_data_waiting(rl));
716 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
717 /* The following can happen in tlsany_meth after HRR */
718 && rl->version == TLS1_3_VERSION
719 && rl->is_first_handshake) {
721 * CCS messages must be exactly 1 byte long, containing the value 0x01
723 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
724 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
725 SSL_R_INVALID_CCS_MESSAGE);
726 return OSSL_RECORD_RETURN_FATAL;
729 * CCS messages are ignored in TLSv1.3. We treat it like an empty
732 thisrr->type = SSL3_RT_HANDSHAKE;
733 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
734 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
735 SSL_R_UNEXPECTED_CCS_MESSAGE);
736 return OSSL_RECORD_RETURN_FATAL;
740 rl->num_released = 0;
742 return OSSL_RECORD_RETURN_SUCCESS;
745 if (rl->md_ctx != NULL) {
746 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
749 imac_size = EVP_MD_get_size(tmpmd);
750 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
751 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
752 return OSSL_RECORD_RETURN_FATAL;
754 mac_size = (size_t)imac_size;
759 * If in encrypt-then-mac mode calculate mac from encrypted record. All
760 * the details below are public so no timing details can leak.
762 if (rl->use_etm && rl->md_ctx != NULL) {
765 for (j = 0; j < num_recs; j++) {
768 if (thisrr->length < mac_size) {
769 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
770 return OSSL_RECORD_RETURN_FATAL;
772 thisrr->length -= mac_size;
773 mac = thisrr->data + thisrr->length;
774 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
775 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
776 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
777 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
778 return OSSL_RECORD_RETURN_FATAL;
782 * We've handled the mac now - there is no MAC inside the encrypted
789 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
790 if (macbufs == NULL) {
791 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
792 return OSSL_RECORD_RETURN_FATAL;
796 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
800 * 0: if the record is publicly invalid, or an internal error, or AEAD
801 * decryption failed, or ETM decryption failed.
802 * 1: Success or MTE decryption failed (MAC will be randomised)
805 if (rl->alert != SSL_AD_NO_ALERT) {
806 /* RLAYERfatal() already got called */
810 && rl->skip_early_data != NULL
811 && rl->skip_early_data(rl->cbarg)) {
813 * Valid early_data that we cannot decrypt will fail here. We treat
814 * it like an empty record.
819 if (!rlayer_early_data_count_ok(rl, thisrr->length,
820 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
821 /* RLAYERfatal() already called */
828 rl->num_released = 0;
829 /* Reset the read sequence */
830 memset(rl->sequence, 0, sizeof(rl->sequence));
834 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
835 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
838 OSSL_TRACE_BEGIN(TLS) {
839 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
840 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
841 } OSSL_TRACE_END(TLS);
843 /* r->length is now the compressed data plus mac */
844 if (rl->enc_ctx != NULL
846 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
847 for (j = 0; j < num_recs; j++) {
848 SSL_MAC_BUF *thismb = &macbufs[j];
852 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
853 if (i == 0 || thismb == NULL || thismb->mac == NULL
854 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
856 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
862 if (rl->alert != SSL_AD_NO_ALERT) {
863 /* We already called RLAYERfatal() */
867 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
868 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
869 * failure is directly visible from the ciphertext anyway, we should
870 * not reveal which kind of error occurred -- this might become
871 * visible to an attacker (e.g. via a logfile)
873 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
874 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
878 for (j = 0; j < num_recs; j++) {
881 if (!rl->funcs->post_process_record(rl, thisrr)) {
882 /* RLAYERfatal already called */
887 * Check if the received packet overflows the current
888 * Max Fragment Length setting.
889 * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
891 if (thisrr->length > rl->max_frag_len) {
892 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
898 * So at this point the following is true
899 * thisrr->type is the type of record
900 * thisrr->length == number of bytes in record
901 * thisrr->off == offset to first valid byte
902 * thisrr->data == where to take bytes from, increment after use :-).
905 /* just read a 0 length packet */
906 if (thisrr->length == 0) {
907 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
908 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
909 SSL_R_RECORD_TOO_SMALL);
913 rl->empty_record_count = 0;
917 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
919 if (thisrr->type == SSL3_RT_APPLICATION_DATA
920 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
921 /* RLAYERfatal already called */
926 rl->num_recs = num_recs;
928 rl->num_released = 0;
929 ret = OSSL_RECORD_RETURN_SUCCESS;
931 if (macbufs != NULL) {
932 for (j = 0; j < num_recs; j++) {
933 if (macbufs[j].alloced)
934 OPENSSL_free(macbufs[j].mac);
936 OPENSSL_free(macbufs);
941 /* Shared by ssl3_meth and tls1_meth */
942 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
944 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
946 if (rec->rec_version != rl->version) {
947 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
951 #ifndef OPENSSL_NO_COMP
953 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
954 * does not include the compression overhead anyway.
956 if (rl->compctx == NULL)
957 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
960 if (rec->length > len) {
961 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
962 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
969 int tls_do_compress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *wr)
971 #ifndef OPENSSL_NO_COMP
974 i = COMP_compress_block(rl->compctx, wr->data,
975 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
976 wr->input, (int)wr->length);
981 wr->input = wr->data;
988 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
990 #ifndef OPENSSL_NO_COMP
993 if (rec->comp == NULL) {
994 rec->comp = (unsigned char *)
995 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
997 if (rec->comp == NULL)
1000 i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
1001 rec->data, (int)rec->length);
1006 rec->data = rec->comp;
1013 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
1014 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
1016 if (rl->compctx != NULL) {
1017 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1018 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1019 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1022 if (!tls_do_uncompress(rl, rec)) {
1023 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
1024 SSL_R_BAD_DECOMPRESSION);
1029 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1030 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1037 /* Shared by tls13_meth and ktls_meth */
1038 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
1040 if (rec->type != SSL3_RT_APPLICATION_DATA
1041 && rec->type != SSL3_RT_ALERT
1042 && rec->type != SSL3_RT_HANDSHAKE) {
1043 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1047 if (rl->msg_callback != NULL)
1048 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
1052 * TLSv1.3 alert and handshake records are required to be non-zero in
1055 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1056 && rec->length == 0) {
1057 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1064 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1065 int *type, unsigned char **data, size_t *datalen,
1066 uint16_t *epoch, unsigned char *seq_num)
1071 * tls_get_more_records() can return success without actually reading
1072 * anything useful (i.e. if empty records are read). We loop here until
1073 * we have something useful. tls_get_more_records() will eventually fail if
1074 * too many sequential empty records are read.
1076 while (rl->curr_rec >= rl->num_recs) {
1079 if (rl->num_released != rl->num_recs) {
1080 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1081 return OSSL_RECORD_RETURN_FATAL;
1084 ret = rl->funcs->get_more_records(rl);
1086 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1091 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1092 * points to the next one to read.
1094 rec = &rl->rrec[rl->curr_rec++];
1097 *rversion = rec->rec_version;
1099 *data = rec->data + rec->off;
1100 *datalen = rec->length;
1102 *epoch = rec->epoch;
1103 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1106 return OSSL_RECORD_RETURN_SUCCESS;
1109 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
1111 if (!ossl_assert(rl->num_released < rl->curr_rec)
1112 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
1113 /* Should not happen */
1114 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1115 return OSSL_RECORD_RETURN_FATAL;
1120 if (rl->curr_rec == rl->num_released
1121 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1122 && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
1123 tls_release_read_buffer(rl);
1125 return OSSL_RECORD_RETURN_SUCCESS;
1128 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1130 const OSSL_PARAM *p;
1132 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1133 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1134 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1138 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1139 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1140 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1144 if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
1145 p = OSSL_PARAM_locate_const(options,
1146 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1147 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1148 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1152 p = OSSL_PARAM_locate_const(options,
1153 OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
1154 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
1155 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1160 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1162 * We ignore any read_ahead setting prior to the application protection
1163 * level. Otherwise we may read ahead data in a lower protection level
1164 * that is destined for a higher protection level. To simplify the logic
1165 * we don't support that at this stage.
1167 p = OSSL_PARAM_locate_const(options,
1168 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1169 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1170 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1179 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1180 int role, int direction, int level, unsigned char *key,
1181 size_t keylen, unsigned char *iv, size_t ivlen,
1182 unsigned char *mackey, size_t mackeylen,
1183 const EVP_CIPHER *ciph, size_t taglen,
1185 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
1186 BIO *transport, BIO *next, BIO_ADDR *local,
1187 BIO_ADDR *peer, const OSSL_PARAM *settings,
1188 const OSSL_PARAM *options,
1189 const OSSL_DISPATCH *fns, void *cbarg,
1190 OSSL_RECORD_LAYER **retrl)
1192 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1193 const OSSL_PARAM *p;
1198 return OSSL_RECORD_RETURN_FATAL;
1201 * Default the value for max_frag_len. This may be overridden by the
1204 rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH;
1206 /* Loop through all the settings since they must all be understood */
1207 if (settings != NULL) {
1208 for (p = settings; p->key != NULL; p++) {
1209 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1210 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1211 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1214 } else if (strcmp(p->key,
1215 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1216 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1217 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1220 } else if (strcmp(p->key,
1221 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1222 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1223 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1226 } else if (strcmp(p->key,
1227 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1228 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1229 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1232 } else if (strcmp(p->key,
1233 OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1234 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1235 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1239 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1245 rl->libctx = libctx;
1250 rl->direction = direction;
1253 rl->alert = SSL_AD_NO_ALERT;
1255 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1256 rl->is_first_record = 1;
1258 if (!tls_set1_bio(rl, transport))
1261 if (prev != NULL && !BIO_up_ref(prev))
1265 if (next != NULL && !BIO_up_ref(next))
1271 for (; fns->function_id != 0; fns++) {
1272 switch (fns->function_id) {
1273 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1274 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1276 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1277 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1279 case OSSL_FUNC_RLAYER_SECURITY:
1280 rl->security = OSSL_FUNC_rlayer_security(fns);
1282 case OSSL_FUNC_RLAYER_PADDING:
1283 rl->padding = OSSL_FUNC_rlayer_padding(fns);
1285 /* Just ignore anything we don't understand */
1291 if (!tls_set_options(rl, options)) {
1292 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1296 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
1297 && rl->version <= TLS1_VERSION
1298 && !EVP_CIPHER_is_a(ciph, "NULL")
1299 && !EVP_CIPHER_is_a(ciph, "RC4")) {
1301 * Enable vulnerability countermeasure for CBC ciphers with known-IV
1302 * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
1304 rl->need_empty_fragments = 1;
1308 return OSSL_RECORD_RETURN_SUCCESS;
1311 return OSSL_RECORD_RETURN_FATAL;
1315 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1316 int role, int direction, int level, uint16_t epoch,
1317 unsigned char *key, size_t keylen, unsigned char *iv,
1318 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1319 const EVP_CIPHER *ciph, size_t taglen,
1321 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
1322 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1323 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1324 const OSSL_DISPATCH *fns, void *cbarg,
1325 OSSL_RECORD_LAYER **retrl)
1329 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1330 key, keylen, iv, ivlen, mackey, mackeylen,
1331 ciph, taglen, mactype, md, comp, prev,
1332 transport, next, local, peer, settings,
1333 options, fns, cbarg, retrl);
1335 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1339 case TLS_ANY_VERSION:
1340 (*retrl)->funcs = &tls_any_funcs;
1342 case TLS1_3_VERSION:
1343 (*retrl)->funcs = &tls_1_3_funcs;
1345 case TLS1_2_VERSION:
1346 case TLS1_1_VERSION:
1348 (*retrl)->funcs = &tls_1_funcs;
1351 (*retrl)->funcs = &ssl_3_0_funcs;
1354 /* Should not happen */
1355 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1356 ret = OSSL_RECORD_RETURN_FATAL;
1360 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1361 ivlen, mackey, mackeylen, ciph,
1362 taglen, mactype, md, comp);
1365 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1366 OPENSSL_free(*retrl);
1372 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1377 SSL3_BUFFER_release(&rl->rbuf);
1379 tls_release_write_buffer(rl);
1381 EVP_CIPHER_CTX_free(rl->enc_ctx);
1382 EVP_MD_CTX_free(rl->md_ctx);
1383 #ifndef OPENSSL_NO_COMP
1384 COMP_CTX_free(rl->compctx);
1387 if (rl->version == SSL3_VERSION)
1388 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1390 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1395 int tls_free(OSSL_RECORD_LAYER *rl)
1398 size_t left, written;
1403 left = SSL3_BUFFER_get_left(rbuf);
1406 * This record layer is closing but we still have data left in our
1407 * buffer. It must be destined for the next epoch - so push it there.
1409 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1416 int tls_reset(OSSL_RECORD_LAYER *rl)
1418 memset(rl, 0, sizeof(*rl));
1422 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1424 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1427 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1429 return rl->curr_rec < rl->num_recs;
1432 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1437 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1438 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1440 num += rl->rrec[i].length;
1445 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1450 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1455 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, int type, size_t len,
1456 size_t maxfrag, size_t *preffrag)
1459 * TODO(RECLAYER): There is no test for the pipelining code. We should add
1463 * If we have a pipeline capable cipher, and we have been configured to use
1464 * it, then return the preferred number of pipelines.
1466 if (rl->max_pipelines > 0
1467 && rl->enc_ctx != NULL
1468 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
1469 & EVP_CIPH_FLAG_PIPELINE) != 0
1470 && RLAYER_USE_EXPLICIT_IV(rl)) {
1475 pipes = ((len - 1) / *preffrag) + 1;
1477 return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
1483 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
1484 size_t maxfrag, size_t *preffrag)
1486 return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
1489 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
1490 OSSL_RECORD_TEMPLATE *templates,
1494 if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
1495 /* RLAYERfatal() already called */
1502 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
1503 OSSL_RECORD_TEMPLATE *templates,
1505 OSSL_RECORD_TEMPLATE *prefixtempl,
1514 for (j = 0; j < numtempl; j++) {
1518 wb->type = templates[j].type;
1520 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1521 align = (size_t)SSL3_BUFFER_get_buf(wb);
1522 align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
1523 align = SSL3_ALIGN_PAYLOAD - 1
1524 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1526 SSL3_BUFFER_set_offset(wb, align);
1528 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1529 SSL3_BUFFER_get_len(wb), 0)) {
1530 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1534 if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
1535 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1543 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
1545 OSSL_RECORD_TEMPLATE *templ,
1546 unsigned int rectype,
1547 unsigned char **recdata)
1553 maxcomplen = templ->buflen;
1554 if (rl->compctx != NULL)
1555 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1557 if (!WPACKET_put_bytes_u8(thispkt, rectype)
1558 || !WPACKET_put_bytes_u16(thispkt, templ->version)
1559 || !WPACKET_start_sub_packet_u16(thispkt)
1561 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
1563 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1565 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1572 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
1575 SSL3_RECORD *thiswr)
1578 unsigned char *recordstart;
1581 * we should still have the output to thiswr->data and the input from
1582 * wr->input. Length should be thiswr->length. thiswr->data still points
1586 if (!rl->use_etm && mac_size != 0) {
1589 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1590 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1591 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1597 * Reserve some bytes for any growth that may occur during encryption.
1598 * This will be at most one cipher block or the tag length if using
1599 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1601 if (!WPACKET_reserve_bytes(thispkt,
1602 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1605 * We also need next the amount of bytes written to this
1608 || !WPACKET_get_length(thispkt, &len)) {
1609 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1613 /* Get a pointer to the start of this record excluding header */
1614 recordstart = WPACKET_get_curr(thispkt) - len;
1615 SSL3_RECORD_set_data(thiswr, recordstart);
1616 SSL3_RECORD_reset_input(thiswr);
1617 SSL3_RECORD_set_length(thiswr, len);
1622 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
1624 OSSL_RECORD_TEMPLATE *thistempl,
1626 SSL3_RECORD *thiswr)
1628 size_t origlen, len;
1629 size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
1630 : SSL3_RT_HEADER_LENGTH;
1632 /* Allocate bytes for the encryption overhead */
1633 if (!WPACKET_get_length(thispkt, &origlen)
1634 /* Encryption should never shrink the data! */
1635 || origlen > thiswr->length
1636 || (thiswr->length > origlen
1637 && !WPACKET_allocate_bytes(thispkt,
1638 thiswr->length - origlen,
1640 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1643 if (rl->use_etm && mac_size != 0) {
1646 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1647 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1648 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1652 SSL3_RECORD_add_length(thiswr, mac_size);
1655 if (!WPACKET_get_length(thispkt, &len)
1656 || !WPACKET_close(thispkt)) {
1657 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1661 if (rl->msg_callback != NULL) {
1662 unsigned char *recordstart;
1664 recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
1665 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1666 headerlen, rl->cbarg);
1668 if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
1669 unsigned char ctype = thistempl->type;
1671 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1672 &ctype, 1, rl->cbarg);
1676 if (!WPACKET_finish(thispkt)) {
1677 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1681 SSL3_RECORD_add_length(thiswr, headerlen);
1686 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
1687 OSSL_RECORD_TEMPLATE *templates,
1690 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1691 SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1693 SSL3_RECORD *thiswr;
1694 int mac_size = 0, ret = 0;
1695 size_t wpinited = 0;
1696 size_t j, prefix = 0;
1697 OSSL_RECORD_TEMPLATE prefixtempl;
1698 OSSL_RECORD_TEMPLATE *thistempl;
1700 if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
1701 mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
1703 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1708 if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
1709 /* RLAYERfatal() already called */
1713 if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
1714 &prefixtempl, pkt, rl->wbuf,
1716 /* RLAYERfatal() already called */
1720 /* Clear our SSL3_RECORD structures */
1721 memset(wr, 0, sizeof(wr));
1722 for (j = 0; j < numtempl + prefix; j++) {
1723 unsigned char *compressdata = NULL;
1724 unsigned int rectype;
1728 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1731 * Default to the record type as specified in the template unless the
1732 * protocol implementation says differently.
1734 if (rl->funcs->get_record_type != NULL)
1735 rectype = rl->funcs->get_record_type(rl, thistempl);
1737 rectype = thistempl->type;
1739 SSL3_RECORD_set_type(thiswr, rectype);
1740 SSL3_RECORD_set_rec_version(thiswr, thistempl->version);
1742 if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
1744 /* RLAYERfatal() already called */
1748 /* lets setup the record stuff. */
1749 SSL3_RECORD_set_data(thiswr, compressdata);
1750 SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1752 SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1755 * we now 'read' from thiswr->input, thiswr->length bytes into
1759 /* first we compress */
1760 if (rl->compctx != NULL) {
1761 if (!tls_do_compress(rl, thiswr)
1762 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1763 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1766 } else if (compressdata != NULL) {
1767 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1768 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1771 SSL3_RECORD_reset_input(&wr[j]);
1774 if (rl->funcs->add_record_padding != NULL
1775 && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
1777 /* RLAYERfatal() already called */
1781 if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
1782 /* RLAYERfatal() already called */
1788 if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
1789 if (rl->alert == SSL_AD_NO_ALERT) {
1790 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1796 if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
1797 if (rl->alert == SSL_AD_NO_ALERT) {
1798 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1803 for (j = 0; j < numtempl + prefix; j++) {
1806 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1808 if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
1810 /* RLAYERfatal() already called */
1814 /* now let's set up wb */
1815 SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
1820 for (j = 0; j < wpinited; j++)
1821 WPACKET_cleanup(&pkt[j]);
1825 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1828 /* Check we don't have pending data waiting to write */
1829 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1830 || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1831 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1832 return OSSL_RECORD_RETURN_FATAL;
1835 if (!rl->funcs->write_records(rl, templates, numtempl)) {
1836 /* RLAYERfatal already called */
1837 return OSSL_RECORD_RETURN_FATAL;
1841 /* we now just need to write the buffers */
1842 return tls_retry_write_records(rl);
1845 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1848 SSL3_BUFFER *thiswb;
1851 if (rl->nextwbuf >= rl->numwpipes)
1852 return OSSL_RECORD_RETURN_SUCCESS;
1855 thiswb = &rl->wbuf[rl->nextwbuf];
1858 if (rl->bio != NULL) {
1859 if (rl->funcs->prepare_write_bio != NULL) {
1860 ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
1861 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1864 i = BIO_write(rl->bio, (char *)
1865 &(SSL3_BUFFER_get_buf(thiswb)
1866 [SSL3_BUFFER_get_offset(thiswb)]),
1867 (unsigned int)SSL3_BUFFER_get_left(thiswb));
1870 if (i == 0 && BIO_should_retry(rl->bio))
1871 ret = OSSL_RECORD_RETURN_RETRY;
1873 ret = OSSL_RECORD_RETURN_SUCCESS;
1875 if (BIO_should_retry(rl->bio))
1876 ret = OSSL_RECORD_RETURN_RETRY;
1878 ret = OSSL_RECORD_RETURN_FATAL;
1881 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1882 ret = OSSL_RECORD_RETURN_FATAL;
1887 * When an empty fragment is sent on a connection using KTLS,
1888 * it is sent as a write of zero bytes. If this zero byte
1889 * write succeeds, i will be 0 rather than a non-zero value.
1890 * Treat i == 0 as success rather than an error for zero byte
1891 * writes to permit this case.
1893 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1894 SSL3_BUFFER_set_left(thiswb, 0);
1895 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1896 if (++(rl->nextwbuf) < rl->numwpipes)
1899 if (rl->nextwbuf == rl->numwpipes
1900 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1901 tls_release_write_buffer(rl);
1902 return OSSL_RECORD_RETURN_SUCCESS;
1903 } else if (i <= 0) {
1906 * For DTLS, just drop it. That's kind of the whole point in
1907 * using a datagram service
1909 SSL3_BUFFER_set_left(thiswb, 0);
1910 if (++(rl->nextwbuf) == rl->numwpipes
1911 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1912 tls_release_write_buffer(rl);
1917 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1918 SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1922 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1927 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1929 if (bio != NULL && !BIO_up_ref(bio))
1937 /* Shared by most methods except tlsany_meth */
1938 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1940 if (rl->version != version)
1946 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1948 return rl->funcs->set_protocol_version(rl, version);
1951 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1953 rl->allow_plain_alerts = allow;
1956 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1958 rl->is_first_handshake = first;
1961 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1963 rl->max_pipelines = max_pipelines;
1964 if (max_pipelines > 1)
1968 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1969 const char **longstr)
1971 const char *shrt, *lng;
1973 switch (rl->rstate) {
1974 case SSL_ST_READ_HEADER:
1976 lng = "read header";
1978 case SSL_ST_READ_BODY:
1983 shrt = lng = "unknown";
1986 if (shortstr != NULL)
1988 if (longstr != NULL)
1992 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
1994 #ifndef OPENSSL_NO_COMP
1995 return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
2001 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
2003 rl->max_frag_len = max_frag_len;
2005 * We don't need to adjust buffer sizes. Write buffer sizes are
2006 * automatically checked anyway. We should only be changing the read buffer
2007 * size during the handshake, so we will create a new buffer when we create
2008 * the new record layer. We can't change the existing buffer because it may
2009 * already have data in it.
2013 int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
2017 /* Increment the sequence counter */
2018 for (i = SEQ_NUM_SIZE; i > 0; i--) {
2019 ++(rl->sequence[i - 1]);
2020 if (rl->sequence[i - 1] != 0)
2024 /* Sequence has wrapped */
2025 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
2031 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2032 tls_new_record_layer,
2035 tls_unprocessed_read_pending,
2036 tls_processed_read_pending,
2037 tls_app_data_pending,
2039 tls_get_max_record_len,
2040 tls_get_max_records,
2042 tls_retry_write_records,
2047 tls_set_protocol_version,
2048 tls_set_plain_alerts,
2049 tls_set_first_handshake,
2050 tls_set_max_pipelines,
2054 tls_get_compression,
2055 tls_set_max_frag_len,
2057 tls_increment_sequence_ctr