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 <openssl/param_build.h>
19 #include "record_local.h"
20 #include "internal/packet.h"
22 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
23 !( defined(AES_ASM) && ( \
24 defined(__x86_64) || defined(__x86_64__) || \
25 defined(_M_AMD64) || defined(_M_X64) ) \
27 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
28 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
31 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
34 RECORD_LAYER_set_first_record(&s->rlayer);
35 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
38 void RECORD_LAYER_clear(RECORD_LAYER *rl)
40 rl->rstate = SSL_ST_READ_HEADER;
43 * Do I need to clear read_ahead? As far as I can tell read_ahead did not
44 * previously get reset by SSL_clear...so I'll keep it that way..but is
49 rl->packet_length = 0;
51 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
52 rl->handshake_fragment_len = 0;
58 SSL3_BUFFER_clear(&rl->rbuf);
59 ssl3_release_write_buffer(rl->s);
61 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
63 RECORD_LAYER_reset_read_sequence(rl);
64 RECORD_LAYER_reset_write_sequence(rl);
67 DTLS_RECORD_LAYER_clear(rl);
70 void RECORD_LAYER_release(RECORD_LAYER *rl)
72 if (SSL3_BUFFER_is_initialised(&rl->rbuf))
73 ssl3_release_read_buffer(rl->s);
74 if (rl->numwpipes > 0)
75 ssl3_release_write_buffer(rl->s);
76 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
79 /* Checks if we have unprocessed read ahead data pending */
80 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
83 * TODO(RECLAYER): Temporarily do it the old way until DTLS is converted to
84 * the new record layer code
86 if (SSL_CONNECTION_IS_DTLS(rl->s))
87 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
89 return rl->s->rrlmethod->unprocessed_read_pending(rl->s->rrl);
92 /* Checks if we have decrypted unread record data pending */
93 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
96 * TODO(RECLAYER): Temporarily do it the old way until DTLS is converted to
97 * the new record layer code
99 if (SSL_CONNECTION_IS_DTLS(rl->s)) {
100 const SSL3_RECORD *rr = rl->rrec;
102 size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl);
104 while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]))
107 return curr_rec < num_recs;
110 return (rl->curr_rec < rl->num_recs)
111 || rl->s->rrlmethod->processed_read_pending(rl->s->rrl);
114 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
116 return (rl->numwpipes > 0)
117 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
120 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
122 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
125 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
127 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
130 size_t ssl3_pending(const SSL *s)
133 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
138 if (sc->rlayer.rstate == SSL_ST_READ_BODY)
142 * TODO(RECLAYER): We need to do it the old way temporary for DTLS until
143 * that is converted to use the new record layer code
145 if (SSL_CONNECTION_IS_DTLS(sc)) {
146 DTLS1_RECORD_DATA *rdata;
149 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
150 while ((item = pqueue_next(&iter)) != NULL) {
152 num += rdata->rrec.length;
155 for (i = 0; i < RECORD_LAYER_get_numrpipes(&sc->rlayer); i++) {
156 if (SSL3_RECORD_get_type(&sc->rlayer.rrec[i])
157 != SSL3_RT_APPLICATION_DATA)
159 num += SSL3_RECORD_get_length(&sc->rlayer.rrec[i]);
162 for (i = 0; i <sc->rlayer.num_recs; i++) {
163 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
165 num += sc->rlayer.tlsrecs[i].length;
172 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
174 ctx->default_read_buf_len = len;
177 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
179 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
183 SSL3_BUFFER_set_default_len(sc->rrlmethod->get0_rbuf(sc->rrl), len);
186 const char *SSL_rstate_string_long(const SSL *s)
188 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
193 switch (sc->rlayer.rstate) {
194 case SSL_ST_READ_HEADER:
195 return "read header";
196 case SSL_ST_READ_BODY:
198 case SSL_ST_READ_DONE:
205 const char *SSL_rstate_string(const SSL *s)
207 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
212 switch (sc->rlayer.rstate) {
213 case SSL_ST_READ_HEADER:
215 case SSL_ST_READ_BODY:
217 case SSL_ST_READ_DONE:
226 * Call this to write data in records of type 'type' It will return <= 0 if
227 * not all data has been sent or non-blocking IO.
229 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
232 const unsigned char *buf = buf_;
234 size_t n, max_send_fragment, split_send_fragment, maxpipes;
235 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
241 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
246 wb = &s->rlayer.wbuf[0];
247 s->rwstate = SSL_NOTHING;
248 tot = s->rlayer.wnum;
250 * ensure that if we end up with a smaller value of data to write out
251 * than the original len from a write which didn't complete for
252 * non-blocking I/O and also somehow ended up avoiding the check for
253 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
254 * possible to end up with (len-tot) as a large number that will then
255 * promptly send beyond the end of the users buffer ... so we trap and
256 * report the error in a way the user will notice
258 if ((len < s->rlayer.wnum)
259 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
260 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
264 if (s->early_data_state == SSL_EARLY_DATA_WRITING
265 && !ossl_early_data_count_ok(s, len, 0, 1)) {
266 /* SSLfatal() already called */
273 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
274 * into init unless we have writes pending - in which case we should finish
277 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
278 || s->ext.extra_tickets_expected > 0))
279 ossl_statem_set_in_init(s, 1);
282 * When writing early data on the server side we could be "in_init" in
283 * between receiving the EoED and the CF - but we don't want to handle those
286 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
287 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
288 i = s->handshake_func(ssl);
289 /* SSLfatal() already called */
298 * first check if there is a SSL3_BUFFER still being written out. This
299 * will happen with non blocking IO
302 /* SSLfatal() already called if appropriate */
303 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
306 /* XXX should we ssl3_release_write_buffer if i<0? */
307 s->rlayer.wnum = tot;
310 tot += tmpwrit; /* this might be last fragment */
312 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
314 * Depending on platform multi-block can deliver several *times*
315 * better performance. Downside is that it has to allocate
316 * jumbo buffer to accommodate up to 8 records, but the
317 * compromise is considered worthy.
319 if (type == SSL3_RT_APPLICATION_DATA
320 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
321 && s->compress == NULL
322 && s->msg_callback == NULL
324 && SSL_USE_EXPLICIT_IV(s)
325 && !BIO_get_ktls_send(s->wbio)
326 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
327 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
328 unsigned char aad[13];
329 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
333 /* minimize address aliasing conflicts */
334 if ((max_send_fragment & 0xfff) == 0)
335 max_send_fragment -= 512;
337 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
338 ssl3_release_write_buffer(s);
340 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
341 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
342 (int)max_send_fragment, NULL);
344 if (len >= 8 * max_send_fragment)
349 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
350 /* SSLfatal() already called */
353 } else if (tot == len) { /* done? */
354 /* free jumbo buffer */
355 ssl3_release_write_buffer(s);
362 if (n < 4 * max_send_fragment) {
363 /* free jumbo buffer */
364 ssl3_release_write_buffer(s);
368 if (s->s3.alert_dispatch) {
369 i = ssl->method->ssl_dispatch_alert(ssl);
371 /* SSLfatal() already called if appropriate */
372 s->rlayer.wnum = tot;
377 if (n >= 8 * max_send_fragment)
378 nw = max_send_fragment * (mb_param.interleave = 8);
380 nw = max_send_fragment * (mb_param.interleave = 4);
382 memcpy(aad, s->rlayer.write_sequence, 8);
384 aad[9] = (unsigned char)(s->version >> 8);
385 aad[10] = (unsigned char)(s->version);
392 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
393 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
394 sizeof(mb_param), &mb_param);
395 packlen = (size_t)packleni;
396 if (packleni <= 0 || packlen > wb->len) { /* never happens */
397 /* free jumbo buffer */
398 ssl3_release_write_buffer(s);
402 mb_param.out = wb->buf;
403 mb_param.inp = &buf[tot];
406 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
407 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
408 sizeof(mb_param), &mb_param) <= 0)
411 s->rlayer.write_sequence[7] += mb_param.interleave;
412 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
414 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
420 s->rlayer.wpend_tot = nw;
421 s->rlayer.wpend_buf = &buf[tot];
422 s->rlayer.wpend_type = type;
423 s->rlayer.wpend_ret = nw;
425 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
427 /* SSLfatal() already called if appropriate */
428 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
429 /* free jumbo buffer */
430 ssl3_release_write_buffer(s);
432 s->rlayer.wnum = tot;
436 /* free jumbo buffer */
437 ssl3_release_write_buffer(s);
438 *written = tot + tmpwrit;
445 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
446 if (tot == len) { /* done? */
447 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
448 ssl3_release_write_buffer(s);
456 max_send_fragment = ssl_get_max_send_fragment(s);
457 split_send_fragment = ssl_get_split_send_fragment(s);
459 * If max_pipelines is 0 then this means "undefined" and we default to
460 * 1 pipeline. Similarly if the cipher does not support pipelined
461 * processing then we also only use 1 pipeline, or if we're not using
464 maxpipes = s->max_pipelines;
465 if (maxpipes > SSL_MAX_PIPELINES) {
467 * We should have prevented this when we set max_pipelines so we
470 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
474 || s->enc_write_ctx == NULL
475 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
476 & EVP_CIPH_FLAG_PIPELINE) == 0
477 || !SSL_USE_EXPLICIT_IV(s))
479 if (max_send_fragment == 0
480 || split_send_fragment == 0
481 || split_send_fragment > max_send_fragment) {
483 * We should have prevented this when we set/get the split and max send
484 * fragments so we shouldn't get here
486 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
491 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
497 numpipes = ((n - 1) / split_send_fragment) + 1;
498 if (numpipes > maxpipes)
501 if (n / numpipes >= max_send_fragment) {
503 * We have enough data to completely fill all available
506 for (j = 0; j < numpipes; j++) {
507 pipelens[j] = max_send_fragment;
510 /* We can partially fill all available pipelines */
511 tmppipelen = n / numpipes;
512 remain = n % numpipes;
513 for (j = 0; j < numpipes; j++) {
514 pipelens[j] = tmppipelen;
520 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
523 /* SSLfatal() already called if appropriate */
524 /* XXX should we ssl3_release_write_buffer if i<0? */
525 s->rlayer.wnum = tot;
530 (type == SSL3_RT_APPLICATION_DATA &&
531 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
533 * next chunk of data should get another prepended empty fragment
534 * in ciphersuites with known-IV weakness:
536 s->s3.empty_fragment_done = 0;
539 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
540 && !SSL_CONNECTION_IS_DTLS(s))
541 ssl3_release_write_buffer(s);
543 *written = tot + tmpwrit;
552 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
553 size_t *pipelens, size_t numpipes,
554 int create_empty_fragment, size_t *written)
556 WPACKET pkt[SSL_MAX_PIPELINES];
557 SSL3_RECORD wr[SSL_MAX_PIPELINES];
560 unsigned char *recordstart;
561 int i, mac_size, clear = 0;
562 size_t prefix_len = 0;
567 size_t totlen = 0, len, wpinited = 0;
570 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
572 for (j = 0; j < numpipes; j++)
573 totlen += pipelens[j];
575 * first check if there is a SSL3_BUFFER still being written out. This
576 * will happen with non blocking IO
578 if (RECORD_LAYER_write_pending(&s->rlayer)) {
579 /* Calls SSLfatal() as required */
580 return ssl3_write_pending(s, type, buf, totlen, written);
583 /* If we have an alert to send, lets send it */
584 if (s->s3.alert_dispatch) {
585 i = ssl->method->ssl_dispatch_alert(ssl);
587 /* SSLfatal() already called if appropriate */
590 /* if it went, fall through and send more stuff */
593 if (s->rlayer.numwpipes < numpipes) {
594 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
595 /* SSLfatal() already called */
600 if (totlen == 0 && !create_empty_fragment)
606 || (s->enc_write_ctx == NULL)
607 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
608 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
611 mac_size = EVP_MD_CTX_get_size(s->write_hash);
613 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
619 * 'create_empty_fragment' is true only when this function calls itself
621 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
623 * countermeasure against known-IV weakness in CBC ciphersuites (see
624 * http://www.openssl.org/~bodo/tls-cbc.txt)
627 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
629 * recursive function call with 'create_empty_fragment' set; this
630 * prepares and buffers the data for an empty fragment (these
631 * 'prefix_len' bytes are sent out later together with the actual
634 size_t tmppipelen = 0;
637 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
639 /* SSLfatal() already called if appropriate */
644 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
645 /* insufficient space */
646 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
651 s->s3.empty_fragment_done = 1;
654 using_ktls = BIO_get_ktls_send(s->wbio);
657 * ktls doesn't modify the buffer, but to avoid a warning we need to
658 * discard the const qualifier.
659 * This doesn't leak memory because the buffers have been released when
662 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
663 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
664 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
665 goto wpacket_init_complete;
668 if (create_empty_fragment) {
669 wb = &s->rlayer.wbuf[0];
670 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
672 * extra fragment would be couple of cipher blocks, which would be
673 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
674 * payload, then we can just pretend we simply have two headers.
676 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
677 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
679 SSL3_BUFFER_set_offset(wb, align);
680 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
681 SSL3_BUFFER_get_len(wb), 0)
682 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
683 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
687 } else if (prefix_len) {
688 wb = &s->rlayer.wbuf[0];
689 if (!WPACKET_init_static_len(&pkt[0],
690 SSL3_BUFFER_get_buf(wb),
691 SSL3_BUFFER_get_len(wb), 0)
692 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
693 + prefix_len, NULL)) {
694 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
699 for (j = 0; j < numpipes; j++) {
702 wb = &s->rlayer.wbuf[j];
703 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
704 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
705 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
707 SSL3_BUFFER_set_offset(wb, align);
708 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
709 SSL3_BUFFER_get_len(wb), 0)
710 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
711 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
718 /* Explicit IV length, block ciphers appropriate version flag */
719 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
720 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
721 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
722 if (mode == EVP_CIPH_CBC_MODE) {
723 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
725 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
730 } else if (mode == EVP_CIPH_GCM_MODE) {
731 /* Need explicit part of IV for GCM mode */
732 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
733 } else if (mode == EVP_CIPH_CCM_MODE) {
734 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
738 wpacket_init_complete:
741 /* Clear our SSL3_RECORD structures */
742 memset(wr, 0, sizeof(wr));
743 for (j = 0; j < numpipes; j++) {
744 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
746 unsigned char *compressdata = NULL;
748 unsigned int rectype;
754 * In TLSv1.3, once encrypting, we always use application data for the
757 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
758 && s->enc_write_ctx != NULL
759 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
760 || type != SSL3_RT_ALERT))
761 rectype = SSL3_RT_APPLICATION_DATA;
764 SSL3_RECORD_set_type(thiswr, rectype);
767 * Some servers hang if initial client hello is larger than 256 bytes
768 * and record version number > TLS 1.0
770 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
772 && TLS1_get_version(ssl) > TLS1_VERSION
773 && s->hello_retry_request == SSL_HRR_NONE)
774 version = TLS1_VERSION;
775 SSL3_RECORD_set_rec_version(thiswr, version);
777 maxcomplen = pipelens[j];
778 if (s->compress != NULL)
779 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
782 * When using offload kernel will write the header.
783 * Otherwise write the header now
786 && (!WPACKET_put_bytes_u8(thispkt, rectype)
787 || !WPACKET_put_bytes_u16(thispkt, version)
788 || !WPACKET_start_sub_packet_u16(thispkt)
790 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
792 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
794 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
798 /* lets setup the record stuff. */
799 SSL3_RECORD_set_data(thiswr, compressdata);
800 SSL3_RECORD_set_length(thiswr, pipelens[j]);
801 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
802 totlen += pipelens[j];
805 * we now 'read' from thiswr->input, thiswr->length bytes into
809 /* first we compress */
810 if (s->compress != NULL) {
811 if (!ssl3_do_compress(s, thiswr)
812 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
813 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
818 SSL3_RECORD_reset_data(&wr[j]);
820 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
821 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
824 SSL3_RECORD_reset_input(&wr[j]);
828 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
830 && s->enc_write_ctx != NULL
831 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
832 || type != SSL3_RT_ALERT)) {
833 size_t rlen, max_send_fragment;
835 if (!WPACKET_put_bytes_u8(thispkt, type)) {
836 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
839 SSL3_RECORD_add_length(thiswr, 1);
841 /* Add TLS1.3 padding */
842 max_send_fragment = ssl_get_max_send_fragment(s);
843 rlen = SSL3_RECORD_get_length(thiswr);
844 if (rlen < max_send_fragment) {
846 size_t max_padding = max_send_fragment - rlen;
847 if (s->record_padding_cb != NULL) {
848 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
849 } else if (s->block_padding > 0) {
850 size_t mask = s->block_padding - 1;
853 /* optimize for power of 2 */
854 if ((s->block_padding & mask) == 0)
855 remainder = rlen & mask;
857 remainder = rlen % s->block_padding;
858 /* don't want to add a block of padding if we don't have to */
862 padding = s->block_padding - remainder;
865 /* do not allow the record to exceed max plaintext length */
866 if (padding > max_padding)
867 padding = max_padding;
868 if (!WPACKET_memset(thispkt, 0, padding)) {
869 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
870 ERR_R_INTERNAL_ERROR);
873 SSL3_RECORD_add_length(thiswr, padding);
879 * we should still have the output to thiswr->data and the input from
880 * wr->input. Length should be thiswr->length. thiswr->data still points
884 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
887 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
888 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
889 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
895 * Reserve some bytes for any growth that may occur during encryption.
896 * This will be at most one cipher block or the tag length if using
897 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
900 if (!WPACKET_reserve_bytes(thispkt,
901 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
904 * We also need next the amount of bytes written to this
907 || !WPACKET_get_length(thispkt, &len)) {
908 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
912 /* Get a pointer to the start of this record excluding header */
913 recordstart = WPACKET_get_curr(thispkt) - len;
914 SSL3_RECORD_set_data(thiswr, recordstart);
915 SSL3_RECORD_reset_input(thiswr);
916 SSL3_RECORD_set_length(thiswr, len);
920 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
922 * We haven't actually negotiated the version yet, but we're trying to
923 * send early data - so we need to use the tls13enc function.
925 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
926 if (!ossl_statem_in_error(s)) {
927 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
933 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
935 if (!ossl_statem_in_error(s)) {
936 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
943 for (j = 0; j < numpipes; j++) {
952 /* Allocate bytes for the encryption overhead */
953 if (!WPACKET_get_length(thispkt, &origlen)
954 /* Encryption should never shrink the data! */
955 || origlen > thiswr->length
956 || (thiswr->length > origlen
957 && !WPACKET_allocate_bytes(thispkt,
958 thiswr->length - origlen,
960 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
963 if (SSL_WRITE_ETM(s) && mac_size != 0) {
966 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
967 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
968 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
971 SSL3_RECORD_add_length(thiswr, mac_size);
974 if (!WPACKET_get_length(thispkt, &len)
975 || !WPACKET_close(thispkt)) {
976 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
980 if (s->msg_callback) {
981 recordstart = WPACKET_get_curr(thispkt) - len
982 - SSL3_RT_HEADER_LENGTH;
983 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
984 SSL3_RT_HEADER_LENGTH, ssl,
985 s->msg_callback_arg);
987 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
988 unsigned char ctype = type;
990 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
991 &ctype, 1, ssl, s->msg_callback_arg);
995 if (!WPACKET_finish(thispkt)) {
996 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1000 /* header is added by the kernel when using offload */
1001 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1003 if (create_empty_fragment) {
1005 * we are in a recursive call; just return the length, don't write
1009 /* We should never be pipelining an empty fragment!! */
1010 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1013 *written = SSL3_RECORD_get_length(thiswr);
1019 * we should now have thiswr->data pointing to the encrypted data, which
1020 * is thiswr->length long
1022 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
1025 /* now let's set up wb */
1026 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
1027 prefix_len + SSL3_RECORD_get_length(thiswr));
1031 * memorize arguments so that ssl3_write_pending can detect bad write
1034 s->rlayer.wpend_tot = totlen;
1035 s->rlayer.wpend_buf = buf;
1036 s->rlayer.wpend_type = type;
1037 s->rlayer.wpend_ret = totlen;
1039 /* we now just need to write the buffer */
1040 return ssl3_write_pending(s, type, buf, totlen, written);
1042 for (j = 0; j < wpinited; j++)
1043 WPACKET_cleanup(&pkt[j]);
1047 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1049 * Return values are as per SSL_write()
1051 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1052 size_t len, size_t *written)
1055 SSL3_BUFFER *wb = s->rlayer.wbuf;
1059 if ((s->rlayer.wpend_tot > len)
1060 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1061 && (s->rlayer.wpend_buf != buf))
1062 || (s->rlayer.wpend_type != type)) {
1063 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1068 /* Loop until we find a buffer we haven't written out yet */
1069 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1070 && currbuf < s->rlayer.numwpipes - 1) {
1075 if (s->wbio != NULL) {
1076 s->rwstate = SSL_WRITING;
1079 * To prevent coalescing of control and data messages,
1080 * such as in buffer_write, we flush the BIO
1082 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1083 i = BIO_flush(s->wbio);
1086 BIO_set_ktls_ctrl_msg(s->wbio, type);
1088 i = BIO_write(s->wbio, (char *)
1089 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1090 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1091 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1095 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1100 * When an empty fragment is sent on a connection using KTLS,
1101 * it is sent as a write of zero bytes. If this zero byte
1102 * write succeeds, i will be 0 rather than a non-zero value.
1103 * Treat i == 0 as success rather than an error for zero byte
1104 * writes to permit this case.
1106 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1107 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1108 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1109 if (currbuf + 1 < s->rlayer.numwpipes)
1111 s->rwstate = SSL_NOTHING;
1112 *written = s->rlayer.wpend_ret;
1114 } else if (i <= 0) {
1115 if (SSL_CONNECTION_IS_DTLS(s)) {
1117 * For DTLS, just drop it. That's kind of the whole point in
1118 * using a datagram service
1120 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1124 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1125 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1129 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1132 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1134 if (ret == OSSL_RECORD_RETURN_RETRY) {
1135 s->rwstate = SSL_READING;
1138 s->rwstate = SSL_NOTHING;
1139 if (ret == OSSL_RECORD_RETURN_EOF) {
1140 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1141 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1142 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1145 ERR_set_debug(file, line, 0);
1146 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1147 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1149 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1151 ERR_set_debug(file, line, 0);
1152 ossl_statem_fatal(s, s->rrlmethod->get_alert_code(s->rrl),
1153 SSL_R_RECORD_LAYER_FAILURE, NULL);
1156 * The record layer distinguishes the cases of EOF, non-fatal
1157 * err and retry. Upper layers do not.
1158 * If we got a retry or success then *ret is already correct,
1159 * otherwise we need to convert the return value.
1162 * TODO(RECLAYER): What does a non fatal err that isn't a retry even
1165 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1167 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1175 * Return up to 'len' payload bytes received in 'type' records.
1176 * 'type' is one of the following:
1178 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1179 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1180 * - 0 (during a shutdown, no data has to be returned)
1182 * If we don't have stored data to work from, read a SSL/TLS record first
1183 * (possibly multiple records if we still don't have anything to return).
1185 * This function must handle any surprises the peer may have for us, such as
1186 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1187 * messages are treated as if they were handshake messages *if* the |recvd_type|
1188 * argument is non NULL.
1189 * Also if record payloads contain fragments too small to process, we store
1190 * them until there is enough for the respective protocol (the record protocol
1191 * may use arbitrary fragmentation and even interleaving):
1192 * Change cipher spec protocol
1193 * just 1 byte needed, no need for keeping anything stored
1195 * 2 bytes needed (AlertLevel, AlertDescription)
1196 * Handshake protocol
1197 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1198 * to detect unexpected Client Hello and Hello Request messages
1199 * here, anything else is handled by higher layers
1200 * Application data protocol
1201 * none of our business
1203 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1204 size_t len, int peek, size_t *readbytes)
1207 size_t n, curr_rec, totalbytes;
1209 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1211 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1213 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1216 && (type != SSL3_RT_APPLICATION_DATA)
1217 && (type != SSL3_RT_HANDSHAKE))
1218 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1219 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1223 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1224 /* (partially) satisfy request from storage */
1226 unsigned char *src = s->rlayer.handshake_fragment;
1227 unsigned char *dst = buf;
1232 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1235 s->rlayer.handshake_fragment_len--;
1238 /* move any remaining fragment bytes: */
1239 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1240 s->rlayer.handshake_fragment[k] = *src++;
1242 if (recvd_type != NULL)
1243 *recvd_type = SSL3_RT_HANDSHAKE;
1250 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1253 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1254 /* type == SSL3_RT_APPLICATION_DATA */
1255 i = s->handshake_func(ssl);
1256 /* SSLfatal() already called */
1263 s->rwstate = SSL_NOTHING;
1266 * For each record 'i' up to |num_recs]
1267 * rr[i].type - is the type of record
1268 * rr[i].data, - data
1269 * rr[i].off, - offset into 'data' for next read
1270 * rr[i].length, - number of bytes.
1272 /* get new records if necessary */
1273 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1274 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1276 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1278 ret = HANDLE_RLAYER_RETURN(s,
1279 s->rrlmethod->read_record(s->rrl, &rr->rechandle,
1280 &rr->version, &rr->type,
1281 &rr->data, &rr->length,
1284 /* SSLfatal() already called if appropriate */
1288 s->rlayer.num_recs++;
1289 } while (s->rrlmethod->processed_read_pending(s->rrl)
1290 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1292 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1294 if (s->rlayer.handshake_fragment_len > 0
1295 && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1296 && SSL_CONNECTION_IS_TLS13(s)) {
1297 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1298 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1303 * Reset the count of consecutive warning alerts if we've got a non-empty
1304 * record that isn't an alert.
1306 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1307 s->rlayer.alert_count = 0;
1309 /* we now have a packet which can be read and processed */
1311 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1312 * reset by ssl3_get_finished */
1313 && (rr->type != SSL3_RT_HANDSHAKE)) {
1314 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1315 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1320 * If the other end has shut down, throw anything we read away (even in
1323 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1324 s->rlayer.curr_rec++;
1325 s->rwstate = SSL_NOTHING;
1329 if (type == rr->type
1330 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1331 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1334 * SSL3_RT_APPLICATION_DATA or
1335 * SSL3_RT_HANDSHAKE or
1336 * SSL3_RT_CHANGE_CIPHER_SPEC
1339 * make sure that we are not getting application data when we are
1340 * doing a handshake for the first time
1342 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1343 && s->enc_read_ctx == NULL) {
1344 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1348 if (type == SSL3_RT_HANDSHAKE
1349 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1350 && s->rlayer.handshake_fragment_len > 0) {
1351 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1355 if (recvd_type != NULL)
1356 *recvd_type = rr->type;
1360 * Skip a zero length record. This ensures multiple calls to
1361 * SSL_read() with a zero length buffer will eventually cause
1362 * SSL_pending() to report data as being available.
1364 if (rr->length == 0) {
1365 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1366 s->rlayer.curr_rec++;
1372 curr_rec = s->rlayer.curr_rec;
1374 if (len - totalbytes > rr->length)
1377 n = len - totalbytes;
1379 memcpy(buf, &(rr->data[rr->off]), n);
1382 /* Mark any zero length record as consumed CVE-2016-6305 */
1383 if (rr->length == 0) {
1384 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1385 s->rlayer.curr_rec++;
1388 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1389 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1392 if (rr->length == 0) {
1393 /* TODO(RECLAYER): What to do with this? Is it needed? */
1395 s->rlayer.rstate = SSL_ST_READ_HEADER;
1397 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1398 s->rlayer.curr_rec++;
1402 || (peek && n == rr->length)) {
1407 } while (type == SSL3_RT_APPLICATION_DATA
1408 && curr_rec < s->rlayer.num_recs
1409 && totalbytes < len);
1410 if (totalbytes == 0) {
1411 /* We must have read empty records. Get more data */
1414 /* TODO(RECLAYER): FIX ME */
1416 if (!peek && curr_rec == s->rlayer.num_recs
1417 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1418 && SSL3_BUFFER_get_left(rbuf) == 0)
1419 ssl3_release_read_buffer(s);
1421 *readbytes = totalbytes;
1426 * If we get here, then type != rr->type; if we have a handshake message,
1427 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1428 * were actually expecting a CCS).
1432 * Lets just double check that we've not got an SSLv2 record
1434 if (rr->version == SSL2_VERSION) {
1436 * Should never happen. ssl3_get_record() should only give us an SSLv2
1437 * record back if this is the first packet and we are looking for an
1438 * initial ClientHello. Therefore |type| should always be equal to
1439 * |rr->type|. If not then something has gone horribly wrong
1441 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1445 if (ssl->method->version == TLS_ANY_VERSION
1446 && (s->server || rr->type != SSL3_RT_ALERT)) {
1448 * If we've got this far and still haven't decided on what version
1449 * we're using then this must be a client side alert we're dealing
1450 * with. We shouldn't be receiving anything other than a ClientHello
1451 * if we are a server.
1453 s->version = rr->version;
1454 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1459 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1460 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1463 if (rr->type == SSL3_RT_ALERT) {
1464 unsigned int alert_level, alert_descr;
1465 unsigned char *alert_bytes = rr->data
1469 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1470 || !PACKET_get_1(&alert, &alert_level)
1471 || !PACKET_get_1(&alert, &alert_descr)
1472 || PACKET_remaining(&alert) != 0) {
1473 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1477 if (s->msg_callback)
1478 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1479 s->msg_callback_arg);
1481 if (s->info_callback != NULL)
1482 cb = s->info_callback;
1483 else if (ssl->ctx->info_callback != NULL)
1484 cb = ssl->ctx->info_callback;
1487 j = (alert_level << 8) | alert_descr;
1488 cb(ssl, SSL_CB_READ_ALERT, j);
1491 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1492 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1493 s->s3.warn_alert = alert_descr;
1494 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1495 s->rlayer.curr_rec++;
1497 s->rlayer.alert_count++;
1498 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1499 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1500 SSL_R_TOO_MANY_WARN_ALERTS);
1506 * Apart from close_notify the only other warning alert in TLSv1.3
1507 * is user_cancelled - which we just ignore.
1509 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1511 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1512 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1513 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1515 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1516 s->rwstate = SSL_NOTHING;
1517 s->s3.fatal_alert = alert_descr;
1518 SSLfatal_data(s, SSL_AD_NO_ALERT,
1519 SSL_AD_REASON_OFFSET + alert_descr,
1520 "SSL alert number %d", alert_descr);
1521 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1522 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1523 s->rlayer.curr_rec++;
1524 SSL_CTX_remove_session(s->session_ctx, s->session);
1526 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1528 * This is a warning but we receive it if we requested
1529 * renegotiation and the peer denied it. Terminate with a fatal
1530 * alert because if application tried to renegotiate it
1531 * presumably had a good reason and expects it to succeed. In
1532 * future we might have a renegotiation where we don't care if
1533 * the peer refused it where we carry on.
1535 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1537 } else if (alert_level == SSL3_AL_WARNING) {
1538 /* We ignore any other warning alert in TLSv1.2 and below */
1542 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1546 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1547 if (rr->type == SSL3_RT_HANDSHAKE) {
1551 * We ignore any handshake messages sent to us unless they are
1552 * TLSv1.3 in which case we want to process them. For all other
1553 * handshake messages we can't do anything reasonable with them
1554 * because we are unable to write any response due to having already
1555 * sent close_notify.
1557 if (!SSL_CONNECTION_IS_TLS13(s)) {
1558 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1559 s->rlayer.curr_rec++;
1561 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1564 s->rwstate = SSL_READING;
1565 rbio = SSL_get_rbio(ssl);
1566 BIO_clear_retry_flags(rbio);
1567 BIO_set_retry_read(rbio);
1572 * The peer is continuing to send application data, but we have
1573 * already sent close_notify. If this was expected we should have
1574 * been called via SSL_read() and this would have been handled
1576 * No alert sent because we already sent close_notify
1578 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1579 s->rlayer.curr_rec++;
1580 SSLfatal(s, SSL_AD_NO_ALERT,
1581 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1587 * For handshake data we have 'fragment' storage, so fill that so that we
1588 * can process the header at a fixed place. This is done after the
1589 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1590 * that we're just going to discard.
1592 if (rr->type == SSL3_RT_HANDSHAKE) {
1593 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1594 unsigned char *dest = s->rlayer.handshake_fragment;
1595 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1597 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1599 n = rr->length; /* available bytes */
1601 /* now move 'n' bytes: */
1602 memcpy(dest + *dest_len, rr->data + rr->off, n);
1606 if (rr->length == 0) {
1607 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1608 s->rlayer.curr_rec++;
1611 if (*dest_len < dest_maxlen)
1612 goto start; /* fragment was too small */
1615 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1616 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1621 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1622 * protocol violation)
1624 if ((s->rlayer.handshake_fragment_len >= 4)
1625 && !ossl_statem_get_in_handshake(s)) {
1626 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1628 /* We found handshake data, so we're going back into init */
1629 ossl_statem_set_in_init(s, 1);
1631 i = s->handshake_func(ssl);
1632 /* SSLfatal() already called if appropriate */
1640 * If we were actually trying to read early data and we found a
1641 * handshake message, then we don't want to continue to try and read
1642 * the application data any more. It won't be "early" now.
1647 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1648 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1651 * In the case where we try to read application data, but we
1652 * trigger an SSL handshake, we return -1 with the retry
1653 * option set. Otherwise renegotiation may cause nasty
1654 * problems in the blocking world
1656 s->rwstate = SSL_READING;
1657 bio = SSL_get_rbio(ssl);
1658 BIO_clear_retry_flags(bio);
1659 BIO_set_retry_read(bio);
1669 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1670 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1671 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1672 * no progress is being made and the peer continually sends unrecognised
1673 * record types, using up resources processing them.
1675 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1677 case SSL3_RT_CHANGE_CIPHER_SPEC:
1679 case SSL3_RT_HANDSHAKE:
1681 * we already handled all of these, with the possible exception of
1682 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1683 * that should not happen when type != rr->type
1685 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1687 case SSL3_RT_APPLICATION_DATA:
1689 * At this point, we were expecting handshake data, but have
1690 * application data. If the library was running inside ssl3_read()
1691 * (i.e. in_read_app_data is set) and it makes sense to read
1692 * application data at this point (session renegotiation not yet
1693 * started), we will indulge it.
1695 if (ossl_statem_app_data_allowed(s)) {
1696 s->s3.in_read_app_data = 2;
1698 } else if (ossl_statem_skip_early_data(s)) {
1700 * This can happen after a client sends a CH followed by early_data,
1701 * but the server responds with a HelloRetryRequest. The server
1702 * reads the next record from the client expecting to find a
1703 * plaintext ClientHello but gets a record which appears to be
1704 * application data. The trial decrypt "works" because null
1705 * decryption was applied. We just skip it and move on to the next
1708 if (!ossl_early_data_count_ok(s, rr->length,
1709 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1710 /* SSLfatal() already called */
1713 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1714 s->rlayer.curr_rec++;
1717 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1723 void ssl3_record_sequence_update(unsigned char *seq)
1727 for (i = 7; i >= 0; i--) {
1735 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1736 * format and false otherwise.
1738 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1740 if (SSL_CONNECTION_IS_DTLS(rl->s))
1742 return rl->tlsrecs[0].version == SSL2_VERSION;
1746 * Returns the length in bytes of the current rrec
1748 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1750 return SSL3_RECORD_get_length(&rl->rrec[0]);
1753 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1757 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1758 if (SSL_CONNECTION_IS_DTLS(s))
1759 return &ossl_dtls_record_method;
1761 return &ossl_tls_record_method;
1764 #ifndef OPENSSL_NO_KTLS
1765 /* KTLS does not support renegotiation */
1766 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1767 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1768 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1769 return &ossl_ktls_record_method;
1772 /* Default to the current OSSL_RECORD_METHOD */
1773 return s->rrlmethod;
1776 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1778 #ifndef OPENSSL_NO_KTLS
1779 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1781 if (s->rrlmethod == &ossl_ktls_record_method) {
1782 /* KTLS does not support renegotiation so disallow it */
1783 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1786 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rrlmethod->set_first_handshake != NULL)
1787 s->rrlmethod->set_first_handshake(s->rrl, 1);
1791 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1792 int direction, int level,
1793 unsigned char *key, size_t keylen,
1794 unsigned char *iv, size_t ivlen,
1795 unsigned char *mackey, size_t mackeylen,
1796 const EVP_CIPHER *ciph, size_t taglen,
1797 int mactype, const EVP_MD *md,
1798 const SSL_COMP *comp)
1800 OSSL_PARAM_BLD *tmpl = NULL;
1801 OSSL_PARAM *options = NULL;
1802 const OSSL_RECORD_METHOD *origmeth = s->rrlmethod;
1804 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1805 const OSSL_RECORD_METHOD *meth;
1807 meth = ssl_select_next_record_layer(s, level);
1809 if (s->rrlmethod != NULL)
1810 s->rrlmethod->free(s->rrl);
1813 s->rrlmethod = meth;
1815 if (!ossl_assert(s->rrlmethod != NULL)) {
1816 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1820 if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
1821 || !OSSL_PARAM_BLD_push_uint64(tmpl,
1822 OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1824 || !OSSL_PARAM_BLD_push_uint32(tmpl,
1825 OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1827 || !OSSL_PARAM_BLD_push_int(tmpl,
1828 OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1829 s->rlayer.read_ahead)
1830 || (options = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
1831 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1838 rlret = s->rrlmethod->new_record_layer(sctx->libctx, sctx->propq,
1839 version, s->server, direction,
1840 level, key, keylen, iv, ivlen,
1841 mackey, mackeylen, ciph, taglen,
1842 mactype, md, comp, s->rbio,
1843 NULL, NULL, NULL, options,
1846 case OSSL_RECORD_RETURN_FATAL:
1847 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1850 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1851 if (s->rrlmethod != origmeth && origmeth != NULL) {
1853 * We tried a new record layer method, but it didn't work out,
1854 * so we fallback to the original method and try again
1856 s->rrlmethod = origmeth;
1859 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1862 case OSSL_RECORD_RETURN_SUCCESS:
1866 /* Should not happen */
1867 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1873 ret = ssl_post_record_layer_select(s);
1875 OSSL_PARAM_free(options);
1876 OSSL_PARAM_BLD_free(tmpl);