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 # define SSL_AD_NO_ALERT -1
22 static void tls_int_free(OSSL_RECORD_LAYER *rl);
24 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
30 ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
36 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
38 const EVP_CIPHER *ciph,
42 * Provided cipher, the TLS padding/MAC removal is performed provider
43 * side so we need to tell the ctx about our TLS version and mac size
45 OSSL_PARAM params[3], *pprm = params;
49 if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
51 imacsize = EVP_MD_get_size(md);
53 macsize = (size_t)imacsize;
55 *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
57 *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
59 *pprm = OSSL_PARAM_construct_end();
61 if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
62 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
70 * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
71 * which ssl3_cbc_digest_record supports.
73 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
75 switch (EVP_MD_CTX_get_type(ctx)) {
88 #ifndef OPENSSL_NO_COMP
89 static int rlayer_allow_compression(OSSL_RECORD_LAYER *rl)
91 if (rl->options & SSL_OP_NO_COMPRESSION)
94 return rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
98 int rlayer_setup_read_buffer(OSSL_RECORD_LAYER *rl)
101 size_t len, align = 0, headerlen;
107 headerlen = DTLS1_RT_HEADER_LENGTH;
109 headerlen = SSL3_RT_HEADER_LENGTH;
111 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
112 align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
115 if (b->buf == NULL) {
116 len = SSL3_RT_MAX_PLAIN_LENGTH
117 + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
118 #ifndef OPENSSL_NO_COMP
119 if (rlayer_allow_compression(rl))
120 len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
122 if (b->default_len > len)
123 len = b->default_len;
124 if ((p = OPENSSL_malloc(len)) == NULL) {
126 * We've got a malloc failure, and we're still initialising buffers.
127 * We assume we're so doomed that we won't even be able to send an
130 RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
140 static int rlayer_release_read_buffer(OSSL_RECORD_LAYER *rl)
145 if (rl->options & SSL_OP_CLEANSE_PLAINTEXT)
146 OPENSSL_cleanse(b->buf, b->len);
147 OPENSSL_free(b->buf);
153 * Return values are as per SSL_read()
155 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
156 int clearold, size_t *readbytes)
159 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
160 * packet by another n bytes. The packet will be in the sub-array of
161 * s->rlayer.rbuf.buf specified by s->rlayer.packet and
162 * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
163 * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
164 * if clearold == 1, move the packet to the start of the buffer; if
165 * clearold == 0 then leave any old packets where they were
167 size_t len, left, align = 0;
172 return OSSL_RECORD_RETURN_NON_FATAL_ERR;
176 * TODO(RECLAYER): Once this function is only called from inside the rlayer
177 * directly, we can probably remove this since it is initialised in
178 * tls_get_more_records
180 if (rb->buf == NULL) {
181 if (!rlayer_setup_read_buffer(rl)) {
182 /* RLAYERfatal() already called */
183 return OSSL_RECORD_RETURN_FATAL;
188 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
189 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
190 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
194 /* start with empty packet ... */
197 } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
199 * check if next packet length is large enough to justify payload
202 pkt = rb->buf + rb->offset;
203 if (pkt[0] == SSL3_RT_APPLICATION_DATA
204 && (pkt[3] << 8 | pkt[4]) >= 128) {
206 * Note that even if packet is corrupted and its length field
207 * is insane, we can only be led to wrong decision about
208 * whether memmove will occur or not. Header values has no
209 * effect on memmove arguments and therefore no buffer
210 * overrun can be triggered.
212 memmove(rb->buf + align, pkt, left);
216 rl->packet = rb->buf + rb->offset;
217 rl->packet_length = 0;
218 /* ... now we can act as if 'extend' was set */
221 len = rl->packet_length;
222 pkt = rb->buf + align;
224 * Move any available bytes to front of buffer: 'len' bytes already
225 * pointed to by 'packet', 'left' extra ones at the end
227 if (rl->packet != pkt && clearold == 1) {
228 memmove(pkt, rl->packet, len + left);
230 rb->offset = len + align;
234 * For DTLS/UDP reads should not span multiple packets because the read
235 * operation returns the whole packet at once (as long as it fits into
239 if (left == 0 && extend)
241 if (left > 0 && n > left)
245 /* if there is enough in the buffer from a previous read, take some */
247 rl->packet_length += n;
251 return OSSL_RECORD_RETURN_SUCCESS;
254 /* else we need to read more data */
256 if (n > rb->len - rb->offset) {
257 /* does not happen */
258 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
259 return OSSL_RECORD_RETURN_FATAL;
262 /* We always act like read_ahead is set for DTLS */
263 if (!rl->read_ahead && !rl->isdtls) {
264 /* ignore max parameter */
269 if (max > rb->len - rb->offset)
270 max = rb->len - rb->offset;
276 BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
279 * Now we have len+left bytes at the front of s->s3.rbuf.buf and
280 * need to read in more until we have len+n (up to len+max if
286 ret = BIO_read(bio, pkt + len + left, max - left);
289 ret = OSSL_RECORD_RETURN_SUCCESS;
290 } else if (BIO_should_retry(bio)) {
291 if (rl->prev != NULL) {
293 * We were reading from the previous epoch. Now there is no
294 * more data, so swap to the actual transport BIO
300 ret = OSSL_RECORD_RETURN_RETRY;
301 } else if (BIO_eof(bio)) {
302 ret = OSSL_RECORD_RETURN_EOF;
304 ret = OSSL_RECORD_RETURN_FATAL;
307 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
308 ret = OSSL_RECORD_RETURN_FATAL;
311 if (ret <= OSSL_RECORD_RETURN_RETRY) {
313 if (rl->mode & SSL_MODE_RELEASE_BUFFERS && !rl->isdtls)
315 rlayer_release_read_buffer(rl);
320 * reads should *never* span multiple packets for DTLS because the
321 * underlying transport protocol is message oriented as opposed to
322 * byte oriented as in the TLS case.
326 n = left; /* makes the while condition false */
330 /* done reading, now the book-keeping */
333 rl->packet_length += n;
335 return OSSL_RECORD_RETURN_SUCCESS;
339 * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
340 * for us in the buffer.
342 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
350 p = SSL3_BUFFER_get_buf(rbuf);
354 left = SSL3_BUFFER_get_left(rbuf);
356 if (left < SSL3_RT_HEADER_LENGTH)
359 p += SSL3_BUFFER_get_offset(rbuf);
362 * We only check the type and record length, we will sanity check version
365 if (*p != SSL3_RT_APPLICATION_DATA)
371 if (left < SSL3_RT_HEADER_LENGTH + len)
377 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
378 size_t overhead, int send)
380 uint32_t max_early_data = rl->max_early_data;
382 if (max_early_data == 0) {
383 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
384 SSL_R_TOO_MUCH_EARLY_DATA);
388 /* If we are dealing with ciphertext we need to allow for the overhead */
389 max_early_data += overhead;
391 if (rl->early_data_count + length > max_early_data) {
392 RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
393 SSL_R_TOO_MUCH_EARLY_DATA);
396 rl->early_data_count += length;
402 * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
403 * will be processed per call to ssl3_get_record. Without this limit an
404 * attacker could send empty records at a faster rate than we can process and
405 * cause ssl3_get_record to loop forever.
407 #define MAX_EMPTY_RECORDS 32
409 #define SSL2_RT_HEADER_LENGTH 2
412 * Call this to buffer new input records in rl->rrec.
413 * It will return a OSSL_RECORD_RETURN_* value.
414 * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
415 * records have been decoded. For each record 'i':
416 * rrec[i].type - is the type of record
417 * rrec[i].data, - data
418 * rrec[i].length, - number of bytes
419 * Multiple records will only be returned if the record types are all
420 * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
423 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
428 SSL3_RECORD *rr, *thisrr;
431 unsigned char md[EVP_MAX_MD_SIZE];
432 unsigned int version;
435 size_t num_recs = 0, max_recs, j;
436 PACKET pkt, sslv2pkt;
437 SSL_MAC_BUF *macbufs = NULL;
438 int ret = OSSL_RECORD_RETURN_FATAL;
442 if (rbuf->buf == NULL) {
443 if (!rlayer_setup_read_buffer(rl)) {
444 /* RLAYERfatal() already called */
445 return OSSL_RECORD_RETURN_FATAL;
449 max_recs = rl->max_pipelines;
455 thisrr = &rr[num_recs];
457 /* check if we have the header */
458 if ((rl->rstate != SSL_ST_READ_BODY) ||
459 (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
463 rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
464 SSL3_BUFFER_get_len(rbuf), 0,
465 num_recs == 0 ? 1 : 0, &n);
467 if (rret < OSSL_RECORD_RETURN_SUCCESS)
468 return rret; /* error or non-blocking */
470 rl->rstate = SSL_ST_READ_BODY;
473 if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
474 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
475 return OSSL_RECORD_RETURN_FATAL;
478 if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
479 || !PACKET_get_1(&sslv2pkt, &type)) {
480 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
481 return OSSL_RECORD_RETURN_FATAL;
484 * The first record received by the server may be a V2ClientHello.
486 if (rl->role == OSSL_RECORD_ROLE_SERVER
487 && rl->is_first_record
488 && (sslv2len & 0x8000) != 0
489 && (type == SSL2_MT_CLIENT_HELLO)) {
493 * |num_recs| here will actually always be 0 because
494 * |num_recs > 0| only ever occurs when we are processing
495 * multiple app data records - which we know isn't the case here
496 * because it is an SSLv2ClientHello. We keep it using
497 * |num_recs| for the sake of consistency
499 thisrr->type = SSL3_RT_HANDSHAKE;
500 thisrr->rec_version = SSL2_VERSION;
502 thisrr->length = sslv2len & 0x7fff;
504 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
505 - SSL2_RT_HEADER_LENGTH) {
506 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
507 SSL_R_PACKET_LENGTH_TOO_LONG);
508 return OSSL_RECORD_RETURN_FATAL;
511 /* SSLv3+ style record */
513 /* Pull apart the header into the SSL3_RECORD */
514 if (!PACKET_get_1(&pkt, &type)
515 || !PACKET_get_net_2(&pkt, &version)
516 || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
517 rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
518 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
519 return OSSL_RECORD_RETURN_FATAL;
522 thisrr->rec_version = version;
525 * When we call validate_record_header() only records actually
526 * received in SSLv2 format should have the record version set
527 * to SSL2_VERSION. This way validate_record_header() can know
528 * what format the record was in based on the version.
530 if (thisrr->rec_version == SSL2_VERSION) {
531 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
532 SSL_R_WRONG_VERSION_NUMBER);
533 return OSSL_RECORD_RETURN_FATAL;
536 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
539 SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
540 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
541 SSL_R_PACKET_LENGTH_TOO_LONG);
542 return OSSL_RECORD_RETURN_FATAL;
546 if (!rl->funcs->validate_record_header(rl, thisrr)) {
547 /* RLAYERfatal already called */
548 return OSSL_RECORD_RETURN_FATAL;
551 /* now rl->rstate == SSL_ST_READ_BODY */
555 * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
556 * how much more data we need to read for the rest of the record
558 if (thisrr->rec_version == SSL2_VERSION) {
559 more = thisrr->length + SSL2_RT_HEADER_LENGTH
560 - SSL3_RT_HEADER_LENGTH;
562 more = thisrr->length;
566 /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
568 rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
569 if (rret < OSSL_RECORD_RETURN_SUCCESS)
570 return rret; /* error or non-blocking io */
573 /* set state for later operations */
574 rl->rstate = SSL_ST_READ_HEADER;
577 * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
578 * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
579 * + thisrr->length and we have that many bytes in rl->packet
581 if (thisrr->rec_version == SSL2_VERSION)
582 thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
584 thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
587 * ok, we can now read from 'rl->packet' data into 'thisrr'.
588 * thisrr->input points at thisrr->length bytes, which need to be copied
589 * into thisrr->data by either the decryption or by the decompression.
590 * When the data is 'copied' into the thisrr->data buffer,
591 * thisrr->input will be updated to point at the new buffer
595 * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
596 * thisrr->length bytes of encrypted compressed stuff.
599 /* decrypt in place in 'thisrr->input' */
600 thisrr->data = thisrr->input;
601 thisrr->orig_len = thisrr->length;
603 /* Mark this record as not read by upper layers yet */
608 /* we have pulled in a full packet so zero things */
609 rl->packet_length = 0;
610 rl->is_first_record = 0;
611 } while (num_recs < max_recs
612 && thisrr->type == SSL3_RT_APPLICATION_DATA
613 && RLAYER_USE_EXPLICIT_IV(rl)
614 && rl->enc_ctx != NULL
615 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
616 & EVP_CIPH_FLAG_PIPELINE) != 0
617 && tls_record_app_data_waiting(rl));
620 && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
621 /* The following can happen in tlsany_meth after HRR */
622 && rl->version == TLS1_3_VERSION
623 && rl->is_first_handshake) {
625 * CCS messages must be exactly 1 byte long, containing the value 0x01
627 if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
628 RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
629 SSL_R_INVALID_CCS_MESSAGE);
630 return OSSL_RECORD_RETURN_FATAL;
633 * CCS messages are ignored in TLSv1.3. We treat it like an empty
636 thisrr->type = SSL3_RT_HANDSHAKE;
637 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
638 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
639 SSL_R_UNEXPECTED_CCS_MESSAGE);
640 return OSSL_RECORD_RETURN_FATAL;
645 rl->num_released = 0;
647 return OSSL_RECORD_RETURN_SUCCESS;
650 if (rl->md_ctx != NULL) {
651 const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
654 imac_size = EVP_MD_get_size(tmpmd);
655 if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
656 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
657 return OSSL_RECORD_RETURN_FATAL;
659 mac_size = (size_t)imac_size;
664 * If in encrypt-then-mac mode calculate mac from encrypted record. All
665 * the details below are public so no timing details can leak.
667 if (rl->use_etm && rl->md_ctx) {
670 for (j = 0; j < num_recs; j++) {
673 if (thisrr->length < mac_size) {
674 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
675 return OSSL_RECORD_RETURN_FATAL;
677 thisrr->length -= mac_size;
678 mac = thisrr->data + thisrr->length;
679 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
680 if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
681 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
682 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
683 return OSSL_RECORD_RETURN_FATAL;
687 * We've handled the mac now - there is no MAC inside the encrypted
694 macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
695 if (macbufs == NULL) {
696 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
697 return OSSL_RECORD_RETURN_FATAL;
701 enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
705 * 0: if the record is publicly invalid, or an internal error, or AEAD
706 * decryption failed, or ETM decryption failed.
707 * 1: Success or MTE decryption failed (MAC will be randomised)
710 if (rl->alert != 0) {
711 /* RLAYERfatal() already got called */
714 if (num_recs == 1 && rl->skip_early_data(rl->cbarg)) {
716 * Valid early_data that we cannot decrypt will fail here. We treat
717 * it like an empty record.
722 if (!rlayer_early_data_count_ok(rl, thisrr->length,
723 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
724 /* RLAYERfatal() already called */
732 rl->num_released = 0;
733 /* Reset the read sequence */
734 memset(rl->sequence, 0, sizeof(rl->sequence));
738 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
739 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
742 OSSL_TRACE_BEGIN(TLS) {
743 BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
744 BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
745 } OSSL_TRACE_END(TLS);
747 /* r->length is now the compressed data plus mac */
748 if (rl->enc_ctx != NULL
750 && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
751 /* rl->md_ctx != NULL => mac_size != -1 */
753 for (j = 0; j < num_recs; j++) {
754 SSL_MAC_BUF *thismb = &macbufs[j];
757 i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
758 if (i == 0 || thismb == NULL || thismb->mac == NULL
759 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
761 if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
767 if (rl->alert != 0) {
768 /* We already called RLAYERfatal() */
772 * A separate 'decryption_failed' alert was introduced with TLS 1.0,
773 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
774 * failure is directly visible from the ciphertext anyway, we should
775 * not reveal which kind of error occurred -- this might become
776 * visible to an attacker (e.g. via a logfile)
778 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
779 SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
783 for (j = 0; j < num_recs; j++) {
786 if (!rl->funcs->post_process_record(rl, thisrr)) {
787 /* RLAYERfatal already called */
792 * Check if the received packet overflows the current
793 * Max Fragment Length setting.
794 * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
796 if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
797 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
803 * So at this point the following is true
804 * thisrr->type is the type of record
805 * thisrr->length == number of bytes in record
806 * thisrr->off == offset to first valid byte
807 * thisrr->data == where to take bytes from, increment after use :-).
810 /* just read a 0 length packet */
811 if (thisrr->length == 0) {
812 if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
813 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL);
817 rl->empty_record_count = 0;
821 if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
823 if (thisrr->type == SSL3_RT_APPLICATION_DATA
824 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
825 /* RLAYERfatal already called */
830 rl->num_recs = num_recs;
832 rl->num_released = 0;
833 ret = OSSL_RECORD_RETURN_SUCCESS;
835 if (macbufs != NULL) {
836 for (j = 0; j < num_recs; j++) {
837 if (macbufs[j].alloced)
838 OPENSSL_free(macbufs[j].mac);
840 OPENSSL_free(macbufs);
845 /* Shared by ssl3_meth and tls1_meth */
846 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
848 size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
850 if (rec->rec_version != rl->version) {
851 RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
855 #ifndef OPENSSL_NO_COMP
857 * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
858 * does not include the compression overhead anyway.
860 if (rl->expand == NULL)
861 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
864 if (rec->length > len) {
865 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
866 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
873 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
875 #ifndef OPENSSL_NO_COMP
878 if (rec->comp == NULL) {
879 rec->comp = (unsigned char *)
880 OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
882 if (rec->comp == NULL)
885 i = COMP_expand_block(rl->expand, rec->comp,
886 SSL3_RT_MAX_PLAIN_LENGTH, rec->data, (int)rec->length);
891 rec->data = rec->comp;
898 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
899 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
901 if (rl->expand != NULL) {
902 if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
903 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
904 SSL_R_COMPRESSED_LENGTH_TOO_LONG);
907 if (!tls_do_uncompress(rl, rec)) {
908 RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
909 SSL_R_BAD_DECOMPRESSION);
914 if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
915 RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
922 /* Shared by tls13_meth and ktls_meth */
923 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
925 if (rec->type != SSL3_RT_APPLICATION_DATA
926 && rec->type != SSL3_RT_ALERT
927 && rec->type != SSL3_RT_HANDSHAKE) {
928 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
932 rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
936 * TLSv1.3 alert and handshake records are required to be non-zero in
939 if ((rec->type == SSL3_RT_HANDSHAKE
940 || rec->type == SSL3_RT_ALERT)
941 && rec->length == 0) {
942 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
949 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
950 int *type, unsigned char **data, size_t *datalen,
951 uint16_t *epoch, unsigned char *seq_num)
956 * tls_get_more_records() can return success without actually reading
957 * anything useful (i.e. if empty records are read). We loop here until
958 * we have something useful. tls_get_more_records() will eventually fail if
959 * too many sequential empty records are read.
961 while (rl->curr_rec >= rl->num_recs) {
964 if (rl->num_released != rl->num_recs) {
965 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
966 return OSSL_RECORD_RETURN_FATAL;
969 ret = rl->funcs->get_more_records(rl);
971 if (ret != OSSL_RECORD_RETURN_SUCCESS)
976 * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
977 * points to the next one to read.
979 rec = &rl->rrec[rl->curr_rec++];
982 *rversion = rec->rec_version;
984 *data = rec->data + rec->off;
985 *datalen = rec->length;
987 *epoch = (uint16_t)rec->epoch;
988 memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
991 return OSSL_RECORD_RETURN_SUCCESS;
994 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
996 if (!ossl_assert(rl->num_released < rl->curr_rec)
997 || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
998 /* Should not happen */
999 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1000 return OSSL_RECORD_RETURN_FATAL;
1005 return OSSL_RECORD_RETURN_SUCCESS;
1009 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1010 int role, int direction, int level, unsigned char *key,
1011 size_t keylen, unsigned char *iv, size_t ivlen,
1012 unsigned char *mackey, size_t mackeylen,
1013 const EVP_CIPHER *ciph, size_t taglen,
1015 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1016 BIO *transport, BIO *next, BIO_ADDR *local,
1017 BIO_ADDR *peer, const OSSL_PARAM *settings,
1018 const OSSL_PARAM *options,
1019 const OSSL_DISPATCH *fns, void *cbarg,
1020 OSSL_RECORD_LAYER **retrl)
1022 OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1023 const OSSL_PARAM *p;
1028 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1029 return OSSL_RECORD_RETURN_FATAL;
1033 * TODO(RECLAYER): Need to handle the case where the params are updated
1034 * after the record layer has been created.
1036 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1037 if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1038 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1042 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1043 if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1044 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1048 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1049 if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1050 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1054 /* Loop through all the settings since they must all be understood */
1055 for (p = settings; p->key != NULL; p++) {
1056 if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1057 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1058 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1061 } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1062 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1063 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1066 } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1067 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1068 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1071 } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1072 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1073 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1076 } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1077 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1078 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1082 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1088 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1090 * We ignore any read_ahead setting prior to the application protection
1091 * level. Otherwise we may read ahead data in a lower protection level
1092 * that is destined for a higher protection level. To simplify the logic
1093 * we don't support that at this stage.
1096 * TODO(RECLAYER): Handle the case of read_ahead at the application
1097 * level and a key update/reneg occurs.
1099 p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1100 if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1101 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1106 rl->libctx = libctx;
1111 rl->direction = direction;
1114 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1115 rl->is_first_record = 1;
1117 if (!tls_set1_bio(rl, transport))
1120 if (prev != NULL && !BIO_up_ref(prev))
1124 if (next != NULL && !BIO_up_ref(next))
1129 for (; fns->function_id != 0; fns++) {
1130 switch (fns->function_id) {
1131 case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1132 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1134 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1135 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1137 case OSSL_FUNC_RLAYER_SECURITY:
1138 rl->security = OSSL_FUNC_rlayer_security(fns);
1141 /* Just ignore anything we don't understand */
1147 return OSSL_RECORD_RETURN_SUCCESS;
1150 return OSSL_RECORD_RETURN_FATAL;
1154 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1155 int role, int direction, int level, unsigned int epoch,
1156 unsigned char *key, size_t keylen, unsigned char *iv,
1157 size_t ivlen, unsigned char *mackey, size_t mackeylen,
1158 const EVP_CIPHER *ciph, size_t taglen,
1160 const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1161 BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1162 const OSSL_PARAM *settings, const OSSL_PARAM *options,
1163 const OSSL_DISPATCH *fns, void *cbarg,
1164 OSSL_RECORD_LAYER **retrl)
1168 ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1169 key, keylen, iv, ivlen, mackey, mackeylen,
1170 ciph, taglen, mactype, md, comp, prev,
1171 transport, next, local, peer, settings,
1172 options, fns, cbarg, retrl);
1174 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1178 case TLS_ANY_VERSION:
1179 (*retrl)->funcs = &tls_any_funcs;
1181 case TLS1_3_VERSION:
1182 (*retrl)->funcs = &tls_1_3_funcs;
1184 case TLS1_2_VERSION:
1185 case TLS1_1_VERSION:
1187 (*retrl)->funcs = &tls_1_funcs;
1190 (*retrl)->funcs = &ssl_3_0_funcs;
1193 /* Should not happen */
1194 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1195 ret = OSSL_RECORD_RETURN_FATAL;
1199 ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1200 ivlen, mackey, mackeylen, ciph,
1201 taglen, mactype, md, comp);
1204 if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1205 OPENSSL_free(*retrl);
1211 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1213 /* TODO(RECLAYER): Cleanse sensitive fields */
1217 SSL3_BUFFER_release(&rl->rbuf);
1219 EVP_CIPHER_CTX_free(rl->enc_ctx);
1220 EVP_MD_CTX_free(rl->md_ctx);
1221 #ifndef OPENSSL_NO_COMP
1222 COMP_CTX_free(rl->expand);
1228 int tls_free(OSSL_RECORD_LAYER *rl)
1231 size_t left, written;
1236 left = SSL3_BUFFER_get_left(rbuf);
1239 * This record layer is closing but we still have data left in our
1240 * buffer. It must be destined for the next epoch - so push it there.
1242 ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1250 int tls_reset(OSSL_RECORD_LAYER *rl)
1252 memset(rl, 0, sizeof(*rl));
1256 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1258 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1261 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1263 return rl->curr_rec < rl->num_recs;
1266 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1271 for (i = rl->curr_rec; i <rl->num_recs; i++) {
1272 if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1274 num += rl->rrec[i].length;
1279 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1284 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1289 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1294 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE **templates,
1295 size_t numtempl, size_t allowance, size_t *sent)
1300 int tls_retry_write_records(OSSL_RECORD_LAYER *rl, size_t allowance,
1307 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1312 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1314 if (bio != NULL && !BIO_up_ref(bio))
1322 /* Shared by most methods except tlsany_meth */
1323 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1325 if (rl->version != version)
1331 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1333 return rl->funcs->set_protocol_version(rl, version);
1336 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1338 rl->allow_plain_alerts = allow;
1341 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1343 rl->is_first_handshake = first;
1346 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1348 rl->max_pipelines = max_pipelines;
1349 if (max_pipelines > 1)
1353 const OSSL_RECORD_METHOD ossl_tls_record_method = {
1354 tls_new_record_layer,
1357 tls_unprocessed_read_pending,
1358 tls_processed_read_pending,
1359 tls_app_data_pending,
1361 tls_get_max_record_len,
1362 tls_get_max_records,
1364 tls_retry_write_records,
1369 tls_set_protocol_version,
1370 tls_set_plain_alerts,
1371 tls_set_first_handshake,
1372 tls_set_max_pipelines,