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;
1406 left = SSL3_BUFFER_get_left(rbuf);
1409 * This record layer is closing but we still have data left in our
1410 * buffer. It must be destined for the next epoch - so push it there.
1412 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1419 int tls_reset(OSSL_RECORD_LAYER *rl)
1421 memset(rl, 0, sizeof(*rl));
1425 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1427 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1430 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1432 return rl->curr_rec < rl->num_recs;
1435 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1440 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1441 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1443 num += rl->rrec[i].length;
1448 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, int type, size_t len,
1449 size_t maxfrag, size_t *preffrag)
1452 * If we have a pipeline capable cipher, and we have been configured to use
1453 * it, then return the preferred number of pipelines.
1455 if (rl->max_pipelines > 0
1456 && rl->enc_ctx != NULL
1457 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
1458 & EVP_CIPH_FLAG_PIPELINE) != 0
1459 && RLAYER_USE_EXPLICIT_IV(rl)) {
1464 pipes = ((len - 1) / *preffrag) + 1;
1466 return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
1472 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
1473 size_t maxfrag, size_t *preffrag)
1475 return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
1478 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
1479 OSSL_RECORD_TEMPLATE *templates,
1483 if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
1484 /* RLAYERfatal() already called */
1491 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
1492 OSSL_RECORD_TEMPLATE *templates,
1494 OSSL_RECORD_TEMPLATE *prefixtempl,
1503 for (j = 0; j < numtempl; j++) {
1507 wb->type = templates[j].type;
1509 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1510 align = (size_t)SSL3_BUFFER_get_buf(wb);
1511 align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
1512 align = SSL3_ALIGN_PAYLOAD - 1
1513 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1515 SSL3_BUFFER_set_offset(wb, align);
1517 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1518 SSL3_BUFFER_get_len(wb), 0)) {
1519 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1523 if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
1524 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1532 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
1534 OSSL_RECORD_TEMPLATE *templ,
1535 unsigned int rectype,
1536 unsigned char **recdata)
1542 maxcomplen = templ->buflen;
1543 if (rl->compctx != NULL)
1544 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1546 if (!WPACKET_put_bytes_u8(thispkt, rectype)
1547 || !WPACKET_put_bytes_u16(thispkt, templ->version)
1548 || !WPACKET_start_sub_packet_u16(thispkt)
1550 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
1552 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1554 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1561 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
1564 SSL3_RECORD *thiswr)
1567 unsigned char *recordstart;
1570 * we should still have the output to thiswr->data and the input from
1571 * wr->input. Length should be thiswr->length. thiswr->data still points
1575 if (!rl->use_etm && mac_size != 0) {
1578 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1579 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1580 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1586 * Reserve some bytes for any growth that may occur during encryption.
1587 * This will be at most one cipher block or the tag length if using
1588 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1590 if (!WPACKET_reserve_bytes(thispkt,
1591 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1594 * We also need next the amount of bytes written to this
1597 || !WPACKET_get_length(thispkt, &len)) {
1598 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1602 /* Get a pointer to the start of this record excluding header */
1603 recordstart = WPACKET_get_curr(thispkt) - len;
1604 SSL3_RECORD_set_data(thiswr, recordstart);
1605 SSL3_RECORD_reset_input(thiswr);
1606 SSL3_RECORD_set_length(thiswr, len);
1611 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
1613 OSSL_RECORD_TEMPLATE *thistempl,
1615 SSL3_RECORD *thiswr)
1617 size_t origlen, len;
1618 size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
1619 : SSL3_RT_HEADER_LENGTH;
1621 /* Allocate bytes for the encryption overhead */
1622 if (!WPACKET_get_length(thispkt, &origlen)
1623 /* Encryption should never shrink the data! */
1624 || origlen > thiswr->length
1625 || (thiswr->length > origlen
1626 && !WPACKET_allocate_bytes(thispkt,
1627 thiswr->length - origlen,
1629 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1632 if (rl->use_etm && mac_size != 0) {
1635 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1636 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1637 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1641 SSL3_RECORD_add_length(thiswr, mac_size);
1644 if (!WPACKET_get_length(thispkt, &len)
1645 || !WPACKET_close(thispkt)) {
1646 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1650 if (rl->msg_callback != NULL) {
1651 unsigned char *recordstart;
1653 recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
1654 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1655 headerlen, rl->cbarg);
1657 if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
1658 unsigned char ctype = thistempl->type;
1660 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1661 &ctype, 1, rl->cbarg);
1665 if (!WPACKET_finish(thispkt)) {
1666 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1670 SSL3_RECORD_add_length(thiswr, headerlen);
1675 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
1676 OSSL_RECORD_TEMPLATE *templates,
1679 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1680 SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1682 SSL3_RECORD *thiswr;
1683 int mac_size = 0, ret = 0;
1684 size_t wpinited = 0;
1685 size_t j, prefix = 0;
1686 OSSL_RECORD_TEMPLATE prefixtempl;
1687 OSSL_RECORD_TEMPLATE *thistempl;
1689 if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
1690 mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
1692 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1697 if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
1698 /* RLAYERfatal() already called */
1702 if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
1703 &prefixtempl, pkt, rl->wbuf,
1705 /* RLAYERfatal() already called */
1709 /* Clear our SSL3_RECORD structures */
1710 memset(wr, 0, sizeof(wr));
1711 for (j = 0; j < numtempl + prefix; j++) {
1712 unsigned char *compressdata = NULL;
1713 unsigned int rectype;
1717 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1720 * Default to the record type as specified in the template unless the
1721 * protocol implementation says differently.
1723 if (rl->funcs->get_record_type != NULL)
1724 rectype = rl->funcs->get_record_type(rl, thistempl);
1726 rectype = thistempl->type;
1728 SSL3_RECORD_set_type(thiswr, rectype);
1729 SSL3_RECORD_set_rec_version(thiswr, thistempl->version);
1731 if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
1733 /* RLAYERfatal() already called */
1737 /* lets setup the record stuff. */
1738 SSL3_RECORD_set_data(thiswr, compressdata);
1739 SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1741 SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1744 * we now 'read' from thiswr->input, thiswr->length bytes into
1748 /* first we compress */
1749 if (rl->compctx != NULL) {
1750 if (!tls_do_compress(rl, thiswr)
1751 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1752 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1755 } else if (compressdata != NULL) {
1756 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1757 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1760 SSL3_RECORD_reset_input(&wr[j]);
1763 if (rl->funcs->add_record_padding != NULL
1764 && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
1766 /* RLAYERfatal() already called */
1770 if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
1771 /* RLAYERfatal() already called */
1777 if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
1778 if (rl->alert == SSL_AD_NO_ALERT) {
1779 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1785 if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
1786 if (rl->alert == SSL_AD_NO_ALERT) {
1787 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1792 for (j = 0; j < numtempl + prefix; j++) {
1795 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1797 if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
1799 /* RLAYERfatal() already called */
1803 /* now let's set up wb */
1804 SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
1809 for (j = 0; j < wpinited; j++)
1810 WPACKET_cleanup(&pkt[j]);
1814 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1817 /* Check we don't have pending data waiting to write */
1818 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1819 || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1820 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1821 return OSSL_RECORD_RETURN_FATAL;
1824 if (!rl->funcs->write_records(rl, templates, numtempl)) {
1825 /* RLAYERfatal already called */
1826 return OSSL_RECORD_RETURN_FATAL;
1830 /* we now just need to write the buffers */
1831 return tls_retry_write_records(rl);
1834 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1837 SSL3_BUFFER *thiswb;
1840 if (rl->nextwbuf >= rl->numwpipes)
1841 return OSSL_RECORD_RETURN_SUCCESS;
1844 thiswb = &rl->wbuf[rl->nextwbuf];
1847 if (rl->bio != NULL) {
1848 if (rl->funcs->prepare_write_bio != NULL) {
1849 ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
1850 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1853 i = BIO_write(rl->bio, (char *)
1854 &(SSL3_BUFFER_get_buf(thiswb)
1855 [SSL3_BUFFER_get_offset(thiswb)]),
1856 (unsigned int)SSL3_BUFFER_get_left(thiswb));
1859 if (i == 0 && BIO_should_retry(rl->bio))
1860 ret = OSSL_RECORD_RETURN_RETRY;
1862 ret = OSSL_RECORD_RETURN_SUCCESS;
1864 if (BIO_should_retry(rl->bio))
1865 ret = OSSL_RECORD_RETURN_RETRY;
1867 ret = OSSL_RECORD_RETURN_FATAL;
1870 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1871 ret = OSSL_RECORD_RETURN_FATAL;
1876 * When an empty fragment is sent on a connection using KTLS,
1877 * it is sent as a write of zero bytes. If this zero byte
1878 * write succeeds, i will be 0 rather than a non-zero value.
1879 * Treat i == 0 as success rather than an error for zero byte
1880 * writes to permit this case.
1882 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1883 SSL3_BUFFER_set_left(thiswb, 0);
1884 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1885 if (++(rl->nextwbuf) < rl->numwpipes)
1888 if (rl->nextwbuf == rl->numwpipes
1889 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1890 tls_release_write_buffer(rl);
1891 return OSSL_RECORD_RETURN_SUCCESS;
1892 } else if (i <= 0) {
1895 * For DTLS, just drop it. That's kind of the whole point in
1896 * using a datagram service
1898 SSL3_BUFFER_set_left(thiswb, 0);
1899 if (++(rl->nextwbuf) == rl->numwpipes
1900 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1901 tls_release_write_buffer(rl);
1906 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1907 SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1911 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1916 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1918 if (bio != NULL && !BIO_up_ref(bio))
1926 /* Shared by most methods except tlsany_meth */
1927 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1929 if (rl->version != version)
1935 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1937 return rl->funcs->set_protocol_version(rl, version);
1940 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1942 rl->allow_plain_alerts = allow;
1945 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1947 rl->is_first_handshake = first;
1950 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1952 rl->max_pipelines = max_pipelines;
1953 if (max_pipelines > 1)
1957 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1958 const char **longstr)
1960 const char *shrt, *lng;
1962 switch (rl->rstate) {
1963 case SSL_ST_READ_HEADER:
1965 lng = "read header";
1967 case SSL_ST_READ_BODY:
1972 shrt = lng = "unknown";
1975 if (shortstr != NULL)
1977 if (longstr != NULL)
1981 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
1983 #ifndef OPENSSL_NO_COMP
1984 return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
1990 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
1992 rl->max_frag_len = max_frag_len;
1994 * We don't need to adjust buffer sizes. Write buffer sizes are
1995 * automatically checked anyway. We should only be changing the read buffer
1996 * size during the handshake, so we will create a new buffer when we create
1997 * the new record layer. We can't change the existing buffer because it may
1998 * already have data in it.
2002 int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
2006 /* Increment the sequence counter */
2007 for (i = SEQ_NUM_SIZE; i > 0; i--) {
2008 ++(rl->sequence[i - 1]);
2009 if (rl->sequence[i - 1] != 0)
2013 /* Sequence has wrapped */
2014 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
2020 int tls_alloc_buffers(OSSL_RECORD_LAYER *rl)
2022 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2023 /* If we have a pending write then buffers are already allocated */
2024 if (rl->nextwbuf < rl->numwpipes)
2027 * We assume 1 pipe with default sized buffer. If what we need ends up
2028 * being a different size to that then it will be reallocated on demand.
2029 * If we need more than 1 pipe then that will also be allocated on
2032 if (!tls_setup_write_buffer(rl, 1, 0, 0))
2036 * Normally when we allocate write buffers we immediately write
2037 * something into it. In this case we're not doing that so mark the
2040 SSL3_BUFFER_set_left(&rl->wbuf[0], 0);
2044 /* Read direction */
2046 /* If we have pending data to be read then buffers are already allocated */
2047 if (rl->curr_rec < rl->num_recs || SSL3_BUFFER_get_left(&rl->rbuf) != 0)
2049 return tls_setup_read_buffer(rl);
2052 int tls_free_buffers(OSSL_RECORD_LAYER *rl)
2054 if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2055 if (rl->nextwbuf < rl->numwpipes) {
2057 * We may have pending data. If we've just got one empty buffer
2058 * allocated then it has probably just been alloc'd via
2059 * tls_alloc_buffers, and it is fine to free it. Otherwise this
2060 * looks like real pending data and it is an error.
2062 if (rl->nextwbuf != 0
2063 || rl->numwpipes != 1
2064 || SSL3_BUFFER_get_left(&rl->wbuf[0]) != 0)
2067 tls_release_write_buffer(rl);
2071 /* Read direction */
2073 /* If we have pending data to be read then fail */
2074 if (rl->curr_rec < rl->num_recs || SSL3_BUFFER_get_left(&rl->rbuf) != 0)
2077 return tls_release_read_buffer(rl);
2080 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2081 tls_new_record_layer,
2084 tls_unprocessed_read_pending,
2085 tls_processed_read_pending,
2086 tls_app_data_pending,
2087 tls_get_max_records,
2089 tls_retry_write_records,
2094 tls_set_protocol_version,
2095 tls_set_plain_alerts,
2096 tls_set_first_handshake,
2097 tls_set_max_pipelines,
2101 tls_get_compression,
2102 tls_set_max_frag_len,
2104 tls_increment_sequence_ctr,