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 "internal/e_os.h"
16 #include "internal/packet.h"
17 #include "../../ssl_local.h"
18 #include "../record_local.h"
19 #include "recmethod_local.h"
21 static void tls_int_free(OSSL_RECORD_LAYER *rl);
23 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
29 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
35 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
37 const EVP_CIPHER *ciph,
41 * Provided cipher, the TLS padding/MAC removal is performed provider
42 * side so we need to tell the ctx about our TLS version and mac size
44 OSSL_PARAM params[3], *pprm = params;
48 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
50 imacsize = EVP_MD_get_size(md);
52 macsize = (size_t)imacsize;
54 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
56 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
58 *pprm = OSSL_PARAM_construct_end();
60 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
61 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
69 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
70 * which ssl3_cbc_digest_record supports.
72 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
74 switch (EVP_MD_CTX_get_type(ctx)) {
87 #ifndef OPENSSL_NO_COMP
88 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
90 if (rl->options & SSL_OP_NO_COMPRESSION)
93 return rl->security == NULL
94 || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
98 static int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
102 size_t align = 0, headerlen;
105 SSL_CONNECTION *s = (SSL_CONNECTION *)rl->cbarg;
107 rl->numwpipes = numwpipes;
110 if (SSL_CONNECTION_IS_DTLS(s))
111 headerlen = DTLS1_RT_HEADER_LENGTH + 1;
113 headerlen = SSL3_RT_HEADER_LENGTH;
115 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
116 align = SSL3_ALIGN_PAYLOAD - 1;
119 len = ssl_get_max_send_fragment(s)
120 + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
121 #ifndef OPENSSL_NO_COMP
122 if (ssl_allow_compression(s))
123 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
125 if (!(rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
126 len += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
130 for (currpipe = 0; currpipe < numwpipes; currpipe++) {
131 SSL3_BUFFER *thiswb = &wb[currpipe];
133 if (thiswb->len != len) {
134 OPENSSL_free(thiswb->buf);
135 thiswb->buf = NULL; /* force reallocation */
138 if (thiswb->buf == NULL) {
139 if (s->wbio == NULL || !BIO_get_ktls_send(s->wbio)) {
140 p = OPENSSL_malloc(len);
142 rl->numwpipes = currpipe;
144 * We've got a malloc failure, and we're still initialising
145 * buffers. We assume we're so doomed that we won't even be able
148 SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
154 memset(thiswb, 0, sizeof(SSL3_BUFFER));
163 static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
168 pipes = rl->numwpipes;
171 wb = &rl->wbuf[pipes - 1];
173 if (SSL3_BUFFER_is_app_buffer(wb))
174 SSL3_BUFFER_set_app_buffer(wb, 0);
176 OPENSSL_free(wb->buf);
184 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
187 size_t len, align = 0, headerlen;
193 headerlen = DTLS1_RT_HEADER_LENGTH;
195 headerlen = SSL3_RT_HEADER_LENGTH;
197 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
198 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
201 if (b->buf == NULL) {
202 len = SSL3_RT_MAX_PLAIN_LENGTH
203 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
204 #ifndef OPENSSL_NO_COMP
205 if (tls_allow_compression(rl))
206 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
208 if (b->default_len > len)
209 len = b->default_len;
210 if ((p = OPENSSL_malloc(len)) == NULL) {
212 * We've got a malloc failure, and we're still initialising buffers.
213 * We assume we're so doomed that we won't even be able to send an
216 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
226 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
231 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
232 OPENSSL_cleanse(b->buf, b->len);
233 OPENSSL_free(b->buf);
239 * Return values are as per SSL_read()
241 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
242 int clearold, size_t *readbytes)
245 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
246 * packet by another n bytes. The packet will be in the sub-array of
247 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
248 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
249 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
250 * packet to the start of the buffer; if clearold == 0 then leave any old
251 * packets where they were
253 size_t len, left, align = 0;
258 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
262 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
263 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
264 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
268 /* start with empty packet ... */
271 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
273 * check if next packet length is large enough to justify payload
276 pkt = rb->buf + rb->offset;
277 if (pkt[0] == SSL3_RT_APPLICATION_DATA
278 && (pkt[3] << 8 | pkt[4]) >= 128) {
280 * Note that even if packet is corrupted and its length field
281 * is insane, we can only be led to wrong decision about
282 * whether memmove will occur or not. Header values has no
283 * effect on memmove arguments and therefore no buffer
284 * overrun can be triggered.
286 memmove(rb->buf + align, pkt, left);
290 rl->packet = rb->buf + rb->offset;
291 rl->packet_length = 0;
292 /* ... now we can act as if 'extend' was set */
295 len = rl->packet_length;
296 pkt = rb->buf + align;
298 * Move any available bytes to front of buffer: 'len' bytes already
299 * pointed to by 'packet', 'left' extra ones at the end
301 if (rl->packet != pkt && clearold == 1) {
302 memmove(pkt, rl->packet, len + left);
304 rb->offset = len + align;
308 * For DTLS/UDP reads should not span multiple packets because the read
309 * operation returns the whole packet at once (as long as it fits into
313 if (left == 0 && extend)
315 if (left > 0 && n > left)
319 /* if there is enough in the buffer from a previous read, take some */
321 rl->packet_length += n;
325 return OSSL_RECORD_RETURN_SUCCESS;
328 /* else we need to read more data */
330 if (n > rb->len - rb->offset) {
331 /* does not happen */
332 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
333 return OSSL_RECORD_RETURN_FATAL;
336 /* We always act like read_ahead is set for DTLS */
337 if (!rl->read_ahead && !rl->isdtls) {
338 /* ignore max parameter */
343 if (max > rb->len - rb->offset)
344 max = rb->len - rb->offset;
350 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
353 * Now we have len+left bytes at the front of rl->rbuf.buf and
354 * need to read in more until we have len + n (up to len + max if
360 ret = BIO_read(bio, pkt + len + left, max - left);
363 ret = OSSL_RECORD_RETURN_SUCCESS;
364 } else if (BIO_should_retry(bio)) {
365 if (rl->prev != NULL) {
367 * We were reading from the previous epoch. Now there is no
368 * more data, so swap to the actual transport BIO
374 ret = OSSL_RECORD_RETURN_RETRY;
375 } else if (BIO_eof(bio)) {
376 ret = OSSL_RECORD_RETURN_EOF;
378 ret = OSSL_RECORD_RETURN_FATAL;
381 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
382 ret = OSSL_RECORD_RETURN_FATAL;
385 if (ret <= OSSL_RECORD_RETURN_RETRY) {
387 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
389 tls_release_read_buffer(rl);
394 * reads should *never* span multiple packets for DTLS because the
395 * underlying transport protocol is message oriented as opposed to
396 * byte oriented as in the TLS case.
400 n = left; /* makes the while condition false */
404 /* done reading, now the book-keeping */
407 rl->packet_length += n;
409 return OSSL_RECORD_RETURN_SUCCESS;
413 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
414 * for us in the buffer.
416 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
424 p = SSL3_BUFFER_get_buf(rbuf);
428 left = SSL3_BUFFER_get_left(rbuf);
430 if (left < SSL3_RT_HEADER_LENGTH)
433 p += SSL3_BUFFER_get_offset(rbuf);
436 * We only check the type and record length, we will sanity check version
439 if (*p != SSL3_RT_APPLICATION_DATA)
445 if (left < SSL3_RT_HEADER_LENGTH + len)
451 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
452 size_t overhead, int send)
454 uint32_t max_early_data = rl->max_early_data;
456 if (max_early_data == 0) {
457 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
458 SSL_R_TOO_MUCH_EARLY_DATA);
462 /* If we are dealing with ciphertext we need to allow for the overhead */
463 max_early_data += overhead;
465 if (rl->early_data_count + length > max_early_data) {
466 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
467 SSL_R_TOO_MUCH_EARLY_DATA);
470 rl->early_data_count += length;
476 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
477 * will be processed per call to tls_get_more_records. Without this limit an
478 * attacker could send empty records at a faster rate than we can process and
479 * cause tls_get_more_records to loop forever.
481 #define MAX_EMPTY_RECORDS 32
483 #define SSL2_RT_HEADER_LENGTH 2
486 * Call this to buffer new input records in rl->rrec.
487 * It will return a OSSL_RECORD_RETURN_* value.
488 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
489 * records have been decoded. For each record 'i':
490 * rrec[i].type - is the type of record
491 * rrec[i].data, - data
492 * rrec[i].length, - number of bytes
493 * Multiple records will only be returned if the record types are all
494 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
497 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
502 SSL3_RECORD *rr, *thisrr;
505 unsigned char md[EVP_MAX_MD_SIZE];
506 unsigned int version;
509 size_t num_recs = 0, max_recs, j;
510 PACKET pkt, sslv2pkt;
511 SSL_MAC_BUF *macbufs = NULL;
512 int ret = OSSL_RECORD_RETURN_FATAL;
516 if (rbuf->buf == NULL) {
517 if (!tls_setup_read_buffer(rl)) {
518 /* RLAYERfatal() already called */
519 return OSSL_RECORD_RETURN_FATAL;
523 max_recs = rl->max_pipelines;
529 thisrr = &rr[num_recs];
531 /* check if we have the header */
532 if ((rl->rstate != SSL_ST_READ_BODY) ||
533 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
537 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
538 SSL3_BUFFER_get_len(rbuf), 0,
539 num_recs == 0 ? 1 : 0, &n);
541 if (rret < OSSL_RECORD_RETURN_SUCCESS)
542 return rret; /* error or non-blocking */
544 rl->rstate = SSL_ST_READ_BODY;
547 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
548 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
549 return OSSL_RECORD_RETURN_FATAL;
552 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
553 || !PACKET_get_1(&sslv2pkt, &type)) {
554 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
555 return OSSL_RECORD_RETURN_FATAL;
558 * The first record received by the server may be a V2ClientHello.
560 if (rl->role == OSSL_RECORD_ROLE_SERVER
561 && rl->is_first_record
562 && (sslv2len & 0x8000) != 0
563 && (type == SSL2_MT_CLIENT_HELLO)) {
567 * |num_recs| here will actually always be 0 because
568 * |num_recs > 0| only ever occurs when we are processing
569 * multiple app data records - which we know isn't the case here
570 * because it is an SSLv2ClientHello. We keep it using
571 * |num_recs| for the sake of consistency
573 thisrr->type = SSL3_RT_HANDSHAKE;
574 thisrr->rec_version = SSL2_VERSION;
576 thisrr->length = sslv2len & 0x7fff;
578 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
579 - SSL2_RT_HEADER_LENGTH) {
580 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
581 SSL_R_PACKET_LENGTH_TOO_LONG);
582 return OSSL_RECORD_RETURN_FATAL;
585 /* SSLv3+ style record */
587 /* Pull apart the header into the SSL3_RECORD */
588 if (!PACKET_get_1(&pkt, &type)
589 || !PACKET_get_net_2(&pkt, &version)
590 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
591 if (rl->msg_callback != NULL)
592 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
593 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
594 return OSSL_RECORD_RETURN_FATAL;
597 thisrr->rec_version = version;
600 * When we call validate_record_header() only records actually
601 * received in SSLv2 format should have the record version set
602 * to SSL2_VERSION. This way validate_record_header() can know
603 * what format the record was in based on the version.
605 if (thisrr->rec_version == SSL2_VERSION) {
606 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
607 SSL_R_WRONG_VERSION_NUMBER);
608 return OSSL_RECORD_RETURN_FATAL;
611 if (rl->msg_callback != NULL)
612 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
615 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
616 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
617 SSL_R_PACKET_LENGTH_TOO_LONG);
618 return OSSL_RECORD_RETURN_FATAL;
622 if (!rl->funcs->validate_record_header(rl, thisrr)) {
623 /* RLAYERfatal already called */
624 return OSSL_RECORD_RETURN_FATAL;
627 /* now rl->rstate == SSL_ST_READ_BODY */
631 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
632 * how much more data we need to read for the rest of the record
634 if (thisrr->rec_version == SSL2_VERSION) {
635 more = thisrr->length + SSL2_RT_HEADER_LENGTH
636 - SSL3_RT_HEADER_LENGTH;
638 more = thisrr->length;
642 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
644 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
645 if (rret < OSSL_RECORD_RETURN_SUCCESS)
646 return rret; /* error or non-blocking io */
649 /* set state for later operations */
650 rl->rstate = SSL_ST_READ_HEADER;
653 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
654 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
655 * + thisrr->length and we have that many bytes in rl->packet
657 if (thisrr->rec_version == SSL2_VERSION)
658 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
660 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
663 * ok, we can now read from 'rl->packet' data into 'thisrr'.
664 * thisrr->input points at thisrr->length bytes, which need to be copied
665 * into thisrr->data by either the decryption or by the decompression.
666 * When the data is 'copied' into the thisrr->data buffer,
667 * thisrr->input will be updated to point at the new buffer
671 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
672 * thisrr->length bytes of encrypted compressed stuff.
675 /* decrypt in place in 'thisrr->input' */
676 thisrr->data = thisrr->input;
677 thisrr->orig_len = thisrr->length;
681 /* we have pulled in a full packet so zero things */
682 rl->packet_length = 0;
683 rl->is_first_record = 0;
684 } while (num_recs < max_recs
685 && thisrr->type == SSL3_RT_APPLICATION_DATA
686 && RLAYER_USE_EXPLICIT_IV(rl)
687 && rl->enc_ctx != NULL
688 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
689 & EVP_CIPH_FLAG_PIPELINE) != 0
690 && tls_record_app_data_waiting(rl));
693 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
694 /* The following can happen in tlsany_meth after HRR */
695 && rl->version == TLS1_3_VERSION
696 && rl->is_first_handshake) {
698 * CCS messages must be exactly 1 byte long, containing the value 0x01
700 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
701 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
702 SSL_R_INVALID_CCS_MESSAGE);
703 return OSSL_RECORD_RETURN_FATAL;
706 * CCS messages are ignored in TLSv1.3. We treat it like an empty
709 thisrr->type = SSL3_RT_HANDSHAKE;
710 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
711 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
712 SSL_R_UNEXPECTED_CCS_MESSAGE);
713 return OSSL_RECORD_RETURN_FATAL;
717 rl->num_released = 0;
719 return OSSL_RECORD_RETURN_SUCCESS;
722 if (rl->md_ctx != NULL) {
723 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
726 imac_size = EVP_MD_get_size(tmpmd);
727 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
728 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
729 return OSSL_RECORD_RETURN_FATAL;
731 mac_size = (size_t)imac_size;
736 * If in encrypt-then-mac mode calculate mac from encrypted record. All
737 * the details below are public so no timing details can leak.
739 if (rl->use_etm && rl->md_ctx) {
742 for (j = 0; j < num_recs; j++) {
745 if (thisrr->length < mac_size) {
746 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
747 return OSSL_RECORD_RETURN_FATAL;
749 thisrr->length -= mac_size;
750 mac = thisrr->data + thisrr->length;
751 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
752 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
753 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
754 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
755 return OSSL_RECORD_RETURN_FATAL;
759 * We've handled the mac now - there is no MAC inside the encrypted
766 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
767 if (macbufs == NULL) {
768 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
769 return OSSL_RECORD_RETURN_FATAL;
773 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
777 * 0: if the record is publicly invalid, or an internal error, or AEAD
778 * decryption failed, or ETM decryption failed.
779 * 1: Success or MTE decryption failed (MAC will be randomised)
782 if (rl->alert != SSL_AD_NO_ALERT) {
783 /* RLAYERfatal() already got called */
787 && rl->skip_early_data != NULL
788 && rl->skip_early_data(rl->cbarg)) {
790 * Valid early_data that we cannot decrypt will fail here. We treat
791 * it like an empty record.
796 if (!rlayer_early_data_count_ok(rl, thisrr->length,
797 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
798 /* RLAYERfatal() already called */
805 rl->num_released = 0;
806 /* Reset the read sequence */
807 memset(rl->sequence, 0, sizeof(rl->sequence));
811 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
812 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
815 OSSL_TRACE_BEGIN(TLS) {
816 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
817 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
818 } OSSL_TRACE_END(TLS);
820 /* r->length is now the compressed data plus mac */
821 if (rl->enc_ctx != NULL
823 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
824 /* rl->md_ctx != NULL => mac_size != -1 */
826 for (j = 0; j < num_recs; j++) {
827 SSL_MAC_BUF *thismb = &macbufs[j];
831 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
832 if (i == 0 || thismb == NULL || thismb->mac == NULL
833 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
835 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
841 if (rl->alert != SSL_AD_NO_ALERT) {
842 /* We already called RLAYERfatal() */
846 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
847 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
848 * failure is directly visible from the ciphertext anyway, we should
849 * not reveal which kind of error occurred -- this might become
850 * visible to an attacker (e.g. via a logfile)
852 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
853 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
857 for (j = 0; j < num_recs; j++) {
860 if (!rl->funcs->post_process_record(rl, thisrr)) {
861 /* RLAYERfatal already called */
866 * Check if the received packet overflows the current
867 * Max Fragment Length setting.
868 * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
870 if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
871 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
877 * So at this point the following is true
878 * thisrr->type is the type of record
879 * thisrr->length == number of bytes in record
880 * thisrr->off == offset to first valid byte
881 * thisrr->data == where to take bytes from, increment after use :-).
884 /* just read a 0 length packet */
885 if (thisrr->length == 0) {
886 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
887 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
888 SSL_R_RECORD_TOO_SMALL);
892 rl->empty_record_count = 0;
896 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
898 if (thisrr->type == SSL3_RT_APPLICATION_DATA
899 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
900 /* RLAYERfatal already called */
905 rl->num_recs = num_recs;
907 rl->num_released = 0;
908 ret = OSSL_RECORD_RETURN_SUCCESS;
910 if (macbufs != NULL) {
911 for (j = 0; j < num_recs; j++) {
912 if (macbufs[j].alloced)
913 OPENSSL_free(macbufs[j].mac);
915 OPENSSL_free(macbufs);
920 /* Shared by ssl3_meth and tls1_meth */
921 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
923 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
925 if (rec->rec_version != rl->version) {
926 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
930 #ifndef OPENSSL_NO_COMP
932 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
933 * does not include the compression overhead anyway.
935 if (rl->expand == NULL)
936 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
939 if (rec->length > len) {
940 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
941 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
948 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
950 #ifndef OPENSSL_NO_COMP
953 if (rec->comp == NULL) {
954 rec->comp = (unsigned char *)
955 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
957 if (rec->comp == NULL)
960 i = COMP_expand_block(rl->expand, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
961 rec->data, (int)rec->length);
966 rec->data = rec->comp;
973 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
974 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
976 if (rl->expand != NULL) {
977 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
978 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
979 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
982 if (!tls_do_uncompress(rl, rec)) {
983 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
984 SSL_R_BAD_DECOMPRESSION);
989 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
990 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
997 /* Shared by tls13_meth and ktls_meth */
998 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
1000 if (rec->type != SSL3_RT_APPLICATION_DATA
1001 && rec->type != SSL3_RT_ALERT
1002 && rec->type != SSL3_RT_HANDSHAKE) {
1003 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1007 if (rl->msg_callback != NULL)
1008 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
1012 * TLSv1.3 alert and handshake records are required to be non-zero in
1015 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1016 && rec->length == 0) {
1017 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1024 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1025 int *type, unsigned char **data, size_t *datalen,
1026 uint16_t *epoch, unsigned char *seq_num)
1031 * tls_get_more_records() can return success without actually reading
1032 * anything useful (i.e. if empty records are read). We loop here until
1033 * we have something useful. tls_get_more_records() will eventually fail if
1034 * too many sequential empty records are read.
1036 while (rl->curr_rec >= rl->num_recs) {
1039 if (rl->num_released != rl->num_recs) {
1040 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1041 return OSSL_RECORD_RETURN_FATAL;
1044 ret = rl->funcs->get_more_records(rl);
1046 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1051 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1052 * points to the next one to read.
1054 rec = &rl->rrec[rl->curr_rec++];
1057 *rversion = rec->rec_version;
1059 *data = rec->data + rec->off;
1060 *datalen = rec->length;
1062 *epoch = rec->epoch;
1063 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1066 return OSSL_RECORD_RETURN_SUCCESS;
1069 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
1071 if (!ossl_assert(rl->num_released < rl->curr_rec)
1072 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
1073 /* Should not happen */
1074 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1075 return OSSL_RECORD_RETURN_FATAL;
1080 if (rl->curr_rec == rl->num_released
1081 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1082 && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
1083 tls_release_read_buffer(rl);
1085 return OSSL_RECORD_RETURN_SUCCESS;
1088 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1090 const OSSL_PARAM *p;
1092 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1093 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1094 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1098 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1099 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1100 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1104 if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
1105 p = OSSL_PARAM_locate_const(options,
1106 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1107 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1108 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1112 p = OSSL_PARAM_locate_const(options,
1113 OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
1114 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
1115 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1120 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1122 * We ignore any read_ahead setting prior to the application protection
1123 * level. Otherwise we may read ahead data in a lower protection level
1124 * that is destined for a higher protection level. To simplify the logic
1125 * we don't support that at this stage.
1127 p = OSSL_PARAM_locate_const(options,
1128 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1129 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1130 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1139 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1140 int role, int direction, int level, unsigned char *key,
1141 size_t keylen, unsigned char *iv, size_t ivlen,
1142 unsigned char *mackey, size_t mackeylen,
1143 const EVP_CIPHER *ciph, size_t taglen,
1145 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1146 BIO *transport, BIO *next, BIO_ADDR *local,
1147 BIO_ADDR *peer, const OSSL_PARAM *settings,
1148 const OSSL_PARAM *options,
1149 const OSSL_DISPATCH *fns, void *cbarg,
1150 OSSL_RECORD_LAYER **retrl)
1152 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1153 const OSSL_PARAM *p;
1158 ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
1159 return OSSL_RECORD_RETURN_FATAL;
1162 /* Loop through all the settings since they must all be understood */
1163 if (settings != NULL) {
1164 for (p = settings; p->key != NULL; p++) {
1165 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1166 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1167 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1170 } else if (strcmp(p->key,
1171 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1172 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1173 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1176 } else if (strcmp(p->key,
1177 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1178 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1179 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1182 } else if (strcmp(p->key,
1183 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1184 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1185 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1188 } else if (strcmp(p->key,
1189 OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1190 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1191 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1195 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1201 rl->libctx = libctx;
1206 rl->direction = direction;
1209 rl->alert = SSL_AD_NO_ALERT;
1211 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1212 rl->is_first_record = 1;
1214 if (!tls_set1_bio(rl, transport))
1217 if (prev != NULL && !BIO_up_ref(prev))
1221 if (next != NULL && !BIO_up_ref(next))
1227 for (; fns->function_id != 0; fns++) {
1228 switch (fns->function_id) {
1229 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1230 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1232 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1233 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1235 case OSSL_FUNC_RLAYER_SECURITY:
1236 rl->security = OSSL_FUNC_rlayer_security(fns);
1238 case OSSL_FUNC_RLAYER_PADDING:
1239 rl->padding = OSSL_FUNC_rlayer_padding(fns);
1241 /* Just ignore anything we don't understand */
1247 if (!tls_set_options(rl, options)) {
1248 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1252 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
1253 && rl->version <= TLS1_VERSION
1254 && !EVP_CIPHER_is_a(ciph, "NULL")
1255 && !EVP_CIPHER_is_a(ciph, "RC4")) {
1257 * Enable vulnerability countermeasure for CBC ciphers with known-IV
1258 * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
1260 rl->need_empty_fragments = 1;
1264 return OSSL_RECORD_RETURN_SUCCESS;
1267 return OSSL_RECORD_RETURN_FATAL;
1271 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1272 int role, int direction, int level, uint16_t epoch,
1273 unsigned char *key, size_t keylen, unsigned char *iv,
1274 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1275 const EVP_CIPHER *ciph, size_t taglen,
1277 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1278 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1279 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1280 const OSSL_DISPATCH *fns, void *cbarg,
1281 OSSL_RECORD_LAYER **retrl)
1285 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1286 key, keylen, iv, ivlen, mackey, mackeylen,
1287 ciph, taglen, mactype, md, comp, prev,
1288 transport, next, local, peer, settings,
1289 options, fns, cbarg, retrl);
1291 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1295 case TLS_ANY_VERSION:
1296 (*retrl)->funcs = &tls_any_funcs;
1298 case TLS1_3_VERSION:
1299 (*retrl)->funcs = &tls_1_3_funcs;
1301 case TLS1_2_VERSION:
1302 case TLS1_1_VERSION:
1304 (*retrl)->funcs = &tls_1_funcs;
1307 (*retrl)->funcs = &ssl_3_0_funcs;
1310 /* Should not happen */
1311 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1312 ret = OSSL_RECORD_RETURN_FATAL;
1316 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1317 ivlen, mackey, mackeylen, ciph,
1318 taglen, mactype, md, comp);
1321 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1322 OPENSSL_free(*retrl);
1328 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1333 SSL3_BUFFER_release(&rl->rbuf);
1335 tls_release_write_buffer(rl);
1337 EVP_CIPHER_CTX_free(rl->enc_ctx);
1338 EVP_MD_CTX_free(rl->md_ctx);
1339 #ifndef OPENSSL_NO_COMP
1340 COMP_CTX_free(rl->expand);
1343 if (rl->version == SSL3_VERSION)
1344 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1346 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1351 int tls_free(OSSL_RECORD_LAYER *rl)
1354 size_t left, written;
1359 left = SSL3_BUFFER_get_left(rbuf);
1362 * This record layer is closing but we still have data left in our
1363 * buffer. It must be destined for the next epoch - so push it there.
1365 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1372 int tls_reset(OSSL_RECORD_LAYER *rl)
1374 memset(rl, 0, sizeof(*rl));
1378 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1380 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1383 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1385 return rl->curr_rec < rl->num_recs;
1388 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1393 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1394 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1396 num += rl->rrec[i].length;
1401 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1406 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1411 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1416 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1419 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1420 SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1422 SSL3_RECORD *thiswr;
1423 unsigned char *recordstart;
1424 int mac_size, clear = 0;
1429 size_t totlen = 0, len, wpinited = 0;
1430 size_t j, prefix = 0;
1432 /* TODO(RECLAYER): REMOVE ME */
1433 SSL_CONNECTION *s = rl->cbarg;
1434 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1435 OSSL_RECORD_TEMPLATE prefixtempl;
1436 OSSL_RECORD_TEMPLATE *thistempl;
1438 /* Check we don't have pending data waiting to write */
1439 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1440 || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1441 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1448 || (s->enc_write_ctx == NULL)
1449 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
1450 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
1453 mac_size = EVP_MD_CTX_get_size(s->write_hash);
1455 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1461 * 'create_empty_fragment' is true only when we have recursively called
1463 * Do we need to do that recursion in order to add an empty record prefix?
1465 prefix = rl->need_empty_fragments
1467 && templates[0].type == SSL3_RT_APPLICATION_DATA;
1469 if (rl->numwpipes < numtempl + prefix) {
1471 * TODO(RECLAYER): In the prefix case the first buffer can be a lot
1472 * smaller. It is wasteful to allocate a full sized buffer here
1474 if (!tls_setup_write_buffer(rl, numtempl + prefix, 0)) {
1475 /* SSLfatal() already called */
1480 using_ktls = BIO_get_ktls_send(rl->bio);
1481 if (!ossl_assert(!using_ktls || !prefix)) {
1482 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1488 * countermeasure against known-IV weakness in CBC ciphersuites (see
1489 * http://www.openssl.org/~bodo/tls-cbc.txt)
1491 prefixtempl.buf = NULL;
1492 prefixtempl.version = templates[0].version;
1493 prefixtempl.buflen = 0;
1494 prefixtempl.type = SSL3_RT_APPLICATION_DATA;
1498 /* TODO(RECLAYER): This alignment calculation no longer seems right */
1499 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
1501 * extra fragment would be couple of cipher blocks, which would be
1502 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
1503 * payload, then we can just pretend we simply have two headers.
1505 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
1506 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1508 SSL3_BUFFER_set_offset(wb, align);
1509 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
1510 SSL3_BUFFER_get_len(wb), 0)
1511 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
1512 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1517 for (j = 0; j < numtempl; j++) {
1518 thispkt = &pkt[prefix + j];
1520 wb = &rl->wbuf[prefix + j];
1521 wb->type = templates[j].type;
1525 * ktls doesn't modify the buffer, but to avoid a warning we need
1526 * to discard the const qualifier.
1527 * This doesn't leak memory because the buffers have been
1528 * released when switching to ktls.
1530 SSL3_BUFFER_set_buf(wb, (unsigned char *)templates[j].buf);
1531 SSL3_BUFFER_set_offset(wb, 0);
1532 SSL3_BUFFER_set_app_buffer(wb, 1);
1534 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1535 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
1536 align = SSL3_ALIGN_PAYLOAD - 1
1537 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1539 /* TODO(RECLAYER): Is this alignment actually used somewhere? */
1540 SSL3_BUFFER_set_offset(wb, align);
1541 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1542 SSL3_BUFFER_get_len(wb), 0)
1543 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
1544 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1552 /* Explicit IV length, block ciphers appropriate version flag */
1553 if (s->enc_write_ctx != NULL && RLAYER_USE_EXPLICIT_IV(rl)
1554 && rl->version != TLS1_3_VERSION) {
1555 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
1556 if (mode == EVP_CIPH_CBC_MODE) {
1557 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
1559 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
1564 } else if (mode == EVP_CIPH_GCM_MODE) {
1565 /* Need explicit part of IV for GCM mode */
1566 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
1567 } else if (mode == EVP_CIPH_CCM_MODE) {
1568 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
1574 /* Clear our SSL3_RECORD structures */
1575 memset(wr, 0, sizeof(wr));
1576 for (j = 0; j < numtempl + prefix; j++) {
1577 unsigned char *compressdata = NULL;
1579 unsigned int rectype;
1583 thistempl = (j == 0 && prefix == 1) ? &prefixtempl :
1584 &templates[j - prefix];
1587 * In TLSv1.3, once encrypting, we always use application data for the
1590 if (rl->version == TLS1_3_VERSION
1591 && s->enc_write_ctx != NULL
1592 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1593 || thistempl->type != SSL3_RT_ALERT))
1594 rectype = SSL3_RT_APPLICATION_DATA;
1596 rectype = thistempl->type;
1598 SSL3_RECORD_set_type(thiswr, rectype);
1599 SSL3_RECORD_set_rec_version(thiswr, thistempl->version);
1601 maxcomplen = thistempl->buflen;
1602 if (s->compress != NULL)
1603 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1606 * When using offload kernel will write the header.
1607 * Otherwise write the header now
1610 && (!WPACKET_put_bytes_u8(thispkt, rectype)
1611 || !WPACKET_put_bytes_u16(thispkt, thistempl->version)
1612 || !WPACKET_start_sub_packet_u16(thispkt)
1614 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
1616 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1618 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1622 /* lets setup the record stuff. */
1623 SSL3_RECORD_set_data(thiswr, compressdata);
1624 SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1626 * TODO(RECLAYER): Cast away the const. Should be safe - by why is this
1629 SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1630 totlen += thistempl->buflen;
1633 * we now 'read' from thiswr->input, thiswr->length bytes into
1637 /* first we compress */
1638 if (s->compress != NULL) {
1639 if (!ssl3_do_compress(s, thiswr)
1640 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1641 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1646 SSL3_RECORD_reset_data(&wr[j]);
1648 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1649 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1652 SSL3_RECORD_reset_input(&wr[j]);
1656 if (rl->version == TLS1_3_VERSION
1658 && s->enc_write_ctx != NULL
1659 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1660 || thistempl->type != SSL3_RT_ALERT)) {
1661 size_t rlen, max_send_fragment;
1663 if (!WPACKET_put_bytes_u8(thispkt, thistempl->type)) {
1664 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1667 SSL3_RECORD_add_length(thiswr, 1);
1669 /* Add TLS1.3 padding */
1670 max_send_fragment = ssl_get_max_send_fragment(s);
1671 rlen = SSL3_RECORD_get_length(thiswr);
1672 if (rlen < max_send_fragment) {
1674 size_t max_padding = max_send_fragment - rlen;
1676 if (rl->padding != NULL) {
1677 padding = rl->padding(rl->cbarg, thistempl->type, rlen);
1678 } else if (rl->block_padding > 0) {
1679 size_t mask = rl->block_padding - 1;
1682 /* optimize for power of 2 */
1683 if ((rl->block_padding & mask) == 0)
1684 remainder = rlen & mask;
1686 remainder = rlen % rl->block_padding;
1687 /* don't want to add a block of padding if we don't have to */
1691 padding = rl->block_padding - remainder;
1694 /* do not allow the record to exceed max plaintext length */
1695 if (padding > max_padding)
1696 padding = max_padding;
1697 if (!WPACKET_memset(thispkt, 0, padding)) {
1698 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1699 ERR_R_INTERNAL_ERROR);
1702 SSL3_RECORD_add_length(thiswr, padding);
1708 * we should still have the output to thiswr->data and the input from
1709 * wr->input. Length should be thiswr->length. thiswr->data still points
1713 if (!using_ktls && !rl->use_etm && mac_size != 0) {
1716 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1717 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1718 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1724 * Reserve some bytes for any growth that may occur during encryption.
1725 * This will be at most one cipher block or the tag length if using
1726 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1729 if (!WPACKET_reserve_bytes(thispkt,
1730 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1733 * We also need next the amount of bytes written to this
1736 || !WPACKET_get_length(thispkt, &len)) {
1737 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1741 /* Get a pointer to the start of this record excluding header */
1742 recordstart = WPACKET_get_curr(thispkt) - len;
1743 SSL3_RECORD_set_data(thiswr, recordstart);
1744 SSL3_RECORD_reset_input(thiswr);
1745 SSL3_RECORD_set_length(thiswr, len);
1749 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
1751 * We haven't actually negotiated the version yet, but we're trying to
1752 * send early data - so we need to use the tls13enc function.
1754 if (tls13_enc(s, wr, numtempl, 1, NULL, mac_size) < 1) {
1755 if (!ossl_statem_in_error(s)) {
1756 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1763 if (ssl->method->ssl3_enc->enc(s, wr, 1, 1, NULL, mac_size) < 1) {
1764 if (!ossl_statem_in_error(s)) {
1765 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1770 if (ssl->method->ssl3_enc->enc(s, wr + prefix, numtempl, 1, NULL,
1772 if (!ossl_statem_in_error(s)) {
1773 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1780 for (j = 0; j < prefix + numtempl; j++) {
1785 thistempl = (prefix == 1 && j == 0) ? &prefixtempl
1786 : &templates[j - prefix];
1791 /* Allocate bytes for the encryption overhead */
1792 if (!WPACKET_get_length(thispkt, &origlen)
1793 /* Encryption should never shrink the data! */
1794 || origlen > thiswr->length
1795 || (thiswr->length > origlen
1796 && !WPACKET_allocate_bytes(thispkt,
1797 thiswr->length - origlen,
1799 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1802 if (rl->use_etm && mac_size != 0) {
1805 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1806 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1807 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1810 SSL3_RECORD_add_length(thiswr, mac_size);
1813 if (!WPACKET_get_length(thispkt, &len)
1814 || !WPACKET_close(thispkt)) {
1815 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1819 if (rl->msg_callback) {
1820 recordstart = WPACKET_get_curr(thispkt) - len
1821 - SSL3_RT_HEADER_LENGTH;
1822 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1823 SSL3_RT_HEADER_LENGTH, rl->cbarg);
1825 if (rl->version == TLS1_3_VERSION && s->enc_write_ctx != NULL) {
1826 unsigned char ctype = thistempl->type;
1828 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1829 &ctype, 1, rl->cbarg);
1833 if (!WPACKET_finish(thispkt)) {
1834 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1838 /* header is added by the kernel when using offload */
1839 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1843 * we should now have thiswr->data pointing to the encrypted data, which
1844 * is thiswr->length long.
1845 * Setting the type is not needed but helps for debugging
1847 SSL3_RECORD_set_type(thiswr, thistempl->type);
1849 /* now let's set up wb */
1850 SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
1854 /* we now just need to write the buffers */
1855 return tls_retry_write_records(rl);
1857 for (j = 0; j < wpinited; j++)
1858 WPACKET_cleanup(&pkt[j]);
1862 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1864 * Return values are as per SSL_write()
1866 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1869 SSL3_BUFFER *thiswb;
1871 SSL_CONNECTION *s = rl->cbarg;
1873 if (rl->nextwbuf >= rl->numwpipes)
1877 thiswb = &rl->wbuf[rl->nextwbuf];
1880 if (rl->bio != NULL) {
1881 s->rwstate = SSL_WRITING;
1884 * To prevent coalescing of control and data messages,
1885 * such as in buffer_write, we flush the BIO
1887 if (BIO_get_ktls_send(rl->bio)
1888 && thiswb->type != SSL3_RT_APPLICATION_DATA) {
1889 i = BIO_flush(rl->bio);
1892 BIO_set_ktls_ctrl_msg(rl->bio, thiswb->type);
1894 i = BIO_write(rl->bio, (char *)
1895 &(SSL3_BUFFER_get_buf(thiswb)
1896 [SSL3_BUFFER_get_offset(thiswb)]),
1897 (unsigned int)SSL3_BUFFER_get_left(thiswb));
1901 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1906 * When an empty fragment is sent on a connection using KTLS,
1907 * it is sent as a write of zero bytes. If this zero byte
1908 * write succeeds, i will be 0 rather than a non-zero value.
1909 * Treat i == 0 as success rather than an error for zero byte
1910 * writes to permit this case.
1912 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1913 SSL3_BUFFER_set_left(thiswb, 0);
1914 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1915 if (++(rl->nextwbuf) < rl->numwpipes)
1917 s->rwstate = SSL_NOTHING;
1919 if (rl->nextwbuf == rl->numwpipes
1920 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1921 tls_release_write_buffer(rl);
1923 } else if (i <= 0) {
1926 * For DTLS, just drop it. That's kind of the whole point in
1927 * using a datagram service
1929 SSL3_BUFFER_set_left(thiswb, 0);
1930 if (++(rl->nextwbuf) == rl->numwpipes
1931 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1932 tls_release_write_buffer(rl);
1937 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1938 SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1942 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1947 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1949 if (bio != NULL && !BIO_up_ref(bio))
1957 /* Shared by most methods except tlsany_meth */
1958 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1960 if (rl->version != version)
1966 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1968 return rl->funcs->set_protocol_version(rl, version);
1971 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1973 rl->allow_plain_alerts = allow;
1976 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1978 rl->is_first_handshake = first;
1981 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1983 rl->max_pipelines = max_pipelines;
1984 if (max_pipelines > 1)
1988 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1989 const char **longstr)
1991 const char *shrt, *lng;
1993 switch (rl->rstate) {
1994 case SSL_ST_READ_HEADER:
1996 lng = "read header";
1998 case SSL_ST_READ_BODY:
2003 shrt = lng = "unknown";
2006 if (shortstr != NULL)
2008 if (longstr != NULL)
2012 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2013 tls_new_record_layer,
2016 tls_unprocessed_read_pending,
2017 tls_processed_read_pending,
2018 tls_app_data_pending,
2020 tls_get_max_record_len,
2021 tls_get_max_records,
2023 tls_retry_write_records,
2028 tls_set_protocol_version,
2029 tls_set_plain_alerts,
2030 tls_set_first_handshake,
2031 tls_set_max_pipelines,