2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include <openssl/core_names.h>
18 #include "record_local.h"
19 #include "internal/packet.h"
21 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
22 !( defined(AES_ASM) && ( \
23 defined(__x86_64) || defined(__x86_64__) || \
24 defined(_M_AMD64) || defined(_M_X64) ) \
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
30 void RECORD_LAYER_init(RECORD_LAYER
*rl
, SSL_CONNECTION
*s
)
35 void RECORD_LAYER_clear(RECORD_LAYER
*rl
)
37 rl
->rstate
= SSL_ST_READ_HEADER
;
40 memset(rl
->handshake_fragment
, 0, sizeof(rl
->handshake_fragment
));
41 rl
->handshake_fragment_len
= 0;
47 ssl3_release_write_buffer(rl
->s
);
49 RECORD_LAYER_reset_read_sequence(rl
);
50 RECORD_LAYER_reset_write_sequence(rl
);
52 if (rl
->rrlmethod
!= NULL
)
53 rl
->rrlmethod
->free(rl
->rrl
); /* Ignore return value */
54 BIO_free(rl
->rrlnext
);
59 DTLS_RECORD_LAYER_clear(rl
);
62 void RECORD_LAYER_release(RECORD_LAYER
*rl
)
64 if (rl
->numwpipes
> 0)
65 ssl3_release_write_buffer(rl
->s
);
68 /* Checks if we have unprocessed read ahead data pending */
69 int RECORD_LAYER_read_pending(const RECORD_LAYER
*rl
)
71 return rl
->rrlmethod
->unprocessed_read_pending(rl
->rrl
);
74 /* Checks if we have decrypted unread record data pending */
75 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER
*rl
)
77 return (rl
->curr_rec
< rl
->num_recs
)
78 || rl
->rrlmethod
->processed_read_pending(rl
->rrl
);
81 int RECORD_LAYER_write_pending(const RECORD_LAYER
*rl
)
83 return (rl
->numwpipes
> 0)
84 && SSL3_BUFFER_get_left(&rl
->wbuf
[rl
->numwpipes
- 1]) != 0;
87 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER
*rl
)
89 memset(rl
->read_sequence
, 0, sizeof(rl
->read_sequence
));
92 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER
*rl
)
94 memset(rl
->write_sequence
, 0, sizeof(rl
->write_sequence
));
97 size_t ssl3_pending(const SSL
*s
)
100 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
105 if (SSL_CONNECTION_IS_DTLS(sc
)) {
109 iter
= pqueue_iterator(sc
->rlayer
.d
->buffered_app_data
.q
);
110 while ((item
= pqueue_next(&iter
)) != NULL
) {
112 num
+= rdata
->length
;
116 for (i
= 0; i
< sc
->rlayer
.num_recs
; i
++) {
117 if (sc
->rlayer
.tlsrecs
[i
].type
!= SSL3_RT_APPLICATION_DATA
)
119 num
+= sc
->rlayer
.tlsrecs
[i
].length
;
122 num
+= sc
->rlayer
.rrlmethod
->app_data_pending(sc
->rlayer
.rrl
);
127 void SSL_CTX_set_default_read_buffer_len(SSL_CTX
*ctx
, size_t len
)
129 ctx
->default_read_buf_len
= len
;
132 void SSL_set_default_read_buffer_len(SSL
*s
, size_t len
)
134 SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_SSL(s
);
138 sc
->rlayer
.default_read_buf_len
= len
;
141 const char *SSL_rstate_string_long(const SSL
*s
)
143 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
148 /* TODO(RECLAYER): Fix me */
149 switch (sc
->rlayer
.rstate
) {
150 case SSL_ST_READ_HEADER
:
151 return "read header";
152 case SSL_ST_READ_BODY
:
154 case SSL_ST_READ_DONE
:
161 const char *SSL_rstate_string(const SSL
*s
)
163 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
168 /* TODO(RECLAYER): Fix me */
169 switch (sc
->rlayer
.rstate
) {
170 case SSL_ST_READ_HEADER
:
172 case SSL_ST_READ_BODY
:
174 case SSL_ST_READ_DONE
:
183 * Call this to write data in records of type 'type' It will return <= 0 if
184 * not all data has been sent or non-blocking IO.
186 int ssl3_write_bytes(SSL
*ssl
, int type
, const void *buf_
, size_t len
,
189 const unsigned char *buf
= buf_
;
191 size_t n
, max_send_fragment
, split_send_fragment
, maxpipes
;
192 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
198 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
203 wb
= &s
->rlayer
.wbuf
[0];
204 s
->rwstate
= SSL_NOTHING
;
205 tot
= s
->rlayer
.wnum
;
207 * ensure that if we end up with a smaller value of data to write out
208 * than the original len from a write which didn't complete for
209 * non-blocking I/O and also somehow ended up avoiding the check for
210 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
211 * possible to end up with (len-tot) as a large number that will then
212 * promptly send beyond the end of the users buffer ... so we trap and
213 * report the error in a way the user will notice
215 if ((len
< s
->rlayer
.wnum
)
216 || ((wb
->left
!= 0) && (len
< (s
->rlayer
.wnum
+ s
->rlayer
.wpend_tot
)))) {
217 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_LENGTH
);
221 if (s
->early_data_state
== SSL_EARLY_DATA_WRITING
222 && !ossl_early_data_count_ok(s
, len
, 0, 1)) {
223 /* SSLfatal() already called */
230 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
231 * into init unless we have writes pending - in which case we should finish
234 if (wb
->left
== 0 && (s
->key_update
!= SSL_KEY_UPDATE_NONE
235 || s
->ext
.extra_tickets_expected
> 0))
236 ossl_statem_set_in_init(s
, 1);
239 * When writing early data on the server side we could be "in_init" in
240 * between receiving the EoED and the CF - but we don't want to handle those
243 if (SSL_in_init(ssl
) && !ossl_statem_get_in_handshake(s
)
244 && s
->early_data_state
!= SSL_EARLY_DATA_UNAUTH_WRITING
) {
245 i
= s
->handshake_func(ssl
);
246 /* SSLfatal() already called */
255 * first check if there is a SSL3_BUFFER still being written out. This
256 * will happen with non blocking IO
259 /* SSLfatal() already called if appropriate */
260 i
= ssl3_write_pending(s
, type
, &buf
[tot
], s
->rlayer
.wpend_tot
,
263 /* XXX should we ssl3_release_write_buffer if i<0? */
264 s
->rlayer
.wnum
= tot
;
267 tot
+= tmpwrit
; /* this might be last fragment */
269 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
271 * Depending on platform multi-block can deliver several *times*
272 * better performance. Downside is that it has to allocate
273 * jumbo buffer to accommodate up to 8 records, but the
274 * compromise is considered worthy.
276 if (type
== SSL3_RT_APPLICATION_DATA
277 && len
>= 4 * (max_send_fragment
= ssl_get_max_send_fragment(s
))
278 && s
->compress
== NULL
279 && s
->msg_callback
== NULL
281 && SSL_USE_EXPLICIT_IV(s
)
282 && !BIO_get_ktls_send(s
->wbio
)
283 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s
->enc_write_ctx
))
284 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
) != 0) {
285 unsigned char aad
[13];
286 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param
;
290 /* minimize address aliasing conflicts */
291 if ((max_send_fragment
& 0xfff) == 0)
292 max_send_fragment
-= 512;
294 if (tot
== 0 || wb
->buf
== NULL
) { /* allocate jumbo buffer */
295 ssl3_release_write_buffer(s
);
297 packlen
= EVP_CIPHER_CTX_ctrl(s
->enc_write_ctx
,
298 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE
,
299 (int)max_send_fragment
, NULL
);
301 if (len
>= 8 * max_send_fragment
)
306 if (!ssl3_setup_write_buffer(s
, 1, packlen
)) {
307 /* SSLfatal() already called */
310 } else if (tot
== len
) { /* done? */
311 /* free jumbo buffer */
312 ssl3_release_write_buffer(s
);
319 if (n
< 4 * max_send_fragment
) {
320 /* free jumbo buffer */
321 ssl3_release_write_buffer(s
);
325 if (s
->s3
.alert_dispatch
) {
326 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
328 /* SSLfatal() already called if appropriate */
329 s
->rlayer
.wnum
= tot
;
334 if (n
>= 8 * max_send_fragment
)
335 nw
= max_send_fragment
* (mb_param
.interleave
= 8);
337 nw
= max_send_fragment
* (mb_param
.interleave
= 4);
339 memcpy(aad
, s
->rlayer
.write_sequence
, 8);
341 aad
[9] = (unsigned char)(s
->version
>> 8);
342 aad
[10] = (unsigned char)(s
->version
);
349 packleni
= EVP_CIPHER_CTX_ctrl(s
->enc_write_ctx
,
350 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD
,
351 sizeof(mb_param
), &mb_param
);
352 packlen
= (size_t)packleni
;
353 if (packleni
<= 0 || packlen
> wb
->len
) { /* never happens */
354 /* free jumbo buffer */
355 ssl3_release_write_buffer(s
);
359 mb_param
.out
= wb
->buf
;
360 mb_param
.inp
= &buf
[tot
];
363 if (EVP_CIPHER_CTX_ctrl(s
->enc_write_ctx
,
364 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT
,
365 sizeof(mb_param
), &mb_param
) <= 0)
368 s
->rlayer
.write_sequence
[7] += mb_param
.interleave
;
369 if (s
->rlayer
.write_sequence
[7] < mb_param
.interleave
) {
371 while (j
>= 0 && (++s
->rlayer
.write_sequence
[j
--]) == 0) ;
377 s
->rlayer
.wpend_tot
= nw
;
378 s
->rlayer
.wpend_buf
= &buf
[tot
];
379 s
->rlayer
.wpend_type
= type
;
380 s
->rlayer
.wpend_ret
= nw
;
382 i
= ssl3_write_pending(s
, type
, &buf
[tot
], nw
, &tmpwrit
);
384 /* SSLfatal() already called if appropriate */
385 if (i
< 0 && (!s
->wbio
|| !BIO_should_retry(s
->wbio
))) {
386 /* free jumbo buffer */
387 ssl3_release_write_buffer(s
);
389 s
->rlayer
.wnum
= tot
;
393 /* free jumbo buffer */
394 ssl3_release_write_buffer(s
);
395 *written
= tot
+ tmpwrit
;
402 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
403 if (tot
== len
) { /* done? */
404 if (s
->mode
& SSL_MODE_RELEASE_BUFFERS
&& !SSL_CONNECTION_IS_DTLS(s
))
405 ssl3_release_write_buffer(s
);
413 max_send_fragment
= ssl_get_max_send_fragment(s
);
414 split_send_fragment
= ssl_get_split_send_fragment(s
);
416 * If max_pipelines is 0 then this means "undefined" and we default to
417 * 1 pipeline. Similarly if the cipher does not support pipelined
418 * processing then we also only use 1 pipeline, or if we're not using
421 maxpipes
= s
->max_pipelines
;
422 if (maxpipes
> SSL_MAX_PIPELINES
) {
424 * We should have prevented this when we set max_pipelines so we
427 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
431 || s
->enc_write_ctx
== NULL
432 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s
->enc_write_ctx
))
433 & EVP_CIPH_FLAG_PIPELINE
) == 0
434 || !SSL_USE_EXPLICIT_IV(s
))
436 if (max_send_fragment
== 0
437 || split_send_fragment
== 0
438 || split_send_fragment
> max_send_fragment
) {
440 * We should have prevented this when we set/get the split and max send
441 * fragments so we shouldn't get here
443 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
448 size_t pipelens
[SSL_MAX_PIPELINES
], tmppipelen
, remain
;
454 numpipes
= ((n
- 1) / split_send_fragment
) + 1;
455 if (numpipes
> maxpipes
)
458 if (n
/ numpipes
>= max_send_fragment
) {
460 * We have enough data to completely fill all available
463 for (j
= 0; j
< numpipes
; j
++) {
464 pipelens
[j
] = max_send_fragment
;
467 /* We can partially fill all available pipelines */
468 tmppipelen
= n
/ numpipes
;
469 remain
= n
% numpipes
;
470 for (j
= 0; j
< numpipes
; j
++) {
471 pipelens
[j
] = tmppipelen
;
477 i
= do_ssl3_write(s
, type
, &(buf
[tot
]), pipelens
, numpipes
, 0,
480 /* SSLfatal() already called if appropriate */
481 /* XXX should we ssl3_release_write_buffer if i<0? */
482 s
->rlayer
.wnum
= tot
;
487 (type
== SSL3_RT_APPLICATION_DATA
&&
488 (s
->mode
& SSL_MODE_ENABLE_PARTIAL_WRITE
))) {
490 * next chunk of data should get another prepended empty fragment
491 * in ciphersuites with known-IV weakness:
493 s
->s3
.empty_fragment_done
= 0;
496 && (s
->mode
& SSL_MODE_RELEASE_BUFFERS
) != 0
497 && !SSL_CONNECTION_IS_DTLS(s
))
498 ssl3_release_write_buffer(s
);
500 *written
= tot
+ tmpwrit
;
509 int do_ssl3_write(SSL_CONNECTION
*s
, int type
, const unsigned char *buf
,
510 size_t *pipelens
, size_t numpipes
,
511 int create_empty_fragment
, size_t *written
)
513 WPACKET pkt
[SSL_MAX_PIPELINES
];
514 SSL3_RECORD wr
[SSL_MAX_PIPELINES
];
517 unsigned char *recordstart
;
518 int i
, mac_size
, clear
= 0;
519 size_t prefix_len
= 0;
524 size_t totlen
= 0, len
, wpinited
= 0;
527 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
529 for (j
= 0; j
< numpipes
; j
++)
530 totlen
+= pipelens
[j
];
532 * first check if there is a SSL3_BUFFER still being written out. This
533 * will happen with non blocking IO
535 if (RECORD_LAYER_write_pending(&s
->rlayer
)) {
536 /* Calls SSLfatal() as required */
537 return ssl3_write_pending(s
, type
, buf
, totlen
, written
);
540 /* If we have an alert to send, lets send it */
541 if (s
->s3
.alert_dispatch
) {
542 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
544 /* SSLfatal() already called if appropriate */
547 /* if it went, fall through and send more stuff */
550 if (s
->rlayer
.numwpipes
< numpipes
) {
551 if (!ssl3_setup_write_buffer(s
, numpipes
, 0)) {
552 /* SSLfatal() already called */
557 if (totlen
== 0 && !create_empty_fragment
)
563 || (s
->enc_write_ctx
== NULL
)
564 || (EVP_MD_CTX_get0_md(s
->write_hash
) == NULL
)) {
565 clear
= s
->enc_write_ctx
? 0 : 1; /* must be AEAD cipher */
568 mac_size
= EVP_MD_CTX_get_size(s
->write_hash
);
570 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
576 * 'create_empty_fragment' is true only when this function calls itself
578 if (!clear
&& !create_empty_fragment
&& !s
->s3
.empty_fragment_done
) {
580 * countermeasure against known-IV weakness in CBC ciphersuites (see
581 * http://www.openssl.org/~bodo/tls-cbc.txt)
584 if (s
->s3
.need_empty_fragments
&& type
== SSL3_RT_APPLICATION_DATA
) {
586 * recursive function call with 'create_empty_fragment' set; this
587 * prepares and buffers the data for an empty fragment (these
588 * 'prefix_len' bytes are sent out later together with the actual
591 size_t tmppipelen
= 0;
594 ret
= do_ssl3_write(s
, type
, buf
, &tmppipelen
, 1, 1, &prefix_len
);
596 /* SSLfatal() already called if appropriate */
601 (SSL3_RT_HEADER_LENGTH
+ SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD
)) {
602 /* insufficient space */
603 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
608 s
->s3
.empty_fragment_done
= 1;
611 using_ktls
= BIO_get_ktls_send(s
->wbio
);
614 * ktls doesn't modify the buffer, but to avoid a warning we need to
615 * discard the const qualifier.
616 * This doesn't leak memory because the buffers have been released when
619 SSL3_BUFFER_set_buf(&s
->rlayer
.wbuf
[0], (unsigned char *)buf
);
620 SSL3_BUFFER_set_offset(&s
->rlayer
.wbuf
[0], 0);
621 SSL3_BUFFER_set_app_buffer(&s
->rlayer
.wbuf
[0], 1);
622 goto wpacket_init_complete
;
625 if (create_empty_fragment
) {
626 wb
= &s
->rlayer
.wbuf
[0];
627 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
629 * extra fragment would be couple of cipher blocks, which would be
630 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
631 * payload, then we can just pretend we simply have two headers.
633 align
= (size_t)SSL3_BUFFER_get_buf(wb
) + 2 * SSL3_RT_HEADER_LENGTH
;
634 align
= SSL3_ALIGN_PAYLOAD
- 1 - ((align
- 1) % SSL3_ALIGN_PAYLOAD
);
636 SSL3_BUFFER_set_offset(wb
, align
);
637 if (!WPACKET_init_static_len(&pkt
[0], SSL3_BUFFER_get_buf(wb
),
638 SSL3_BUFFER_get_len(wb
), 0)
639 || !WPACKET_allocate_bytes(&pkt
[0], align
, NULL
)) {
640 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
644 } else if (prefix_len
) {
645 wb
= &s
->rlayer
.wbuf
[0];
646 if (!WPACKET_init_static_len(&pkt
[0],
647 SSL3_BUFFER_get_buf(wb
),
648 SSL3_BUFFER_get_len(wb
), 0)
649 || !WPACKET_allocate_bytes(&pkt
[0], SSL3_BUFFER_get_offset(wb
)
650 + prefix_len
, NULL
)) {
651 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
656 for (j
= 0; j
< numpipes
; j
++) {
659 wb
= &s
->rlayer
.wbuf
[j
];
660 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
661 align
= (size_t)SSL3_BUFFER_get_buf(wb
) + SSL3_RT_HEADER_LENGTH
;
662 align
= SSL3_ALIGN_PAYLOAD
- 1 - ((align
- 1) % SSL3_ALIGN_PAYLOAD
);
664 SSL3_BUFFER_set_offset(wb
, align
);
665 if (!WPACKET_init_static_len(thispkt
, SSL3_BUFFER_get_buf(wb
),
666 SSL3_BUFFER_get_len(wb
), 0)
667 || !WPACKET_allocate_bytes(thispkt
, align
, NULL
)) {
668 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
675 /* Explicit IV length, block ciphers appropriate version flag */
676 if (s
->enc_write_ctx
&& SSL_USE_EXPLICIT_IV(s
)
677 && !SSL_CONNECTION_TREAT_AS_TLS13(s
)) {
678 int mode
= EVP_CIPHER_CTX_get_mode(s
->enc_write_ctx
);
679 if (mode
== EVP_CIPH_CBC_MODE
) {
680 eivlen
= EVP_CIPHER_CTX_get_iv_length(s
->enc_write_ctx
);
682 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_LIBRARY_BUG
);
687 } else if (mode
== EVP_CIPH_GCM_MODE
) {
688 /* Need explicit part of IV for GCM mode */
689 eivlen
= EVP_GCM_TLS_EXPLICIT_IV_LEN
;
690 } else if (mode
== EVP_CIPH_CCM_MODE
) {
691 eivlen
= EVP_CCM_TLS_EXPLICIT_IV_LEN
;
695 wpacket_init_complete
:
698 /* Clear our SSL3_RECORD structures */
699 memset(wr
, 0, sizeof(wr
));
700 for (j
= 0; j
< numpipes
; j
++) {
701 unsigned int version
= (s
->version
== TLS1_3_VERSION
) ? TLS1_2_VERSION
703 unsigned char *compressdata
= NULL
;
705 unsigned int rectype
;
711 * In TLSv1.3, once encrypting, we always use application data for the
714 if (SSL_CONNECTION_TREAT_AS_TLS13(s
)
715 && s
->enc_write_ctx
!= NULL
716 && (s
->statem
.enc_write_state
!= ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
717 || type
!= SSL3_RT_ALERT
))
718 rectype
= SSL3_RT_APPLICATION_DATA
;
721 SSL3_RECORD_set_type(thiswr
, rectype
);
724 * Some servers hang if initial client hello is larger than 256 bytes
725 * and record version number > TLS 1.0
727 if (SSL_get_state(ssl
) == TLS_ST_CW_CLNT_HELLO
729 && TLS1_get_version(ssl
) > TLS1_VERSION
730 && s
->hello_retry_request
== SSL_HRR_NONE
)
731 version
= TLS1_VERSION
;
732 SSL3_RECORD_set_rec_version(thiswr
, version
);
734 maxcomplen
= pipelens
[j
];
735 if (s
->compress
!= NULL
)
736 maxcomplen
+= SSL3_RT_MAX_COMPRESSED_OVERHEAD
;
739 * When using offload kernel will write the header.
740 * Otherwise write the header now
743 && (!WPACKET_put_bytes_u8(thispkt
, rectype
)
744 || !WPACKET_put_bytes_u16(thispkt
, version
)
745 || !WPACKET_start_sub_packet_u16(thispkt
)
747 && !WPACKET_allocate_bytes(thispkt
, eivlen
, NULL
))
749 && !WPACKET_reserve_bytes(thispkt
, maxcomplen
,
751 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
755 /* lets setup the record stuff. */
756 SSL3_RECORD_set_data(thiswr
, compressdata
);
757 SSL3_RECORD_set_length(thiswr
, pipelens
[j
]);
758 SSL3_RECORD_set_input(thiswr
, (unsigned char *)&buf
[totlen
]);
759 totlen
+= pipelens
[j
];
762 * we now 'read' from thiswr->input, thiswr->length bytes into
766 /* first we compress */
767 if (s
->compress
!= NULL
) {
768 if (!ssl3_do_compress(s
, thiswr
)
769 || !WPACKET_allocate_bytes(thispkt
, thiswr
->length
, NULL
)) {
770 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_COMPRESSION_FAILURE
);
775 SSL3_RECORD_reset_data(&wr
[j
]);
777 if (!WPACKET_memcpy(thispkt
, thiswr
->input
, thiswr
->length
)) {
778 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
781 SSL3_RECORD_reset_input(&wr
[j
]);
785 if (SSL_CONNECTION_TREAT_AS_TLS13(s
)
787 && s
->enc_write_ctx
!= NULL
788 && (s
->statem
.enc_write_state
!= ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
789 || type
!= SSL3_RT_ALERT
)) {
790 size_t rlen
, max_send_fragment
;
792 if (!WPACKET_put_bytes_u8(thispkt
, type
)) {
793 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
796 SSL3_RECORD_add_length(thiswr
, 1);
798 /* Add TLS1.3 padding */
799 max_send_fragment
= ssl_get_max_send_fragment(s
);
800 rlen
= SSL3_RECORD_get_length(thiswr
);
801 if (rlen
< max_send_fragment
) {
803 size_t max_padding
= max_send_fragment
- rlen
;
804 if (s
->record_padding_cb
!= NULL
) {
805 padding
= s
->record_padding_cb(ssl
, type
, rlen
, s
->record_padding_arg
);
806 } else if (s
->block_padding
> 0) {
807 size_t mask
= s
->block_padding
- 1;
810 /* optimize for power of 2 */
811 if ((s
->block_padding
& mask
) == 0)
812 remainder
= rlen
& mask
;
814 remainder
= rlen
% s
->block_padding
;
815 /* don't want to add a block of padding if we don't have to */
819 padding
= s
->block_padding
- remainder
;
822 /* do not allow the record to exceed max plaintext length */
823 if (padding
> max_padding
)
824 padding
= max_padding
;
825 if (!WPACKET_memset(thispkt
, 0, padding
)) {
826 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
,
827 ERR_R_INTERNAL_ERROR
);
830 SSL3_RECORD_add_length(thiswr
, padding
);
836 * we should still have the output to thiswr->data and the input from
837 * wr->input. Length should be thiswr->length. thiswr->data still points
841 if (!using_ktls
&& !SSL_WRITE_ETM(s
) && mac_size
!= 0) {
844 if (!WPACKET_allocate_bytes(thispkt
, mac_size
, &mac
)
845 || !ssl
->method
->ssl3_enc
->mac(s
, thiswr
, mac
, 1)) {
846 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
852 * Reserve some bytes for any growth that may occur during encryption.
853 * This will be at most one cipher block or the tag length if using
854 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
857 if (!WPACKET_reserve_bytes(thispkt
,
858 SSL_RT_MAX_CIPHER_BLOCK_SIZE
,
861 * We also need next the amount of bytes written to this
864 || !WPACKET_get_length(thispkt
, &len
)) {
865 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
869 /* Get a pointer to the start of this record excluding header */
870 recordstart
= WPACKET_get_curr(thispkt
) - len
;
871 SSL3_RECORD_set_data(thiswr
, recordstart
);
872 SSL3_RECORD_reset_input(thiswr
);
873 SSL3_RECORD_set_length(thiswr
, len
);
877 if (s
->statem
.enc_write_state
== ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
) {
879 * We haven't actually negotiated the version yet, but we're trying to
880 * send early data - so we need to use the tls13enc function.
882 if (tls13_enc(s
, wr
, numpipes
, 1, NULL
, mac_size
) < 1) {
883 if (!ossl_statem_in_error(s
)) {
884 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
890 if (ssl
->method
->ssl3_enc
->enc(s
, wr
, numpipes
, 1, NULL
,
892 if (!ossl_statem_in_error(s
)) {
893 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
900 for (j
= 0; j
< numpipes
; j
++) {
909 /* Allocate bytes for the encryption overhead */
910 if (!WPACKET_get_length(thispkt
, &origlen
)
911 /* Encryption should never shrink the data! */
912 || origlen
> thiswr
->length
913 || (thiswr
->length
> origlen
914 && !WPACKET_allocate_bytes(thispkt
,
915 thiswr
->length
- origlen
,
917 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
920 if (SSL_WRITE_ETM(s
) && mac_size
!= 0) {
923 if (!WPACKET_allocate_bytes(thispkt
, mac_size
, &mac
)
924 || !ssl
->method
->ssl3_enc
->mac(s
, thiswr
, mac
, 1)) {
925 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
928 SSL3_RECORD_add_length(thiswr
, mac_size
);
931 if (!WPACKET_get_length(thispkt
, &len
)
932 || !WPACKET_close(thispkt
)) {
933 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
937 if (s
->msg_callback
) {
938 recordstart
= WPACKET_get_curr(thispkt
) - len
939 - SSL3_RT_HEADER_LENGTH
;
940 s
->msg_callback(1, thiswr
->rec_version
, SSL3_RT_HEADER
, recordstart
,
941 SSL3_RT_HEADER_LENGTH
, ssl
,
942 s
->msg_callback_arg
);
944 if (SSL_CONNECTION_TREAT_AS_TLS13(s
) && s
->enc_write_ctx
!= NULL
) {
945 unsigned char ctype
= type
;
947 s
->msg_callback(1, thiswr
->rec_version
, SSL3_RT_INNER_CONTENT_TYPE
,
948 &ctype
, 1, ssl
, s
->msg_callback_arg
);
952 if (!WPACKET_finish(thispkt
)) {
953 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
957 /* header is added by the kernel when using offload */
958 SSL3_RECORD_add_length(thiswr
, SSL3_RT_HEADER_LENGTH
);
960 if (create_empty_fragment
) {
962 * we are in a recursive call; just return the length, don't write
966 /* We should never be pipelining an empty fragment!! */
967 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
970 *written
= SSL3_RECORD_get_length(thiswr
);
976 * we should now have thiswr->data pointing to the encrypted data, which
977 * is thiswr->length long
979 SSL3_RECORD_set_type(thiswr
, type
); /* not needed but helps for
982 /* now let's set up wb */
983 SSL3_BUFFER_set_left(&s
->rlayer
.wbuf
[j
],
984 prefix_len
+ SSL3_RECORD_get_length(thiswr
));
988 * memorize arguments so that ssl3_write_pending can detect bad write
991 s
->rlayer
.wpend_tot
= totlen
;
992 s
->rlayer
.wpend_buf
= buf
;
993 s
->rlayer
.wpend_type
= type
;
994 s
->rlayer
.wpend_ret
= totlen
;
996 /* we now just need to write the buffer */
997 return ssl3_write_pending(s
, type
, buf
, totlen
, written
);
999 for (j
= 0; j
< wpinited
; j
++)
1000 WPACKET_cleanup(&pkt
[j
]);
1004 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1006 * Return values are as per SSL_write()
1008 int ssl3_write_pending(SSL_CONNECTION
*s
, int type
, const unsigned char *buf
,
1009 size_t len
, size_t *written
)
1012 SSL3_BUFFER
*wb
= s
->rlayer
.wbuf
;
1016 if ((s
->rlayer
.wpend_tot
> len
)
1017 || (!(s
->mode
& SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
)
1018 && (s
->rlayer
.wpend_buf
!= buf
))
1019 || (s
->rlayer
.wpend_type
!= type
)) {
1020 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_WRITE_RETRY
);
1025 /* Loop until we find a buffer we haven't written out yet */
1026 if (SSL3_BUFFER_get_left(&wb
[currbuf
]) == 0
1027 && currbuf
< s
->rlayer
.numwpipes
- 1) {
1032 if (s
->wbio
!= NULL
) {
1033 s
->rwstate
= SSL_WRITING
;
1036 * To prevent coalescing of control and data messages,
1037 * such as in buffer_write, we flush the BIO
1039 if (BIO_get_ktls_send(s
->wbio
) && type
!= SSL3_RT_APPLICATION_DATA
) {
1040 i
= BIO_flush(s
->wbio
);
1043 BIO_set_ktls_ctrl_msg(s
->wbio
, type
);
1045 i
= BIO_write(s
->wbio
, (char *)
1046 &(SSL3_BUFFER_get_buf(&wb
[currbuf
])
1047 [SSL3_BUFFER_get_offset(&wb
[currbuf
])]),
1048 (unsigned int)SSL3_BUFFER_get_left(&wb
[currbuf
]));
1052 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BIO_NOT_SET
);
1057 * When an empty fragment is sent on a connection using KTLS,
1058 * it is sent as a write of zero bytes. If this zero byte
1059 * write succeeds, i will be 0 rather than a non-zero value.
1060 * Treat i == 0 as success rather than an error for zero byte
1061 * writes to permit this case.
1063 if (i
>= 0 && tmpwrit
== SSL3_BUFFER_get_left(&wb
[currbuf
])) {
1064 SSL3_BUFFER_set_left(&wb
[currbuf
], 0);
1065 SSL3_BUFFER_add_offset(&wb
[currbuf
], tmpwrit
);
1066 if (currbuf
+ 1 < s
->rlayer
.numwpipes
)
1068 s
->rwstate
= SSL_NOTHING
;
1069 *written
= s
->rlayer
.wpend_ret
;
1071 } else if (i
<= 0) {
1072 if (SSL_CONNECTION_IS_DTLS(s
)) {
1074 * For DTLS, just drop it. That's kind of the whole point in
1075 * using a datagram service
1077 SSL3_BUFFER_set_left(&wb
[currbuf
], 0);
1081 SSL3_BUFFER_add_offset(&wb
[currbuf
], tmpwrit
);
1082 SSL3_BUFFER_sub_left(&wb
[currbuf
], tmpwrit
);
1086 int ossl_tls_handle_rlayer_return(SSL_CONNECTION
*s
, int ret
, char *file
,
1089 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1091 if (ret
== OSSL_RECORD_RETURN_RETRY
) {
1092 s
->rwstate
= SSL_READING
;
1095 s
->rwstate
= SSL_NOTHING
;
1096 if (ret
== OSSL_RECORD_RETURN_EOF
) {
1097 if (s
->options
& SSL_OP_IGNORE_UNEXPECTED_EOF
) {
1098 SSL_set_shutdown(ssl
, SSL_RECEIVED_SHUTDOWN
);
1099 s
->s3
.warn_alert
= SSL_AD_CLOSE_NOTIFY
;
1102 ERR_set_debug(file
, line
, 0);
1103 ossl_statem_fatal(s
, SSL_AD_DECODE_ERROR
,
1104 SSL_R_UNEXPECTED_EOF_WHILE_READING
, NULL
);
1106 } else if (ret
== OSSL_RECORD_RETURN_FATAL
) {
1108 ERR_set_debug(file
, line
, 0);
1109 ossl_statem_fatal(s
, s
->rlayer
.rrlmethod
->get_alert_code(s
->rlayer
.rrl
),
1110 SSL_R_RECORD_LAYER_FAILURE
, NULL
);
1113 * The record layer distinguishes the cases of EOF, non-fatal
1114 * err and retry. Upper layers do not.
1115 * If we got a retry or success then *ret is already correct,
1116 * otherwise we need to convert the return value.
1118 if (ret
== OSSL_RECORD_RETURN_NON_FATAL_ERR
|| ret
== OSSL_RECORD_RETURN_EOF
)
1120 else if (ret
< OSSL_RECORD_RETURN_NON_FATAL_ERR
)
1127 void ssl_release_record(SSL_CONNECTION
*s
, TLS_RECORD
*rr
)
1129 if (rr
->rechandle
!= NULL
) {
1130 /* The record layer allocated the buffers for this record */
1131 s
->rlayer
.rrlmethod
->release_record(s
->rlayer
.rrl
, rr
->rechandle
);
1133 /* We allocated the buffers for this record (only happens with DTLS) */
1134 OPENSSL_free(rr
->data
);
1136 s
->rlayer
.curr_rec
++;
1140 * Return up to 'len' payload bytes received in 'type' records.
1141 * 'type' is one of the following:
1143 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1144 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1145 * - 0 (during a shutdown, no data has to be returned)
1147 * If we don't have stored data to work from, read a SSL/TLS record first
1148 * (possibly multiple records if we still don't have anything to return).
1150 * This function must handle any surprises the peer may have for us, such as
1151 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1152 * messages are treated as if they were handshake messages *if* the |recvd_type|
1153 * argument is non NULL.
1154 * Also if record payloads contain fragments too small to process, we store
1155 * them until there is enough for the respective protocol (the record protocol
1156 * may use arbitrary fragmentation and even interleaving):
1157 * Change cipher spec protocol
1158 * just 1 byte needed, no need for keeping anything stored
1160 * 2 bytes needed (AlertLevel, AlertDescription)
1161 * Handshake protocol
1162 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1163 * to detect unexpected Client Hello and Hello Request messages
1164 * here, anything else is handled by higher layers
1165 * Application data protocol
1166 * none of our business
1168 int ssl3_read_bytes(SSL
*ssl
, int type
, int *recvd_type
, unsigned char *buf
,
1169 size_t len
, int peek
, size_t *readbytes
)
1172 size_t n
, curr_rec
, totalbytes
;
1174 void (*cb
) (const SSL
*ssl
, int type2
, int val
) = NULL
;
1176 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
1178 is_tls13
= SSL_CONNECTION_IS_TLS13(s
);
1181 && (type
!= SSL3_RT_APPLICATION_DATA
)
1182 && (type
!= SSL3_RT_HANDSHAKE
))
1183 || (peek
&& (type
!= SSL3_RT_APPLICATION_DATA
))) {
1184 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1188 if ((type
== SSL3_RT_HANDSHAKE
) && (s
->rlayer
.handshake_fragment_len
> 0))
1189 /* (partially) satisfy request from storage */
1191 unsigned char *src
= s
->rlayer
.handshake_fragment
;
1192 unsigned char *dst
= buf
;
1197 while ((len
> 0) && (s
->rlayer
.handshake_fragment_len
> 0)) {
1200 s
->rlayer
.handshake_fragment_len
--;
1203 /* move any remaining fragment bytes: */
1204 for (k
= 0; k
< s
->rlayer
.handshake_fragment_len
; k
++)
1205 s
->rlayer
.handshake_fragment
[k
] = *src
++;
1207 if (recvd_type
!= NULL
)
1208 *recvd_type
= SSL3_RT_HANDSHAKE
;
1215 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1218 if (!ossl_statem_get_in_handshake(s
) && SSL_in_init(ssl
)) {
1219 /* type == SSL3_RT_APPLICATION_DATA */
1220 i
= s
->handshake_func(ssl
);
1221 /* SSLfatal() already called */
1228 s
->rwstate
= SSL_NOTHING
;
1231 * For each record 'i' up to |num_recs]
1232 * rr[i].type - is the type of record
1233 * rr[i].data, - data
1234 * rr[i].off, - offset into 'data' for next read
1235 * rr[i].length, - number of bytes.
1237 /* get new records if necessary */
1238 if (s
->rlayer
.curr_rec
>= s
->rlayer
.num_recs
) {
1239 s
->rlayer
.curr_rec
= s
->rlayer
.num_recs
= 0;
1241 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.num_recs
];
1243 ret
= HANDLE_RLAYER_RETURN(s
,
1244 s
->rlayer
.rrlmethod
->read_record(s
->rlayer
.rrl
,
1246 &rr
->version
, &rr
->type
,
1247 &rr
->data
, &rr
->length
,
1250 /* SSLfatal() already called if appropriate */
1254 s
->rlayer
.num_recs
++;
1255 } while (s
->rlayer
.rrlmethod
->processed_read_pending(s
->rlayer
.rrl
)
1256 && s
->rlayer
.num_recs
< SSL_MAX_PIPELINES
);
1258 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.curr_rec
];
1260 if (s
->rlayer
.handshake_fragment_len
> 0
1261 && rr
->type
!= SSL3_RT_HANDSHAKE
1262 && SSL_CONNECTION_IS_TLS13(s
)) {
1263 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
1264 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA
);
1269 * Reset the count of consecutive warning alerts if we've got a non-empty
1270 * record that isn't an alert.
1272 if (rr
->type
!= SSL3_RT_ALERT
&& rr
->length
!= 0)
1273 s
->rlayer
.alert_count
= 0;
1275 /* we now have a packet which can be read and processed */
1277 if (s
->s3
.change_cipher_spec
/* set when we receive ChangeCipherSpec,
1278 * reset by ssl3_get_finished */
1279 && (rr
->type
!= SSL3_RT_HANDSHAKE
)) {
1280 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
1281 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED
);
1286 * If the other end has shut down, throw anything we read away (even in
1289 if (s
->shutdown
& SSL_RECEIVED_SHUTDOWN
) {
1290 s
->rlayer
.curr_rec
++;
1291 s
->rwstate
= SSL_NOTHING
;
1295 if (type
== rr
->type
1296 || (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
1297 && type
== SSL3_RT_HANDSHAKE
&& recvd_type
!= NULL
1300 * SSL3_RT_APPLICATION_DATA or
1301 * SSL3_RT_HANDSHAKE or
1302 * SSL3_RT_CHANGE_CIPHER_SPEC
1305 * make sure that we are not getting application data when we are
1306 * doing a handshake for the first time
1308 if (SSL_in_init(ssl
) && type
== SSL3_RT_APPLICATION_DATA
1309 && s
->enc_read_ctx
== NULL
) {
1310 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_APP_DATA_IN_HANDSHAKE
);
1314 if (type
== SSL3_RT_HANDSHAKE
1315 && rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
1316 && s
->rlayer
.handshake_fragment_len
> 0) {
1317 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
1321 if (recvd_type
!= NULL
)
1322 *recvd_type
= rr
->type
;
1326 * Skip a zero length record. This ensures multiple calls to
1327 * SSL_read() with a zero length buffer will eventually cause
1328 * SSL_pending() to report data as being available.
1330 if (rr
->length
== 0)
1331 ssl_release_record(s
, rr
);
1337 curr_rec
= s
->rlayer
.curr_rec
;
1339 if (len
- totalbytes
> rr
->length
)
1342 n
= len
- totalbytes
;
1344 memcpy(buf
, &(rr
->data
[rr
->off
]), n
);
1347 /* Mark any zero length record as consumed CVE-2016-6305 */
1348 if (rr
->length
== 0)
1349 ssl_release_record(s
, rr
);
1351 if (s
->options
& SSL_OP_CLEANSE_PLAINTEXT
)
1352 OPENSSL_cleanse(&(rr
->data
[rr
->off
]), n
);
1355 if (rr
->length
== 0)
1356 ssl_release_record(s
, rr
);
1359 || (peek
&& n
== rr
->length
)) {
1364 } while (type
== SSL3_RT_APPLICATION_DATA
1365 && curr_rec
< s
->rlayer
.num_recs
1366 && totalbytes
< len
);
1367 if (totalbytes
== 0) {
1368 /* We must have read empty records. Get more data */
1371 *readbytes
= totalbytes
;
1376 * If we get here, then type != rr->type; if we have a handshake message,
1377 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1378 * were actually expecting a CCS).
1382 * Lets just double check that we've not got an SSLv2 record
1384 if (rr
->version
== SSL2_VERSION
) {
1386 * Should never happen. ssl3_get_record() should only give us an SSLv2
1387 * record back if this is the first packet and we are looking for an
1388 * initial ClientHello. Therefore |type| should always be equal to
1389 * |rr->type|. If not then something has gone horribly wrong
1391 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1395 if (ssl
->method
->version
== TLS_ANY_VERSION
1396 && (s
->server
|| rr
->type
!= SSL3_RT_ALERT
)) {
1398 * If we've got this far and still haven't decided on what version
1399 * we're using then this must be a client side alert we're dealing
1400 * with. We shouldn't be receiving anything other than a ClientHello
1401 * if we are a server.
1403 s
->version
= rr
->version
;
1404 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_MESSAGE
);
1409 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1410 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1413 if (rr
->type
== SSL3_RT_ALERT
) {
1414 unsigned int alert_level
, alert_descr
;
1415 unsigned char *alert_bytes
= rr
->data
1419 if (!PACKET_buf_init(&alert
, alert_bytes
, rr
->length
)
1420 || !PACKET_get_1(&alert
, &alert_level
)
1421 || !PACKET_get_1(&alert
, &alert_descr
)
1422 || PACKET_remaining(&alert
) != 0) {
1423 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_INVALID_ALERT
);
1427 if (s
->msg_callback
)
1428 s
->msg_callback(0, s
->version
, SSL3_RT_ALERT
, alert_bytes
, 2, ssl
,
1429 s
->msg_callback_arg
);
1431 if (s
->info_callback
!= NULL
)
1432 cb
= s
->info_callback
;
1433 else if (ssl
->ctx
->info_callback
!= NULL
)
1434 cb
= ssl
->ctx
->info_callback
;
1437 j
= (alert_level
<< 8) | alert_descr
;
1438 cb(ssl
, SSL_CB_READ_ALERT
, j
);
1441 if ((!is_tls13
&& alert_level
== SSL3_AL_WARNING
)
1442 || (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
)) {
1443 s
->s3
.warn_alert
= alert_descr
;
1444 ssl_release_record(s
, rr
);
1446 s
->rlayer
.alert_count
++;
1447 if (s
->rlayer
.alert_count
== MAX_WARN_ALERT_COUNT
) {
1448 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
1449 SSL_R_TOO_MANY_WARN_ALERTS
);
1455 * Apart from close_notify the only other warning alert in TLSv1.3
1456 * is user_cancelled - which we just ignore.
1458 if (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
) {
1460 } else if (alert_descr
== SSL_AD_CLOSE_NOTIFY
1461 && (is_tls13
|| alert_level
== SSL3_AL_WARNING
)) {
1462 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
1464 } else if (alert_level
== SSL3_AL_FATAL
|| is_tls13
) {
1465 s
->rwstate
= SSL_NOTHING
;
1466 s
->s3
.fatal_alert
= alert_descr
;
1467 SSLfatal_data(s
, SSL_AD_NO_ALERT
,
1468 SSL_AD_REASON_OFFSET
+ alert_descr
,
1469 "SSL alert number %d", alert_descr
);
1470 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
1471 ssl_release_record(s
, rr
);
1472 SSL_CTX_remove_session(s
->session_ctx
, s
->session
);
1474 } else if (alert_descr
== SSL_AD_NO_RENEGOTIATION
) {
1476 * This is a warning but we receive it if we requested
1477 * renegotiation and the peer denied it. Terminate with a fatal
1478 * alert because if application tried to renegotiate it
1479 * presumably had a good reason and expects it to succeed. In
1480 * future we might have a renegotiation where we don't care if
1481 * the peer refused it where we carry on.
1483 SSLfatal(s
, SSL_AD_HANDSHAKE_FAILURE
, SSL_R_NO_RENEGOTIATION
);
1485 } else if (alert_level
== SSL3_AL_WARNING
) {
1486 /* We ignore any other warning alert in TLSv1.2 and below */
1490 SSLfatal(s
, SSL_AD_ILLEGAL_PARAMETER
, SSL_R_UNKNOWN_ALERT_TYPE
);
1494 if ((s
->shutdown
& SSL_SENT_SHUTDOWN
) != 0) {
1495 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
1499 * We ignore any handshake messages sent to us unless they are
1500 * TLSv1.3 in which case we want to process them. For all other
1501 * handshake messages we can't do anything reasonable with them
1502 * because we are unable to write any response due to having already
1503 * sent close_notify.
1505 if (!SSL_CONNECTION_IS_TLS13(s
)) {
1506 ssl_release_record(s
, rr
);
1508 if ((s
->mode
& SSL_MODE_AUTO_RETRY
) != 0)
1511 s
->rwstate
= SSL_READING
;
1512 rbio
= SSL_get_rbio(ssl
);
1513 BIO_clear_retry_flags(rbio
);
1514 BIO_set_retry_read(rbio
);
1519 * The peer is continuing to send application data, but we have
1520 * already sent close_notify. If this was expected we should have
1521 * been called via SSL_read() and this would have been handled
1523 * No alert sent because we already sent close_notify
1525 ssl_release_record(s
, rr
);
1526 SSLfatal(s
, SSL_AD_NO_ALERT
,
1527 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY
);
1533 * For handshake data we have 'fragment' storage, so fill that so that we
1534 * can process the header at a fixed place. This is done after the
1535 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1536 * that we're just going to discard.
1538 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
1539 size_t dest_maxlen
= sizeof(s
->rlayer
.handshake_fragment
);
1540 unsigned char *dest
= s
->rlayer
.handshake_fragment
;
1541 size_t *dest_len
= &s
->rlayer
.handshake_fragment_len
;
1543 n
= dest_maxlen
- *dest_len
; /* available space in 'dest' */
1545 n
= rr
->length
; /* available bytes */
1547 /* now move 'n' bytes: */
1548 memcpy(dest
+ *dest_len
, rr
->data
+ rr
->off
, n
);
1552 if (rr
->length
== 0)
1553 ssl_release_record(s
, rr
);
1555 if (*dest_len
< dest_maxlen
)
1556 goto start
; /* fragment was too small */
1559 if (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
) {
1560 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
1565 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1566 * protocol violation)
1568 if ((s
->rlayer
.handshake_fragment_len
>= 4)
1569 && !ossl_statem_get_in_handshake(s
)) {
1570 int ined
= (s
->early_data_state
== SSL_EARLY_DATA_READING
);
1572 /* We found handshake data, so we're going back into init */
1573 ossl_statem_set_in_init(s
, 1);
1575 i
= s
->handshake_func(ssl
);
1576 /* SSLfatal() already called if appropriate */
1584 * If we were actually trying to read early data and we found a
1585 * handshake message, then we don't want to continue to try and read
1586 * the application data any more. It won't be "early" now.
1591 if (!(s
->mode
& SSL_MODE_AUTO_RETRY
)) {
1592 if (!RECORD_LAYER_read_pending(&s
->rlayer
)) {
1595 * In the case where we try to read application data, but we
1596 * trigger an SSL handshake, we return -1 with the retry
1597 * option set. Otherwise renegotiation may cause nasty
1598 * problems in the blocking world
1600 s
->rwstate
= SSL_READING
;
1601 bio
= SSL_get_rbio(ssl
);
1602 BIO_clear_retry_flags(bio
);
1603 BIO_set_retry_read(bio
);
1613 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1614 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1615 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1616 * no progress is being made and the peer continually sends unrecognised
1617 * record types, using up resources processing them.
1619 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
1621 case SSL3_RT_CHANGE_CIPHER_SPEC
:
1623 case SSL3_RT_HANDSHAKE
:
1625 * we already handled all of these, with the possible exception of
1626 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1627 * that should not happen when type != rr->type
1629 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, ERR_R_INTERNAL_ERROR
);
1631 case SSL3_RT_APPLICATION_DATA
:
1633 * At this point, we were expecting handshake data, but have
1634 * application data. If the library was running inside ssl3_read()
1635 * (i.e. in_read_app_data is set) and it makes sense to read
1636 * application data at this point (session renegotiation not yet
1637 * started), we will indulge it.
1639 if (ossl_statem_app_data_allowed(s
)) {
1640 s
->s3
.in_read_app_data
= 2;
1642 } else if (ossl_statem_skip_early_data(s
)) {
1644 * This can happen after a client sends a CH followed by early_data,
1645 * but the server responds with a HelloRetryRequest. The server
1646 * reads the next record from the client expecting to find a
1647 * plaintext ClientHello but gets a record which appears to be
1648 * application data. The trial decrypt "works" because null
1649 * decryption was applied. We just skip it and move on to the next
1652 if (!ossl_early_data_count_ok(s
, rr
->length
,
1653 EARLY_DATA_CIPHERTEXT_OVERHEAD
, 0)) {
1654 /* SSLfatal() already called */
1657 ssl_release_record(s
, rr
);
1660 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
1666 void ssl3_record_sequence_update(unsigned char *seq
)
1670 for (i
= 7; i
>= 0; i
--) {
1678 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1679 * format and false otherwise.
1681 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER
*rl
)
1683 if (SSL_CONNECTION_IS_DTLS(rl
->s
))
1685 return rl
->tlsrecs
[0].version
== SSL2_VERSION
;
1688 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper
;
1689 static void rlayer_msg_callback_wrapper(int write_p
, int version
,
1690 int content_type
, const void *buf
,
1691 size_t len
, void *cbarg
)
1693 SSL_CONNECTION
*s
= cbarg
;
1694 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1696 if (s
->msg_callback
!= NULL
)
1697 s
->msg_callback(write_p
, version
, content_type
, buf
, len
, ssl
,
1698 s
->msg_callback_arg
);
1701 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper
;
1702 static int rlayer_security_wrapper(void *cbarg
, int op
, int bits
, int nid
,
1705 SSL_CONNECTION
*s
= cbarg
;
1707 return ssl_security(s
, op
, bits
, nid
, other
);
1710 static const OSSL_DISPATCH rlayer_dispatch
[] = {
1711 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA
, (void (*)(void))ossl_statem_skip_early_data
},
1712 { OSSL_FUNC_RLAYER_MSG_CALLBACK
, (void (*)(void))rlayer_msg_callback_wrapper
},
1713 { OSSL_FUNC_RLAYER_SECURITY
, (void (*)(void))rlayer_security_wrapper
},
1717 static const OSSL_RECORD_METHOD
*ssl_select_next_record_layer(SSL_CONNECTION
*s
,
1721 if (level
== OSSL_RECORD_PROTECTION_LEVEL_NONE
) {
1722 if (SSL_CONNECTION_IS_DTLS(s
))
1723 return &ossl_dtls_record_method
;
1725 return &ossl_tls_record_method
;
1728 #ifndef OPENSSL_NO_KTLS
1729 /* KTLS does not support renegotiation */
1730 if (level
== OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1731 && (s
->options
& SSL_OP_ENABLE_KTLS
) != 0
1732 && (SSL_CONNECTION_IS_TLS13(s
) || SSL_IS_FIRST_HANDSHAKE(s
)))
1733 return &ossl_ktls_record_method
;
1736 /* Default to the current OSSL_RECORD_METHOD */
1737 return s
->rlayer
.rrlmethod
;
1740 static int ssl_post_record_layer_select(SSL_CONNECTION
*s
)
1742 #ifndef OPENSSL_NO_KTLS
1743 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1745 if (s
->rlayer
.rrlmethod
== &ossl_ktls_record_method
) {
1746 /* KTLS does not support renegotiation so disallow it */
1747 SSL_set_options(ssl
, SSL_OP_NO_RENEGOTIATION
);
1750 if (SSL_IS_FIRST_HANDSHAKE(s
) && s
->rlayer
.rrlmethod
->set_first_handshake
!= NULL
)
1751 s
->rlayer
.rrlmethod
->set_first_handshake(s
->rlayer
.rrl
, 1);
1753 if (s
->max_pipelines
!= 0 && s
->rlayer
.rrlmethod
->set_max_pipelines
!= NULL
)
1754 s
->rlayer
.rrlmethod
->set_max_pipelines(s
->rlayer
.rrl
, s
->max_pipelines
);
1759 int ssl_set_new_record_layer(SSL_CONNECTION
*s
, int version
,
1760 int direction
, int level
,
1761 unsigned char *key
, size_t keylen
,
1762 unsigned char *iv
, size_t ivlen
,
1763 unsigned char *mackey
, size_t mackeylen
,
1764 const EVP_CIPHER
*ciph
, size_t taglen
,
1765 int mactype
, const EVP_MD
*md
,
1766 const SSL_COMP
*comp
)
1768 OSSL_PARAM options
[5], *opts
= options
;
1769 OSSL_PARAM settings
[6], *set
= settings
;
1770 const OSSL_RECORD_METHOD
*origmeth
= s
->rlayer
.rrlmethod
;
1771 SSL_CTX
*sctx
= SSL_CONNECTION_GET_CTX(s
);
1772 const OSSL_RECORD_METHOD
*meth
;
1773 int use_etm
, stream_mac
= 0, tlstree
= 0;
1774 unsigned int maxfrag
= SSL3_RT_MAX_PLAIN_LENGTH
;
1775 int use_early_data
= 0;
1776 uint32_t max_early_data
;
1778 meth
= ssl_select_next_record_layer(s
, level
);
1780 if (s
->rlayer
.rrlmethod
!= NULL
&& !s
->rlayer
.rrlmethod
->free(s
->rlayer
.rrl
)) {
1781 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1786 s
->rlayer
.rrlmethod
= meth
;
1788 if (!ossl_assert(s
->rlayer
.rrlmethod
!= NULL
)) {
1789 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1793 /* Parameters that *may* be supported by a record layer if passed */
1794 *opts
++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS
,
1796 *opts
++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE
,
1798 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN
,
1799 &s
->rlayer
.default_read_buf_len
);
1800 *opts
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD
,
1801 &s
->rlayer
.read_ahead
);
1802 *opts
= OSSL_PARAM_construct_end();
1804 /* Parameters that *must* be supported by a record layer if passed */
1805 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1806 use_etm
= SSL_READ_ETM(s
) ? 1 : 0;
1807 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_STREAM
) != 0)
1810 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_TLSTREE
) != 0)
1813 use_etm
= SSL_WRITE_ETM(s
) ? 1 : 0;
1814 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_STREAM
) != 0)
1817 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_TLSTREE
) != 0)
1822 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM
,
1826 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC
,
1830 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE
,
1833 if (s
->session
!= NULL
&& USE_MAX_FRAGMENT_LENGTH_EXT(s
->session
))
1834 maxfrag
= GET_MAX_FRAGMENT_LENGTH(s
->session
);
1836 if (maxfrag
!= SSL3_RT_MAX_PLAIN_LENGTH
)
1837 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN
,
1841 * The record layer must check the amount of early data sent or received
1842 * using the early keys. A server also needs to worry about rejected early
1843 * data that might arrive when the handshake keys are in force.
1845 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1846 if (s
->server
&& direction
== OSSL_RECORD_DIRECTION_READ
) {
1847 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
1848 || level
== OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
);
1849 } else if (!s
->server
&& direction
== OSSL_RECORD_DIRECTION_WRITE
) {
1850 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
);
1852 if (use_early_data
) {
1853 max_early_data
= ossl_get_max_early_data(s
);
1855 if (max_early_data
!= 0)
1856 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA
,
1860 *set
= OSSL_PARAM_construct_end();
1864 BIO
*prev
= s
->rlayer
.rrlnext
;
1865 unsigned int epoch
= 0;;
1867 if (SSL_CONNECTION_IS_DTLS(s
)
1868 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1869 epoch
= DTLS_RECORD_LAYER_get_r_epoch(&s
->rlayer
) + 1; /* new epoch */
1871 if (SSL_CONNECTION_IS_DTLS(s
))
1872 s
->rlayer
.rrlnext
= BIO_new(BIO_s_dgram_mem());
1874 s
->rlayer
.rrlnext
= BIO_new(BIO_s_mem());
1876 if (s
->rlayer
.rrlnext
== NULL
) {
1878 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1882 rlret
= s
->rlayer
.rrlmethod
->new_record_layer(sctx
->libctx
,
1885 direction
, level
, epoch
,
1886 key
, keylen
, iv
, ivlen
,
1887 mackey
, mackeylen
, ciph
,
1888 taglen
, mactype
, md
, comp
,
1890 s
->rlayer
.rrlnext
, NULL
,
1891 NULL
, settings
, options
,
1896 case OSSL_RECORD_RETURN_FATAL
:
1897 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_RECORD_LAYER_FAILURE
);
1900 case OSSL_RECORD_RETURN_NON_FATAL_ERR
:
1901 if (s
->rlayer
.rrlmethod
!= origmeth
&& origmeth
!= NULL
) {
1903 * We tried a new record layer method, but it didn't work out,
1904 * so we fallback to the original method and try again
1906 s
->rlayer
.rrlmethod
= origmeth
;
1909 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_NO_SUITABLE_RECORD_LAYER
);
1912 case OSSL_RECORD_RETURN_SUCCESS
:
1916 /* Should not happen */
1917 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1923 return ssl_post_record_layer_select(s
);