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)
33 RECORD_LAYER_set_first_record(&s->rlayer);
34 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
37 void RECORD_LAYER_clear(RECORD_LAYER *rl)
39 rl->rstate = SSL_ST_READ_HEADER;
42 * Do I need to clear read_ahead? As far as I can tell read_ahead did not
43 * previously get reset by SSL_clear...so I'll keep it that way..but is
48 rl->packet_length = 0;
50 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
51 rl->handshake_fragment_len = 0;
57 SSL3_BUFFER_clear(&rl->rbuf);
58 ssl3_release_write_buffer(rl->s);
60 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
62 RECORD_LAYER_reset_read_sequence(rl);
63 RECORD_LAYER_reset_write_sequence(rl);
66 DTLS_RECORD_LAYER_clear(rl);
69 void RECORD_LAYER_release(RECORD_LAYER *rl)
71 if (SSL3_BUFFER_is_initialised(&rl->rbuf))
72 ssl3_release_read_buffer(rl->s);
73 if (rl->numwpipes > 0)
74 ssl3_release_write_buffer(rl->s);
75 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
78 /* Checks if we have unprocessed read ahead data pending */
79 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
82 * TODO(RECLAYER): Temporarily do it the old way until DTLS is converted to
83 * the new record layer code
85 if (SSL_CONNECTION_IS_DTLS(rl->s))
86 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
88 return rl->s->rrlmethod->unprocessed_read_pending(rl->s->rrl);
91 /* Checks if we have decrypted unread record data pending */
92 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
95 * TODO(RECLAYER): Temporarily do it the old way until DTLS is converted to
96 * the new record layer code
98 if (SSL_CONNECTION_IS_DTLS(rl->s)) {
99 const SSL3_RECORD *rr = rl->rrec;
101 size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl);
103 while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]))
106 return curr_rec < num_recs;
109 return (rl->curr_rec < rl->num_recs)
110 || rl->s->rrlmethod->processed_read_pending(rl->s->rrl);
113 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
115 return (rl->numwpipes > 0)
116 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
119 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
121 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
124 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
126 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
129 size_t ssl3_pending(const SSL *s)
132 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
137 if (sc->rlayer.rstate == SSL_ST_READ_BODY)
141 * TODO(RECLAYER): We need to do it the old way temporary for DTLS until
142 * that is converted to use the new record layer code
144 if (SSL_CONNECTION_IS_DTLS(sc)) {
145 DTLS1_RECORD_DATA *rdata;
148 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
149 while ((item = pqueue_next(&iter)) != NULL) {
151 num += rdata->rrec.length;
154 for (i = 0; i < RECORD_LAYER_get_numrpipes(&sc->rlayer); i++) {
155 if (SSL3_RECORD_get_type(&sc->rlayer.rrec[i])
156 != SSL3_RT_APPLICATION_DATA)
158 num += SSL3_RECORD_get_length(&sc->rlayer.rrec[i]);
161 for (i = 0; i <sc->rlayer.num_recs; i++) {
162 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
164 num += sc->rlayer.tlsrecs[i].length;
171 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
173 ctx->default_read_buf_len = len;
176 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
178 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
182 SSL3_BUFFER_set_default_len(sc->rrlmethod->get0_rbuf(sc->rrl), len);
185 const char *SSL_rstate_string_long(const SSL *s)
187 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
192 switch (sc->rlayer.rstate) {
193 case SSL_ST_READ_HEADER:
194 return "read header";
195 case SSL_ST_READ_BODY:
197 case SSL_ST_READ_DONE:
204 const char *SSL_rstate_string(const SSL *s)
206 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
211 switch (sc->rlayer.rstate) {
212 case SSL_ST_READ_HEADER:
214 case SSL_ST_READ_BODY:
216 case SSL_ST_READ_DONE:
225 * Call this to write data in records of type 'type' It will return <= 0 if
226 * not all data has been sent or non-blocking IO.
228 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
231 const unsigned char *buf = buf_;
233 size_t n, max_send_fragment, split_send_fragment, maxpipes;
234 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
240 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
245 wb = &s->rlayer.wbuf[0];
246 s->rwstate = SSL_NOTHING;
247 tot = s->rlayer.wnum;
249 * ensure that if we end up with a smaller value of data to write out
250 * than the original len from a write which didn't complete for
251 * non-blocking I/O and also somehow ended up avoiding the check for
252 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
253 * possible to end up with (len-tot) as a large number that will then
254 * promptly send beyond the end of the users buffer ... so we trap and
255 * report the error in a way the user will notice
257 if ((len < s->rlayer.wnum)
258 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
259 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
263 if (s->early_data_state == SSL_EARLY_DATA_WRITING
264 && !ossl_early_data_count_ok(s, len, 0, 1)) {
265 /* SSLfatal() already called */
272 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
273 * into init unless we have writes pending - in which case we should finish
276 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
277 || s->ext.extra_tickets_expected > 0))
278 ossl_statem_set_in_init(s, 1);
281 * When writing early data on the server side we could be "in_init" in
282 * between receiving the EoED and the CF - but we don't want to handle those
285 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
286 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
287 i = s->handshake_func(ssl);
288 /* SSLfatal() already called */
297 * first check if there is a SSL3_BUFFER still being written out. This
298 * will happen with non blocking IO
301 /* SSLfatal() already called if appropriate */
302 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
305 /* XXX should we ssl3_release_write_buffer if i<0? */
306 s->rlayer.wnum = tot;
309 tot += tmpwrit; /* this might be last fragment */
311 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
313 * Depending on platform multi-block can deliver several *times*
314 * better performance. Downside is that it has to allocate
315 * jumbo buffer to accommodate up to 8 records, but the
316 * compromise is considered worthy.
318 if (type == SSL3_RT_APPLICATION_DATA
319 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
320 && s->compress == NULL
321 && s->msg_callback == NULL
323 && SSL_USE_EXPLICIT_IV(s)
324 && !BIO_get_ktls_send(s->wbio)
325 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
326 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
327 unsigned char aad[13];
328 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
332 /* minimize address aliasing conflicts */
333 if ((max_send_fragment & 0xfff) == 0)
334 max_send_fragment -= 512;
336 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
337 ssl3_release_write_buffer(s);
339 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
340 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
341 (int)max_send_fragment, NULL);
343 if (len >= 8 * max_send_fragment)
348 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
349 /* SSLfatal() already called */
352 } else if (tot == len) { /* done? */
353 /* free jumbo buffer */
354 ssl3_release_write_buffer(s);
361 if (n < 4 * max_send_fragment) {
362 /* free jumbo buffer */
363 ssl3_release_write_buffer(s);
367 if (s->s3.alert_dispatch) {
368 i = ssl->method->ssl_dispatch_alert(ssl);
370 /* SSLfatal() already called if appropriate */
371 s->rlayer.wnum = tot;
376 if (n >= 8 * max_send_fragment)
377 nw = max_send_fragment * (mb_param.interleave = 8);
379 nw = max_send_fragment * (mb_param.interleave = 4);
381 memcpy(aad, s->rlayer.write_sequence, 8);
383 aad[9] = (unsigned char)(s->version >> 8);
384 aad[10] = (unsigned char)(s->version);
391 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
392 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
393 sizeof(mb_param), &mb_param);
394 packlen = (size_t)packleni;
395 if (packleni <= 0 || packlen > wb->len) { /* never happens */
396 /* free jumbo buffer */
397 ssl3_release_write_buffer(s);
401 mb_param.out = wb->buf;
402 mb_param.inp = &buf[tot];
405 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
406 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
407 sizeof(mb_param), &mb_param) <= 0)
410 s->rlayer.write_sequence[7] += mb_param.interleave;
411 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
413 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
419 s->rlayer.wpend_tot = nw;
420 s->rlayer.wpend_buf = &buf[tot];
421 s->rlayer.wpend_type = type;
422 s->rlayer.wpend_ret = nw;
424 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
426 /* SSLfatal() already called if appropriate */
427 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
428 /* free jumbo buffer */
429 ssl3_release_write_buffer(s);
431 s->rlayer.wnum = tot;
435 /* free jumbo buffer */
436 ssl3_release_write_buffer(s);
437 *written = tot + tmpwrit;
444 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
445 if (tot == len) { /* done? */
446 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
447 ssl3_release_write_buffer(s);
455 max_send_fragment = ssl_get_max_send_fragment(s);
456 split_send_fragment = ssl_get_split_send_fragment(s);
458 * If max_pipelines is 0 then this means "undefined" and we default to
459 * 1 pipeline. Similarly if the cipher does not support pipelined
460 * processing then we also only use 1 pipeline, or if we're not using
463 maxpipes = s->max_pipelines;
464 if (maxpipes > SSL_MAX_PIPELINES) {
466 * We should have prevented this when we set max_pipelines so we
469 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
473 || s->enc_write_ctx == NULL
474 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
475 & EVP_CIPH_FLAG_PIPELINE) == 0
476 || !SSL_USE_EXPLICIT_IV(s))
478 if (max_send_fragment == 0
479 || split_send_fragment == 0
480 || split_send_fragment > max_send_fragment) {
482 * We should have prevented this when we set/get the split and max send
483 * fragments so we shouldn't get here
485 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
490 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
496 numpipes = ((n - 1) / split_send_fragment) + 1;
497 if (numpipes > maxpipes)
500 if (n / numpipes >= max_send_fragment) {
502 * We have enough data to completely fill all available
505 for (j = 0; j < numpipes; j++) {
506 pipelens[j] = max_send_fragment;
509 /* We can partially fill all available pipelines */
510 tmppipelen = n / numpipes;
511 remain = n % numpipes;
512 for (j = 0; j < numpipes; j++) {
513 pipelens[j] = tmppipelen;
519 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
522 /* SSLfatal() already called if appropriate */
523 /* XXX should we ssl3_release_write_buffer if i<0? */
524 s->rlayer.wnum = tot;
529 (type == SSL3_RT_APPLICATION_DATA &&
530 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
532 * next chunk of data should get another prepended empty fragment
533 * in ciphersuites with known-IV weakness:
535 s->s3.empty_fragment_done = 0;
538 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
539 && !SSL_CONNECTION_IS_DTLS(s))
540 ssl3_release_write_buffer(s);
542 *written = tot + tmpwrit;
551 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
552 size_t *pipelens, size_t numpipes,
553 int create_empty_fragment, size_t *written)
555 WPACKET pkt[SSL_MAX_PIPELINES];
556 SSL3_RECORD wr[SSL_MAX_PIPELINES];
559 unsigned char *recordstart;
560 int i, mac_size, clear = 0;
561 size_t prefix_len = 0;
566 size_t totlen = 0, len, wpinited = 0;
569 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
571 for (j = 0; j < numpipes; j++)
572 totlen += pipelens[j];
574 * first check if there is a SSL3_BUFFER still being written out. This
575 * will happen with non blocking IO
577 if (RECORD_LAYER_write_pending(&s->rlayer)) {
578 /* Calls SSLfatal() as required */
579 return ssl3_write_pending(s, type, buf, totlen, written);
582 /* If we have an alert to send, lets send it */
583 if (s->s3.alert_dispatch) {
584 i = ssl->method->ssl_dispatch_alert(ssl);
586 /* SSLfatal() already called if appropriate */
589 /* if it went, fall through and send more stuff */
592 if (s->rlayer.numwpipes < numpipes) {
593 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
594 /* SSLfatal() already called */
599 if (totlen == 0 && !create_empty_fragment)
605 || (s->enc_write_ctx == NULL)
606 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
607 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
610 mac_size = EVP_MD_CTX_get_size(s->write_hash);
612 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
618 * 'create_empty_fragment' is true only when this function calls itself
620 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
622 * countermeasure against known-IV weakness in CBC ciphersuites (see
623 * http://www.openssl.org/~bodo/tls-cbc.txt)
626 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
628 * recursive function call with 'create_empty_fragment' set; this
629 * prepares and buffers the data for an empty fragment (these
630 * 'prefix_len' bytes are sent out later together with the actual
633 size_t tmppipelen = 0;
636 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
638 /* SSLfatal() already called if appropriate */
643 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
644 /* insufficient space */
645 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
650 s->s3.empty_fragment_done = 1;
653 using_ktls = BIO_get_ktls_send(s->wbio);
656 * ktls doesn't modify the buffer, but to avoid a warning we need to
657 * discard the const qualifier.
658 * This doesn't leak memory because the buffers have been released when
661 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
662 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
663 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
664 goto wpacket_init_complete;
667 if (create_empty_fragment) {
668 wb = &s->rlayer.wbuf[0];
669 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
671 * extra fragment would be couple of cipher blocks, which would be
672 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
673 * payload, then we can just pretend we simply have two headers.
675 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
676 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
678 SSL3_BUFFER_set_offset(wb, align);
679 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
680 SSL3_BUFFER_get_len(wb), 0)
681 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
682 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
686 } else if (prefix_len) {
687 wb = &s->rlayer.wbuf[0];
688 if (!WPACKET_init_static_len(&pkt[0],
689 SSL3_BUFFER_get_buf(wb),
690 SSL3_BUFFER_get_len(wb), 0)
691 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
692 + prefix_len, NULL)) {
693 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
698 for (j = 0; j < numpipes; j++) {
701 wb = &s->rlayer.wbuf[j];
702 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
703 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
704 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
706 SSL3_BUFFER_set_offset(wb, align);
707 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
708 SSL3_BUFFER_get_len(wb), 0)
709 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
710 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
717 /* Explicit IV length, block ciphers appropriate version flag */
718 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
719 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
720 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
721 if (mode == EVP_CIPH_CBC_MODE) {
722 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
724 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
729 } else if (mode == EVP_CIPH_GCM_MODE) {
730 /* Need explicit part of IV for GCM mode */
731 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
732 } else if (mode == EVP_CIPH_CCM_MODE) {
733 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
737 wpacket_init_complete:
740 /* Clear our SSL3_RECORD structures */
741 memset(wr, 0, sizeof(wr));
742 for (j = 0; j < numpipes; j++) {
743 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
745 unsigned char *compressdata = NULL;
747 unsigned int rectype;
753 * In TLSv1.3, once encrypting, we always use application data for the
756 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
757 && s->enc_write_ctx != NULL
758 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
759 || type != SSL3_RT_ALERT))
760 rectype = SSL3_RT_APPLICATION_DATA;
763 SSL3_RECORD_set_type(thiswr, rectype);
766 * Some servers hang if initial client hello is larger than 256 bytes
767 * and record version number > TLS 1.0
769 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
771 && TLS1_get_version(ssl) > TLS1_VERSION
772 && s->hello_retry_request == SSL_HRR_NONE)
773 version = TLS1_VERSION;
774 SSL3_RECORD_set_rec_version(thiswr, version);
776 maxcomplen = pipelens[j];
777 if (s->compress != NULL)
778 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
781 * When using offload kernel will write the header.
782 * Otherwise write the header now
785 && (!WPACKET_put_bytes_u8(thispkt, rectype)
786 || !WPACKET_put_bytes_u16(thispkt, version)
787 || !WPACKET_start_sub_packet_u16(thispkt)
789 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
791 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
793 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
797 /* lets setup the record stuff. */
798 SSL3_RECORD_set_data(thiswr, compressdata);
799 SSL3_RECORD_set_length(thiswr, pipelens[j]);
800 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
801 totlen += pipelens[j];
804 * we now 'read' from thiswr->input, thiswr->length bytes into
808 /* first we compress */
809 if (s->compress != NULL) {
810 if (!ssl3_do_compress(s, thiswr)
811 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
812 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
817 SSL3_RECORD_reset_data(&wr[j]);
819 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
820 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
823 SSL3_RECORD_reset_input(&wr[j]);
827 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
829 && s->enc_write_ctx != NULL
830 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
831 || type != SSL3_RT_ALERT)) {
832 size_t rlen, max_send_fragment;
834 if (!WPACKET_put_bytes_u8(thispkt, type)) {
835 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
838 SSL3_RECORD_add_length(thiswr, 1);
840 /* Add TLS1.3 padding */
841 max_send_fragment = ssl_get_max_send_fragment(s);
842 rlen = SSL3_RECORD_get_length(thiswr);
843 if (rlen < max_send_fragment) {
845 size_t max_padding = max_send_fragment - rlen;
846 if (s->record_padding_cb != NULL) {
847 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
848 } else if (s->block_padding > 0) {
849 size_t mask = s->block_padding - 1;
852 /* optimize for power of 2 */
853 if ((s->block_padding & mask) == 0)
854 remainder = rlen & mask;
856 remainder = rlen % s->block_padding;
857 /* don't want to add a block of padding if we don't have to */
861 padding = s->block_padding - remainder;
864 /* do not allow the record to exceed max plaintext length */
865 if (padding > max_padding)
866 padding = max_padding;
867 if (!WPACKET_memset(thispkt, 0, padding)) {
868 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
869 ERR_R_INTERNAL_ERROR);
872 SSL3_RECORD_add_length(thiswr, padding);
878 * we should still have the output to thiswr->data and the input from
879 * wr->input. Length should be thiswr->length. thiswr->data still points
883 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
886 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
887 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
888 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
894 * Reserve some bytes for any growth that may occur during encryption.
895 * This will be at most one cipher block or the tag length if using
896 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
899 if (!WPACKET_reserve_bytes(thispkt,
900 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
903 * We also need next the amount of bytes written to this
906 || !WPACKET_get_length(thispkt, &len)) {
907 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
911 /* Get a pointer to the start of this record excluding header */
912 recordstart = WPACKET_get_curr(thispkt) - len;
913 SSL3_RECORD_set_data(thiswr, recordstart);
914 SSL3_RECORD_reset_input(thiswr);
915 SSL3_RECORD_set_length(thiswr, len);
919 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
921 * We haven't actually negotiated the version yet, but we're trying to
922 * send early data - so we need to use the tls13enc function.
924 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
925 if (!ossl_statem_in_error(s)) {
926 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
932 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
934 if (!ossl_statem_in_error(s)) {
935 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
942 for (j = 0; j < numpipes; j++) {
951 /* Allocate bytes for the encryption overhead */
952 if (!WPACKET_get_length(thispkt, &origlen)
953 /* Encryption should never shrink the data! */
954 || origlen > thiswr->length
955 || (thiswr->length > origlen
956 && !WPACKET_allocate_bytes(thispkt,
957 thiswr->length - origlen,
959 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
962 if (SSL_WRITE_ETM(s) && mac_size != 0) {
965 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
966 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
967 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
970 SSL3_RECORD_add_length(thiswr, mac_size);
973 if (!WPACKET_get_length(thispkt, &len)
974 || !WPACKET_close(thispkt)) {
975 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
979 if (s->msg_callback) {
980 recordstart = WPACKET_get_curr(thispkt) - len
981 - SSL3_RT_HEADER_LENGTH;
982 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
983 SSL3_RT_HEADER_LENGTH, ssl,
984 s->msg_callback_arg);
986 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
987 unsigned char ctype = type;
989 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
990 &ctype, 1, ssl, s->msg_callback_arg);
994 if (!WPACKET_finish(thispkt)) {
995 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
999 /* header is added by the kernel when using offload */
1000 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1002 if (create_empty_fragment) {
1004 * we are in a recursive call; just return the length, don't write
1008 /* We should never be pipelining an empty fragment!! */
1009 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1012 *written = SSL3_RECORD_get_length(thiswr);
1018 * we should now have thiswr->data pointing to the encrypted data, which
1019 * is thiswr->length long
1021 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
1024 /* now let's set up wb */
1025 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
1026 prefix_len + SSL3_RECORD_get_length(thiswr));
1030 * memorize arguments so that ssl3_write_pending can detect bad write
1033 s->rlayer.wpend_tot = totlen;
1034 s->rlayer.wpend_buf = buf;
1035 s->rlayer.wpend_type = type;
1036 s->rlayer.wpend_ret = totlen;
1038 /* we now just need to write the buffer */
1039 return ssl3_write_pending(s, type, buf, totlen, written);
1041 for (j = 0; j < wpinited; j++)
1042 WPACKET_cleanup(&pkt[j]);
1046 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1048 * Return values are as per SSL_write()
1050 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1051 size_t len, size_t *written)
1054 SSL3_BUFFER *wb = s->rlayer.wbuf;
1058 if ((s->rlayer.wpend_tot > len)
1059 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1060 && (s->rlayer.wpend_buf != buf))
1061 || (s->rlayer.wpend_type != type)) {
1062 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1067 /* Loop until we find a buffer we haven't written out yet */
1068 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1069 && currbuf < s->rlayer.numwpipes - 1) {
1074 if (s->wbio != NULL) {
1075 s->rwstate = SSL_WRITING;
1078 * To prevent coalescing of control and data messages,
1079 * such as in buffer_write, we flush the BIO
1081 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1082 i = BIO_flush(s->wbio);
1085 BIO_set_ktls_ctrl_msg(s->wbio, type);
1087 i = BIO_write(s->wbio, (char *)
1088 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1089 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1090 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1094 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1099 * When an empty fragment is sent on a connection using KTLS,
1100 * it is sent as a write of zero bytes. If this zero byte
1101 * write succeeds, i will be 0 rather than a non-zero value.
1102 * Treat i == 0 as success rather than an error for zero byte
1103 * writes to permit this case.
1105 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1106 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1107 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1108 if (currbuf + 1 < s->rlayer.numwpipes)
1110 s->rwstate = SSL_NOTHING;
1111 *written = s->rlayer.wpend_ret;
1113 } else if (i <= 0) {
1114 if (SSL_CONNECTION_IS_DTLS(s)) {
1116 * For DTLS, just drop it. That's kind of the whole point in
1117 * using a datagram service
1119 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1123 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1124 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1128 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
1131 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1133 if (ret == OSSL_RECORD_RETURN_RETRY) {
1134 s->rwstate = SSL_READING;
1137 s->rwstate = SSL_NOTHING;
1138 if (ret == OSSL_RECORD_RETURN_EOF) {
1139 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
1140 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
1141 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
1144 ERR_set_debug(file, line, 0);
1145 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
1146 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
1148 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
1150 ERR_set_debug(file, line, 0);
1151 ossl_statem_fatal(s, s->rrlmethod->get_alert_code(s->rrl),
1152 SSL_R_RECORD_LAYER_FAILURE, NULL);
1155 * The record layer distinguishes the cases of EOF, non-fatal
1156 * err and retry. Upper layers do not.
1157 * If we got a retry or success then *ret is already correct,
1158 * otherwise we need to convert the return value.
1161 * TODO(RECLAYER): What does a non fatal err that isn't a retry even
1164 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
1166 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
1174 * Return up to 'len' payload bytes received in 'type' records.
1175 * 'type' is one of the following:
1177 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1178 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1179 * - 0 (during a shutdown, no data has to be returned)
1181 * If we don't have stored data to work from, read a SSL/TLS record first
1182 * (possibly multiple records if we still don't have anything to return).
1184 * This function must handle any surprises the peer may have for us, such as
1185 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1186 * messages are treated as if they were handshake messages *if* the |recvd_type|
1187 * argument is non NULL.
1188 * Also if record payloads contain fragments too small to process, we store
1189 * them until there is enough for the respective protocol (the record protocol
1190 * may use arbitrary fragmentation and even interleaving):
1191 * Change cipher spec protocol
1192 * just 1 byte needed, no need for keeping anything stored
1194 * 2 bytes needed (AlertLevel, AlertDescription)
1195 * Handshake protocol
1196 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1197 * to detect unexpected Client Hello and Hello Request messages
1198 * here, anything else is handled by higher layers
1199 * Application data protocol
1200 * none of our business
1202 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1203 size_t len, int peek, size_t *readbytes)
1206 size_t n, curr_rec, totalbytes;
1208 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1210 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1212 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1215 && (type != SSL3_RT_APPLICATION_DATA)
1216 && (type != SSL3_RT_HANDSHAKE))
1217 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
1218 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1222 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1223 /* (partially) satisfy request from storage */
1225 unsigned char *src = s->rlayer.handshake_fragment;
1226 unsigned char *dst = buf;
1231 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1234 s->rlayer.handshake_fragment_len--;
1237 /* move any remaining fragment bytes: */
1238 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1239 s->rlayer.handshake_fragment[k] = *src++;
1241 if (recvd_type != NULL)
1242 *recvd_type = SSL3_RT_HANDSHAKE;
1249 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1252 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1253 /* type == SSL3_RT_APPLICATION_DATA */
1254 i = s->handshake_func(ssl);
1255 /* SSLfatal() already called */
1262 s->rwstate = SSL_NOTHING;
1265 * For each record 'i' up to |num_recs]
1266 * rr[i].type - is the type of record
1267 * rr[i].data, - data
1268 * rr[i].off, - offset into 'data' for next read
1269 * rr[i].length, - number of bytes.
1271 /* get new records if necessary */
1272 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
1273 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
1275 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
1277 ret = HANDLE_RLAYER_RETURN(s,
1278 s->rrlmethod->read_record(s->rrl, &rr->rechandle,
1279 &rr->version, &rr->type,
1280 &rr->data, &rr->length,
1283 /* SSLfatal() already called if appropriate */
1287 s->rlayer.num_recs++;
1288 } while (s->rrlmethod->processed_read_pending(s->rrl)
1289 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
1291 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1293 if (s->rlayer.handshake_fragment_len > 0
1294 && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1295 && SSL_CONNECTION_IS_TLS13(s)) {
1296 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1297 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1302 * Reset the count of consecutive warning alerts if we've got a non-empty
1303 * record that isn't an alert.
1305 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
1306 s->rlayer.alert_count = 0;
1308 /* we now have a packet which can be read and processed */
1310 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1311 * reset by ssl3_get_finished */
1312 && (rr->type != SSL3_RT_HANDSHAKE)) {
1313 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1314 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1319 * If the other end has shut down, throw anything we read away (even in
1322 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1323 s->rlayer.curr_rec++;
1324 s->rwstate = SSL_NOTHING;
1328 if (type == rr->type
1329 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1330 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1333 * SSL3_RT_APPLICATION_DATA or
1334 * SSL3_RT_HANDSHAKE or
1335 * SSL3_RT_CHANGE_CIPHER_SPEC
1338 * make sure that we are not getting application data when we are
1339 * doing a handshake for the first time
1341 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1342 && s->enc_read_ctx == NULL) {
1343 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1347 if (type == SSL3_RT_HANDSHAKE
1348 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
1349 && s->rlayer.handshake_fragment_len > 0) {
1350 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1354 if (recvd_type != NULL)
1355 *recvd_type = rr->type;
1359 * Skip a zero length record. This ensures multiple calls to
1360 * SSL_read() with a zero length buffer will eventually cause
1361 * SSL_pending() to report data as being available.
1363 if (rr->length == 0) {
1364 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1365 s->rlayer.curr_rec++;
1371 curr_rec = s->rlayer.curr_rec;
1373 if (len - totalbytes > rr->length)
1376 n = len - totalbytes;
1378 memcpy(buf, &(rr->data[rr->off]), n);
1381 /* Mark any zero length record as consumed CVE-2016-6305 */
1382 if (rr->length == 0) {
1383 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1384 s->rlayer.curr_rec++;
1387 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1388 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1391 if (rr->length == 0) {
1392 /* TODO(RECLAYER): What to do with this? Is it needed? */
1394 s->rlayer.rstate = SSL_ST_READ_HEADER;
1396 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1397 s->rlayer.curr_rec++;
1401 || (peek && n == rr->length)) {
1406 } while (type == SSL3_RT_APPLICATION_DATA
1407 && curr_rec < s->rlayer.num_recs
1408 && totalbytes < len);
1409 if (totalbytes == 0) {
1410 /* We must have read empty records. Get more data */
1413 /* TODO(RECLAYER): FIX ME */
1415 if (!peek && curr_rec == s->rlayer.num_recs
1416 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1417 && SSL3_BUFFER_get_left(rbuf) == 0)
1418 ssl3_release_read_buffer(s);
1420 *readbytes = totalbytes;
1425 * If we get here, then type != rr->type; if we have a handshake message,
1426 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1427 * were actually expecting a CCS).
1431 * Lets just double check that we've not got an SSLv2 record
1433 if (rr->version == SSL2_VERSION) {
1435 * Should never happen. ssl3_get_record() should only give us an SSLv2
1436 * record back if this is the first packet and we are looking for an
1437 * initial ClientHello. Therefore |type| should always be equal to
1438 * |rr->type|. If not then something has gone horribly wrong
1440 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1444 if (ssl->method->version == TLS_ANY_VERSION
1445 && (s->server || rr->type != SSL3_RT_ALERT)) {
1447 * If we've got this far and still haven't decided on what version
1448 * we're using then this must be a client side alert we're dealing
1449 * with. We shouldn't be receiving anything other than a ClientHello
1450 * if we are a server.
1452 s->version = rr->version;
1453 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1458 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1459 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1462 if (rr->type == SSL3_RT_ALERT) {
1463 unsigned int alert_level, alert_descr;
1464 unsigned char *alert_bytes = rr->data
1468 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
1469 || !PACKET_get_1(&alert, &alert_level)
1470 || !PACKET_get_1(&alert, &alert_descr)
1471 || PACKET_remaining(&alert) != 0) {
1472 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1476 if (s->msg_callback)
1477 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1478 s->msg_callback_arg);
1480 if (s->info_callback != NULL)
1481 cb = s->info_callback;
1482 else if (ssl->ctx->info_callback != NULL)
1483 cb = ssl->ctx->info_callback;
1486 j = (alert_level << 8) | alert_descr;
1487 cb(ssl, SSL_CB_READ_ALERT, j);
1490 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
1491 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1492 s->s3.warn_alert = alert_descr;
1493 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1494 s->rlayer.curr_rec++;
1496 s->rlayer.alert_count++;
1497 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1498 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1499 SSL_R_TOO_MANY_WARN_ALERTS);
1505 * Apart from close_notify the only other warning alert in TLSv1.3
1506 * is user_cancelled - which we just ignore.
1508 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1510 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1511 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1512 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1514 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1515 s->rwstate = SSL_NOTHING;
1516 s->s3.fatal_alert = alert_descr;
1517 SSLfatal_data(s, SSL_AD_NO_ALERT,
1518 SSL_AD_REASON_OFFSET + alert_descr,
1519 "SSL alert number %d", alert_descr);
1520 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1521 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1522 s->rlayer.curr_rec++;
1523 SSL_CTX_remove_session(s->session_ctx, s->session);
1525 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1527 * This is a warning but we receive it if we requested
1528 * renegotiation and the peer denied it. Terminate with a fatal
1529 * alert because if application tried to renegotiate it
1530 * presumably had a good reason and expects it to succeed. In
1531 * future we might have a renegotiation where we don't care if
1532 * the peer refused it where we carry on.
1534 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1536 } else if (alert_level == SSL3_AL_WARNING) {
1537 /* We ignore any other warning alert in TLSv1.2 and below */
1541 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1545 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1546 if (rr->type == SSL3_RT_HANDSHAKE) {
1550 * We ignore any handshake messages sent to us unless they are
1551 * TLSv1.3 in which case we want to process them. For all other
1552 * handshake messages we can't do anything reasonable with them
1553 * because we are unable to write any response due to having already
1554 * sent close_notify.
1556 if (!SSL_CONNECTION_IS_TLS13(s)) {
1557 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1558 s->rlayer.curr_rec++;
1560 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1563 s->rwstate = SSL_READING;
1564 rbio = SSL_get_rbio(ssl);
1565 BIO_clear_retry_flags(rbio);
1566 BIO_set_retry_read(rbio);
1571 * The peer is continuing to send application data, but we have
1572 * already sent close_notify. If this was expected we should have
1573 * been called via SSL_read() and this would have been handled
1575 * No alert sent because we already sent close_notify
1577 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1578 s->rlayer.curr_rec++;
1579 SSLfatal(s, SSL_AD_NO_ALERT,
1580 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1586 * For handshake data we have 'fragment' storage, so fill that so that we
1587 * can process the header at a fixed place. This is done after the
1588 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1589 * that we're just going to discard.
1591 if (rr->type == SSL3_RT_HANDSHAKE) {
1592 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1593 unsigned char *dest = s->rlayer.handshake_fragment;
1594 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1596 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1598 n = rr->length; /* available bytes */
1600 /* now move 'n' bytes: */
1601 memcpy(dest + *dest_len, rr->data + rr->off, n);
1605 if (rr->length == 0) {
1606 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1607 s->rlayer.curr_rec++;
1610 if (*dest_len < dest_maxlen)
1611 goto start; /* fragment was too small */
1614 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1615 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1620 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1621 * protocol violation)
1623 if ((s->rlayer.handshake_fragment_len >= 4)
1624 && !ossl_statem_get_in_handshake(s)) {
1625 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1627 /* We found handshake data, so we're going back into init */
1628 ossl_statem_set_in_init(s, 1);
1630 i = s->handshake_func(ssl);
1631 /* SSLfatal() already called if appropriate */
1639 * If we were actually trying to read early data and we found a
1640 * handshake message, then we don't want to continue to try and read
1641 * the application data any more. It won't be "early" now.
1646 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1647 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1650 * In the case where we try to read application data, but we
1651 * trigger an SSL handshake, we return -1 with the retry
1652 * option set. Otherwise renegotiation may cause nasty
1653 * problems in the blocking world
1655 s->rwstate = SSL_READING;
1656 bio = SSL_get_rbio(ssl);
1657 BIO_clear_retry_flags(bio);
1658 BIO_set_retry_read(bio);
1668 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1669 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1670 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1671 * no progress is being made and the peer continually sends unrecognised
1672 * record types, using up resources processing them.
1674 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1676 case SSL3_RT_CHANGE_CIPHER_SPEC:
1678 case SSL3_RT_HANDSHAKE:
1680 * we already handled all of these, with the possible exception of
1681 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1682 * that should not happen when type != rr->type
1684 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1686 case SSL3_RT_APPLICATION_DATA:
1688 * At this point, we were expecting handshake data, but have
1689 * application data. If the library was running inside ssl3_read()
1690 * (i.e. in_read_app_data is set) and it makes sense to read
1691 * application data at this point (session renegotiation not yet
1692 * started), we will indulge it.
1694 if (ossl_statem_app_data_allowed(s)) {
1695 s->s3.in_read_app_data = 2;
1697 } else if (ossl_statem_skip_early_data(s)) {
1699 * This can happen after a client sends a CH followed by early_data,
1700 * but the server responds with a HelloRetryRequest. The server
1701 * reads the next record from the client expecting to find a
1702 * plaintext ClientHello but gets a record which appears to be
1703 * application data. The trial decrypt "works" because null
1704 * decryption was applied. We just skip it and move on to the next
1707 if (!ossl_early_data_count_ok(s, rr->length,
1708 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1709 /* SSLfatal() already called */
1712 s->rrlmethod->release_record(s->rrl, rr->rechandle);
1713 s->rlayer.curr_rec++;
1716 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1722 void ssl3_record_sequence_update(unsigned char *seq)
1726 for (i = 7; i >= 0; i--) {
1734 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1735 * format and false otherwise.
1737 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1739 if (SSL_CONNECTION_IS_DTLS(rl->s))
1741 return rl->tlsrecs[0].version == SSL2_VERSION;
1745 * Returns the length in bytes of the current rrec
1747 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1749 return SSL3_RECORD_get_length(&rl->rrec[0]);
1752 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1756 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1757 if (SSL_CONNECTION_IS_DTLS(s))
1758 return &ossl_dtls_record_method;
1760 return &ossl_tls_record_method;
1763 #ifndef OPENSSL_NO_KTLS
1764 /* KTLS does not support renegotiation */
1765 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1766 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1767 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1768 return &ossl_ktls_record_method;
1771 /* Default to the current OSSL_RECORD_METHOD */
1772 return s->rrlmethod;
1775 static int ssl_post_record_layer_select(SSL_CONNECTION *s)
1777 #ifndef OPENSSL_NO_KTLS
1778 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1780 if (s->rrlmethod == &ossl_ktls_record_method) {
1781 /* KTLS does not support renegotiation so disallow it */
1782 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1785 if (SSL_IS_FIRST_HANDSHAKE(s) && s->rrlmethod->set_first_handshake != NULL)
1786 s->rrlmethod->set_first_handshake(s->rrl, 1);
1790 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1791 int direction, int level,
1792 unsigned char *key, size_t keylen,
1793 unsigned char *iv, size_t ivlen,
1794 unsigned char *mackey, size_t mackeylen,
1795 const EVP_CIPHER *ciph, size_t taglen,
1796 int mactype, const EVP_MD *md,
1797 const SSL_COMP *comp)
1799 OSSL_PARAM options[4], *opts = options;
1800 OSSL_PARAM settings[3], *set = settings;
1801 const OSSL_RECORD_METHOD *origmeth = s->rrlmethod;
1802 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1803 const OSSL_RECORD_METHOD *meth;
1805 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1807 meth = ssl_select_next_record_layer(s, level);
1809 if (s->rrlmethod != NULL && !s->rrlmethod->free(s->rrl)) {
1810 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1815 s->rrlmethod = meth;
1817 if (!ossl_assert(s->rrlmethod != NULL)) {
1818 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1822 /* Parameters that *may* be supported by a record layer if passed */
1823 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1825 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1827 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1828 &s->rlayer.read_ahead);
1829 *opts = OSSL_PARAM_construct_end();
1831 /* Parameters that *must* be supported by a record layer if passed */
1832 if (direction == OSSL_RECORD_DIRECTION_READ)
1833 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1835 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1838 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1841 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1842 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1844 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1845 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1848 *set = OSSL_PARAM_construct_end();
1852 BIO *prev = s->rrlnext;
1854 s->rrlnext = BIO_new(BIO_s_mem());
1856 if (s->rrlnext == NULL) {
1858 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1862 rlret = s->rrlmethod->new_record_layer(sctx->libctx, sctx->propq,
1863 version, s->server, direction,
1864 level, key, keylen, iv, ivlen,
1865 mackey, mackeylen, ciph, taglen,
1866 mactype, md, comp, prev, s->rbio,
1867 s->rrlnext, NULL, NULL, settings,
1868 options, &s->rrl, s);
1871 case OSSL_RECORD_RETURN_FATAL:
1872 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1875 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1876 if (s->rrlmethod != origmeth && origmeth != NULL) {
1878 * We tried a new record layer method, but it didn't work out,
1879 * so we fallback to the original method and try again
1881 s->rrlmethod = origmeth;
1884 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1887 case OSSL_RECORD_RETURN_SUCCESS:
1891 /* Should not happen */
1892 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1898 return ssl_post_record_layer_select(s);