2 * Copyright 1995-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
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include <openssl/core_names.h>
18 #include "record_local.h"
19 #include "internal/packet.h"
21 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
22 !( defined(AES_ASM) && ( \
23 defined(__x86_64) || defined(__x86_64__) || \
24 defined(_M_AMD64) || defined(_M_X64) ) \
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
30 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
35 void RECORD_LAYER_clear(RECORD_LAYER *rl)
38 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
39 rl->handshake_fragment_len = 0;
45 ssl3_release_write_buffer(rl->s);
47 RECORD_LAYER_reset_write_sequence(rl);
49 if (rl->rrlmethod != NULL)
50 rl->rrlmethod->free(rl->rrl); /* Ignore return value */
51 BIO_free(rl->rrlnext);
56 DTLS_RECORD_LAYER_clear(rl);
59 void RECORD_LAYER_release(RECORD_LAYER *rl)
61 if (rl->numwpipes > 0)
62 ssl3_release_write_buffer(rl->s);
65 /* Checks if we have unprocessed read ahead data pending */
66 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
68 return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
71 /* Checks if we have decrypted unread record data pending */
72 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
74 return (rl->curr_rec < rl->num_recs)
75 || rl->rrlmethod->processed_read_pending(rl->rrl);
78 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
80 return (rl->numwpipes > 0)
81 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
84 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
86 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
89 size_t ssl3_pending(const SSL *s)
92 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
97 if (SSL_CONNECTION_IS_DTLS(sc)) {
101 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
102 while ((item = pqueue_next(&iter)) != NULL) {
104 num += rdata->length;
108 for (i = 0; i < sc->rlayer.num_recs; i++) {
109 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
111 num += sc->rlayer.tlsrecs[i].length;
114 num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
119 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
121 ctx->default_read_buf_len = len;
124 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
126 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
130 sc->rlayer.default_read_buf_len = len;
133 const char *SSL_rstate_string_long(const SSL *s)
135 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
141 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
144 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
149 const char *SSL_rstate_string(const SSL *s)
151 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
157 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
160 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
166 * Call this to write data in records of type 'type' It will return <= 0 if
167 * not all data has been sent or non-blocking IO.
169 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
172 const unsigned char *buf = buf_;
174 size_t n, max_send_fragment, split_send_fragment, maxpipes;
175 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
181 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
186 wb = &s->rlayer.wbuf[0];
187 s->rwstate = SSL_NOTHING;
188 tot = s->rlayer.wnum;
190 * ensure that if we end up with a smaller value of data to write out
191 * than the original len from a write which didn't complete for
192 * non-blocking I/O and also somehow ended up avoiding the check for
193 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
194 * possible to end up with (len-tot) as a large number that will then
195 * promptly send beyond the end of the users buffer ... so we trap and
196 * report the error in a way the user will notice
198 if ((len < s->rlayer.wnum)
199 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
200 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
204 if (s->early_data_state == SSL_EARLY_DATA_WRITING
205 && !ossl_early_data_count_ok(s, len, 0, 1)) {
206 /* SSLfatal() already called */
213 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
214 * into init unless we have writes pending - in which case we should finish
217 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
218 || s->ext.extra_tickets_expected > 0))
219 ossl_statem_set_in_init(s, 1);
222 * When writing early data on the server side we could be "in_init" in
223 * between receiving the EoED and the CF - but we don't want to handle those
226 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
227 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
228 i = s->handshake_func(ssl);
229 /* SSLfatal() already called */
238 * first check if there is a SSL3_BUFFER still being written out. This
239 * will happen with non blocking IO
242 /* SSLfatal() already called if appropriate */
243 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
246 /* XXX should we ssl3_release_write_buffer if i<0? */
247 s->rlayer.wnum = tot;
250 tot += tmpwrit; /* this might be last fragment */
252 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
254 * Depending on platform multi-block can deliver several *times*
255 * better performance. Downside is that it has to allocate
256 * jumbo buffer to accommodate up to 8 records, but the
257 * compromise is considered worthy.
259 if (type == SSL3_RT_APPLICATION_DATA
260 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
261 && s->compress == NULL
262 && s->msg_callback == NULL
264 && SSL_USE_EXPLICIT_IV(s)
265 && !BIO_get_ktls_send(s->wbio)
266 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
267 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
268 unsigned char aad[13];
269 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
273 /* minimize address aliasing conflicts */
274 if ((max_send_fragment & 0xfff) == 0)
275 max_send_fragment -= 512;
277 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
278 ssl3_release_write_buffer(s);
280 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
281 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
282 (int)max_send_fragment, NULL);
284 if (len >= 8 * max_send_fragment)
289 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
290 /* SSLfatal() already called */
293 } else if (tot == len) { /* done? */
294 /* free jumbo buffer */
295 ssl3_release_write_buffer(s);
302 if (n < 4 * max_send_fragment) {
303 /* free jumbo buffer */
304 ssl3_release_write_buffer(s);
308 if (s->s3.alert_dispatch) {
309 i = ssl->method->ssl_dispatch_alert(ssl);
311 /* SSLfatal() already called if appropriate */
312 s->rlayer.wnum = tot;
317 if (n >= 8 * max_send_fragment)
318 nw = max_send_fragment * (mb_param.interleave = 8);
320 nw = max_send_fragment * (mb_param.interleave = 4);
322 memcpy(aad, s->rlayer.write_sequence, 8);
324 aad[9] = (unsigned char)(s->version >> 8);
325 aad[10] = (unsigned char)(s->version);
332 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
333 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
334 sizeof(mb_param), &mb_param);
335 packlen = (size_t)packleni;
336 if (packleni <= 0 || packlen > wb->len) { /* never happens */
337 /* free jumbo buffer */
338 ssl3_release_write_buffer(s);
342 mb_param.out = wb->buf;
343 mb_param.inp = &buf[tot];
346 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
347 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
348 sizeof(mb_param), &mb_param) <= 0)
351 s->rlayer.write_sequence[7] += mb_param.interleave;
352 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
354 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
360 s->rlayer.wpend_tot = nw;
361 s->rlayer.wpend_buf = &buf[tot];
362 s->rlayer.wpend_type = type;
363 s->rlayer.wpend_ret = nw;
365 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
367 /* SSLfatal() already called if appropriate */
368 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
369 /* free jumbo buffer */
370 ssl3_release_write_buffer(s);
372 s->rlayer.wnum = tot;
376 /* free jumbo buffer */
377 ssl3_release_write_buffer(s);
378 *written = tot + tmpwrit;
385 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
386 if (tot == len) { /* done? */
387 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
388 ssl3_release_write_buffer(s);
396 max_send_fragment = ssl_get_max_send_fragment(s);
397 split_send_fragment = ssl_get_split_send_fragment(s);
399 * If max_pipelines is 0 then this means "undefined" and we default to
400 * 1 pipeline. Similarly if the cipher does not support pipelined
401 * processing then we also only use 1 pipeline, or if we're not using
404 maxpipes = s->max_pipelines;
405 if (maxpipes > SSL_MAX_PIPELINES) {
407 * We should have prevented this when we set max_pipelines so we
410 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
414 || s->enc_write_ctx == NULL
415 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
416 & EVP_CIPH_FLAG_PIPELINE) == 0
417 || !SSL_USE_EXPLICIT_IV(s))
419 if (max_send_fragment == 0
420 || split_send_fragment == 0
421 || split_send_fragment > max_send_fragment) {
423 * We should have prevented this when we set/get the split and max send
424 * fragments so we shouldn't get here
426 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
431 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
437 numpipes = ((n - 1) / split_send_fragment) + 1;
438 if (numpipes > maxpipes)
441 if (n / numpipes >= max_send_fragment) {
443 * We have enough data to completely fill all available
446 for (j = 0; j < numpipes; j++) {
447 pipelens[j] = max_send_fragment;
450 /* We can partially fill all available pipelines */
451 tmppipelen = n / numpipes;
452 remain = n % numpipes;
453 for (j = 0; j < numpipes; j++) {
454 pipelens[j] = tmppipelen;
460 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
463 /* SSLfatal() already called if appropriate */
464 /* XXX should we ssl3_release_write_buffer if i<0? */
465 s->rlayer.wnum = tot;
470 (type == SSL3_RT_APPLICATION_DATA &&
471 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
473 * next chunk of data should get another prepended empty fragment
474 * in ciphersuites with known-IV weakness:
476 s->s3.empty_fragment_done = 0;
479 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
480 && !SSL_CONNECTION_IS_DTLS(s))
481 ssl3_release_write_buffer(s);
483 *written = tot + tmpwrit;
492 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
493 size_t *pipelens, size_t numpipes,
494 int create_empty_fragment, size_t *written)
496 WPACKET pkt[SSL_MAX_PIPELINES];
497 SSL3_RECORD wr[SSL_MAX_PIPELINES];
500 unsigned char *recordstart;
501 int i, mac_size, clear = 0;
502 size_t prefix_len = 0;
507 size_t totlen = 0, len, wpinited = 0;
510 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
512 for (j = 0; j < numpipes; j++)
513 totlen += pipelens[j];
515 * first check if there is a SSL3_BUFFER still being written out. This
516 * will happen with non blocking IO
518 if (RECORD_LAYER_write_pending(&s->rlayer)) {
519 /* Calls SSLfatal() as required */
520 return ssl3_write_pending(s, type, buf, totlen, written);
523 /* If we have an alert to send, lets send it */
524 if (s->s3.alert_dispatch) {
525 i = ssl->method->ssl_dispatch_alert(ssl);
527 /* SSLfatal() already called if appropriate */
530 /* if it went, fall through and send more stuff */
533 if (s->rlayer.numwpipes < numpipes) {
534 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
535 /* SSLfatal() already called */
540 if (totlen == 0 && !create_empty_fragment)
546 || (s->enc_write_ctx == NULL)
547 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
548 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
551 mac_size = EVP_MD_CTX_get_size(s->write_hash);
553 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
559 * 'create_empty_fragment' is true only when this function calls itself
561 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
563 * countermeasure against known-IV weakness in CBC ciphersuites (see
564 * http://www.openssl.org/~bodo/tls-cbc.txt)
567 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
569 * recursive function call with 'create_empty_fragment' set; this
570 * prepares and buffers the data for an empty fragment (these
571 * 'prefix_len' bytes are sent out later together with the actual
574 size_t tmppipelen = 0;
577 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
579 /* SSLfatal() already called if appropriate */
584 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
585 /* insufficient space */
586 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
591 s->s3.empty_fragment_done = 1;
594 using_ktls = BIO_get_ktls_send(s->wbio);
597 * ktls doesn't modify the buffer, but to avoid a warning we need to
598 * discard the const qualifier.
599 * This doesn't leak memory because the buffers have been released when
602 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
603 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
604 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
605 goto wpacket_init_complete;
608 if (create_empty_fragment) {
609 wb = &s->rlayer.wbuf[0];
610 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
612 * extra fragment would be couple of cipher blocks, which would be
613 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
614 * payload, then we can just pretend we simply have two headers.
616 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
617 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
619 SSL3_BUFFER_set_offset(wb, align);
620 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
621 SSL3_BUFFER_get_len(wb), 0)
622 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
623 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
627 } else if (prefix_len) {
628 wb = &s->rlayer.wbuf[0];
629 if (!WPACKET_init_static_len(&pkt[0],
630 SSL3_BUFFER_get_buf(wb),
631 SSL3_BUFFER_get_len(wb), 0)
632 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
633 + prefix_len, NULL)) {
634 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
639 for (j = 0; j < numpipes; j++) {
642 wb = &s->rlayer.wbuf[j];
643 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
644 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
645 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
647 SSL3_BUFFER_set_offset(wb, align);
648 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
649 SSL3_BUFFER_get_len(wb), 0)
650 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
651 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
658 /* Explicit IV length, block ciphers appropriate version flag */
659 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
660 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
661 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
662 if (mode == EVP_CIPH_CBC_MODE) {
663 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
665 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
670 } else if (mode == EVP_CIPH_GCM_MODE) {
671 /* Need explicit part of IV for GCM mode */
672 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
673 } else if (mode == EVP_CIPH_CCM_MODE) {
674 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
678 wpacket_init_complete:
681 /* Clear our SSL3_RECORD structures */
682 memset(wr, 0, sizeof(wr));
683 for (j = 0; j < numpipes; j++) {
684 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
686 unsigned char *compressdata = NULL;
688 unsigned int rectype;
694 * In TLSv1.3, once encrypting, we always use application data for the
697 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
698 && s->enc_write_ctx != NULL
699 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
700 || type != SSL3_RT_ALERT))
701 rectype = SSL3_RT_APPLICATION_DATA;
704 SSL3_RECORD_set_type(thiswr, rectype);
707 * Some servers hang if initial client hello is larger than 256 bytes
708 * and record version number > TLS 1.0
710 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
712 && TLS1_get_version(ssl) > TLS1_VERSION
713 && s->hello_retry_request == SSL_HRR_NONE)
714 version = TLS1_VERSION;
715 SSL3_RECORD_set_rec_version(thiswr, version);
717 maxcomplen = pipelens[j];
718 if (s->compress != NULL)
719 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
722 * When using offload kernel will write the header.
723 * Otherwise write the header now
726 && (!WPACKET_put_bytes_u8(thispkt, rectype)
727 || !WPACKET_put_bytes_u16(thispkt, version)
728 || !WPACKET_start_sub_packet_u16(thispkt)
730 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
732 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
734 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
738 /* lets setup the record stuff. */
739 SSL3_RECORD_set_data(thiswr, compressdata);
740 SSL3_RECORD_set_length(thiswr, pipelens[j]);
741 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
742 totlen += pipelens[j];
745 * we now 'read' from thiswr->input, thiswr->length bytes into
749 /* first we compress */
750 if (s->compress != NULL) {
751 if (!ssl3_do_compress(s, thiswr)
752 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
753 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
758 SSL3_RECORD_reset_data(&wr[j]);
760 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
761 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
764 SSL3_RECORD_reset_input(&wr[j]);
768 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
770 && s->enc_write_ctx != NULL
771 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
772 || type != SSL3_RT_ALERT)) {
773 size_t rlen, max_send_fragment;
775 if (!WPACKET_put_bytes_u8(thispkt, type)) {
776 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
779 SSL3_RECORD_add_length(thiswr, 1);
781 /* Add TLS1.3 padding */
782 max_send_fragment = ssl_get_max_send_fragment(s);
783 rlen = SSL3_RECORD_get_length(thiswr);
784 if (rlen < max_send_fragment) {
786 size_t max_padding = max_send_fragment - rlen;
787 if (s->record_padding_cb != NULL) {
788 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
789 } else if (s->block_padding > 0) {
790 size_t mask = s->block_padding - 1;
793 /* optimize for power of 2 */
794 if ((s->block_padding & mask) == 0)
795 remainder = rlen & mask;
797 remainder = rlen % s->block_padding;
798 /* don't want to add a block of padding if we don't have to */
802 padding = s->block_padding - remainder;
805 /* do not allow the record to exceed max plaintext length */
806 if (padding > max_padding)
807 padding = max_padding;
808 if (!WPACKET_memset(thispkt, 0, padding)) {
809 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
810 ERR_R_INTERNAL_ERROR);
813 SSL3_RECORD_add_length(thiswr, padding);
819 * we should still have the output to thiswr->data and the input from
820 * wr->input. Length should be thiswr->length. thiswr->data still points
824 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
827 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
828 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
829 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
835 * Reserve some bytes for any growth that may occur during encryption.
836 * This will be at most one cipher block or the tag length if using
837 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
840 if (!WPACKET_reserve_bytes(thispkt,
841 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
844 * We also need next the amount of bytes written to this
847 || !WPACKET_get_length(thispkt, &len)) {
848 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
852 /* Get a pointer to the start of this record excluding header */
853 recordstart = WPACKET_get_curr(thispkt) - len;
854 SSL3_RECORD_set_data(thiswr, recordstart);
855 SSL3_RECORD_reset_input(thiswr);
856 SSL3_RECORD_set_length(thiswr, len);
860 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
862 * We haven't actually negotiated the version yet, but we're trying to
863 * send early data - so we need to use the tls13enc function.
865 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
866 if (!ossl_statem_in_error(s)) {
867 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
873 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
875 if (!ossl_statem_in_error(s)) {
876 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
883 for (j = 0; j < numpipes; j++) {
892 /* Allocate bytes for the encryption overhead */
893 if (!WPACKET_get_length(thispkt, &origlen)
894 /* Encryption should never shrink the data! */
895 || origlen > thiswr->length
896 || (thiswr->length > origlen
897 && !WPACKET_allocate_bytes(thispkt,
898 thiswr->length - origlen,
900 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
903 if (SSL_WRITE_ETM(s) && mac_size != 0) {
906 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
907 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
908 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
911 SSL3_RECORD_add_length(thiswr, mac_size);
914 if (!WPACKET_get_length(thispkt, &len)
915 || !WPACKET_close(thispkt)) {
916 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
920 if (s->msg_callback) {
921 recordstart = WPACKET_get_curr(thispkt) - len
922 - SSL3_RT_HEADER_LENGTH;
923 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
924 SSL3_RT_HEADER_LENGTH, ssl,
925 s->msg_callback_arg);
927 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
928 unsigned char ctype = type;
930 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
931 &ctype, 1, ssl, s->msg_callback_arg);
935 if (!WPACKET_finish(thispkt)) {
936 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
940 /* header is added by the kernel when using offload */
941 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
943 if (create_empty_fragment) {
945 * we are in a recursive call; just return the length, don't write
949 /* We should never be pipelining an empty fragment!! */
950 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
953 *written = SSL3_RECORD_get_length(thiswr);
959 * we should now have thiswr->data pointing to the encrypted data, which
960 * is thiswr->length long
962 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
965 /* now let's set up wb */
966 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
967 prefix_len + SSL3_RECORD_get_length(thiswr));
971 * memorize arguments so that ssl3_write_pending can detect bad write
974 s->rlayer.wpend_tot = totlen;
975 s->rlayer.wpend_buf = buf;
976 s->rlayer.wpend_type = type;
977 s->rlayer.wpend_ret = totlen;
979 /* we now just need to write the buffer */
980 return ssl3_write_pending(s, type, buf, totlen, written);
982 for (j = 0; j < wpinited; j++)
983 WPACKET_cleanup(&pkt[j]);
987 /* if SSL3_BUFFER_get_left() != 0, we need to call this
989 * Return values are as per SSL_write()
991 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
992 size_t len, size_t *written)
995 SSL3_BUFFER *wb = s->rlayer.wbuf;
999 if ((s->rlayer.wpend_tot > len)
1000 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1001 && (s->rlayer.wpend_buf != buf))
1002 || (s->rlayer.wpend_type != type)) {
1003 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1008 /* Loop until we find a buffer we haven't written out yet */
1009 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1010 && currbuf < s->rlayer.numwpipes - 1) {
1015 if (s->wbio != NULL) {
1016 s->rwstate = SSL_WRITING;
1019 * To prevent coalescing of control and data messages,
1020 * such as in buffer_write, we flush the BIO
1022 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1023 i = BIO_flush(s->wbio);
1026 BIO_set_ktls_ctrl_msg(s->wbio, type);
1028 i = BIO_write(s->wbio, (char *)
1029 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1030 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1031 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1035 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1040 * When an empty fragment is sent on a connection using KTLS,
1041 * it is sent as a write of zero bytes. If this zero byte
1042 * write succeeds, i will be 0 rather than a non-zero value.
1043 * Treat i == 0 as success rather than an error for zero byte
1044 * writes to permit this case.
1046 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1047 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1048 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1049 if (currbuf + 1 < s->rlayer.numwpipes)
1051 s->rwstate = SSL_NOTHING;
1052 *written = s->rlayer.wpend_ret;
1054 } else if (i <= 0) {
1055 if (SSL_CONNECTION_IS_DTLS(s)) {
1057 * For DTLS, just drop it. That's kind of the whole point in
1058 * using a datagram service
1060 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1064 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1065 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1069 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1072 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1074 if (ret == OSSL_RECORD_RETURN_RETRY) {
1075 s->rwstate = SSL_READING;
1078 s->rwstate = SSL_NOTHING;
1079 if (ret == OSSL_RECORD_RETURN_EOF) {
1080 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1081 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1082 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1085 ERR_set_debug(file, line, 0);
1086 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1087 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1089 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1090 int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
1092 if (al != SSL_AD_NO_ALERT) {
1094 ERR_set_debug(file, line, 0);
1095 ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
1098 * else some failure but there is no alert code. We don't log an
1099 * error for this. The record layer should have logged an error
1100 * already or, if not, its due to some sys call error which will be
1101 * reported via SSL_ERROR_SYSCALL and errno.
1105 * The record layer distinguishes the cases of EOF, non-fatal
1106 * err and retry. Upper layers do not.
1107 * If we got a retry or success then *ret is already correct,
1108 * otherwise we need to convert the return value.
1110 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1112 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1119 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
1121 if (rr->rechandle != NULL) {
1122 /* The record layer allocated the buffers for this record */
1123 s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
1125 /* We allocated the buffers for this record (only happens with DTLS) */
1126 OPENSSL_free(rr->data);
1128 s->rlayer.curr_rec++;
1132 * Return up to 'len' payload bytes received in 'type' records.
1133 * 'type' is one of the following:
1135 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1136 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1137 * - 0 (during a shutdown, no data has to be returned)
1139 * If we don't have stored data to work from, read a SSL/TLS record first
1140 * (possibly multiple records if we still don't have anything to return).
1142 * This function must handle any surprises the peer may have for us, such as
1143 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1144 * messages are treated as if they were handshake messages *if* the |recvd_type|
1145 * argument is non NULL.
1146 * Also if record payloads contain fragments too small to process, we store
1147 * them until there is enough for the respective protocol (the record protocol
1148 * may use arbitrary fragmentation and even interleaving):
1149 * Change cipher spec protocol
1150 * just 1 byte needed, no need for keeping anything stored
1152 * 2 bytes needed (AlertLevel, AlertDescription)
1153 * Handshake protocol
1154 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1155 * to detect unexpected Client Hello and Hello Request messages
1156 * here, anything else is handled by higher layers
1157 * Application data protocol
1158 * none of our business
1160 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1161 size_t len, int peek, size_t *readbytes)
1164 size_t n, curr_rec, totalbytes;
1166 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1168 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1170 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1173 && (type != SSL3_RT_APPLICATION_DATA)
1174 && (type != SSL3_RT_HANDSHAKE))
1175 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1176 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1180 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1181 /* (partially) satisfy request from storage */
1183 unsigned char *src = s->rlayer.handshake_fragment;
1184 unsigned char *dst = buf;
1189 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1192 s->rlayer.handshake_fragment_len--;
1195 /* move any remaining fragment bytes: */
1196 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1197 s->rlayer.handshake_fragment[k] = *src++;
1199 if (recvd_type != NULL)
1200 *recvd_type = SSL3_RT_HANDSHAKE;
1207 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1210 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1211 /* type == SSL3_RT_APPLICATION_DATA */
1212 i = s->handshake_func(ssl);
1213 /* SSLfatal() already called */
1220 s->rwstate = SSL_NOTHING;
1223 * For each record 'i' up to |num_recs]
1224 * rr[i].type - is the type of record
1225 * rr[i].data, - data
1226 * rr[i].off, - offset into 'data' for next read
1227 * rr[i].length, - number of bytes.
1229 /* get new records if necessary */
1230 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1231 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1233 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1235 ret = HANDLE_RLAYER_RETURN(s,
1236 s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
1238 &rr->version, &rr->type,
1239 &rr->data, &rr->length,
1242 /* SSLfatal() already called if appropriate */
1246 s->rlayer.num_recs++;
1247 } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
1248 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1250 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1252 if (s->rlayer.handshake_fragment_len > 0
1253 && rr->type != SSL3_RT_HANDSHAKE
1254 && SSL_CONNECTION_IS_TLS13(s)) {
1255 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1256 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1261 * Reset the count of consecutive warning alerts if we've got a non-empty
1262 * record that isn't an alert.
1264 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1265 s->rlayer.alert_count = 0;
1267 /* we now have a packet which can be read and processed */
1269 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1270 * reset by ssl3_get_finished */
1271 && (rr->type != SSL3_RT_HANDSHAKE)) {
1272 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1273 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1278 * If the other end has shut down, throw anything we read away (even in
1281 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1282 s->rlayer.curr_rec++;
1283 s->rwstate = SSL_NOTHING;
1287 if (type == rr->type
1288 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1289 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1292 * SSL3_RT_APPLICATION_DATA or
1293 * SSL3_RT_HANDSHAKE or
1294 * SSL3_RT_CHANGE_CIPHER_SPEC
1297 * make sure that we are not getting application data when we are
1298 * doing a handshake for the first time
1300 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1301 && s->enc_read_ctx == NULL) {
1302 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1306 if (type == SSL3_RT_HANDSHAKE
1307 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1308 && s->rlayer.handshake_fragment_len > 0) {
1309 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1313 if (recvd_type != NULL)
1314 *recvd_type = rr->type;
1318 * Skip a zero length record. This ensures multiple calls to
1319 * SSL_read() with a zero length buffer will eventually cause
1320 * SSL_pending() to report data as being available.
1322 if (rr->length == 0)
1323 ssl_release_record(s, rr);
1329 curr_rec = s->rlayer.curr_rec;
1331 if (len - totalbytes > rr->length)
1334 n = len - totalbytes;
1336 memcpy(buf, &(rr->data[rr->off]), n);
1339 /* Mark any zero length record as consumed CVE-2016-6305 */
1340 if (rr->length == 0)
1341 ssl_release_record(s, rr);
1343 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1344 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1347 if (rr->length == 0)
1348 ssl_release_record(s, rr);
1351 || (peek && n == rr->length)) {
1356 } while (type == SSL3_RT_APPLICATION_DATA
1357 && curr_rec < s->rlayer.num_recs
1358 && totalbytes < len);
1359 if (totalbytes == 0) {
1360 /* We must have read empty records. Get more data */
1363 *readbytes = totalbytes;
1368 * If we get here, then type != rr->type; if we have a handshake message,
1369 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1370 * were actually expecting a CCS).
1374 * Lets just double check that we've not got an SSLv2 record
1376 if (rr->version == SSL2_VERSION) {
1378 * Should never happen. ssl3_get_record() should only give us an SSLv2
1379 * record back if this is the first packet and we are looking for an
1380 * initial ClientHello. Therefore |type| should always be equal to
1381 * |rr->type|. If not then something has gone horribly wrong
1383 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1387 if (ssl->method->version == TLS_ANY_VERSION
1388 && (s->server || rr->type != SSL3_RT_ALERT)) {
1390 * If we've got this far and still haven't decided on what version
1391 * we're using then this must be a client side alert we're dealing
1392 * with. We shouldn't be receiving anything other than a ClientHello
1393 * if we are a server.
1395 s->version = rr->version;
1396 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1401 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1402 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1405 if (rr->type == SSL3_RT_ALERT) {
1406 unsigned int alert_level, alert_descr;
1407 unsigned char *alert_bytes = rr->data
1411 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1412 || !PACKET_get_1(&alert, &alert_level)
1413 || !PACKET_get_1(&alert, &alert_descr)
1414 || PACKET_remaining(&alert) != 0) {
1415 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1419 if (s->msg_callback)
1420 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1421 s->msg_callback_arg);
1423 if (s->info_callback != NULL)
1424 cb = s->info_callback;
1425 else if (ssl->ctx->info_callback != NULL)
1426 cb = ssl->ctx->info_callback;
1429 j = (alert_level << 8) | alert_descr;
1430 cb(ssl, SSL_CB_READ_ALERT, j);
1433 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1434 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1435 s->s3.warn_alert = alert_descr;
1436 ssl_release_record(s, rr);
1438 s->rlayer.alert_count++;
1439 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1440 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1441 SSL_R_TOO_MANY_WARN_ALERTS);
1447 * Apart from close_notify the only other warning alert in TLSv1.3
1448 * is user_cancelled - which we just ignore.
1450 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1452 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1453 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1454 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1456 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1457 s->rwstate = SSL_NOTHING;
1458 s->s3.fatal_alert = alert_descr;
1459 SSLfatal_data(s, SSL_AD_NO_ALERT,
1460 SSL_AD_REASON_OFFSET + alert_descr,
1461 "SSL alert number %d", alert_descr);
1462 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1463 ssl_release_record(s, rr);
1464 SSL_CTX_remove_session(s->session_ctx, s->session);
1466 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1468 * This is a warning but we receive it if we requested
1469 * renegotiation and the peer denied it. Terminate with a fatal
1470 * alert because if application tried to renegotiate it
1471 * presumably had a good reason and expects it to succeed. In
1472 * future we might have a renegotiation where we don't care if
1473 * the peer refused it where we carry on.
1475 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1477 } else if (alert_level == SSL3_AL_WARNING) {
1478 /* We ignore any other warning alert in TLSv1.2 and below */
1482 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1486 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1487 if (rr->type == SSL3_RT_HANDSHAKE) {
1491 * We ignore any handshake messages sent to us unless they are
1492 * TLSv1.3 in which case we want to process them. For all other
1493 * handshake messages we can't do anything reasonable with them
1494 * because we are unable to write any response due to having already
1495 * sent close_notify.
1497 if (!SSL_CONNECTION_IS_TLS13(s)) {
1498 ssl_release_record(s, rr);
1500 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1503 s->rwstate = SSL_READING;
1504 rbio = SSL_get_rbio(ssl);
1505 BIO_clear_retry_flags(rbio);
1506 BIO_set_retry_read(rbio);
1511 * The peer is continuing to send application data, but we have
1512 * already sent close_notify. If this was expected we should have
1513 * been called via SSL_read() and this would have been handled
1515 * No alert sent because we already sent close_notify
1517 ssl_release_record(s, rr);
1518 SSLfatal(s, SSL_AD_NO_ALERT,
1519 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1525 * For handshake data we have 'fragment' storage, so fill that so that we
1526 * can process the header at a fixed place. This is done after the
1527 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1528 * that we're just going to discard.
1530 if (rr->type == SSL3_RT_HANDSHAKE) {
1531 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1532 unsigned char *dest = s->rlayer.handshake_fragment;
1533 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1535 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1537 n = rr->length; /* available bytes */
1539 /* now move 'n' bytes: */
1540 memcpy(dest + *dest_len, rr->data + rr->off, n);
1544 if (rr->length == 0)
1545 ssl_release_record(s, rr);
1547 if (*dest_len < dest_maxlen)
1548 goto start; /* fragment was too small */
1551 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1552 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1557 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1558 * protocol violation)
1560 if ((s->rlayer.handshake_fragment_len >= 4)
1561 && !ossl_statem_get_in_handshake(s)) {
1562 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1564 /* We found handshake data, so we're going back into init */
1565 ossl_statem_set_in_init(s, 1);
1567 i = s->handshake_func(ssl);
1568 /* SSLfatal() already called if appropriate */
1576 * If we were actually trying to read early data and we found a
1577 * handshake message, then we don't want to continue to try and read
1578 * the application data any more. It won't be "early" now.
1583 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1584 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1587 * In the case where we try to read application data, but we
1588 * trigger an SSL handshake, we return -1 with the retry
1589 * option set. Otherwise renegotiation may cause nasty
1590 * problems in the blocking world
1592 s->rwstate = SSL_READING;
1593 bio = SSL_get_rbio(ssl);
1594 BIO_clear_retry_flags(bio);
1595 BIO_set_retry_read(bio);
1605 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1606 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1607 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1608 * no progress is being made and the peer continually sends unrecognised
1609 * record types, using up resources processing them.
1611 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1613 case SSL3_RT_CHANGE_CIPHER_SPEC:
1615 case SSL3_RT_HANDSHAKE:
1617 * we already handled all of these, with the possible exception of
1618 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1619 * that should not happen when type != rr->type
1621 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1623 case SSL3_RT_APPLICATION_DATA:
1625 * At this point, we were expecting handshake data, but have
1626 * application data. If the library was running inside ssl3_read()
1627 * (i.e. in_read_app_data is set) and it makes sense to read
1628 * application data at this point (session renegotiation not yet
1629 * started), we will indulge it.
1631 if (ossl_statem_app_data_allowed(s)) {
1632 s->s3.in_read_app_data = 2;
1634 } else if (ossl_statem_skip_early_data(s)) {
1636 * This can happen after a client sends a CH followed by early_data,
1637 * but the server responds with a HelloRetryRequest. The server
1638 * reads the next record from the client expecting to find a
1639 * plaintext ClientHello but gets a record which appears to be
1640 * application data. The trial decrypt "works" because null
1641 * decryption was applied. We just skip it and move on to the next
1644 if (!ossl_early_data_count_ok(s, rr->length,
1645 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1646 /* SSLfatal() already called */
1649 ssl_release_record(s, rr);
1652 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1658 void ssl3_record_sequence_update(unsigned char *seq)
1662 for (i = 7; i >= 0; i--) {
1670 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1671 * format and false otherwise.
1673 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1675 if (SSL_CONNECTION_IS_DTLS(rl->s))
1677 return rl->tlsrecs[0].version == SSL2_VERSION;
1680 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1681 static void rlayer_msg_callback_wrapper(int write_p, int version,
1682 int content_type, const void *buf,
1683 size_t len, void *cbarg)
1685 SSL_CONNECTION *s = cbarg;
1686 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1688 if (s->msg_callback != NULL)
1689 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1690 s->msg_callback_arg);
1693 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1694 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1697 SSL_CONNECTION *s = cbarg;
1699 return ssl_security(s, op, bits, nid, other);
1702 static const OSSL_DISPATCH rlayer_dispatch[] = {
1703 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1704 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1705 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1709 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1713 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1714 if (SSL_CONNECTION_IS_DTLS(s))
1715 return &ossl_dtls_record_method;
1717 return &ossl_tls_record_method;
1720 #ifndef OPENSSL_NO_KTLS
1721 /* KTLS does not support renegotiation */
1722 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1723 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1724 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1725 return &ossl_ktls_record_method;
1728 /* Default to the current OSSL_RECORD_METHOD */
1729 return s->rlayer.rrlmethod;
1732 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1734 #ifndef OPENSSL_NO_KTLS
1735 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1737 if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1738 /* KTLS does not support renegotiation so disallow it */
1739 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1742 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rlayer.rrlmethod->set_first_handshake != NULL)
1743 s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 1);
1745 if (s->max_pipelines != 0 && s->rlayer.rrlmethod->set_max_pipelines != NULL)
1746 s->rlayer.rrlmethod->set_max_pipelines(s->rlayer.rrl, s->max_pipelines);
1751 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1752 int direction, int level,
1753 unsigned char *key, size_t keylen,
1754 unsigned char *iv, size_t ivlen,
1755 unsigned char *mackey, size_t mackeylen,
1756 const EVP_CIPHER *ciph, size_t taglen,
1757 int mactype, const EVP_MD *md,
1758 const SSL_COMP *comp)
1760 OSSL_PARAM options[5], *opts = options;
1761 OSSL_PARAM settings[6], *set = settings;
1762 const OSSL_RECORD_METHOD *origmeth = s->rlayer.rrlmethod;
1763 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1764 const OSSL_RECORD_METHOD *meth;
1765 int use_etm, stream_mac = 0, tlstree = 0;
1766 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1767 int use_early_data = 0;
1768 uint32_t max_early_data;
1770 meth = ssl_select_next_record_layer(s, level);
1772 if (s->rlayer.rrlmethod != NULL && !s->rlayer.rrlmethod->free(s->rlayer.rrl)) {
1773 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1778 s->rlayer.rrlmethod = meth;
1780 if (!ossl_assert(s->rlayer.rrlmethod != NULL)) {
1781 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1785 /* Parameters that *may* be supported by a record layer if passed */
1786 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1788 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1790 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1791 &s->rlayer.default_read_buf_len);
1792 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1793 &s->rlayer.read_ahead);
1794 *opts = OSSL_PARAM_construct_end();
1796 /* Parameters that *must* be supported by a record layer if passed */
1797 if (direction == OSSL_RECORD_DIRECTION_READ) {
1798 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1799 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1802 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1805 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1806 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1809 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1814 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1818 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1822 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1825 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1826 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1828 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1829 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1833 * The record layer must check the amount of early data sent or received
1834 * using the early keys. A server also needs to worry about rejected early
1835 * data that might arrive when the handshake keys are in force.
1837 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1838 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1839 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1840 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1841 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1842 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1844 if (use_early_data) {
1845 max_early_data = ossl_get_max_early_data(s);
1847 if (max_early_data != 0)
1848 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1852 *set = OSSL_PARAM_construct_end();
1856 BIO *prev = s->rlayer.rrlnext;
1857 unsigned int epoch = 0;;
1859 if (SSL_CONNECTION_IS_DTLS(s)
1860 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1861 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1863 if (SSL_CONNECTION_IS_DTLS(s))
1864 s->rlayer.rrlnext = BIO_new(BIO_s_dgram_mem());
1866 s->rlayer.rrlnext = BIO_new(BIO_s_mem());
1868 if (s->rlayer.rrlnext == NULL) {
1870 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1874 rlret = s->rlayer.rrlmethod->new_record_layer(sctx->libctx,
1877 direction, level, epoch,
1878 key, keylen, iv, ivlen,
1879 mackey, mackeylen, ciph,
1880 taglen, mactype, md, comp,
1882 s->rlayer.rrlnext, NULL,
1883 NULL, settings, options,
1888 case OSSL_RECORD_RETURN_FATAL:
1889 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1892 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1893 if (s->rlayer.rrlmethod != origmeth && origmeth != NULL) {
1895 * We tried a new record layer method, but it didn't work out,
1896 * so we fallback to the original method and try again
1898 s->rlayer.rrlmethod = origmeth;
1901 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1904 case OSSL_RECORD_RETURN_SUCCESS:
1908 /* Should not happen */
1909 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1915 return ssl_post_record_layer_select(s);