2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include <openssl/bio.h>
11 #include <openssl/ssl.h>
12 #include <openssl/err.h>
13 #include <openssl/core_names.h>
14 #include "internal/e_os.h"
15 #include "internal/packet.h"
16 #include "../../ssl_local.h"
17 #include "../record_local.h"
18 #include "recmethod_local.h"
20 static void tls_int_free(OSSL_RECORD_LAYER *rl);
22 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
28 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
34 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
36 const EVP_CIPHER *ciph,
40 * Provided cipher, the TLS padding/MAC removal is performed provider
41 * side so we need to tell the ctx about our TLS version and mac size
43 OSSL_PARAM params[3], *pprm = params;
47 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
49 imacsize = EVP_MD_get_size(md);
51 macsize = (size_t)imacsize;
53 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
55 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
57 *pprm = OSSL_PARAM_construct_end();
59 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
60 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
68 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
69 * which ssl3_cbc_digest_record supports.
71 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
73 switch (EVP_MD_CTX_get_type(ctx)) {
86 #ifndef OPENSSL_NO_COMP
87 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
89 if (rl->options & SSL_OP_NO_COMPRESSION)
92 return rl->security == NULL
93 || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
97 static int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
101 size_t align = 0, headerlen;
104 SSL_CONNECTION *s = (SSL_CONNECTION *)rl->cbarg;
106 rl->numwpipes = numwpipes;
109 if (SSL_CONNECTION_IS_DTLS(s))
110 headerlen = DTLS1_RT_HEADER_LENGTH + 1;
112 headerlen = SSL3_RT_HEADER_LENGTH;
114 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
115 align = SSL3_ALIGN_PAYLOAD - 1;
118 len = ssl_get_max_send_fragment(s)
119 + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
120 #ifndef OPENSSL_NO_COMP
121 if (ssl_allow_compression(s))
122 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
124 if (!(rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
125 len += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
129 for (currpipe = 0; currpipe < numwpipes; currpipe++) {
130 SSL3_BUFFER *thiswb = &wb[currpipe];
132 if (thiswb->len != len) {
133 OPENSSL_free(thiswb->buf);
134 thiswb->buf = NULL; /* force reallocation */
137 if (thiswb->buf == NULL) {
138 if (s->wbio == NULL || !BIO_get_ktls_send(s->wbio)) {
139 p = OPENSSL_malloc(len);
141 rl->numwpipes = currpipe;
143 * We've got a malloc failure, and we're still initialising
144 * buffers. We assume we're so doomed that we won't even be able
147 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
153 memset(thiswb, 0, sizeof(SSL3_BUFFER));
162 static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
167 pipes = rl->numwpipes;
170 wb = &rl->wbuf[pipes - 1];
172 if (SSL3_BUFFER_is_app_buffer(wb))
173 SSL3_BUFFER_set_app_buffer(wb, 0);
175 OPENSSL_free(wb->buf);
183 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
186 size_t len, align = 0, headerlen;
192 headerlen = DTLS1_RT_HEADER_LENGTH;
194 headerlen = SSL3_RT_HEADER_LENGTH;
196 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
197 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
200 if (b->buf == NULL) {
201 len = SSL3_RT_MAX_PLAIN_LENGTH
202 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
203 #ifndef OPENSSL_NO_COMP
204 if (tls_allow_compression(rl))
205 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
207 if (b->default_len > len)
208 len = b->default_len;
209 if ((p = OPENSSL_malloc(len)) == NULL) {
211 * We've got a malloc failure, and we're still initialising buffers.
212 * We assume we're so doomed that we won't even be able to send an
215 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
225 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
230 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
231 OPENSSL_cleanse(b->buf, b->len);
232 OPENSSL_free(b->buf);
238 * Return values are as per SSL_read()
240 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
241 int clearold, size_t *readbytes)
244 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
245 * packet by another n bytes. The packet will be in the sub-array of
246 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
247 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
248 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
249 * packet to the start of the buffer; if clearold == 0 then leave any old
250 * packets where they were
252 size_t len, left, align = 0;
257 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
261 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
262 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
263 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
267 /* start with empty packet ... */
270 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
272 * check if next packet length is large enough to justify payload
275 pkt = rb->buf + rb->offset;
276 if (pkt[0] == SSL3_RT_APPLICATION_DATA
277 && (pkt[3] << 8 | pkt[4]) >= 128) {
279 * Note that even if packet is corrupted and its length field
280 * is insane, we can only be led to wrong decision about
281 * whether memmove will occur or not. Header values has no
282 * effect on memmove arguments and therefore no buffer
283 * overrun can be triggered.
285 memmove(rb->buf + align, pkt, left);
289 rl->packet = rb->buf + rb->offset;
290 rl->packet_length = 0;
291 /* ... now we can act as if 'extend' was set */
294 len = rl->packet_length;
295 pkt = rb->buf + align;
297 * Move any available bytes to front of buffer: 'len' bytes already
298 * pointed to by 'packet', 'left' extra ones at the end
300 if (rl->packet != pkt && clearold == 1) {
301 memmove(pkt, rl->packet, len + left);
303 rb->offset = len + align;
307 * For DTLS/UDP reads should not span multiple packets because the read
308 * operation returns the whole packet at once (as long as it fits into
312 if (left == 0 && extend)
314 if (left > 0 && n > left)
318 /* if there is enough in the buffer from a previous read, take some */
320 rl->packet_length += n;
324 return OSSL_RECORD_RETURN_SUCCESS;
327 /* else we need to read more data */
329 if (n > rb->len - rb->offset) {
330 /* does not happen */
331 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
332 return OSSL_RECORD_RETURN_FATAL;
335 /* We always act like read_ahead is set for DTLS */
336 if (!rl->read_ahead && !rl->isdtls) {
337 /* ignore max parameter */
342 if (max > rb->len - rb->offset)
343 max = rb->len - rb->offset;
349 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
352 * Now we have len+left bytes at the front of rl->rbuf.buf and
353 * need to read in more until we have len + n (up to len + max if
359 ret = BIO_read(bio, pkt + len + left, max - left);
362 ret = OSSL_RECORD_RETURN_SUCCESS;
363 } else if (BIO_should_retry(bio)) {
364 if (rl->prev != NULL) {
366 * We were reading from the previous epoch. Now there is no
367 * more data, so swap to the actual transport BIO
373 ret = OSSL_RECORD_RETURN_RETRY;
374 } else if (BIO_eof(bio)) {
375 ret = OSSL_RECORD_RETURN_EOF;
377 ret = OSSL_RECORD_RETURN_FATAL;
380 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
381 ret = OSSL_RECORD_RETURN_FATAL;
384 if (ret <= OSSL_RECORD_RETURN_RETRY) {
386 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
388 tls_release_read_buffer(rl);
393 * reads should *never* span multiple packets for DTLS because the
394 * underlying transport protocol is message oriented as opposed to
395 * byte oriented as in the TLS case.
399 n = left; /* makes the while condition false */
403 /* done reading, now the book-keeping */
406 rl->packet_length += n;
408 return OSSL_RECORD_RETURN_SUCCESS;
412 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
413 * for us in the buffer.
415 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
423 p = SSL3_BUFFER_get_buf(rbuf);
427 left = SSL3_BUFFER_get_left(rbuf);
429 if (left < SSL3_RT_HEADER_LENGTH)
432 p += SSL3_BUFFER_get_offset(rbuf);
435 * We only check the type and record length, we will sanity check version
438 if (*p != SSL3_RT_APPLICATION_DATA)
444 if (left < SSL3_RT_HEADER_LENGTH + len)
450 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
451 size_t overhead, int send)
453 uint32_t max_early_data = rl->max_early_data;
455 if (max_early_data == 0) {
456 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
457 SSL_R_TOO_MUCH_EARLY_DATA);
461 /* If we are dealing with ciphertext we need to allow for the overhead */
462 max_early_data += overhead;
464 if (rl->early_data_count + length > max_early_data) {
465 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
466 SSL_R_TOO_MUCH_EARLY_DATA);
469 rl->early_data_count += length;
475 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
476 * will be processed per call to tls_get_more_records. Without this limit an
477 * attacker could send empty records at a faster rate than we can process and
478 * cause tls_get_more_records to loop forever.
480 #define MAX_EMPTY_RECORDS 32
482 #define SSL2_RT_HEADER_LENGTH 2
485 * Call this to buffer new input records in rl->rrec.
486 * It will return a OSSL_RECORD_RETURN_* value.
487 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
488 * records have been decoded. For each record 'i':
489 * rrec[i].type - is the type of record
490 * rrec[i].data, - data
491 * rrec[i].length, - number of bytes
492 * Multiple records will only be returned if the record types are all
493 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
496 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
501 SSL3_RECORD *rr, *thisrr;
504 unsigned char md[EVP_MAX_MD_SIZE];
505 unsigned int version;
508 size_t num_recs = 0, max_recs, j;
509 PACKET pkt, sslv2pkt;
510 SSL_MAC_BUF *macbufs = NULL;
511 int ret = OSSL_RECORD_RETURN_FATAL;
515 if (rbuf->buf == NULL) {
516 if (!tls_setup_read_buffer(rl)) {
517 /* RLAYERfatal() already called */
518 return OSSL_RECORD_RETURN_FATAL;
522 max_recs = rl->max_pipelines;
528 thisrr = &rr[num_recs];
530 /* check if we have the header */
531 if ((rl->rstate != SSL_ST_READ_BODY) ||
532 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
536 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
537 SSL3_BUFFER_get_len(rbuf), 0,
538 num_recs == 0 ? 1 : 0, &n);
540 if (rret < OSSL_RECORD_RETURN_SUCCESS)
541 return rret; /* error or non-blocking */
543 rl->rstate = SSL_ST_READ_BODY;
546 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
547 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
548 return OSSL_RECORD_RETURN_FATAL;
551 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
552 || !PACKET_get_1(&sslv2pkt, &type)) {
553 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
554 return OSSL_RECORD_RETURN_FATAL;
557 * The first record received by the server may be a V2ClientHello.
559 if (rl->role == OSSL_RECORD_ROLE_SERVER
560 && rl->is_first_record
561 && (sslv2len & 0x8000) != 0
562 && (type == SSL2_MT_CLIENT_HELLO)) {
566 * |num_recs| here will actually always be 0 because
567 * |num_recs > 0| only ever occurs when we are processing
568 * multiple app data records - which we know isn't the case here
569 * because it is an SSLv2ClientHello. We keep it using
570 * |num_recs| for the sake of consistency
572 thisrr->type = SSL3_RT_HANDSHAKE;
573 thisrr->rec_version = SSL2_VERSION;
575 thisrr->length = sslv2len & 0x7fff;
577 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
578 - SSL2_RT_HEADER_LENGTH) {
579 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
580 SSL_R_PACKET_LENGTH_TOO_LONG);
581 return OSSL_RECORD_RETURN_FATAL;
584 /* SSLv3+ style record */
586 /* Pull apart the header into the SSL3_RECORD */
587 if (!PACKET_get_1(&pkt, &type)
588 || !PACKET_get_net_2(&pkt, &version)
589 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
590 if (rl->msg_callback != NULL)
591 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
592 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
593 return OSSL_RECORD_RETURN_FATAL;
596 thisrr->rec_version = version;
599 * When we call validate_record_header() only records actually
600 * received in SSLv2 format should have the record version set
601 * to SSL2_VERSION. This way validate_record_header() can know
602 * what format the record was in based on the version.
604 if (thisrr->rec_version == SSL2_VERSION) {
605 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
606 SSL_R_WRONG_VERSION_NUMBER);
607 return OSSL_RECORD_RETURN_FATAL;
610 if (rl->msg_callback != NULL)
611 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
614 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
615 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
616 SSL_R_PACKET_LENGTH_TOO_LONG);
617 return OSSL_RECORD_RETURN_FATAL;
621 if (!rl->funcs->validate_record_header(rl, thisrr)) {
622 /* RLAYERfatal already called */
623 return OSSL_RECORD_RETURN_FATAL;
626 /* now rl->rstate == SSL_ST_READ_BODY */
630 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
631 * how much more data we need to read for the rest of the record
633 if (thisrr->rec_version == SSL2_VERSION) {
634 more = thisrr->length + SSL2_RT_HEADER_LENGTH
635 - SSL3_RT_HEADER_LENGTH;
637 more = thisrr->length;
641 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
643 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
644 if (rret < OSSL_RECORD_RETURN_SUCCESS)
645 return rret; /* error or non-blocking io */
648 /* set state for later operations */
649 rl->rstate = SSL_ST_READ_HEADER;
652 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
653 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
654 * + thisrr->length and we have that many bytes in rl->packet
656 if (thisrr->rec_version == SSL2_VERSION)
657 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
659 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
662 * ok, we can now read from 'rl->packet' data into 'thisrr'.
663 * thisrr->input points at thisrr->length bytes, which need to be copied
664 * into thisrr->data by either the decryption or by the decompression.
665 * When the data is 'copied' into the thisrr->data buffer,
666 * thisrr->input will be updated to point at the new buffer
670 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
671 * thisrr->length bytes of encrypted compressed stuff.
674 /* decrypt in place in 'thisrr->input' */
675 thisrr->data = thisrr->input;
676 thisrr->orig_len = thisrr->length;
680 /* we have pulled in a full packet so zero things */
681 rl->packet_length = 0;
682 rl->is_first_record = 0;
683 } while (num_recs < max_recs
684 && thisrr->type == SSL3_RT_APPLICATION_DATA
685 && RLAYER_USE_EXPLICIT_IV(rl)
686 && rl->enc_ctx != NULL
687 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
688 & EVP_CIPH_FLAG_PIPELINE) != 0
689 && tls_record_app_data_waiting(rl));
692 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
693 /* The following can happen in tlsany_meth after HRR */
694 && rl->version == TLS1_3_VERSION
695 && rl->is_first_handshake) {
697 * CCS messages must be exactly 1 byte long, containing the value 0x01
699 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
700 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
701 SSL_R_INVALID_CCS_MESSAGE);
702 return OSSL_RECORD_RETURN_FATAL;
705 * CCS messages are ignored in TLSv1.3. We treat it like an empty
708 thisrr->type = SSL3_RT_HANDSHAKE;
709 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
710 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
711 SSL_R_UNEXPECTED_CCS_MESSAGE);
712 return OSSL_RECORD_RETURN_FATAL;
716 rl->num_released = 0;
718 return OSSL_RECORD_RETURN_SUCCESS;
721 if (rl->md_ctx != NULL) {
722 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
725 imac_size = EVP_MD_get_size(tmpmd);
726 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
727 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
728 return OSSL_RECORD_RETURN_FATAL;
730 mac_size = (size_t)imac_size;
735 * If in encrypt-then-mac mode calculate mac from encrypted record. All
736 * the details below are public so no timing details can leak.
738 if (rl->use_etm && rl->md_ctx) {
741 for (j = 0; j < num_recs; j++) {
744 if (thisrr->length < mac_size) {
745 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
746 return OSSL_RECORD_RETURN_FATAL;
748 thisrr->length -= mac_size;
749 mac = thisrr->data + thisrr->length;
750 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
751 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
752 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
753 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
754 return OSSL_RECORD_RETURN_FATAL;
758 * We've handled the mac now - there is no MAC inside the encrypted
765 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
766 if (macbufs == NULL) {
767 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
768 return OSSL_RECORD_RETURN_FATAL;
772 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
776 * 0: if the record is publicly invalid, or an internal error, or AEAD
777 * decryption failed, or ETM decryption failed.
778 * 1: Success or MTE decryption failed (MAC will be randomised)
781 if (rl->alert != SSL_AD_NO_ALERT) {
782 /* RLAYERfatal() already got called */
786 && rl->skip_early_data != NULL
787 && rl->skip_early_data(rl->cbarg)) {
789 * Valid early_data that we cannot decrypt will fail here. We treat
790 * it like an empty record.
795 if (!rlayer_early_data_count_ok(rl, thisrr->length,
796 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
797 /* RLAYERfatal() already called */
804 rl->num_released = 0;
805 /* Reset the read sequence */
806 memset(rl->sequence, 0, sizeof(rl->sequence));
810 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
811 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
814 OSSL_TRACE_BEGIN(TLS) {
815 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
816 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
817 } OSSL_TRACE_END(TLS);
819 /* r->length is now the compressed data plus mac */
820 if (rl->enc_ctx != NULL
822 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
823 /* rl->md_ctx != NULL => mac_size != -1 */
825 for (j = 0; j < num_recs; j++) {
826 SSL_MAC_BUF *thismb = &macbufs[j];
830 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
831 if (i == 0 || thismb == NULL || thismb->mac == NULL
832 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
834 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
840 if (rl->alert != SSL_AD_NO_ALERT) {
841 /* We already called RLAYERfatal() */
845 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
846 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
847 * failure is directly visible from the ciphertext anyway, we should
848 * not reveal which kind of error occurred -- this might become
849 * visible to an attacker (e.g. via a logfile)
851 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
852 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
856 for (j = 0; j < num_recs; j++) {
859 if (!rl->funcs->post_process_record(rl, thisrr)) {
860 /* RLAYERfatal already called */
865 * Check if the received packet overflows the current
866 * Max Fragment Length setting.
867 * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
869 if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
870 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
876 * So at this point the following is true
877 * thisrr->type is the type of record
878 * thisrr->length == number of bytes in record
879 * thisrr->off == offset to first valid byte
880 * thisrr->data == where to take bytes from, increment after use :-).
883 /* just read a 0 length packet */
884 if (thisrr->length == 0) {
885 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
886 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
887 SSL_R_RECORD_TOO_SMALL);
891 rl->empty_record_count = 0;
895 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
897 if (thisrr->type == SSL3_RT_APPLICATION_DATA
898 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
899 /* RLAYERfatal already called */
904 rl->num_recs = num_recs;
906 rl->num_released = 0;
907 ret = OSSL_RECORD_RETURN_SUCCESS;
909 if (macbufs != NULL) {
910 for (j = 0; j < num_recs; j++) {
911 if (macbufs[j].alloced)
912 OPENSSL_free(macbufs[j].mac);
914 OPENSSL_free(macbufs);
919 /* Shared by ssl3_meth and tls1_meth */
920 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
922 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
924 if (rec->rec_version != rl->version) {
925 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
929 #ifndef OPENSSL_NO_COMP
931 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
932 * does not include the compression overhead anyway.
934 if (rl->expand == NULL)
935 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
938 if (rec->length > len) {
939 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
940 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
947 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
949 #ifndef OPENSSL_NO_COMP
952 if (rec->comp == NULL) {
953 rec->comp = (unsigned char *)
954 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
956 if (rec->comp == NULL)
959 i = COMP_expand_block(rl->expand, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
960 rec->data, (int)rec->length);
965 rec->data = rec->comp;
972 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
973 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
975 if (rl->expand != NULL) {
976 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
977 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
978 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
981 if (!tls_do_uncompress(rl, rec)) {
982 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
983 SSL_R_BAD_DECOMPRESSION);
988 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
989 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
996 /* Shared by tls13_meth and ktls_meth */
997 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
999 if (rec->type != SSL3_RT_APPLICATION_DATA
1000 && rec->type != SSL3_RT_ALERT
1001 && rec->type != SSL3_RT_HANDSHAKE) {
1002 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1006 if (rl->msg_callback != NULL)
1007 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
1011 * TLSv1.3 alert and handshake records are required to be non-zero in
1014 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1015 && rec->length == 0) {
1016 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1023 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1024 int *type, unsigned char **data, size_t *datalen,
1025 uint16_t *epoch, unsigned char *seq_num)
1030 * tls_get_more_records() can return success without actually reading
1031 * anything useful (i.e. if empty records are read). We loop here until
1032 * we have something useful. tls_get_more_records() will eventually fail if
1033 * too many sequential empty records are read.
1035 while (rl->curr_rec >= rl->num_recs) {
1038 if (rl->num_released != rl->num_recs) {
1039 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1040 return OSSL_RECORD_RETURN_FATAL;
1043 ret = rl->funcs->get_more_records(rl);
1045 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1050 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1051 * points to the next one to read.
1053 rec = &rl->rrec[rl->curr_rec++];
1056 *rversion = rec->rec_version;
1058 *data = rec->data + rec->off;
1059 *datalen = rec->length;
1061 *epoch = rec->epoch;
1062 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1065 return OSSL_RECORD_RETURN_SUCCESS;
1068 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
1070 if (!ossl_assert(rl->num_released < rl->curr_rec)
1071 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
1072 /* Should not happen */
1073 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1074 return OSSL_RECORD_RETURN_FATAL;
1079 if (rl->curr_rec == rl->num_released
1080 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1081 && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
1082 tls_release_read_buffer(rl);
1084 return OSSL_RECORD_RETURN_SUCCESS;
1087 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1089 const OSSL_PARAM *p;
1091 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1092 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1093 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1097 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1098 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1099 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1103 p = OSSL_PARAM_locate_const(options,
1104 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1105 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1106 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1110 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1112 * We ignore any read_ahead setting prior to the application protection
1113 * level. Otherwise we may read ahead data in a lower protection level
1114 * that is destined for a higher protection level. To simplify the logic
1115 * we don't support that at this stage.
1117 p = OSSL_PARAM_locate_const(options,
1118 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1119 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1120 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1129 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1130 int role, int direction, int level, unsigned char *key,
1131 size_t keylen, unsigned char *iv, size_t ivlen,
1132 unsigned char *mackey, size_t mackeylen,
1133 const EVP_CIPHER *ciph, size_t taglen,
1135 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1136 BIO *transport, BIO *next, BIO_ADDR *local,
1137 BIO_ADDR *peer, const OSSL_PARAM *settings,
1138 const OSSL_PARAM *options,
1139 const OSSL_DISPATCH *fns, void *cbarg,
1140 OSSL_RECORD_LAYER **retrl)
1142 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1143 const OSSL_PARAM *p;
1148 ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
1149 return OSSL_RECORD_RETURN_FATAL;
1152 /* Loop through all the settings since they must all be understood */
1153 if (settings != NULL) {
1154 for (p = settings; p->key != NULL; p++) {
1155 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1156 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1157 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1160 } else if (strcmp(p->key,
1161 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1162 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1163 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1166 } else if (strcmp(p->key,
1167 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1168 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1169 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1172 } else if (strcmp(p->key,
1173 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1174 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1175 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1178 } else if (strcmp(p->key,
1179 OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1180 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1181 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1185 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1191 rl->libctx = libctx;
1196 rl->direction = direction;
1199 rl->alert = SSL_AD_NO_ALERT;
1201 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1202 rl->is_first_record = 1;
1204 if (!tls_set1_bio(rl, transport))
1207 if (prev != NULL && !BIO_up_ref(prev))
1211 if (next != NULL && !BIO_up_ref(next))
1217 for (; fns->function_id != 0; fns++) {
1218 switch (fns->function_id) {
1219 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1220 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1222 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1223 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1225 case OSSL_FUNC_RLAYER_SECURITY:
1226 rl->security = OSSL_FUNC_rlayer_security(fns);
1229 /* Just ignore anything we don't understand */
1235 if (!tls_set_options(rl, options)) {
1236 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1241 return OSSL_RECORD_RETURN_SUCCESS;
1244 return OSSL_RECORD_RETURN_FATAL;
1248 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1249 int role, int direction, int level, uint16_t epoch,
1250 unsigned char *key, size_t keylen, unsigned char *iv,
1251 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1252 const EVP_CIPHER *ciph, size_t taglen,
1254 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1255 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1256 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1257 const OSSL_DISPATCH *fns, void *cbarg,
1258 OSSL_RECORD_LAYER **retrl)
1262 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1263 key, keylen, iv, ivlen, mackey, mackeylen,
1264 ciph, taglen, mactype, md, comp, prev,
1265 transport, next, local, peer, settings,
1266 options, fns, cbarg, retrl);
1268 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1272 case TLS_ANY_VERSION:
1273 (*retrl)->funcs = &tls_any_funcs;
1275 case TLS1_3_VERSION:
1276 (*retrl)->funcs = &tls_1_3_funcs;
1278 case TLS1_2_VERSION:
1279 case TLS1_1_VERSION:
1281 (*retrl)->funcs = &tls_1_funcs;
1284 (*retrl)->funcs = &ssl_3_0_funcs;
1287 /* Should not happen */
1288 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1289 ret = OSSL_RECORD_RETURN_FATAL;
1293 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1294 ivlen, mackey, mackeylen, ciph,
1295 taglen, mactype, md, comp);
1298 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1299 OPENSSL_free(*retrl);
1305 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1310 SSL3_BUFFER_release(&rl->rbuf);
1312 tls_release_write_buffer(rl);
1314 EVP_CIPHER_CTX_free(rl->enc_ctx);
1315 EVP_MD_CTX_free(rl->md_ctx);
1316 #ifndef OPENSSL_NO_COMP
1317 COMP_CTX_free(rl->expand);
1320 if (rl->version == SSL3_VERSION)
1321 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1323 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1328 int tls_free(OSSL_RECORD_LAYER *rl)
1331 size_t left, written;
1336 left = SSL3_BUFFER_get_left(rbuf);
1339 * This record layer is closing but we still have data left in our
1340 * buffer. It must be destined for the next epoch - so push it there.
1342 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1349 int tls_reset(OSSL_RECORD_LAYER *rl)
1351 memset(rl, 0, sizeof(*rl));
1355 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1357 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1360 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1362 return rl->curr_rec < rl->num_recs;
1365 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1370 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1371 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1373 num += rl->rrec[i].length;
1378 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1383 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1388 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1393 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1396 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1397 SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1399 SSL3_RECORD *thiswr;
1400 unsigned char *recordstart;
1401 int mac_size, clear = 0;
1406 size_t totlen = 0, len, wpinited = 0;
1407 size_t j, prefix = 0;
1409 /* TODO(RECLAYER): REMOVE ME */
1410 SSL_CONNECTION *s = rl->cbarg;
1411 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1412 OSSL_RECORD_TEMPLATE prefixtempl;
1413 OSSL_RECORD_TEMPLATE *thistempl;
1415 /* Check we don't have pending data waiting to write */
1416 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1417 || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1418 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1425 || (s->enc_write_ctx == NULL)
1426 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
1427 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
1430 mac_size = EVP_MD_CTX_get_size(s->write_hash);
1432 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1438 * 'create_empty_fragment' is true only when we have recursively called
1440 * Do we need to do that recursion in order to add an empty record prefix?
1442 prefix = s->s3.need_empty_fragments
1444 && !s->s3.empty_fragment_done
1445 && templates[0].type == SSL3_RT_APPLICATION_DATA;
1447 if (rl->numwpipes < numtempl + prefix) {
1449 * TODO(RECLAYER): In the prefix case the first buffer can be a lot
1450 * smaller. It is wasteful to allocate a full sized buffer here
1452 if (!tls_setup_write_buffer(rl, numtempl + prefix, 0)) {
1453 /* SSLfatal() already called */
1458 using_ktls = BIO_get_ktls_send(rl->bio);
1459 if (!ossl_assert(!using_ktls || !prefix)) {
1460 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1466 * countermeasure against known-IV weakness in CBC ciphersuites (see
1467 * http://www.openssl.org/~bodo/tls-cbc.txt)
1469 prefixtempl.buf = NULL;
1470 prefixtempl.buflen = 0;
1471 prefixtempl.type = SSL3_RT_APPLICATION_DATA;
1474 /* TODO(RECLAYER): Do we actually need this? */
1475 s->s3.empty_fragment_done = 1;
1478 /* TODO(RECLAYER): This alignment calculation no longer seems right */
1479 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
1481 * extra fragment would be couple of cipher blocks, which would be
1482 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
1483 * payload, then we can just pretend we simply have two headers.
1485 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
1486 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1488 SSL3_BUFFER_set_offset(wb, align);
1489 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
1490 SSL3_BUFFER_get_len(wb), 0)
1491 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
1492 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1497 for (j = 0; j < numtempl; j++) {
1498 thispkt = &pkt[prefix + j];
1500 wb = &rl->wbuf[prefix + j];
1501 wb->type = templates[j].type;
1505 * ktls doesn't modify the buffer, but to avoid a warning we need
1506 * to discard the const qualifier.
1507 * This doesn't leak memory because the buffers have been
1508 * released when switching to ktls.
1510 SSL3_BUFFER_set_buf(wb, (unsigned char *)templates[j].buf);
1511 SSL3_BUFFER_set_offset(wb, 0);
1512 SSL3_BUFFER_set_app_buffer(wb, 1);
1514 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1515 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
1516 align = SSL3_ALIGN_PAYLOAD - 1
1517 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1519 /* TODO(RECLAYER): Is this alignment actually used somewhere? */
1520 SSL3_BUFFER_set_offset(wb, align);
1521 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1522 SSL3_BUFFER_get_len(wb), 0)
1523 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
1524 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1532 /* Explicit IV length, block ciphers appropriate version flag */
1533 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
1534 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
1535 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
1536 if (mode == EVP_CIPH_CBC_MODE) {
1537 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
1539 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
1544 } else if (mode == EVP_CIPH_GCM_MODE) {
1545 /* Need explicit part of IV for GCM mode */
1546 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
1547 } else if (mode == EVP_CIPH_CCM_MODE) {
1548 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
1554 /* Clear our SSL3_RECORD structures */
1555 memset(wr, 0, sizeof(wr));
1556 for (j = 0; j < numtempl + prefix; j++) {
1557 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
1559 unsigned char *compressdata = NULL;
1561 unsigned int rectype;
1565 thistempl = (j == 0 && prefix == 1) ? &prefixtempl :
1566 &templates[j - prefix];
1569 * In TLSv1.3, once encrypting, we always use application data for the
1572 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
1573 && s->enc_write_ctx != NULL
1574 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1575 || thistempl->type != SSL3_RT_ALERT))
1576 rectype = SSL3_RT_APPLICATION_DATA;
1578 rectype = thistempl->type;
1580 SSL3_RECORD_set_type(thiswr, rectype);
1583 * Some servers hang if initial client hello is larger than 256 bytes
1584 * and record version number > TLS 1.0
1586 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
1588 && TLS1_get_version(ssl) > TLS1_VERSION
1589 && s->hello_retry_request == SSL_HRR_NONE)
1590 version = TLS1_VERSION;
1591 SSL3_RECORD_set_rec_version(thiswr, version);
1593 maxcomplen = thistempl->buflen;
1594 if (s->compress != NULL)
1595 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1598 * When using offload kernel will write the header.
1599 * Otherwise write the header now
1602 && (!WPACKET_put_bytes_u8(thispkt, rectype)
1603 || !WPACKET_put_bytes_u16(thispkt, version)
1604 || !WPACKET_start_sub_packet_u16(thispkt)
1606 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
1608 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1610 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1614 /* lets setup the record stuff. */
1615 SSL3_RECORD_set_data(thiswr, compressdata);
1616 SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1618 * TODO(RECLAYER): Cast away the const. Should be safe - by why is this
1621 SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1622 totlen += thistempl->buflen;
1625 * we now 'read' from thiswr->input, thiswr->length bytes into
1629 /* first we compress */
1630 if (s->compress != NULL) {
1631 if (!ssl3_do_compress(s, thiswr)
1632 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1633 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1638 SSL3_RECORD_reset_data(&wr[j]);
1640 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1641 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1644 SSL3_RECORD_reset_input(&wr[j]);
1648 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
1650 && s->enc_write_ctx != NULL
1651 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1652 || thistempl->type != SSL3_RT_ALERT)) {
1653 size_t rlen, max_send_fragment;
1655 if (!WPACKET_put_bytes_u8(thispkt, thistempl->type)) {
1656 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1659 SSL3_RECORD_add_length(thiswr, 1);
1661 /* Add TLS1.3 padding */
1662 max_send_fragment = ssl_get_max_send_fragment(s);
1663 rlen = SSL3_RECORD_get_length(thiswr);
1664 if (rlen < max_send_fragment) {
1666 size_t max_padding = max_send_fragment - rlen;
1667 if (s->record_padding_cb != NULL) {
1668 padding = s->record_padding_cb(ssl, thistempl->type, rlen,
1669 s->record_padding_arg);
1670 } else if (s->block_padding > 0) {
1671 size_t mask = s->block_padding - 1;
1674 /* optimize for power of 2 */
1675 if ((s->block_padding & mask) == 0)
1676 remainder = rlen & mask;
1678 remainder = rlen % s->block_padding;
1679 /* don't want to add a block of padding if we don't have to */
1683 padding = s->block_padding - remainder;
1686 /* do not allow the record to exceed max plaintext length */
1687 if (padding > max_padding)
1688 padding = max_padding;
1689 if (!WPACKET_memset(thispkt, 0, padding)) {
1690 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1691 ERR_R_INTERNAL_ERROR);
1694 SSL3_RECORD_add_length(thiswr, padding);
1700 * we should still have the output to thiswr->data and the input from
1701 * wr->input. Length should be thiswr->length. thiswr->data still points
1705 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
1708 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1709 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1710 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1716 * Reserve some bytes for any growth that may occur during encryption.
1717 * This will be at most one cipher block or the tag length if using
1718 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1721 if (!WPACKET_reserve_bytes(thispkt,
1722 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1725 * We also need next the amount of bytes written to this
1728 || !WPACKET_get_length(thispkt, &len)) {
1729 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1733 /* Get a pointer to the start of this record excluding header */
1734 recordstart = WPACKET_get_curr(thispkt) - len;
1735 SSL3_RECORD_set_data(thiswr, recordstart);
1736 SSL3_RECORD_reset_input(thiswr);
1737 SSL3_RECORD_set_length(thiswr, len);
1741 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
1743 * We haven't actually negotiated the version yet, but we're trying to
1744 * send early data - so we need to use the tls13enc function.
1746 if (tls13_enc(s, wr, numtempl, 1, NULL, mac_size) < 1) {
1747 if (!ossl_statem_in_error(s)) {
1748 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1755 if (ssl->method->ssl3_enc->enc(s, wr, 1, 1, NULL, mac_size) < 1) {
1756 if (!ossl_statem_in_error(s)) {
1757 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1762 if (ssl->method->ssl3_enc->enc(s, wr + prefix, numtempl, 1, NULL,
1764 if (!ossl_statem_in_error(s)) {
1765 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1772 for (j = 0; j < prefix + numtempl; j++) {
1777 thistempl = (prefix == 1 && j == 0) ? &prefixtempl
1778 : &templates[j - prefix];
1783 /* Allocate bytes for the encryption overhead */
1784 if (!WPACKET_get_length(thispkt, &origlen)
1785 /* Encryption should never shrink the data! */
1786 || origlen > thiswr->length
1787 || (thiswr->length > origlen
1788 && !WPACKET_allocate_bytes(thispkt,
1789 thiswr->length - origlen,
1791 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1794 if (SSL_WRITE_ETM(s) && mac_size != 0) {
1797 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1798 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1799 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1802 SSL3_RECORD_add_length(thiswr, mac_size);
1805 if (!WPACKET_get_length(thispkt, &len)
1806 || !WPACKET_close(thispkt)) {
1807 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1811 if (rl->msg_callback) {
1812 recordstart = WPACKET_get_curr(thispkt) - len
1813 - SSL3_RT_HEADER_LENGTH;
1814 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1815 SSL3_RT_HEADER_LENGTH, rl->cbarg);
1817 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
1818 unsigned char ctype = thistempl->type;
1820 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1821 &ctype, 1, rl->cbarg);
1825 if (!WPACKET_finish(thispkt)) {
1826 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1830 /* header is added by the kernel when using offload */
1831 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1835 * we should now have thiswr->data pointing to the encrypted data, which
1836 * is thiswr->length long.
1837 * Setting the type is not needed but helps for debugging
1839 SSL3_RECORD_set_type(thiswr, thistempl->type);
1841 /* now let's set up wb */
1842 SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
1846 /* we now just need to write the buffers */
1847 return tls_retry_write_records(rl);
1849 for (j = 0; j < wpinited; j++)
1850 WPACKET_cleanup(&pkt[j]);
1854 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1856 * Return values are as per SSL_write()
1858 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1861 SSL3_BUFFER *thiswb;
1863 SSL_CONNECTION *s = rl->cbarg;
1865 if (rl->nextwbuf >= rl->numwpipes)
1869 thiswb = &rl->wbuf[rl->nextwbuf];
1872 if (rl->bio != NULL) {
1873 s->rwstate = SSL_WRITING;
1876 * To prevent coalescing of control and data messages,
1877 * such as in buffer_write, we flush the BIO
1879 if (BIO_get_ktls_send(rl->bio)
1880 && thiswb->type != SSL3_RT_APPLICATION_DATA) {
1881 i = BIO_flush(rl->bio);
1884 BIO_set_ktls_ctrl_msg(rl->bio, thiswb->type);
1886 i = BIO_write(rl->bio, (char *)
1887 &(SSL3_BUFFER_get_buf(thiswb)
1888 [SSL3_BUFFER_get_offset(thiswb)]),
1889 (unsigned int)SSL3_BUFFER_get_left(thiswb));
1893 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1898 * When an empty fragment is sent on a connection using KTLS,
1899 * it is sent as a write of zero bytes. If this zero byte
1900 * write succeeds, i will be 0 rather than a non-zero value.
1901 * Treat i == 0 as success rather than an error for zero byte
1902 * writes to permit this case.
1904 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1905 SSL3_BUFFER_set_left(thiswb, 0);
1906 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1907 if (++(rl->nextwbuf) < rl->numwpipes)
1909 s->rwstate = SSL_NOTHING;
1911 * Next chunk of data should get another prepended empty fragment
1912 * in ciphersuites with known-IV weakness:
1914 s->s3.empty_fragment_done = 0;
1916 if (rl->nextwbuf == rl->numwpipes
1917 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1918 tls_release_write_buffer(rl);
1921 } else if (i <= 0) {
1922 if (SSL_CONNECTION_IS_DTLS(s)) {
1924 * For DTLS, just drop it. That's kind of the whole point in
1925 * using a datagram service
1927 SSL3_BUFFER_set_left(thiswb, 0);
1928 if (++(rl->nextwbuf) == rl->numwpipes
1929 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1930 tls_release_write_buffer(rl);
1935 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1936 SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1940 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1945 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1947 if (bio != NULL && !BIO_up_ref(bio))
1955 /* Shared by most methods except tlsany_meth */
1956 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1958 if (rl->version != version)
1964 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1966 return rl->funcs->set_protocol_version(rl, version);
1969 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1971 rl->allow_plain_alerts = allow;
1974 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1976 rl->is_first_handshake = first;
1979 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1981 rl->max_pipelines = max_pipelines;
1982 if (max_pipelines > 1)
1986 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1987 const char **longstr)
1989 const char *shrt, *lng;
1991 switch (rl->rstate) {
1992 case SSL_ST_READ_HEADER:
1994 lng = "read header";
1996 case SSL_ST_READ_BODY:
2001 shrt = lng = "unknown";
2004 if (shortstr != NULL)
2006 if (longstr != NULL)
2010 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2011 tls_new_record_layer,
2014 tls_unprocessed_read_pending,
2015 tls_processed_read_pending,
2016 tls_app_data_pending,
2018 tls_get_max_record_len,
2019 tls_get_max_records,
2021 tls_retry_write_records,
2026 tls_set_protocol_version,
2027 tls_set_plain_alerts,
2028 tls_set_first_handshake,
2029 tls_set_max_pipelines,