2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
10 #include <openssl/bio.h>
11 #include <openssl/ssl.h>
12 #include <openssl/err.h>
13 #include <openssl/core_names.h>
14 #include "internal/e_os.h"
15 #include "internal/packet.h"
16 #include "../../ssl_local.h"
17 #include "../record_local.h"
18 #include "recmethod_local.h"
20 static void tls_int_free(OSSL_RECORD_LAYER *rl);
22 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
28 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
34 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
36 const EVP_CIPHER *ciph,
40 * Provided cipher, the TLS padding/MAC removal is performed provider
41 * side so we need to tell the ctx about our TLS version and mac size
43 OSSL_PARAM params[3], *pprm = params;
47 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
49 imacsize = EVP_MD_get_size(md);
51 macsize = (size_t)imacsize;
53 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
55 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
57 *pprm = OSSL_PARAM_construct_end();
59 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
60 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
68 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
69 * which ssl3_cbc_digest_record supports.
71 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
73 switch (EVP_MD_CTX_get_type(ctx)) {
86 #ifndef OPENSSL_NO_COMP
87 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
89 if (rl->options & SSL_OP_NO_COMPRESSION)
92 return rl->security == NULL
93 || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
97 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
100 size_t len, align = 0, headerlen;
106 headerlen = DTLS1_RT_HEADER_LENGTH;
108 headerlen = SSL3_RT_HEADER_LENGTH;
110 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
111 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
114 if (b->buf == NULL) {
115 len = SSL3_RT_MAX_PLAIN_LENGTH
116 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
117 #ifndef OPENSSL_NO_COMP
118 if (tls_allow_compression(rl))
119 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
121 if (b->default_len > len)
122 len = b->default_len;
123 if ((p = OPENSSL_malloc(len)) == NULL) {
125 * We've got a malloc failure, and we're still initialising buffers.
126 * We assume we're so doomed that we won't even be able to send an
129 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
139 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
144 if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
145 OPENSSL_cleanse(b->buf, b->len);
146 OPENSSL_free(b->buf);
152 * Return values are as per SSL_read()
154 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
155 int clearold, size_t *readbytes)
158 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
159 * packet by another n bytes. The packet will be in the sub-array of
160 * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
161 * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
162 * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
163 * packet to the start of the buffer; if clearold == 0 then leave any old
164 * packets where they were
166 size_t len, left, align = 0;
171 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
175 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
176 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
177 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
181 /* start with empty packet ... */
184 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
186 * check if next packet length is large enough to justify payload
189 pkt = rb->buf + rb->offset;
190 if (pkt[0] == SSL3_RT_APPLICATION_DATA
191 && (pkt[3] << 8 | pkt[4]) >= 128) {
193 * Note that even if packet is corrupted and its length field
194 * is insane, we can only be led to wrong decision about
195 * whether memmove will occur or not. Header values has no
196 * effect on memmove arguments and therefore no buffer
197 * overrun can be triggered.
199 memmove(rb->buf + align, pkt, left);
203 rl->packet = rb->buf + rb->offset;
204 rl->packet_length = 0;
205 /* ... now we can act as if 'extend' was set */
208 len = rl->packet_length;
209 pkt = rb->buf + align;
211 * Move any available bytes to front of buffer: 'len' bytes already
212 * pointed to by 'packet', 'left' extra ones at the end
214 if (rl->packet != pkt && clearold == 1) {
215 memmove(pkt, rl->packet, len + left);
217 rb->offset = len + align;
221 * For DTLS/UDP reads should not span multiple packets because the read
222 * operation returns the whole packet at once (as long as it fits into
226 if (left == 0 && extend)
228 if (left > 0 && n > left)
232 /* if there is enough in the buffer from a previous read, take some */
234 rl->packet_length += n;
238 return OSSL_RECORD_RETURN_SUCCESS;
241 /* else we need to read more data */
243 if (n > rb->len - rb->offset) {
244 /* does not happen */
245 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
246 return OSSL_RECORD_RETURN_FATAL;
249 /* We always act like read_ahead is set for DTLS */
250 if (!rl->read_ahead && !rl->isdtls) {
251 /* ignore max parameter */
256 if (max > rb->len - rb->offset)
257 max = rb->len - rb->offset;
263 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
266 * Now we have len+left bytes at the front of rl->rbuf.buf and
267 * need to read in more until we have len + n (up to len + max if
273 ret = BIO_read(bio, pkt + len + left, max - left);
276 ret = OSSL_RECORD_RETURN_SUCCESS;
277 } else if (BIO_should_retry(bio)) {
278 if (rl->prev != NULL) {
280 * We were reading from the previous epoch. Now there is no
281 * more data, so swap to the actual transport BIO
287 ret = OSSL_RECORD_RETURN_RETRY;
288 } else if (BIO_eof(bio)) {
289 ret = OSSL_RECORD_RETURN_EOF;
291 ret = OSSL_RECORD_RETURN_FATAL;
294 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
295 ret = OSSL_RECORD_RETURN_FATAL;
298 if (ret <= OSSL_RECORD_RETURN_RETRY) {
300 if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
302 tls_release_read_buffer(rl);
307 * reads should *never* span multiple packets for DTLS because the
308 * underlying transport protocol is message oriented as opposed to
309 * byte oriented as in the TLS case.
313 n = left; /* makes the while condition false */
317 /* done reading, now the book-keeping */
320 rl->packet_length += n;
322 return OSSL_RECORD_RETURN_SUCCESS;
326 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
327 * for us in the buffer.
329 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
337 p = SSL3_BUFFER_get_buf(rbuf);
341 left = SSL3_BUFFER_get_left(rbuf);
343 if (left < SSL3_RT_HEADER_LENGTH)
346 p += SSL3_BUFFER_get_offset(rbuf);
349 * We only check the type and record length, we will sanity check version
352 if (*p != SSL3_RT_APPLICATION_DATA)
358 if (left < SSL3_RT_HEADER_LENGTH + len)
364 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
365 size_t overhead, int send)
367 uint32_t max_early_data = rl->max_early_data;
369 if (max_early_data == 0) {
370 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
371 SSL_R_TOO_MUCH_EARLY_DATA);
375 /* If we are dealing with ciphertext we need to allow for the overhead */
376 max_early_data += overhead;
378 if (rl->early_data_count + length > max_early_data) {
379 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
380 SSL_R_TOO_MUCH_EARLY_DATA);
383 rl->early_data_count += length;
389 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
390 * will be processed per call to tls_get_more_records. Without this limit an
391 * attacker could send empty records at a faster rate than we can process and
392 * cause tls_get_more_records to loop forever.
394 #define MAX_EMPTY_RECORDS 32
396 #define SSL2_RT_HEADER_LENGTH 2
399 * Call this to buffer new input records in rl->rrec.
400 * It will return a OSSL_RECORD_RETURN_* value.
401 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
402 * records have been decoded. For each record 'i':
403 * rrec[i].type - is the type of record
404 * rrec[i].data, - data
405 * rrec[i].length, - number of bytes
406 * Multiple records will only be returned if the record types are all
407 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
410 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
415 SSL3_RECORD *rr, *thisrr;
418 unsigned char md[EVP_MAX_MD_SIZE];
419 unsigned int version;
422 size_t num_recs = 0, max_recs, j;
423 PACKET pkt, sslv2pkt;
424 SSL_MAC_BUF *macbufs = NULL;
425 int ret = OSSL_RECORD_RETURN_FATAL;
429 if (rbuf->buf == NULL) {
430 if (!tls_setup_read_buffer(rl)) {
431 /* RLAYERfatal() already called */
432 return OSSL_RECORD_RETURN_FATAL;
436 max_recs = rl->max_pipelines;
442 thisrr = &rr[num_recs];
444 /* check if we have the header */
445 if ((rl->rstate != SSL_ST_READ_BODY) ||
446 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
450 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
451 SSL3_BUFFER_get_len(rbuf), 0,
452 num_recs == 0 ? 1 : 0, &n);
454 if (rret < OSSL_RECORD_RETURN_SUCCESS)
455 return rret; /* error or non-blocking */
457 rl->rstate = SSL_ST_READ_BODY;
460 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
461 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
462 return OSSL_RECORD_RETURN_FATAL;
465 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
466 || !PACKET_get_1(&sslv2pkt, &type)) {
467 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
468 return OSSL_RECORD_RETURN_FATAL;
471 * The first record received by the server may be a V2ClientHello.
473 if (rl->role == OSSL_RECORD_ROLE_SERVER
474 && rl->is_first_record
475 && (sslv2len & 0x8000) != 0
476 && (type == SSL2_MT_CLIENT_HELLO)) {
480 * |num_recs| here will actually always be 0 because
481 * |num_recs > 0| only ever occurs when we are processing
482 * multiple app data records - which we know isn't the case here
483 * because it is an SSLv2ClientHello. We keep it using
484 * |num_recs| for the sake of consistency
486 thisrr->type = SSL3_RT_HANDSHAKE;
487 thisrr->rec_version = SSL2_VERSION;
489 thisrr->length = sslv2len & 0x7fff;
491 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
492 - SSL2_RT_HEADER_LENGTH) {
493 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
494 SSL_R_PACKET_LENGTH_TOO_LONG);
495 return OSSL_RECORD_RETURN_FATAL;
498 /* SSLv3+ style record */
500 /* Pull apart the header into the SSL3_RECORD */
501 if (!PACKET_get_1(&pkt, &type)
502 || !PACKET_get_net_2(&pkt, &version)
503 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
504 if (rl->msg_callback != NULL)
505 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
506 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
507 return OSSL_RECORD_RETURN_FATAL;
510 thisrr->rec_version = version;
513 * When we call validate_record_header() only records actually
514 * received in SSLv2 format should have the record version set
515 * to SSL2_VERSION. This way validate_record_header() can know
516 * what format the record was in based on the version.
518 if (thisrr->rec_version == SSL2_VERSION) {
519 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
520 SSL_R_WRONG_VERSION_NUMBER);
521 return OSSL_RECORD_RETURN_FATAL;
524 if (rl->msg_callback != NULL)
525 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
528 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
529 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
530 SSL_R_PACKET_LENGTH_TOO_LONG);
531 return OSSL_RECORD_RETURN_FATAL;
535 if (!rl->funcs->validate_record_header(rl, thisrr)) {
536 /* RLAYERfatal already called */
537 return OSSL_RECORD_RETURN_FATAL;
540 /* now rl->rstate == SSL_ST_READ_BODY */
544 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
545 * how much more data we need to read for the rest of the record
547 if (thisrr->rec_version == SSL2_VERSION) {
548 more = thisrr->length + SSL2_RT_HEADER_LENGTH
549 - SSL3_RT_HEADER_LENGTH;
551 more = thisrr->length;
555 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
557 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
558 if (rret < OSSL_RECORD_RETURN_SUCCESS)
559 return rret; /* error or non-blocking io */
562 /* set state for later operations */
563 rl->rstate = SSL_ST_READ_HEADER;
566 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
567 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
568 * + thisrr->length and we have that many bytes in rl->packet
570 if (thisrr->rec_version == SSL2_VERSION)
571 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
573 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
576 * ok, we can now read from 'rl->packet' data into 'thisrr'.
577 * thisrr->input points at thisrr->length bytes, which need to be copied
578 * into thisrr->data by either the decryption or by the decompression.
579 * When the data is 'copied' into the thisrr->data buffer,
580 * thisrr->input will be updated to point at the new buffer
584 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
585 * thisrr->length bytes of encrypted compressed stuff.
588 /* decrypt in place in 'thisrr->input' */
589 thisrr->data = thisrr->input;
590 thisrr->orig_len = thisrr->length;
594 /* we have pulled in a full packet so zero things */
595 rl->packet_length = 0;
596 rl->is_first_record = 0;
597 } while (num_recs < max_recs
598 && thisrr->type == SSL3_RT_APPLICATION_DATA
599 && RLAYER_USE_EXPLICIT_IV(rl)
600 && rl->enc_ctx != NULL
601 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
602 & EVP_CIPH_FLAG_PIPELINE) != 0
603 && tls_record_app_data_waiting(rl));
606 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
607 /* The following can happen in tlsany_meth after HRR */
608 && rl->version == TLS1_3_VERSION
609 && rl->is_first_handshake) {
611 * CCS messages must be exactly 1 byte long, containing the value 0x01
613 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
614 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
615 SSL_R_INVALID_CCS_MESSAGE);
616 return OSSL_RECORD_RETURN_FATAL;
619 * CCS messages are ignored in TLSv1.3. We treat it like an empty
622 thisrr->type = SSL3_RT_HANDSHAKE;
623 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
624 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
625 SSL_R_UNEXPECTED_CCS_MESSAGE);
626 return OSSL_RECORD_RETURN_FATAL;
630 rl->num_released = 0;
632 return OSSL_RECORD_RETURN_SUCCESS;
635 if (rl->md_ctx != NULL) {
636 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
639 imac_size = EVP_MD_get_size(tmpmd);
640 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
641 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
642 return OSSL_RECORD_RETURN_FATAL;
644 mac_size = (size_t)imac_size;
649 * If in encrypt-then-mac mode calculate mac from encrypted record. All
650 * the details below are public so no timing details can leak.
652 if (rl->use_etm && rl->md_ctx) {
655 for (j = 0; j < num_recs; j++) {
658 if (thisrr->length < mac_size) {
659 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
660 return OSSL_RECORD_RETURN_FATAL;
662 thisrr->length -= mac_size;
663 mac = thisrr->data + thisrr->length;
664 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
665 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
666 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
667 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
668 return OSSL_RECORD_RETURN_FATAL;
672 * We've handled the mac now - there is no MAC inside the encrypted
679 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
680 if (macbufs == NULL) {
681 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
682 return OSSL_RECORD_RETURN_FATAL;
686 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
690 * 0: if the record is publicly invalid, or an internal error, or AEAD
691 * decryption failed, or ETM decryption failed.
692 * 1: Success or MTE decryption failed (MAC will be randomised)
695 if (rl->alert != SSL_AD_NO_ALERT) {
696 /* RLAYERfatal() already got called */
700 && rl->skip_early_data != NULL
701 && rl->skip_early_data(rl->cbarg)) {
703 * Valid early_data that we cannot decrypt will fail here. We treat
704 * it like an empty record.
709 if (!rlayer_early_data_count_ok(rl, thisrr->length,
710 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
711 /* RLAYERfatal() already called */
718 rl->num_released = 0;
719 /* Reset the read sequence */
720 memset(rl->sequence, 0, sizeof(rl->sequence));
724 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
725 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
728 OSSL_TRACE_BEGIN(TLS) {
729 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
730 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
731 } OSSL_TRACE_END(TLS);
733 /* r->length is now the compressed data plus mac */
734 if (rl->enc_ctx != NULL
736 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
737 /* rl->md_ctx != NULL => mac_size != -1 */
739 for (j = 0; j < num_recs; j++) {
740 SSL_MAC_BUF *thismb = &macbufs[j];
744 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
745 if (i == 0 || thismb == NULL || thismb->mac == NULL
746 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
748 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
754 if (rl->alert != SSL_AD_NO_ALERT) {
755 /* We already called RLAYERfatal() */
759 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
760 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
761 * failure is directly visible from the ciphertext anyway, we should
762 * not reveal which kind of error occurred -- this might become
763 * visible to an attacker (e.g. via a logfile)
765 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
766 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
770 for (j = 0; j < num_recs; j++) {
773 if (!rl->funcs->post_process_record(rl, thisrr)) {
774 /* RLAYERfatal already called */
779 * Check if the received packet overflows the current
780 * Max Fragment Length setting.
781 * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
783 if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
784 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
790 * So at this point the following is true
791 * thisrr->type is the type of record
792 * thisrr->length == number of bytes in record
793 * thisrr->off == offset to first valid byte
794 * thisrr->data == where to take bytes from, increment after use :-).
797 /* just read a 0 length packet */
798 if (thisrr->length == 0) {
799 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
800 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
801 SSL_R_RECORD_TOO_SMALL);
805 rl->empty_record_count = 0;
809 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
811 if (thisrr->type == SSL3_RT_APPLICATION_DATA
812 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
813 /* RLAYERfatal already called */
818 rl->num_recs = num_recs;
820 rl->num_released = 0;
821 ret = OSSL_RECORD_RETURN_SUCCESS;
823 if (macbufs != NULL) {
824 for (j = 0; j < num_recs; j++) {
825 if (macbufs[j].alloced)
826 OPENSSL_free(macbufs[j].mac);
828 OPENSSL_free(macbufs);
833 /* Shared by ssl3_meth and tls1_meth */
834 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
836 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
838 if (rec->rec_version != rl->version) {
839 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
843 #ifndef OPENSSL_NO_COMP
845 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
846 * does not include the compression overhead anyway.
848 if (rl->expand == NULL)
849 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
852 if (rec->length > len) {
853 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
854 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
861 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
863 #ifndef OPENSSL_NO_COMP
866 if (rec->comp == NULL) {
867 rec->comp = (unsigned char *)
868 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
870 if (rec->comp == NULL)
873 i = COMP_expand_block(rl->expand, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
874 rec->data, (int)rec->length);
879 rec->data = rec->comp;
886 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
887 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
889 if (rl->expand != NULL) {
890 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
891 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
892 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
895 if (!tls_do_uncompress(rl, rec)) {
896 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
897 SSL_R_BAD_DECOMPRESSION);
902 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
903 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
910 /* Shared by tls13_meth and ktls_meth */
911 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
913 if (rec->type != SSL3_RT_APPLICATION_DATA
914 && rec->type != SSL3_RT_ALERT
915 && rec->type != SSL3_RT_HANDSHAKE) {
916 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
920 if (rl->msg_callback != NULL)
921 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
925 * TLSv1.3 alert and handshake records are required to be non-zero in
928 if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
929 && rec->length == 0) {
930 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
937 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
938 int *type, unsigned char **data, size_t *datalen,
939 uint16_t *epoch, unsigned char *seq_num)
944 * tls_get_more_records() can return success without actually reading
945 * anything useful (i.e. if empty records are read). We loop here until
946 * we have something useful. tls_get_more_records() will eventually fail if
947 * too many sequential empty records are read.
949 while (rl->curr_rec >= rl->num_recs) {
952 if (rl->num_released != rl->num_recs) {
953 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
954 return OSSL_RECORD_RETURN_FATAL;
957 ret = rl->funcs->get_more_records(rl);
959 if (ret != OSSL_RECORD_RETURN_SUCCESS)
964 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
965 * points to the next one to read.
967 rec = &rl->rrec[rl->curr_rec++];
970 *rversion = rec->rec_version;
972 *data = rec->data + rec->off;
973 *datalen = rec->length;
976 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
979 return OSSL_RECORD_RETURN_SUCCESS;
982 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
984 if (!ossl_assert(rl->num_released < rl->curr_rec)
985 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
986 /* Should not happen */
987 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
988 return OSSL_RECORD_RETURN_FATAL;
993 if (rl->curr_rec == rl->num_released
994 && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
995 && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
996 tls_release_read_buffer(rl);
998 return OSSL_RECORD_RETURN_SUCCESS;
1001 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1003 const OSSL_PARAM *p;
1005 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1006 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1007 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1011 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1012 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1013 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1017 p = OSSL_PARAM_locate_const(options,
1018 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1019 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1020 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1024 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1026 * We ignore any read_ahead setting prior to the application protection
1027 * level. Otherwise we may read ahead data in a lower protection level
1028 * that is destined for a higher protection level. To simplify the logic
1029 * we don't support that at this stage.
1031 p = OSSL_PARAM_locate_const(options,
1032 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1033 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1034 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1043 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1044 int role, int direction, int level, unsigned char *key,
1045 size_t keylen, unsigned char *iv, size_t ivlen,
1046 unsigned char *mackey, size_t mackeylen,
1047 const EVP_CIPHER *ciph, size_t taglen,
1049 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1050 BIO *transport, BIO *next, BIO_ADDR *local,
1051 BIO_ADDR *peer, const OSSL_PARAM *settings,
1052 const OSSL_PARAM *options,
1053 const OSSL_DISPATCH *fns, void *cbarg,
1054 OSSL_RECORD_LAYER **retrl)
1056 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1057 const OSSL_PARAM *p;
1062 ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
1063 return OSSL_RECORD_RETURN_FATAL;
1066 /* Loop through all the settings since they must all be understood */
1067 if (settings != NULL) {
1068 for (p = settings; p->key != NULL; p++) {
1069 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1070 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1071 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1074 } else if (strcmp(p->key,
1075 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1076 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1077 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1080 } else if (strcmp(p->key,
1081 OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1082 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1083 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1086 } else if (strcmp(p->key,
1087 OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1088 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1089 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1092 } else if (strcmp(p->key,
1093 OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1094 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1095 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1099 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1105 rl->libctx = libctx;
1110 rl->direction = direction;
1113 rl->alert = SSL_AD_NO_ALERT;
1115 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1116 rl->is_first_record = 1;
1118 if (!tls_set1_bio(rl, transport))
1121 if (prev != NULL && !BIO_up_ref(prev))
1125 if (next != NULL && !BIO_up_ref(next))
1131 for (; fns->function_id != 0; fns++) {
1132 switch (fns->function_id) {
1133 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1134 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1136 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1137 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1139 case OSSL_FUNC_RLAYER_SECURITY:
1140 rl->security = OSSL_FUNC_rlayer_security(fns);
1143 /* Just ignore anything we don't understand */
1149 if (!tls_set_options(rl, options)) {
1150 ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1155 return OSSL_RECORD_RETURN_SUCCESS;
1158 return OSSL_RECORD_RETURN_FATAL;
1162 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1163 int role, int direction, int level, uint16_t epoch,
1164 unsigned char *key, size_t keylen, unsigned char *iv,
1165 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1166 const EVP_CIPHER *ciph, size_t taglen,
1168 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1169 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1170 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1171 const OSSL_DISPATCH *fns, void *cbarg,
1172 OSSL_RECORD_LAYER **retrl)
1176 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1177 key, keylen, iv, ivlen, mackey, mackeylen,
1178 ciph, taglen, mactype, md, comp, prev,
1179 transport, next, local, peer, settings,
1180 options, fns, cbarg, retrl);
1182 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1186 case TLS_ANY_VERSION:
1187 (*retrl)->funcs = &tls_any_funcs;
1189 case TLS1_3_VERSION:
1190 (*retrl)->funcs = &tls_1_3_funcs;
1192 case TLS1_2_VERSION:
1193 case TLS1_1_VERSION:
1195 (*retrl)->funcs = &tls_1_funcs;
1198 (*retrl)->funcs = &ssl_3_0_funcs;
1201 /* Should not happen */
1202 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1203 ret = OSSL_RECORD_RETURN_FATAL;
1207 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1208 ivlen, mackey, mackeylen, ciph,
1209 taglen, mactype, md, comp);
1212 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1213 OPENSSL_free(*retrl);
1219 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1224 SSL3_BUFFER_release(&rl->rbuf);
1226 EVP_CIPHER_CTX_free(rl->enc_ctx);
1227 EVP_MD_CTX_free(rl->md_ctx);
1228 #ifndef OPENSSL_NO_COMP
1229 COMP_CTX_free(rl->expand);
1232 if (rl->version == SSL3_VERSION)
1233 OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1235 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1240 int tls_free(OSSL_RECORD_LAYER *rl)
1243 size_t left, written;
1248 left = SSL3_BUFFER_get_left(rbuf);
1251 * This record layer is closing but we still have data left in our
1252 * buffer. It must be destined for the next epoch - so push it there.
1254 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1261 int tls_reset(OSSL_RECORD_LAYER *rl)
1263 memset(rl, 0, sizeof(*rl));
1267 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1269 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1272 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1274 return rl->curr_rec < rl->num_recs;
1277 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1282 for (i = rl->curr_rec; i < rl->num_recs; i++) {
1283 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1285 num += rl->rrec[i].length;
1290 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1295 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1300 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1305 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1308 WPACKET pkt[SSL_MAX_PIPELINES + 1];
1309 SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1311 SSL3_RECORD *thiswr;
1312 unsigned char *recordstart;
1313 int mac_size, clear = 0;
1318 size_t totlen = 0, len, wpinited = 0;
1319 size_t j, prefix = 0;
1321 /* TODO(RECLAYER): REMOVE ME */
1322 SSL_CONNECTION *s = rl->cbarg;
1323 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1324 OSSL_RECORD_TEMPLATE prefixtempl;
1325 OSSL_RECORD_TEMPLATE *thistempl;
1327 if (!ossl_assert(!RECORD_LAYER_write_pending(&s->rlayer))) {
1328 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1335 || (s->enc_write_ctx == NULL)
1336 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
1337 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
1340 mac_size = EVP_MD_CTX_get_size(s->write_hash);
1342 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1348 * 'create_empty_fragment' is true only when we have recursively called
1350 * Do we need to do that recursion in order to add an empty record prefix?
1352 prefix = s->s3.need_empty_fragments
1354 && !s->s3.empty_fragment_done
1355 && templates[0].type == SSL3_RT_APPLICATION_DATA;
1357 if (s->rlayer.numwpipes < numtempl + prefix) {
1359 * TODO(RECLAYER): In the prefix case the first buffer can be a lot
1360 * smaller. It is wasteful to allocate a full sized buffer here
1362 if (!ssl3_setup_write_buffer(s, numtempl + prefix, 0)) {
1363 /* SSLfatal() already called */
1368 using_ktls = BIO_get_ktls_send(s->wbio);
1369 if (!ossl_assert(!using_ktls || !prefix)) {
1370 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1376 * countermeasure against known-IV weakness in CBC ciphersuites (see
1377 * http://www.openssl.org/~bodo/tls-cbc.txt)
1379 prefixtempl.buf = NULL;
1380 prefixtempl.buflen = 0;
1381 prefixtempl.type = SSL3_RT_APPLICATION_DATA;
1384 /* TODO(RECLAYER): Do we actually need this? */
1385 s->s3.empty_fragment_done = 1;
1387 wb = &s->rlayer.wbuf[0];
1388 /* TODO(RECLAYER): This alignment calculation no longer seems right */
1389 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
1391 * extra fragment would be couple of cipher blocks, which would be
1392 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
1393 * payload, then we can just pretend we simply have two headers.
1395 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
1396 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1398 SSL3_BUFFER_set_offset(wb, align);
1399 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
1400 SSL3_BUFFER_get_len(wb), 0)
1401 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
1402 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1407 for (j = 0; j < numtempl; j++) {
1408 thispkt = &pkt[prefix + j];
1410 wb = &s->rlayer.wbuf[prefix + j];
1411 wb->type = templates[j].type;
1415 * ktls doesn't modify the buffer, but to avoid a warning we need
1416 * to discard the const qualifier.
1417 * This doesn't leak memory because the buffers have been
1418 * released when switching to ktls.
1420 SSL3_BUFFER_set_buf(wb, (unsigned char *)templates[j].buf);
1421 SSL3_BUFFER_set_offset(wb, 0);
1422 SSL3_BUFFER_set_app_buffer(wb, 1);
1424 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1425 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
1426 align = SSL3_ALIGN_PAYLOAD - 1
1427 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1429 /* TODO(RECLAYER): Is this alignment actually used somewhere? */
1430 SSL3_BUFFER_set_offset(wb, align);
1431 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1432 SSL3_BUFFER_get_len(wb), 0)
1433 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
1434 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1442 /* Explicit IV length, block ciphers appropriate version flag */
1443 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
1444 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
1445 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
1446 if (mode == EVP_CIPH_CBC_MODE) {
1447 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
1449 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
1454 } else if (mode == EVP_CIPH_GCM_MODE) {
1455 /* Need explicit part of IV for GCM mode */
1456 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
1457 } else if (mode == EVP_CIPH_CCM_MODE) {
1458 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
1464 /* Clear our SSL3_RECORD structures */
1465 memset(wr, 0, sizeof(wr));
1466 for (j = 0; j < numtempl + prefix; j++) {
1467 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
1469 unsigned char *compressdata = NULL;
1471 unsigned int rectype;
1475 thistempl = (j == 0 && prefix == 1) ? &prefixtempl :
1476 &templates[j - prefix];
1479 * In TLSv1.3, once encrypting, we always use application data for the
1482 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
1483 && s->enc_write_ctx != NULL
1484 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1485 || thistempl->type != SSL3_RT_ALERT))
1486 rectype = SSL3_RT_APPLICATION_DATA;
1488 rectype = thistempl->type;
1490 SSL3_RECORD_set_type(thiswr, rectype);
1493 * Some servers hang if initial client hello is larger than 256 bytes
1494 * and record version number > TLS 1.0
1496 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
1498 && TLS1_get_version(ssl) > TLS1_VERSION
1499 && s->hello_retry_request == SSL_HRR_NONE)
1500 version = TLS1_VERSION;
1501 SSL3_RECORD_set_rec_version(thiswr, version);
1503 maxcomplen = thistempl->buflen;
1504 if (s->compress != NULL)
1505 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1508 * When using offload kernel will write the header.
1509 * Otherwise write the header now
1512 && (!WPACKET_put_bytes_u8(thispkt, rectype)
1513 || !WPACKET_put_bytes_u16(thispkt, version)
1514 || !WPACKET_start_sub_packet_u16(thispkt)
1516 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
1518 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1520 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1524 /* lets setup the record stuff. */
1525 SSL3_RECORD_set_data(thiswr, compressdata);
1526 SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1528 * TODO(RECLAYER): Cast away the const. Should be safe - by why is this
1531 SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1532 totlen += thistempl->buflen;
1535 * we now 'read' from thiswr->input, thiswr->length bytes into
1539 /* first we compress */
1540 if (s->compress != NULL) {
1541 if (!ssl3_do_compress(s, thiswr)
1542 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1543 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1548 SSL3_RECORD_reset_data(&wr[j]);
1550 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1551 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1554 SSL3_RECORD_reset_input(&wr[j]);
1558 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
1560 && s->enc_write_ctx != NULL
1561 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1562 || thistempl->type != SSL3_RT_ALERT)) {
1563 size_t rlen, max_send_fragment;
1565 if (!WPACKET_put_bytes_u8(thispkt, thistempl->type)) {
1566 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1569 SSL3_RECORD_add_length(thiswr, 1);
1571 /* Add TLS1.3 padding */
1572 max_send_fragment = ssl_get_max_send_fragment(s);
1573 rlen = SSL3_RECORD_get_length(thiswr);
1574 if (rlen < max_send_fragment) {
1576 size_t max_padding = max_send_fragment - rlen;
1577 if (s->record_padding_cb != NULL) {
1578 padding = s->record_padding_cb(ssl, thistempl->type, rlen,
1579 s->record_padding_arg);
1580 } else if (s->block_padding > 0) {
1581 size_t mask = s->block_padding - 1;
1584 /* optimize for power of 2 */
1585 if ((s->block_padding & mask) == 0)
1586 remainder = rlen & mask;
1588 remainder = rlen % s->block_padding;
1589 /* don't want to add a block of padding if we don't have to */
1593 padding = s->block_padding - remainder;
1596 /* do not allow the record to exceed max plaintext length */
1597 if (padding > max_padding)
1598 padding = max_padding;
1599 if (!WPACKET_memset(thispkt, 0, padding)) {
1600 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1601 ERR_R_INTERNAL_ERROR);
1604 SSL3_RECORD_add_length(thiswr, padding);
1610 * we should still have the output to thiswr->data and the input from
1611 * wr->input. Length should be thiswr->length. thiswr->data still points
1615 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
1618 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1619 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1620 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1626 * Reserve some bytes for any growth that may occur during encryption.
1627 * This will be at most one cipher block or the tag length if using
1628 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1631 if (!WPACKET_reserve_bytes(thispkt,
1632 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1635 * We also need next the amount of bytes written to this
1638 || !WPACKET_get_length(thispkt, &len)) {
1639 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1643 /* Get a pointer to the start of this record excluding header */
1644 recordstart = WPACKET_get_curr(thispkt) - len;
1645 SSL3_RECORD_set_data(thiswr, recordstart);
1646 SSL3_RECORD_reset_input(thiswr);
1647 SSL3_RECORD_set_length(thiswr, len);
1651 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
1653 * We haven't actually negotiated the version yet, but we're trying to
1654 * send early data - so we need to use the tls13enc function.
1656 if (tls13_enc(s, wr, numtempl, 1, NULL, mac_size) < 1) {
1657 if (!ossl_statem_in_error(s)) {
1658 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1665 if (ssl->method->ssl3_enc->enc(s, wr, 1, 1, NULL, mac_size) < 1) {
1666 if (!ossl_statem_in_error(s)) {
1667 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1672 if (ssl->method->ssl3_enc->enc(s, wr + prefix, numtempl, 1, NULL,
1674 if (!ossl_statem_in_error(s)) {
1675 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1682 for (j = 0; j < prefix + numtempl; j++) {
1687 thistempl = (prefix == 1 && j == 0) ? &prefixtempl
1688 : &templates[j - prefix];
1693 /* Allocate bytes for the encryption overhead */
1694 if (!WPACKET_get_length(thispkt, &origlen)
1695 /* Encryption should never shrink the data! */
1696 || origlen > thiswr->length
1697 || (thiswr->length > origlen
1698 && !WPACKET_allocate_bytes(thispkt,
1699 thiswr->length - origlen,
1701 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1704 if (SSL_WRITE_ETM(s) && mac_size != 0) {
1707 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1708 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1709 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1712 SSL3_RECORD_add_length(thiswr, mac_size);
1715 if (!WPACKET_get_length(thispkt, &len)
1716 || !WPACKET_close(thispkt)) {
1717 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1721 if (rl->msg_callback) {
1722 recordstart = WPACKET_get_curr(thispkt) - len
1723 - SSL3_RT_HEADER_LENGTH;
1724 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1725 SSL3_RT_HEADER_LENGTH, rl->cbarg);
1727 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
1728 unsigned char ctype = thistempl->type;
1730 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1731 &ctype, 1, rl->cbarg);
1735 if (!WPACKET_finish(thispkt)) {
1736 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1740 /* header is added by the kernel when using offload */
1741 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1745 * we should now have thiswr->data pointing to the encrypted data, which
1746 * is thiswr->length long.
1747 * Setting the type is not needed but helps for debugging
1749 SSL3_RECORD_set_type(thiswr, thistempl->type);
1751 /* now let's set up wb */
1752 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j], SSL3_RECORD_get_length(thiswr));
1755 /* we now just need to write the buffers */
1756 return tls_retry_write_records(rl);
1758 for (j = 0; j < wpinited; j++)
1759 WPACKET_cleanup(&pkt[j]);
1763 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1765 * Return values are as per SSL_write()
1767 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1770 SSL3_BUFFER *thiswb;
1773 SSL_CONNECTION *s = rl->cbarg;
1776 thiswb = &s->rlayer.wbuf[currbuf];
1777 /* Loop until we find a buffer we haven't written out yet */
1778 if (SSL3_BUFFER_get_left(thiswb) == 0
1779 && currbuf < s->rlayer.numwpipes - 1) {
1784 if (s->wbio != NULL) {
1785 s->rwstate = SSL_WRITING;
1788 * To prevent coalescing of control and data messages,
1789 * such as in buffer_write, we flush the BIO
1791 if (BIO_get_ktls_send(s->wbio)
1792 && thiswb->type != SSL3_RT_APPLICATION_DATA) {
1793 i = BIO_flush(s->wbio);
1796 BIO_set_ktls_ctrl_msg(s->wbio, thiswb->type);
1798 i = BIO_write(s->wbio, (char *)
1799 &(SSL3_BUFFER_get_buf(thiswb)
1800 [SSL3_BUFFER_get_offset(thiswb)]),
1801 (unsigned int)SSL3_BUFFER_get_left(thiswb));
1805 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1810 * When an empty fragment is sent on a connection using KTLS,
1811 * it is sent as a write of zero bytes. If this zero byte
1812 * write succeeds, i will be 0 rather than a non-zero value.
1813 * Treat i == 0 as success rather than an error for zero byte
1814 * writes to permit this case.
1816 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1817 SSL3_BUFFER_set_left(thiswb, 0);
1818 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1819 if (currbuf + 1 < s->rlayer.numwpipes)
1821 s->rwstate = SSL_NOTHING;
1823 * Next chunk of data should get another prepended empty fragment
1824 * in ciphersuites with known-IV weakness:
1826 s->s3.empty_fragment_done = 0;
1828 } else if (i <= 0) {
1829 if (SSL_CONNECTION_IS_DTLS(s)) {
1831 * For DTLS, just drop it. That's kind of the whole point in
1832 * using a datagram service
1834 SSL3_BUFFER_set_left(thiswb, 0);
1838 SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1839 SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1843 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1848 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1850 if (bio != NULL && !BIO_up_ref(bio))
1858 /* Shared by most methods except tlsany_meth */
1859 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1861 if (rl->version != version)
1867 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1869 return rl->funcs->set_protocol_version(rl, version);
1872 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1874 rl->allow_plain_alerts = allow;
1877 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1879 rl->is_first_handshake = first;
1882 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1884 rl->max_pipelines = max_pipelines;
1885 if (max_pipelines > 1)
1889 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1890 const char **longstr)
1892 const char *shrt, *lng;
1894 switch (rl->rstate) {
1895 case SSL_ST_READ_HEADER:
1897 lng = "read header";
1899 case SSL_ST_READ_BODY:
1904 shrt = lng = "unknown";
1907 if (shortstr != NULL)
1909 if (longstr != NULL)
1913 const OSSL_RECORD_METHOD ossl_tls_record_method = {
1914 tls_new_record_layer,
1917 tls_unprocessed_read_pending,
1918 tls_processed_read_pending,
1919 tls_app_data_pending,
1921 tls_get_max_record_len,
1922 tls_get_max_records,
1924 tls_retry_write_records,
1929 tls_set_protocol_version,
1930 tls_set_plain_alerts,
1931 tls_set_first_handshake,
1932 tls_set_max_pipelines,