2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include <openssl/bio.h>
12 #include <openssl/ssl.h>
13 #include <openssl/err.h>
14 #include <openssl/core_names.h>
15 #include <openssl/comp.h>
16 #include <openssl/ssl.h>
17 #include "internal/e_os.h"
18 #include "internal/packet.h"
19 #include "../../ssl_local.h"
20 #include "../record_local.h"
21 #include "recmethod_local.h"
23 static void tls_int_free(OSSL_RECORD_LAYER *rl);
25 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
31 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
37 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
39 const EVP_CIPHER *ciph,
43 * Provided cipher, the TLS padding/MAC removal is performed provider
44 * side so we need to tell the ctx about our TLS version and mac size
46 OSSL_PARAM params[3], *pprm = params;
50 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
52 imacsize = EVP_MD_get_size(md);
54 macsize = (size_t)imacsize;
56 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
58 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
60 *pprm = OSSL_PARAM_construct_end();
62 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
63 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
71 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
72 * which ssl3_cbc_digest_record supports.
74 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
76 switch (EVP_MD_CTX_get_type(ctx)) {
89 #ifndef OPENSSL_NO_COMP
90 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
92 if (rl->options & SSL_OP_NO_COMPRESSION)
95 return rl->security == NULL
96 || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
100 static void tls_release_write_buffer_int(OSSL_RECORD_LAYER *rl, size_t start)
105 pipes = rl->numwpipes;
107 while (pipes > start) {
108 wb = &rl->wbuf[pipes - 1];
110 if (SSL3_BUFFER_is_app_buffer(wb))
111 SSL3_BUFFER_set_app_buffer(wb, 0);
113 OPENSSL_free(wb->buf);
119 int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
120 size_t firstlen, size_t nextlen)
123 size_t align = 0, headerlen;
128 if (firstlen == 0 || (numwpipes > 1 && nextlen == 0)) {
130 headerlen = DTLS1_RT_HEADER_LENGTH + 1;
132 headerlen = SSL3_RT_HEADER_LENGTH;
134 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
135 align = SSL3_ALIGN_PAYLOAD - 1;
138 defltlen = rl->max_frag_len + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
140 #ifndef OPENSSL_NO_COMP
141 if (tls_allow_compression(rl))
142 defltlen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
144 if (!(rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
145 defltlen += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
149 for (currpipe = 0; currpipe < numwpipes; currpipe++) {
150 SSL3_BUFFER *thiswb = &wb[currpipe];
151 size_t len = (currpipe == 0) ? firstlen : nextlen;
156 if (thiswb->len != len) {
157 OPENSSL_free(thiswb->buf);
158 thiswb->buf = NULL; /* force reallocation */
163 p = OPENSSL_malloc(len);
165 if (rl->numwpipes < currpipe)
166 rl->numwpipes = currpipe;
168 * We've got a malloc failure, and we're still initialising
169 * buffers. We assume we're so doomed that we won't even be able
172 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
176 memset(thiswb, 0, sizeof(SSL3_BUFFER));
181 /* Free any previously allocated buffers that we are no longer using */
182 tls_release_write_buffer_int(rl, currpipe);
184 rl->numwpipes = numwpipes;
189 static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
191 tls_release_write_buffer_int(rl, 0);
196 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
199 size_t len, align = 0, headerlen;
205 headerlen = DTLS1_RT_HEADER_LENGTH;
207 headerlen = SSL3_RT_HEADER_LENGTH;
209 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
210 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
213 if (b->buf == NULL) {
214 len = rl->max_frag_len
215 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
216 #ifndef OPENSSL_NO_COMP
217 if (tls_allow_compression(rl))
218 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
220 if (b->default_len > len)
221 len = b->default_len;
222 if ((p = OPENSSL_malloc(len)) == NULL) {
224 * We've got a malloc failure, and we're still initialising buffers.
225 * We assume we're so doomed that we won't even be able to send an
228 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_CRYPTO_LIB);
238 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
243 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
244 OPENSSL_cleanse(b->buf, b->len);
245 OPENSSL_free(b->buf);
251 * Return values are as per SSL_read()
253 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
254 int clearold, size_t *readbytes)
257 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
258 * packet by another n bytes. The packet will be in the sub-array of
259 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
260 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
261 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
262 * packet to the start of the buffer; if clearold == 0 then leave any old
263 * packets where they were
265 size_t len, left, align = 0;
270 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
274 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
275 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
276 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
280 /* start with empty packet ... */
283 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
285 * check if next packet length is large enough to justify payload
288 pkt = rb->buf + rb->offset;
289 if (pkt[0] == SSL3_RT_APPLICATION_DATA
290 && (pkt[3] << 8 | pkt[4]) >= 128) {
292 * Note that even if packet is corrupted and its length field
293 * is insane, we can only be led to wrong decision about
294 * whether memmove will occur or not. Header values has no
295 * effect on memmove arguments and therefore no buffer
296 * overrun can be triggered.
298 memmove(rb->buf + align, pkt, left);
302 rl->packet = rb->buf + rb->offset;
303 rl->packet_length = 0;
304 /* ... now we can act as if 'extend' was set */
307 len = rl->packet_length;
308 pkt = rb->buf + align;
310 * Move any available bytes to front of buffer: 'len' bytes already
311 * pointed to by 'packet', 'left' extra ones at the end
313 if (rl->packet != pkt && clearold == 1) {
314 memmove(pkt, rl->packet, len + left);
316 rb->offset = len + align;
320 * For DTLS/UDP reads should not span multiple packets because the read
321 * operation returns the whole packet at once (as long as it fits into
325 if (left == 0 && extend) {
327 * We received a record with a header but no body data. This will
330 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
332 if (left > 0 && n > left)
336 /* if there is enough in the buffer from a previous read, take some */
338 rl->packet_length += n;
342 return OSSL_RECORD_RETURN_SUCCESS;
345 /* else we need to read more data */
347 if (n > rb->len - rb->offset) {
348 /* does not happen */
349 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
350 return OSSL_RECORD_RETURN_FATAL;
353 /* We always act like read_ahead is set for DTLS */
354 if (!rl->read_ahead && !rl->isdtls) {
355 /* ignore max parameter */
360 if (max > rb->len - rb->offset)
361 max = rb->len - rb->offset;
367 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
370 * Now we have len+left bytes at the front of rl->rbuf.buf and
371 * need to read in more until we have len + n (up to len + max if
377 ret = BIO_read(bio, pkt + len + left, max - left);
380 ret = OSSL_RECORD_RETURN_SUCCESS;
381 } else if (BIO_should_retry(bio)) {
382 if (rl->prev != NULL) {
384 * We were reading from the previous epoch. Now there is no
385 * more data, so swap to the actual transport BIO
391 ret = OSSL_RECORD_RETURN_RETRY;
392 } else if (BIO_eof(bio)) {
393 ret = OSSL_RECORD_RETURN_EOF;
395 ret = OSSL_RECORD_RETURN_FATAL;
398 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
399 ret = OSSL_RECORD_RETURN_FATAL;
402 if (ret <= OSSL_RECORD_RETURN_RETRY) {
404 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
406 tls_release_read_buffer(rl);
411 * reads should *never* span multiple packets for DTLS because the
412 * underlying transport protocol is message oriented as opposed to
413 * byte oriented as in the TLS case.
417 n = left; /* makes the while condition false */
421 /* done reading, now the book-keeping */
424 rl->packet_length += n;
426 return OSSL_RECORD_RETURN_SUCCESS;
430 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
431 * for us in the buffer.
433 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
441 p = SSL3_BUFFER_get_buf(rbuf);
445 left = SSL3_BUFFER_get_left(rbuf);
447 if (left < SSL3_RT_HEADER_LENGTH)
450 p += SSL3_BUFFER_get_offset(rbuf);
453 * We only check the type and record length, we will sanity check version
456 if (*p != SSL3_RT_APPLICATION_DATA)
462 if (left < SSL3_RT_HEADER_LENGTH + len)
468 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
469 size_t overhead, int send)
471 uint32_t max_early_data = rl->max_early_data;
473 if (max_early_data == 0) {
474 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
475 SSL_R_TOO_MUCH_EARLY_DATA);
479 /* If we are dealing with ciphertext we need to allow for the overhead */
480 max_early_data += overhead;
482 if (rl->early_data_count + length > max_early_data) {
483 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
484 SSL_R_TOO_MUCH_EARLY_DATA);
487 rl->early_data_count += length;
493 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
494 * will be processed per call to tls_get_more_records. Without this limit an
495 * attacker could send empty records at a faster rate than we can process and
496 * cause tls_get_more_records to loop forever.
498 #define MAX_EMPTY_RECORDS 32
500 #define SSL2_RT_HEADER_LENGTH 2
503 * Call this to buffer new input records in rl->rrec.
504 * It will return a OSSL_RECORD_RETURN_* value.
505 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
506 * records have been decoded. For each record 'i':
507 * rrec[i].type - is the type of record
508 * rrec[i].data, - data
509 * rrec[i].length, - number of bytes
510 * Multiple records will only be returned if the record types are all
511 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
514 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
519 SSL3_RECORD *rr, *thisrr;
522 unsigned char md[EVP_MAX_MD_SIZE];
523 unsigned int version;
526 size_t num_recs = 0, max_recs, j;
527 PACKET pkt, sslv2pkt;
528 SSL_MAC_BUF *macbufs = NULL;
529 int ret = OSSL_RECORD_RETURN_FATAL;
533 if (rbuf->buf == NULL) {
534 if (!tls_setup_read_buffer(rl)) {
535 /* RLAYERfatal() already called */
536 return OSSL_RECORD_RETURN_FATAL;
540 max_recs = rl->max_pipelines;
546 thisrr = &rr[num_recs];
548 /* check if we have the header */
549 if ((rl->rstate != SSL_ST_READ_BODY) ||
550 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
554 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
555 SSL3_BUFFER_get_len(rbuf), 0,
556 num_recs == 0 ? 1 : 0, &n);
558 if (rret < OSSL_RECORD_RETURN_SUCCESS)
559 return rret; /* error or non-blocking */
561 rl->rstate = SSL_ST_READ_BODY;
564 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
565 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
566 return OSSL_RECORD_RETURN_FATAL;
569 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
570 || !PACKET_get_1(&sslv2pkt, &type)) {
571 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
572 return OSSL_RECORD_RETURN_FATAL;
575 * The first record received by the server may be a V2ClientHello.
577 if (rl->role == OSSL_RECORD_ROLE_SERVER
578 && rl->is_first_record
579 && (sslv2len & 0x8000) != 0
580 && (type == SSL2_MT_CLIENT_HELLO)) {
584 * |num_recs| here will actually always be 0 because
585 * |num_recs > 0| only ever occurs when we are processing
586 * multiple app data records - which we know isn't the case here
587 * because it is an SSLv2ClientHello. We keep it using
588 * |num_recs| for the sake of consistency
590 thisrr->type = SSL3_RT_HANDSHAKE;
591 thisrr->rec_version = SSL2_VERSION;
593 thisrr->length = sslv2len & 0x7fff;
595 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
596 - SSL2_RT_HEADER_LENGTH) {
597 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
598 SSL_R_PACKET_LENGTH_TOO_LONG);
599 return OSSL_RECORD_RETURN_FATAL;
602 /* SSLv3+ style record */
604 /* Pull apart the header into the SSL3_RECORD */
605 if (!PACKET_get_1(&pkt, &type)
606 || !PACKET_get_net_2(&pkt, &version)
607 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
608 if (rl->msg_callback != NULL)
609 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
610 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
611 return OSSL_RECORD_RETURN_FATAL;
614 thisrr->rec_version = version;
617 * When we call validate_record_header() only records actually
618 * received in SSLv2 format should have the record version set
619 * to SSL2_VERSION. This way validate_record_header() can know
620 * what format the record was in based on the version.
622 if (thisrr->rec_version == SSL2_VERSION) {
623 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
624 SSL_R_WRONG_VERSION_NUMBER);
625 return OSSL_RECORD_RETURN_FATAL;
628 if (rl->msg_callback != NULL)
629 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
632 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
633 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
634 SSL_R_PACKET_LENGTH_TOO_LONG);
635 return OSSL_RECORD_RETURN_FATAL;
639 if (!rl->funcs->validate_record_header(rl, thisrr)) {
640 /* RLAYERfatal already called */
641 return OSSL_RECORD_RETURN_FATAL;
644 /* now rl->rstate == SSL_ST_READ_BODY */
648 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
649 * how much more data we need to read for the rest of the record
651 if (thisrr->rec_version == SSL2_VERSION) {
652 more = thisrr->length + SSL2_RT_HEADER_LENGTH
653 - SSL3_RT_HEADER_LENGTH;
655 more = thisrr->length;
659 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
661 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
662 if (rret < OSSL_RECORD_RETURN_SUCCESS)
663 return rret; /* error or non-blocking io */
666 /* set state for later operations */
667 rl->rstate = SSL_ST_READ_HEADER;
670 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
671 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
672 * + thisrr->length and we have that many bytes in rl->packet
674 if (thisrr->rec_version == SSL2_VERSION)
675 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
677 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
680 * ok, we can now read from 'rl->packet' data into 'thisrr'.
681 * thisrr->input points at thisrr->length bytes, which need to be copied
682 * into thisrr->data by either the decryption or by the decompression.
683 * When the data is 'copied' into the thisrr->data buffer,
684 * thisrr->input will be updated to point at the new buffer
688 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
689 * thisrr->length bytes of encrypted compressed stuff.
692 /* decrypt in place in 'thisrr->input' */
693 thisrr->data = thisrr->input;
694 thisrr->orig_len = thisrr->length;
698 /* we have pulled in a full packet so zero things */
699 rl->packet_length = 0;
700 rl->is_first_record = 0;
701 } while (num_recs < max_recs
702 && thisrr->type == SSL3_RT_APPLICATION_DATA
703 && RLAYER_USE_EXPLICIT_IV(rl)
704 && rl->enc_ctx != NULL
705 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
706 & EVP_CIPH_FLAG_PIPELINE) != 0
707 && tls_record_app_data_waiting(rl));
710 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
711 /* The following can happen in tlsany_meth after HRR */
712 && rl->version == TLS1_3_VERSION
713 && rl->is_first_handshake) {
715 * CCS messages must be exactly 1 byte long, containing the value 0x01
717 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
718 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
719 SSL_R_INVALID_CCS_MESSAGE);
720 return OSSL_RECORD_RETURN_FATAL;
723 * CCS messages are ignored in TLSv1.3. We treat it like an empty
726 thisrr->type = SSL3_RT_HANDSHAKE;
727 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
728 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
729 SSL_R_UNEXPECTED_CCS_MESSAGE);
730 return OSSL_RECORD_RETURN_FATAL;
734 rl->num_released = 0;
736 return OSSL_RECORD_RETURN_SUCCESS;
739 if (rl->md_ctx != NULL) {
740 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
743 imac_size = EVP_MD_get_size(tmpmd);
744 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
745 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
746 return OSSL_RECORD_RETURN_FATAL;
748 mac_size = (size_t)imac_size;
753 * If in encrypt-then-mac mode calculate mac from encrypted record. All
754 * the details below are public so no timing details can leak.
756 if (rl->use_etm && rl->md_ctx) {
759 for (j = 0; j < num_recs; j++) {
762 if (thisrr->length < mac_size) {
763 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
764 return OSSL_RECORD_RETURN_FATAL;
766 thisrr->length -= mac_size;
767 mac = thisrr->data + thisrr->length;
768 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
769 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
770 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
771 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
772 return OSSL_RECORD_RETURN_FATAL;
776 * We've handled the mac now - there is no MAC inside the encrypted
783 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
784 if (macbufs == NULL) {
785 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
786 return OSSL_RECORD_RETURN_FATAL;
790 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
794 * 0: if the record is publicly invalid, or an internal error, or AEAD
795 * decryption failed, or ETM decryption failed.
796 * 1: Success or MTE decryption failed (MAC will be randomised)
799 if (rl->alert != SSL_AD_NO_ALERT) {
800 /* RLAYERfatal() already got called */
804 && rl->skip_early_data != NULL
805 && rl->skip_early_data(rl->cbarg)) {
807 * Valid early_data that we cannot decrypt will fail here. We treat
808 * it like an empty record.
813 if (!rlayer_early_data_count_ok(rl, thisrr->length,
814 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
815 /* RLAYERfatal() already called */
822 rl->num_released = 0;
823 /* Reset the read sequence */
824 memset(rl->sequence, 0, sizeof(rl->sequence));
828 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
829 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
832 OSSL_TRACE_BEGIN(TLS) {
833 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
834 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
835 } OSSL_TRACE_END(TLS);
837 /* r->length is now the compressed data plus mac */
838 if (rl->enc_ctx != NULL
840 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
841 /* rl->md_ctx != NULL => mac_size != -1 */
843 for (j = 0; j < num_recs; j++) {
844 SSL_MAC_BUF *thismb = &macbufs[j];
848 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
849 if (i == 0 || thismb == NULL || thismb->mac == NULL
850 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
852 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
858 if (rl->alert != SSL_AD_NO_ALERT) {
859 /* We already called RLAYERfatal() */
863 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
864 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
865 * failure is directly visible from the ciphertext anyway, we should
866 * not reveal which kind of error occurred -- this might become
867 * visible to an attacker (e.g. via a logfile)
869 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
870 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
874 for (j = 0; j < num_recs; j++) {
877 if (!rl->funcs->post_process_record(rl, thisrr)) {
878 /* RLAYERfatal already called */
883 * Check if the received packet overflows the current
884 * Max Fragment Length setting.
885 * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
887 if (thisrr->length > rl->max_frag_len) {
888 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
894 * So at this point the following is true
895 * thisrr->type is the type of record
896 * thisrr->length == number of bytes in record
897 * thisrr->off == offset to first valid byte
898 * thisrr->data == where to take bytes from, increment after use :-).
901 /* just read a 0 length packet */
902 if (thisrr->length == 0) {
903 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
904 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
905 SSL_R_RECORD_TOO_SMALL);
909 rl->empty_record_count = 0;
913 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
915 if (thisrr->type == SSL3_RT_APPLICATION_DATA
916 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
917 /* RLAYERfatal already called */
922 rl->num_recs = num_recs;
924 rl->num_released = 0;
925 ret = OSSL_RECORD_RETURN_SUCCESS;
927 if (macbufs != NULL) {
928 for (j = 0; j < num_recs; j++) {
929 if (macbufs[j].alloced)
930 OPENSSL_free(macbufs[j].mac);
932 OPENSSL_free(macbufs);
937 /* Shared by ssl3_meth and tls1_meth */
938 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
940 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
942 if (rec->rec_version != rl->version) {
943 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
947 #ifndef OPENSSL_NO_COMP
949 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
950 * does not include the compression overhead anyway.
952 if (rl->compctx == NULL)
953 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
956 if (rec->length > len) {
957 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
958 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
965 int tls_do_compress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *wr)
967 #ifndef OPENSSL_NO_COMP
970 i = COMP_compress_block(rl->compctx, wr->data,
971 (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
972 wr->input, (int)wr->length);
977 wr->input = wr->data;
984 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
986 #ifndef OPENSSL_NO_COMP
989 if (rec->comp == NULL) {
990 rec->comp = (unsigned char *)
991 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
993 if (rec->comp == NULL)
996 i = COMP_expand_block(rl->compctx, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
997 rec->data, (int)rec->length);
1002 rec->data = rec->comp;
1009 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
1010 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
1012 if (rl->compctx != NULL) {
1013 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1014 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
1015 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1018 if (!tls_do_uncompress(rl, rec)) {
1019 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
1020 SSL_R_BAD_DECOMPRESSION);
1025 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1026 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
1033 /* Shared by tls13_meth and ktls_meth */
1034 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
1036 if (rec->type != SSL3_RT_APPLICATION_DATA
1037 && rec->type != SSL3_RT_ALERT
1038 && rec->type != SSL3_RT_HANDSHAKE) {
1039 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1043 if (rl->msg_callback != NULL)
1044 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
1048 * TLSv1.3 alert and handshake records are required to be non-zero in
1051 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1052 && rec->length == 0) {
1053 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1060 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1061 int *type, unsigned char **data, size_t *datalen,
1062 uint16_t *epoch, unsigned char *seq_num)
1067 * tls_get_more_records() can return success without actually reading
1068 * anything useful (i.e. if empty records are read). We loop here until
1069 * we have something useful. tls_get_more_records() will eventually fail if
1070 * too many sequential empty records are read.
1072 while (rl->curr_rec >= rl->num_recs) {
1075 if (rl->num_released != rl->num_recs) {
1076 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1077 return OSSL_RECORD_RETURN_FATAL;
1080 ret = rl->funcs->get_more_records(rl);
1082 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1087 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1088 * points to the next one to read.
1090 rec = &rl->rrec[rl->curr_rec++];
1093 *rversion = rec->rec_version;
1095 *data = rec->data + rec->off;
1096 *datalen = rec->length;
1098 *epoch = rec->epoch;
1099 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1102 return OSSL_RECORD_RETURN_SUCCESS;
1105 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
1107 if (!ossl_assert(rl->num_released < rl->curr_rec)
1108 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
1109 /* Should not happen */
1110 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1111 return OSSL_RECORD_RETURN_FATAL;
1116 if (rl->curr_rec == rl->num_released
1117 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1118 && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
1119 tls_release_read_buffer(rl);
1121 return OSSL_RECORD_RETURN_SUCCESS;
1124 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1126 const OSSL_PARAM *p;
1128 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1129 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1130 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1134 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1135 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1136 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1140 if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
1141 p = OSSL_PARAM_locate_const(options,
1142 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1143 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1144 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1148 p = OSSL_PARAM_locate_const(options,
1149 OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
1150 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
1151 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1156 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1158 * We ignore any read_ahead setting prior to the application protection
1159 * level. Otherwise we may read ahead data in a lower protection level
1160 * that is destined for a higher protection level. To simplify the logic
1161 * we don't support that at this stage.
1163 p = OSSL_PARAM_locate_const(options,
1164 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1165 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1166 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1175 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1176 int role, int direction, int level, unsigned char *key,
1177 size_t keylen, unsigned char *iv, size_t ivlen,
1178 unsigned char *mackey, size_t mackeylen,
1179 const EVP_CIPHER *ciph, size_t taglen,
1181 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
1182 BIO *transport, BIO *next, BIO_ADDR *local,
1183 BIO_ADDR *peer, const OSSL_PARAM *settings,
1184 const OSSL_PARAM *options,
1185 const OSSL_DISPATCH *fns, void *cbarg,
1186 OSSL_RECORD_LAYER **retrl)
1188 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1189 const OSSL_PARAM *p;
1194 return OSSL_RECORD_RETURN_FATAL;
1197 * Default the value for max_frag_len. This may be overridden by the
1200 rl->max_frag_len = SSL3_RT_MAX_PLAIN_LENGTH;
1202 /* Loop through all the settings since they must all be understood */
1203 if (settings != NULL) {
1204 for (p = settings; p->key != NULL; p++) {
1205 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1206 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1207 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1210 } else if (strcmp(p->key,
1211 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1212 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1213 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1216 } else if (strcmp(p->key,
1217 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1218 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1219 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1222 } else if (strcmp(p->key,
1223 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1224 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1225 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1228 } else if (strcmp(p->key,
1229 OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1230 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1231 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1235 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1241 rl->libctx = libctx;
1246 rl->direction = direction;
1249 rl->alert = SSL_AD_NO_ALERT;
1251 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1252 rl->is_first_record = 1;
1254 if (!tls_set1_bio(rl, transport))
1257 if (prev != NULL && !BIO_up_ref(prev))
1261 if (next != NULL && !BIO_up_ref(next))
1267 for (; fns->function_id != 0; fns++) {
1268 switch (fns->function_id) {
1269 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1270 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1272 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1273 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1275 case OSSL_FUNC_RLAYER_SECURITY:
1276 rl->security = OSSL_FUNC_rlayer_security(fns);
1278 case OSSL_FUNC_RLAYER_PADDING:
1279 rl->padding = OSSL_FUNC_rlayer_padding(fns);
1281 /* Just ignore anything we don't understand */
1287 if (!tls_set_options(rl, options)) {
1288 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1292 if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
1293 && rl->version <= TLS1_VERSION
1294 && !EVP_CIPHER_is_a(ciph, "NULL")
1295 && !EVP_CIPHER_is_a(ciph, "RC4")) {
1297 * Enable vulnerability countermeasure for CBC ciphers with known-IV
1298 * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
1300 rl->need_empty_fragments = 1;
1304 return OSSL_RECORD_RETURN_SUCCESS;
1307 return OSSL_RECORD_RETURN_FATAL;
1311 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1312 int role, int direction, int level, uint16_t epoch,
1313 unsigned char *key, size_t keylen, unsigned char *iv,
1314 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1315 const EVP_CIPHER *ciph, size_t taglen,
1317 const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
1318 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1319 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1320 const OSSL_DISPATCH *fns, void *cbarg,
1321 OSSL_RECORD_LAYER **retrl)
1325 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1326 key, keylen, iv, ivlen, mackey, mackeylen,
1327 ciph, taglen, mactype, md, comp, prev,
1328 transport, next, local, peer, settings,
1329 options, fns, cbarg, retrl);
1331 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1335 case TLS_ANY_VERSION:
1336 (*retrl)->funcs = &tls_any_funcs;
1338 case TLS1_3_VERSION:
1339 (*retrl)->funcs = &tls_1_3_funcs;
1341 case TLS1_2_VERSION:
1342 case TLS1_1_VERSION:
1344 (*retrl)->funcs = &tls_1_funcs;
1347 (*retrl)->funcs = &ssl_3_0_funcs;
1350 /* Should not happen */
1351 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1352 ret = OSSL_RECORD_RETURN_FATAL;
1356 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1357 ivlen, mackey, mackeylen, ciph,
1358 taglen, mactype, md, comp);
1361 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1362 OPENSSL_free(*retrl);
1368 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1373 SSL3_BUFFER_release(&rl->rbuf);
1375 tls_release_write_buffer(rl);
1377 EVP_CIPHER_CTX_free(rl->enc_ctx);
1378 EVP_MD_CTX_free(rl->md_ctx);
1379 #ifndef OPENSSL_NO_COMP
1380 COMP_CTX_free(rl->compctx);
1383 if (rl->version == SSL3_VERSION)
1384 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1386 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1391 int tls_free(OSSL_RECORD_LAYER *rl)
1394 size_t left, written;
1399 left = SSL3_BUFFER_get_left(rbuf);
1402 * This record layer is closing but we still have data left in our
1403 * buffer. It must be destined for the next epoch - so push it there.
1405 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1412 int tls_reset(OSSL_RECORD_LAYER *rl)
1414 memset(rl, 0, sizeof(*rl));
1418 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1420 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1423 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1425 return rl->curr_rec < rl->num_recs;
1428 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1433 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1434 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1436 num += rl->rrec[i].length;
1441 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1446 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1451 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, int type, size_t len,
1452 size_t maxfrag, size_t *preffrag)
1455 * TODO(RECLAYER): There is no test for the pipelining code. We should add
1459 * If we have a pipeline capable cipher, and we have been configured to use
1460 * it, then return the preferred number of pipelines.
1462 if (rl->max_pipelines > 0
1463 && rl->enc_ctx != NULL
1464 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
1465 & EVP_CIPH_FLAG_PIPELINE) != 0
1466 && RLAYER_USE_EXPLICIT_IV(rl)) {
1471 pipes = ((len - 1) / *preffrag) + 1;
1473 return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
1479 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
1480 size_t maxfrag, size_t *preffrag)
1482 return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
1485 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
1486 OSSL_RECORD_TEMPLATE *templates,
1490 if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
1491 /* RLAYERfatal() already called */
1498 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
1499 OSSL_RECORD_TEMPLATE *templates,
1501 OSSL_RECORD_TEMPLATE *prefixtempl,
1510 for (j = 0; j < numtempl; j++) {
1514 wb->type = templates[j].type;
1516 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1517 align = (size_t)SSL3_BUFFER_get_buf(wb);
1518 align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
1519 align = SSL3_ALIGN_PAYLOAD - 1
1520 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1522 SSL3_BUFFER_set_offset(wb, align);
1524 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1525 SSL3_BUFFER_get_len(wb), 0)) {
1526 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1530 if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
1531 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1539 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
1541 OSSL_RECORD_TEMPLATE *templ,
1542 unsigned int rectype,
1543 unsigned char **recdata)
1549 maxcomplen = templ->buflen;
1550 if (rl->compctx != NULL)
1551 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1553 if (!WPACKET_put_bytes_u8(thispkt, rectype)
1554 || !WPACKET_put_bytes_u16(thispkt, templ->version)
1555 || !WPACKET_start_sub_packet_u16(thispkt)
1557 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
1559 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1561 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1568 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
1571 SSL3_RECORD *thiswr)
1574 unsigned char *recordstart;
1577 * we should still have the output to thiswr->data and the input from
1578 * wr->input. Length should be thiswr->length. thiswr->data still points
1582 if (!rl->use_etm && mac_size != 0) {
1585 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1586 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1587 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1593 * Reserve some bytes for any growth that may occur during encryption.
1594 * This will be at most one cipher block or the tag length if using
1595 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1597 if (!WPACKET_reserve_bytes(thispkt,
1598 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1601 * We also need next the amount of bytes written to this
1604 || !WPACKET_get_length(thispkt, &len)) {
1605 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1609 /* Get a pointer to the start of this record excluding header */
1610 recordstart = WPACKET_get_curr(thispkt) - len;
1611 SSL3_RECORD_set_data(thiswr, recordstart);
1612 SSL3_RECORD_reset_input(thiswr);
1613 SSL3_RECORD_set_length(thiswr, len);
1618 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
1620 OSSL_RECORD_TEMPLATE *thistempl,
1622 SSL3_RECORD *thiswr)
1624 size_t origlen, len;
1625 size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
1626 : SSL3_RT_HEADER_LENGTH;
1628 /* Allocate bytes for the encryption overhead */
1629 if (!WPACKET_get_length(thispkt, &origlen)
1630 /* Encryption should never shrink the data! */
1631 || origlen > thiswr->length
1632 || (thiswr->length > origlen
1633 && !WPACKET_allocate_bytes(thispkt,
1634 thiswr->length - origlen,
1636 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1639 if (rl->use_etm && mac_size != 0) {
1642 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1643 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1644 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1648 SSL3_RECORD_add_length(thiswr, mac_size);
1651 if (!WPACKET_get_length(thispkt, &len)
1652 || !WPACKET_close(thispkt)) {
1653 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1657 if (rl->msg_callback != NULL) {
1658 unsigned char *recordstart;
1660 recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
1661 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1662 headerlen, rl->cbarg);
1664 if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
1665 unsigned char ctype = thistempl->type;
1667 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1668 &ctype, 1, rl->cbarg);
1672 if (!WPACKET_finish(thispkt)) {
1673 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1677 SSL3_RECORD_add_length(thiswr, headerlen);
1682 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
1683 OSSL_RECORD_TEMPLATE *templates,
1686 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1687 SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1689 SSL3_RECORD *thiswr;
1690 int mac_size = 0, ret = 0;
1691 size_t wpinited = 0;
1692 size_t j, prefix = 0;
1693 OSSL_RECORD_TEMPLATE prefixtempl;
1694 OSSL_RECORD_TEMPLATE *thistempl;
1696 if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
1697 mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
1699 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1704 if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
1705 /* RLAYERfatal() already called */
1709 if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
1710 &prefixtempl, pkt, rl->wbuf,
1712 /* RLAYERfatal() already called */
1716 /* Clear our SSL3_RECORD structures */
1717 memset(wr, 0, sizeof(wr));
1718 for (j = 0; j < numtempl + prefix; j++) {
1719 unsigned char *compressdata = NULL;
1720 unsigned int rectype;
1724 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1727 * Default to the record type as specified in the template unless the
1728 * protocol implementation says differently.
1730 if (rl->funcs->get_record_type != NULL)
1731 rectype = rl->funcs->get_record_type(rl, thistempl);
1733 rectype = thistempl->type;
1735 SSL3_RECORD_set_type(thiswr, rectype);
1736 SSL3_RECORD_set_rec_version(thiswr, thistempl->version);
1738 if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
1740 /* RLAYERfatal() already called */
1744 /* lets setup the record stuff. */
1745 SSL3_RECORD_set_data(thiswr, compressdata);
1746 SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1748 SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1751 * we now 'read' from thiswr->input, thiswr->length bytes into
1755 /* first we compress */
1756 if (rl->compctx != NULL) {
1757 if (!tls_do_compress(rl, thiswr)
1758 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1759 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1762 } else if (compressdata != NULL) {
1763 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1764 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1767 SSL3_RECORD_reset_input(&wr[j]);
1770 if (rl->funcs->add_record_padding != NULL
1771 && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
1773 /* RLAYERfatal() already called */
1777 if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
1778 /* RLAYERfatal() already called */
1784 if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
1785 if (rl->alert == SSL_AD_NO_ALERT) {
1786 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1792 if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
1793 if (rl->alert == SSL_AD_NO_ALERT) {
1794 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1799 for (j = 0; j < numtempl + prefix; j++) {
1802 thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1804 if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
1806 /* RLAYERfatal() already called */
1811 * we should now have thiswr->data pointing to the encrypted data, which
1812 * is thiswr->length long.
1813 * Setting the type is not needed but helps for debugging
1815 SSL3_RECORD_set_type(thiswr, thistempl->type);
1817 /* now let's set up wb */
1818 SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
1823 for (j = 0; j < wpinited; j++)
1824 WPACKET_cleanup(&pkt[j]);
1828 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1831 /* Check we don't have pending data waiting to write */
1832 if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1833 || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1834 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1835 return OSSL_RECORD_RETURN_FATAL;
1838 if (!rl->funcs->write_records(rl, templates, numtempl)) {
1839 /* RLAYERfatal already called */
1840 return OSSL_RECORD_RETURN_FATAL;
1844 /* we now just need to write the buffers */
1845 return tls_retry_write_records(rl);
1848 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1851 SSL3_BUFFER *thiswb;
1854 if (rl->nextwbuf >= rl->numwpipes)
1855 return OSSL_RECORD_RETURN_SUCCESS;
1858 thiswb = &rl->wbuf[rl->nextwbuf];
1861 if (rl->bio != NULL) {
1862 if (rl->funcs->prepare_write_bio != NULL) {
1863 ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
1864 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1867 i = BIO_write(rl->bio, (char *)
1868 &(SSL3_BUFFER_get_buf(thiswb)
1869 [SSL3_BUFFER_get_offset(thiswb)]),
1870 (unsigned int)SSL3_BUFFER_get_left(thiswb));
1873 if (i == 0 && BIO_should_retry(rl->bio))
1874 ret = OSSL_RECORD_RETURN_RETRY;
1876 ret = OSSL_RECORD_RETURN_SUCCESS;
1878 if (BIO_should_retry(rl->bio))
1879 ret = OSSL_RECORD_RETURN_RETRY;
1881 ret = OSSL_RECORD_RETURN_FATAL;
1884 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1885 ret = OSSL_RECORD_RETURN_FATAL;
1890 * When an empty fragment is sent on a connection using KTLS,
1891 * it is sent as a write of zero bytes. If this zero byte
1892 * write succeeds, i will be 0 rather than a non-zero value.
1893 * Treat i == 0 as success rather than an error for zero byte
1894 * writes to permit this case.
1896 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1897 SSL3_BUFFER_set_left(thiswb, 0);
1898 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1899 if (++(rl->nextwbuf) < rl->numwpipes)
1902 if (rl->nextwbuf == rl->numwpipes
1903 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1904 tls_release_write_buffer(rl);
1905 return OSSL_RECORD_RETURN_SUCCESS;
1906 } else if (i <= 0) {
1909 * For DTLS, just drop it. That's kind of the whole point in
1910 * using a datagram service
1912 SSL3_BUFFER_set_left(thiswb, 0);
1913 if (++(rl->nextwbuf) == rl->numwpipes
1914 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1915 tls_release_write_buffer(rl);
1920 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1921 SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1925 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1930 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1932 if (bio != NULL && !BIO_up_ref(bio))
1940 /* Shared by most methods except tlsany_meth */
1941 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1943 if (rl->version != version)
1949 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1951 return rl->funcs->set_protocol_version(rl, version);
1954 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1956 rl->allow_plain_alerts = allow;
1959 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1961 rl->is_first_handshake = first;
1964 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1966 rl->max_pipelines = max_pipelines;
1967 if (max_pipelines > 1)
1971 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1972 const char **longstr)
1974 const char *shrt, *lng;
1976 switch (rl->rstate) {
1977 case SSL_ST_READ_HEADER:
1979 lng = "read header";
1981 case SSL_ST_READ_BODY:
1986 shrt = lng = "unknown";
1989 if (shortstr != NULL)
1991 if (longstr != NULL)
1995 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
1997 #ifndef OPENSSL_NO_COMP
1998 return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
2004 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
2006 rl->max_frag_len = max_frag_len;
2008 * We don't need to adjust buffer sizes. Write buffer sizes are
2009 * automatically checked anyway. We should only be changing the read buffer
2010 * size during the handshake, so we will create a new buffer when we create
2011 * the new record layer. We can't change the existing buffer because it may
2012 * already have data in it.
2016 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2017 tls_new_record_layer,
2020 tls_unprocessed_read_pending,
2021 tls_processed_read_pending,
2022 tls_app_data_pending,
2024 tls_get_max_record_len,
2025 tls_get_max_records,
2027 tls_retry_write_records,
2032 tls_set_protocol_version,
2033 tls_set_plain_alerts,
2034 tls_set_first_handshake,
2035 tls_set_max_pipelines,
2039 tls_get_compression,
2040 tls_set_max_frag_len