2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include <openssl/core_names.h>
18 #include "record_local.h"
19 #include "internal/packet.h"
21 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
22 !( defined(AES_ASM) && ( \
23 defined(__x86_64) || defined(__x86_64__) || \
24 defined(_M_AMD64) || defined(_M_X64) ) \
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
30 void RECORD_LAYER_init(RECORD_LAYER
*rl
, SSL_CONNECTION
*s
)
35 void RECORD_LAYER_clear(RECORD_LAYER
*rl
)
38 memset(rl
->handshake_fragment
, 0, sizeof(rl
->handshake_fragment
));
39 rl
->handshake_fragment_len
= 0;
45 ssl3_release_write_buffer(rl
->s
);
47 RECORD_LAYER_reset_write_sequence(rl
);
49 if (rl
->rrlmethod
!= NULL
)
50 rl
->rrlmethod
->free(rl
->rrl
); /* Ignore return value */
51 BIO_free(rl
->rrlnext
);
56 DTLS_RECORD_LAYER_clear(rl
);
59 void RECORD_LAYER_release(RECORD_LAYER
*rl
)
61 if (rl
->numwpipes
> 0)
62 ssl3_release_write_buffer(rl
->s
);
65 /* Checks if we have unprocessed read ahead data pending */
66 int RECORD_LAYER_read_pending(const RECORD_LAYER
*rl
)
68 return rl
->rrlmethod
->unprocessed_read_pending(rl
->rrl
);
71 /* Checks if we have decrypted unread record data pending */
72 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER
*rl
)
74 return (rl
->curr_rec
< rl
->num_recs
)
75 || rl
->rrlmethod
->processed_read_pending(rl
->rrl
);
78 int RECORD_LAYER_write_pending(const RECORD_LAYER
*rl
)
80 return (rl
->numwpipes
> 0)
81 && SSL3_BUFFER_get_left(&rl
->wbuf
[rl
->numwpipes
- 1]) != 0;
84 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER
*rl
)
86 memset(rl
->write_sequence
, 0, sizeof(rl
->write_sequence
));
89 size_t ssl3_pending(const SSL
*s
)
92 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
97 if (SSL_CONNECTION_IS_DTLS(sc
)) {
101 iter
= pqueue_iterator(sc
->rlayer
.d
->buffered_app_data
.q
);
102 while ((item
= pqueue_next(&iter
)) != NULL
) {
104 num
+= rdata
->length
;
108 for (i
= 0; i
< sc
->rlayer
.num_recs
; i
++) {
109 if (sc
->rlayer
.tlsrecs
[i
].type
!= SSL3_RT_APPLICATION_DATA
)
111 num
+= sc
->rlayer
.tlsrecs
[i
].length
;
114 num
+= sc
->rlayer
.rrlmethod
->app_data_pending(sc
->rlayer
.rrl
);
119 void SSL_CTX_set_default_read_buffer_len(SSL_CTX
*ctx
, size_t len
)
121 ctx
->default_read_buf_len
= len
;
124 void SSL_set_default_read_buffer_len(SSL
*s
, size_t len
)
126 SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_SSL(s
);
130 sc
->rlayer
.default_read_buf_len
= len
;
133 const char *SSL_rstate_string_long(const SSL
*s
)
135 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
141 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
144 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, NULL
, &lng
);
149 const char *SSL_rstate_string(const SSL
*s
)
151 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
157 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
160 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, &shrt
, NULL
);
165 static int tls_write_check_pending(SSL_CONNECTION
*s
, int type
,
166 const unsigned char *buf
, size_t len
)
168 if (s
->rlayer
.wpend_tot
== 0)
171 /* We have pending data, so do some sanity checks */
172 if ((s
->rlayer
.wpend_tot
> len
)
173 || (!(s
->mode
& SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
)
174 && (s
->rlayer
.wpend_buf
!= buf
))
175 || (s
->rlayer
.wpend_type
!= type
)) {
176 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_WRITE_RETRY
);
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 /* TODO(RECLAYER): Re-enable multiblock code */
193 #if 0 && !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
198 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
199 OSSL_RECORD_TEMPLATE tmpls
[SSL_MAX_PIPELINES
];
204 wb
= &s
->rlayer
.wbuf
[0];
205 s
->rwstate
= SSL_NOTHING
;
206 tot
= s
->rlayer
.wnum
;
208 * ensure that if we end up with a smaller value of data to write out
209 * than the original len from a write which didn't complete for
210 * non-blocking I/O and also somehow ended up avoiding the check for
211 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
212 * possible to end up with (len-tot) as a large number that will then
213 * promptly send beyond the end of the users buffer ... so we trap and
214 * report the error in a way the user will notice
216 if ((len
< s
->rlayer
.wnum
)
217 || ((wb
->left
!= 0) && (len
< (s
->rlayer
.wnum
+ s
->rlayer
.wpend_tot
)))) {
218 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_LENGTH
);
222 if (s
->early_data_state
== SSL_EARLY_DATA_WRITING
223 && !ossl_early_data_count_ok(s
, len
, 0, 1)) {
224 /* SSLfatal() already called */
231 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
232 * into init unless we have writes pending - in which case we should finish
235 if (wb
->left
== 0 && (s
->key_update
!= SSL_KEY_UPDATE_NONE
236 || s
->ext
.extra_tickets_expected
> 0))
237 ossl_statem_set_in_init(s
, 1);
240 * When writing early data on the server side we could be "in_init" in
241 * between receiving the EoED and the CF - but we don't want to handle those
244 if (SSL_in_init(ssl
) && !ossl_statem_get_in_handshake(s
)
245 && s
->early_data_state
!= SSL_EARLY_DATA_UNAUTH_WRITING
) {
246 i
= s
->handshake_func(ssl
);
247 /* SSLfatal() already called */
255 i
= tls_write_check_pending(s
, type
, buf
, len
);
257 /* SSLfatal() already called */
261 i
= tls_retry_write_records(s
);
264 tot
+= s
->rlayer
.wpend_tot
;
265 s
->rlayer
.wpend_tot
= 0;
266 } /* else no retry required */
270 * We've not previously sent any data for this write so memorize
271 * arguments so that we can detect bad write retries later
273 s
->rlayer
.wpend_tot
= 0;
274 s
->rlayer
.wpend_type
= type
;
275 s
->rlayer
.wpend_buf
= buf
;
276 s
->rlayer
.wpend_ret
= len
;
279 /* TODO(RECLAYER): Re-enable multiblock code */
280 #if 0 && !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
282 * Depending on platform multi-block can deliver several *times*
283 * better performance. Downside is that it has to allocate
284 * jumbo buffer to accommodate up to 8 records, but the
285 * compromise is considered worthy.
287 if (type
== SSL3_RT_APPLICATION_DATA
288 && len
>= 4 * (max_send_fragment
= ssl_get_max_send_fragment(s
))
289 && s
->compress
== NULL
290 && s
->msg_callback
== NULL
292 && SSL_USE_EXPLICIT_IV(s
)
293 && !BIO_get_ktls_send(s
->wbio
)
294 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s
->enc_write_ctx
))
295 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
) != 0) {
296 unsigned char aad
[13];
297 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param
;
301 /* minimize address aliasing conflicts */
302 if ((max_send_fragment
& 0xfff) == 0)
303 max_send_fragment
-= 512;
305 if (tot
== 0 || wb
->buf
== NULL
) { /* allocate jumbo buffer */
306 ssl3_release_write_buffer(s
);
308 packlen
= EVP_CIPHER_CTX_ctrl(s
->enc_write_ctx
,
309 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE
,
310 (int)max_send_fragment
, NULL
);
312 if (len
>= 8 * max_send_fragment
)
317 if (!ssl3_setup_write_buffer(s
, 1, packlen
)) {
318 /* SSLfatal() already called */
321 } else if (tot
== len
) { /* done? */
322 /* free jumbo buffer */
323 ssl3_release_write_buffer(s
);
330 if (n
< 4 * max_send_fragment
) {
331 /* free jumbo buffer */
332 ssl3_release_write_buffer(s
);
336 if (s
->s3
.alert_dispatch
) {
337 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
339 /* SSLfatal() already called if appropriate */
340 s
->rlayer
.wnum
= tot
;
345 if (n
>= 8 * max_send_fragment
)
346 nw
= max_send_fragment
* (mb_param
.interleave
= 8);
348 nw
= max_send_fragment
* (mb_param
.interleave
= 4);
350 memcpy(aad
, s
->rlayer
.write_sequence
, 8);
352 aad
[9] = (unsigned char)(s
->version
>> 8);
353 aad
[10] = (unsigned char)(s
->version
);
360 packleni
= EVP_CIPHER_CTX_ctrl(s
->enc_write_ctx
,
361 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD
,
362 sizeof(mb_param
), &mb_param
);
363 packlen
= (size_t)packleni
;
364 if (packleni
<= 0 || packlen
> wb
->len
) { /* never happens */
365 /* free jumbo buffer */
366 ssl3_release_write_buffer(s
);
370 mb_param
.out
= wb
->buf
;
371 mb_param
.inp
= &buf
[tot
];
374 if (EVP_CIPHER_CTX_ctrl(s
->enc_write_ctx
,
375 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT
,
376 sizeof(mb_param
), &mb_param
) <= 0)
379 s
->rlayer
.write_sequence
[7] += mb_param
.interleave
;
380 if (s
->rlayer
.write_sequence
[7] < mb_param
.interleave
) {
382 while (j
>= 0 && (++s
->rlayer
.write_sequence
[j
--]) == 0) ;
388 s
->rlayer
.wpend_tot
= nw
;
389 s
->rlayer
.wpend_buf
= &buf
[tot
];
390 s
->rlayer
.wpend_type
= type
;
391 s
->rlayer
.wpend_ret
= nw
;
393 i
= ssl3_write_pending(s
, type
, &buf
[tot
], nw
, &tmpwrit
);
395 /* SSLfatal() already called if appropriate */
396 if (i
< 0 && (!s
->wbio
|| !BIO_should_retry(s
->wbio
))) {
397 /* free jumbo buffer */
398 ssl3_release_write_buffer(s
);
400 s
->rlayer
.wnum
= tot
;
404 /* free jumbo buffer */
405 ssl3_release_write_buffer(s
);
406 *written
= tot
+ tmpwrit
;
413 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
414 if (tot
== len
) { /* done? */
415 if (s
->mode
& SSL_MODE_RELEASE_BUFFERS
&& !SSL_CONNECTION_IS_DTLS(s
))
416 ssl3_release_write_buffer(s
);
424 max_send_fragment
= ssl_get_max_send_fragment(s
);
425 split_send_fragment
= ssl_get_split_send_fragment(s
);
427 * TODO(RECLAYER): This comment is now out-of-date and probably needs to
428 * move somewhere else
430 * If max_pipelines is 0 then this means "undefined" and we default to
431 * 1 pipeline. Similarly if the cipher does not support pipelined
432 * processing then we also only use 1 pipeline, or if we're not using
435 maxpipes
= s
->max_pipelines
;
436 if (maxpipes
> SSL_MAX_PIPELINES
) {
438 * We should have prevented this when we set max_pipelines so we
441 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
444 /* If no explicit maxpipes configuration - default to 1 */
445 /* TODO(RECLAYER): Should we ask the record layer how many pipes it supports? */
449 /* TODO(RECLAYER): FIX ME */
451 || s
->enc_write_ctx
== NULL
452 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s
->enc_write_ctx
))
453 & EVP_CIPH_FLAG_PIPELINE
) == 0
454 || !SSL_USE_EXPLICIT_IV(s
))
457 if (max_send_fragment
== 0
458 || split_send_fragment
== 0
459 || split_send_fragment
> max_send_fragment
) {
461 * We should have prevented this when we set/get the split and max send
462 * fragments so we shouldn't get here
464 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
469 size_t tmppipelen
, remain
;
470 size_t numpipes
, j
, lensofar
= 0;
475 numpipes
= ((n
- 1) / split_send_fragment
) + 1;
476 if (numpipes
> maxpipes
)
479 if (n
/ numpipes
>= max_send_fragment
) {
481 * We have enough data to completely fill all available
484 for (j
= 0; j
< numpipes
; j
++) {
485 tmpls
[j
].type
= type
;
486 tmpls
[j
].buf
= &(buf
[tot
]) + (j
* max_send_fragment
);
487 tmpls
[j
].buflen
= max_send_fragment
;
489 /* Remember how much data we are going to be sending */
490 s
->rlayer
.wpend_tot
= numpipes
* max_send_fragment
;
492 /* We can partially fill all available pipelines */
493 tmppipelen
= n
/ numpipes
;
494 remain
= n
% numpipes
;
496 * If there is a remainder we add an extra byte to the first few
501 for (j
= 0; j
< numpipes
; j
++) {
502 tmpls
[j
].type
= type
;
503 tmpls
[j
].buf
= &(buf
[tot
]) + lensofar
;
504 tmpls
[j
].buflen
= tmppipelen
;
505 lensofar
+= tmppipelen
;
509 /* Remember how much data we are going to be sending */
510 s
->rlayer
.wpend_tot
= n
;
513 i
= tls_write_records(s
, tmpls
, numpipes
);
515 /* SSLfatal() already called if appropriate */
516 s
->rlayer
.wnum
= tot
;
520 if (s
->rlayer
.wpend_tot
== n
||
521 (type
== SSL3_RT_APPLICATION_DATA
&&
522 (s
->mode
& SSL_MODE_ENABLE_PARTIAL_WRITE
))) {
523 if (s
->rlayer
.wpend_tot
== n
524 && (s
->mode
& SSL_MODE_RELEASE_BUFFERS
) != 0
525 && !SSL_CONNECTION_IS_DTLS(s
))
526 ssl3_release_write_buffer(s
);
528 *written
= tot
+ s
->rlayer
.wpend_tot
;
529 s
->rlayer
.wpend_tot
= 0;
533 n
-= s
->rlayer
.wpend_tot
;
534 tot
+= s
->rlayer
.wpend_tot
;
538 int tls_write_records(SSL_CONNECTION
*s
, OSSL_RECORD_TEMPLATE
*templates
,
541 WPACKET pkt
[SSL_MAX_PIPELINES
+ 1];
542 SSL3_RECORD wr
[SSL_MAX_PIPELINES
+ 1];
545 unsigned char *recordstart
;
546 int i
, mac_size
, clear
= 0;
551 size_t totlen
= 0, len
, wpinited
= 0;
552 size_t j
, prefix
= 0;
554 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
555 OSSL_RECORD_TEMPLATE prefixtempl
;
556 OSSL_RECORD_TEMPLATE
*thistempl
;
558 if (!ossl_assert(!RECORD_LAYER_write_pending(&s
->rlayer
))) {
559 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
563 /* If we have an alert to send, lets send it */
564 if (s
->s3
.alert_dispatch
) {
565 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
567 /* SSLfatal() already called if appropriate */
570 /* if it went, fall through and send more stuff */
576 || (s
->enc_write_ctx
== NULL
)
577 || (EVP_MD_CTX_get0_md(s
->write_hash
) == NULL
)) {
578 clear
= s
->enc_write_ctx
? 0 : 1; /* must be AEAD cipher */
581 mac_size
= EVP_MD_CTX_get_size(s
->write_hash
);
583 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
589 * 'create_empty_fragment' is true only when we have recursively called
591 * Do we need to do that recursion in order to add an empty record prefix?
593 prefix
= s
->s3
.need_empty_fragments
595 && !s
->s3
.empty_fragment_done
596 && templates
[0].type
== SSL3_RT_APPLICATION_DATA
;
598 if (s
->rlayer
.numwpipes
< numtempl
+ prefix
) {
600 * TODO(RECLAYER): In the prefix case the first buffer can be a lot
601 * smaller. It is wasteful to allocate a full sized buffer here
603 if (!ssl3_setup_write_buffer(s
, numtempl
+ prefix
, 0)) {
604 /* SSLfatal() already called */
609 using_ktls
= BIO_get_ktls_send(s
->wbio
);
610 if (!ossl_assert(!using_ktls
|| !prefix
)) {
611 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
617 * countermeasure against known-IV weakness in CBC ciphersuites (see
618 * http://www.openssl.org/~bodo/tls-cbc.txt)
620 prefixtempl
.buf
= NULL
;
621 prefixtempl
.buflen
= 0;
622 prefixtempl
.type
= SSL3_RT_APPLICATION_DATA
;
625 /* TODO(RECLAYER): Do we actually need this? */
626 s
->s3
.empty_fragment_done
= 1;
628 wb
= &s
->rlayer
.wbuf
[0];
629 /* TODO(RECLAYER): This alignment calculation no longer seems right */
630 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
632 * extra fragment would be couple of cipher blocks, which would be
633 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
634 * payload, then we can just pretend we simply have two headers.
636 align
= (size_t)SSL3_BUFFER_get_buf(wb
) + 2 * SSL3_RT_HEADER_LENGTH
;
637 align
= SSL3_ALIGN_PAYLOAD
- 1 - ((align
- 1) % SSL3_ALIGN_PAYLOAD
);
639 SSL3_BUFFER_set_offset(wb
, align
);
640 if (!WPACKET_init_static_len(&pkt
[0], SSL3_BUFFER_get_buf(wb
),
641 SSL3_BUFFER_get_len(wb
), 0)
642 || !WPACKET_allocate_bytes(&pkt
[0], align
, NULL
)) {
643 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
648 for (j
= 0; j
< numtempl
; j
++) {
649 thispkt
= &pkt
[prefix
+ j
];
651 wb
= &s
->rlayer
.wbuf
[prefix
+ j
];
652 wb
->type
= templates
[j
].type
;
656 * ktls doesn't modify the buffer, but to avoid a warning we need
657 * to discard the const qualifier.
658 * This doesn't leak memory because the buffers have been
659 * released when switching to ktls.
661 SSL3_BUFFER_set_buf(wb
, (unsigned char *)templates
[j
].buf
);
662 SSL3_BUFFER_set_offset(wb
, 0);
663 SSL3_BUFFER_set_app_buffer(wb
, 1);
665 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
666 align
= (size_t)SSL3_BUFFER_get_buf(wb
) + SSL3_RT_HEADER_LENGTH
;
667 align
= SSL3_ALIGN_PAYLOAD
- 1
668 - ((align
- 1) % SSL3_ALIGN_PAYLOAD
);
670 /* TODO(RECLAYER): Is this alignment actually used somewhere? */
671 SSL3_BUFFER_set_offset(wb
, align
);
672 if (!WPACKET_init_static_len(thispkt
, SSL3_BUFFER_get_buf(wb
),
673 SSL3_BUFFER_get_len(wb
), 0)
674 || !WPACKET_allocate_bytes(thispkt
, align
, NULL
)) {
675 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
683 /* Explicit IV length, block ciphers appropriate version flag */
684 if (s
->enc_write_ctx
&& SSL_USE_EXPLICIT_IV(s
)
685 && !SSL_CONNECTION_TREAT_AS_TLS13(s
)) {
686 int mode
= EVP_CIPHER_CTX_get_mode(s
->enc_write_ctx
);
687 if (mode
== EVP_CIPH_CBC_MODE
) {
688 eivlen
= EVP_CIPHER_CTX_get_iv_length(s
->enc_write_ctx
);
690 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_LIBRARY_BUG
);
695 } else if (mode
== EVP_CIPH_GCM_MODE
) {
696 /* Need explicit part of IV for GCM mode */
697 eivlen
= EVP_GCM_TLS_EXPLICIT_IV_LEN
;
698 } else if (mode
== EVP_CIPH_CCM_MODE
) {
699 eivlen
= EVP_CCM_TLS_EXPLICIT_IV_LEN
;
705 /* Clear our SSL3_RECORD structures */
706 memset(wr
, 0, sizeof(wr
));
707 for (j
= 0; j
< numtempl
+ prefix
; j
++) {
708 unsigned int version
= (s
->version
== TLS1_3_VERSION
) ? TLS1_2_VERSION
710 unsigned char *compressdata
= NULL
;
712 unsigned int rectype
;
716 thistempl
= (j
== 0 && prefix
== 1) ? &prefixtempl
:
717 &templates
[j
- prefix
];
720 * In TLSv1.3, once encrypting, we always use application data for the
723 if (SSL_CONNECTION_TREAT_AS_TLS13(s
)
724 && s
->enc_write_ctx
!= NULL
725 && (s
->statem
.enc_write_state
!= ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
726 || thistempl
->type
!= SSL3_RT_ALERT
))
727 rectype
= SSL3_RT_APPLICATION_DATA
;
729 rectype
= thistempl
->type
;
731 SSL3_RECORD_set_type(thiswr
, rectype
);
734 * Some servers hang if initial client hello is larger than 256 bytes
735 * and record version number > TLS 1.0
737 if (SSL_get_state(ssl
) == TLS_ST_CW_CLNT_HELLO
739 && TLS1_get_version(ssl
) > TLS1_VERSION
740 && s
->hello_retry_request
== SSL_HRR_NONE
)
741 version
= TLS1_VERSION
;
742 SSL3_RECORD_set_rec_version(thiswr
, version
);
744 maxcomplen
= thistempl
->buflen
;
745 if (s
->compress
!= NULL
)
746 maxcomplen
+= SSL3_RT_MAX_COMPRESSED_OVERHEAD
;
749 * When using offload kernel will write the header.
750 * Otherwise write the header now
753 && (!WPACKET_put_bytes_u8(thispkt
, rectype
)
754 || !WPACKET_put_bytes_u16(thispkt
, version
)
755 || !WPACKET_start_sub_packet_u16(thispkt
)
757 && !WPACKET_allocate_bytes(thispkt
, eivlen
, NULL
))
759 && !WPACKET_reserve_bytes(thispkt
, maxcomplen
,
761 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
765 /* lets setup the record stuff. */
766 SSL3_RECORD_set_data(thiswr
, compressdata
);
767 SSL3_RECORD_set_length(thiswr
, thistempl
->buflen
);
769 * TODO(RECLAYER): Cast away the const. Should be safe - by why is this
772 SSL3_RECORD_set_input(thiswr
, (unsigned char *)thistempl
->buf
);
773 totlen
+= thistempl
->buflen
;
776 * we now 'read' from thiswr->input, thiswr->length bytes into
780 /* first we compress */
781 if (s
->compress
!= NULL
) {
782 if (!ssl3_do_compress(s
, thiswr
)
783 || !WPACKET_allocate_bytes(thispkt
, thiswr
->length
, NULL
)) {
784 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_COMPRESSION_FAILURE
);
789 SSL3_RECORD_reset_data(&wr
[j
]);
791 if (!WPACKET_memcpy(thispkt
, thiswr
->input
, thiswr
->length
)) {
792 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
795 SSL3_RECORD_reset_input(&wr
[j
]);
799 if (SSL_CONNECTION_TREAT_AS_TLS13(s
)
801 && s
->enc_write_ctx
!= NULL
802 && (s
->statem
.enc_write_state
!= ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
803 || thistempl
->type
!= SSL3_RT_ALERT
)) {
804 size_t rlen
, max_send_fragment
;
806 if (!WPACKET_put_bytes_u8(thispkt
, thistempl
->type
)) {
807 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
810 SSL3_RECORD_add_length(thiswr
, 1);
812 /* Add TLS1.3 padding */
813 max_send_fragment
= ssl_get_max_send_fragment(s
);
814 rlen
= SSL3_RECORD_get_length(thiswr
);
815 if (rlen
< max_send_fragment
) {
817 size_t max_padding
= max_send_fragment
- rlen
;
818 if (s
->record_padding_cb
!= NULL
) {
819 padding
= s
->record_padding_cb(ssl
, thistempl
->type
, rlen
,
820 s
->record_padding_arg
);
821 } else if (s
->block_padding
> 0) {
822 size_t mask
= s
->block_padding
- 1;
825 /* optimize for power of 2 */
826 if ((s
->block_padding
& mask
) == 0)
827 remainder
= rlen
& mask
;
829 remainder
= rlen
% s
->block_padding
;
830 /* don't want to add a block of padding if we don't have to */
834 padding
= s
->block_padding
- remainder
;
837 /* do not allow the record to exceed max plaintext length */
838 if (padding
> max_padding
)
839 padding
= max_padding
;
840 if (!WPACKET_memset(thispkt
, 0, padding
)) {
841 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
,
842 ERR_R_INTERNAL_ERROR
);
845 SSL3_RECORD_add_length(thiswr
, padding
);
851 * we should still have the output to thiswr->data and the input from
852 * wr->input. Length should be thiswr->length. thiswr->data still points
856 if (!using_ktls
&& !SSL_WRITE_ETM(s
) && mac_size
!= 0) {
859 if (!WPACKET_allocate_bytes(thispkt
, mac_size
, &mac
)
860 || !ssl
->method
->ssl3_enc
->mac(s
, thiswr
, mac
, 1)) {
861 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
867 * Reserve some bytes for any growth that may occur during encryption.
868 * This will be at most one cipher block or the tag length if using
869 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
872 if (!WPACKET_reserve_bytes(thispkt
,
873 SSL_RT_MAX_CIPHER_BLOCK_SIZE
,
876 * We also need next the amount of bytes written to this
879 || !WPACKET_get_length(thispkt
, &len
)) {
880 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
884 /* Get a pointer to the start of this record excluding header */
885 recordstart
= WPACKET_get_curr(thispkt
) - len
;
886 SSL3_RECORD_set_data(thiswr
, recordstart
);
887 SSL3_RECORD_reset_input(thiswr
);
888 SSL3_RECORD_set_length(thiswr
, len
);
892 if (s
->statem
.enc_write_state
== ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
) {
894 * We haven't actually negotiated the version yet, but we're trying to
895 * send early data - so we need to use the tls13enc function.
897 if (tls13_enc(s
, wr
, numtempl
, 1, NULL
, mac_size
) < 1) {
898 if (!ossl_statem_in_error(s
)) {
899 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
906 if (ssl
->method
->ssl3_enc
->enc(s
, wr
, 1, 1, NULL
, mac_size
) < 1) {
907 if (!ossl_statem_in_error(s
)) {
908 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
913 if (ssl
->method
->ssl3_enc
->enc(s
, wr
+ prefix
, numtempl
, 1, NULL
,
915 if (!ossl_statem_in_error(s
)) {
916 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
923 for (j
= 0; j
< prefix
+ numtempl
; j
++) {
928 thistempl
= (prefix
== 1 && j
== 0) ? &prefixtempl
929 : &templates
[j
- prefix
];
934 /* Allocate bytes for the encryption overhead */
935 if (!WPACKET_get_length(thispkt
, &origlen
)
936 /* Encryption should never shrink the data! */
937 || origlen
> thiswr
->length
938 || (thiswr
->length
> origlen
939 && !WPACKET_allocate_bytes(thispkt
,
940 thiswr
->length
- origlen
,
942 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
945 if (SSL_WRITE_ETM(s
) && mac_size
!= 0) {
948 if (!WPACKET_allocate_bytes(thispkt
, mac_size
, &mac
)
949 || !ssl
->method
->ssl3_enc
->mac(s
, thiswr
, mac
, 1)) {
950 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
953 SSL3_RECORD_add_length(thiswr
, mac_size
);
956 if (!WPACKET_get_length(thispkt
, &len
)
957 || !WPACKET_close(thispkt
)) {
958 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
962 if (s
->msg_callback
) {
963 recordstart
= WPACKET_get_curr(thispkt
) - len
964 - SSL3_RT_HEADER_LENGTH
;
965 s
->msg_callback(1, thiswr
->rec_version
, SSL3_RT_HEADER
, recordstart
,
966 SSL3_RT_HEADER_LENGTH
, ssl
,
967 s
->msg_callback_arg
);
969 if (SSL_CONNECTION_TREAT_AS_TLS13(s
) && s
->enc_write_ctx
!= NULL
) {
970 unsigned char ctype
= thistempl
->type
;
972 s
->msg_callback(1, thiswr
->rec_version
, SSL3_RT_INNER_CONTENT_TYPE
,
973 &ctype
, 1, ssl
, s
->msg_callback_arg
);
977 if (!WPACKET_finish(thispkt
)) {
978 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
982 /* header is added by the kernel when using offload */
983 SSL3_RECORD_add_length(thiswr
, SSL3_RT_HEADER_LENGTH
);
987 * we should now have thiswr->data pointing to the encrypted data, which
988 * is thiswr->length long.
989 * Setting the type is not needed but helps for debugging
991 SSL3_RECORD_set_type(thiswr
, thistempl
->type
);
993 /* now let's set up wb */
994 SSL3_BUFFER_set_left(&s
->rlayer
.wbuf
[j
], SSL3_RECORD_get_length(thiswr
));
997 /* we now just need to write the buffers */
998 return tls_retry_write_records(s
);
1000 for (j
= 0; j
< wpinited
; j
++)
1001 WPACKET_cleanup(&pkt
[j
]);
1005 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1007 * Return values are as per SSL_write()
1009 int tls_retry_write_records(SSL_CONNECTION
*s
)
1012 SSL3_BUFFER
*thiswb
;
1017 thiswb
= &s
->rlayer
.wbuf
[currbuf
];
1018 /* Loop until we find a buffer we haven't written out yet */
1019 if (SSL3_BUFFER_get_left(thiswb
) == 0
1020 && currbuf
< s
->rlayer
.numwpipes
- 1) {
1025 if (s
->wbio
!= NULL
) {
1026 s
->rwstate
= SSL_WRITING
;
1029 * To prevent coalescing of control and data messages,
1030 * such as in buffer_write, we flush the BIO
1032 if (BIO_get_ktls_send(s
->wbio
)
1033 && thiswb
->type
!= SSL3_RT_APPLICATION_DATA
) {
1034 i
= BIO_flush(s
->wbio
);
1037 BIO_set_ktls_ctrl_msg(s
->wbio
, thiswb
->type
);
1039 i
= BIO_write(s
->wbio
, (char *)
1040 &(SSL3_BUFFER_get_buf(thiswb
)
1041 [SSL3_BUFFER_get_offset(thiswb
)]),
1042 (unsigned int)SSL3_BUFFER_get_left(thiswb
));
1046 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BIO_NOT_SET
);
1051 * When an empty fragment is sent on a connection using KTLS,
1052 * it is sent as a write of zero bytes. If this zero byte
1053 * write succeeds, i will be 0 rather than a non-zero value.
1054 * Treat i == 0 as success rather than an error for zero byte
1055 * writes to permit this case.
1057 if (i
>= 0 && tmpwrit
== SSL3_BUFFER_get_left(thiswb
)) {
1058 SSL3_BUFFER_set_left(thiswb
, 0);
1059 SSL3_BUFFER_add_offset(thiswb
, tmpwrit
);
1060 if (currbuf
+ 1 < s
->rlayer
.numwpipes
)
1062 s
->rwstate
= SSL_NOTHING
;
1064 * Next chunk of data should get another prepended empty fragment
1065 * in ciphersuites with known-IV weakness:
1067 s
->s3
.empty_fragment_done
= 0;
1069 } else if (i
<= 0) {
1070 if (SSL_CONNECTION_IS_DTLS(s
)) {
1072 * For DTLS, just drop it. That's kind of the whole point in
1073 * using a datagram service
1075 SSL3_BUFFER_set_left(thiswb
, 0);
1079 SSL3_BUFFER_add_offset(thiswb
, tmpwrit
);
1080 SSL3_BUFFER_sub_left(thiswb
, tmpwrit
);
1084 int ossl_tls_handle_rlayer_return(SSL_CONNECTION
*s
, int ret
, char *file
,
1087 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1089 if (ret
== OSSL_RECORD_RETURN_RETRY
) {
1090 s
->rwstate
= SSL_READING
;
1093 s
->rwstate
= SSL_NOTHING
;
1094 if (ret
== OSSL_RECORD_RETURN_EOF
) {
1095 if (s
->options
& SSL_OP_IGNORE_UNEXPECTED_EOF
) {
1096 SSL_set_shutdown(ssl
, SSL_RECEIVED_SHUTDOWN
);
1097 s
->s3
.warn_alert
= SSL_AD_CLOSE_NOTIFY
;
1100 ERR_set_debug(file
, line
, 0);
1101 ossl_statem_fatal(s
, SSL_AD_DECODE_ERROR
,
1102 SSL_R_UNEXPECTED_EOF_WHILE_READING
, NULL
);
1104 } else if (ret
== OSSL_RECORD_RETURN_FATAL
) {
1105 int al
= s
->rlayer
.rrlmethod
->get_alert_code(s
->rlayer
.rrl
);
1107 if (al
!= SSL_AD_NO_ALERT
) {
1109 ERR_set_debug(file
, line
, 0);
1110 ossl_statem_fatal(s
, al
, SSL_R_RECORD_LAYER_FAILURE
, NULL
);
1113 * else some failure but there is no alert code. We don't log an
1114 * error for this. The record layer should have logged an error
1115 * already or, if not, its due to some sys call error which will be
1116 * reported via SSL_ERROR_SYSCALL and errno.
1120 * The record layer distinguishes the cases of EOF, non-fatal
1121 * err and retry. Upper layers do not.
1122 * If we got a retry or success then *ret is already correct,
1123 * otherwise we need to convert the return value.
1125 if (ret
== OSSL_RECORD_RETURN_NON_FATAL_ERR
|| ret
== OSSL_RECORD_RETURN_EOF
)
1127 else if (ret
< OSSL_RECORD_RETURN_NON_FATAL_ERR
)
1134 void ssl_release_record(SSL_CONNECTION
*s
, TLS_RECORD
*rr
)
1136 if (rr
->rechandle
!= NULL
) {
1137 /* The record layer allocated the buffers for this record */
1138 s
->rlayer
.rrlmethod
->release_record(s
->rlayer
.rrl
, rr
->rechandle
);
1140 /* We allocated the buffers for this record (only happens with DTLS) */
1141 OPENSSL_free(rr
->data
);
1143 s
->rlayer
.curr_rec
++;
1147 * Return up to 'len' payload bytes received in 'type' records.
1148 * 'type' is one of the following:
1150 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1151 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1152 * - 0 (during a shutdown, no data has to be returned)
1154 * If we don't have stored data to work from, read a SSL/TLS record first
1155 * (possibly multiple records if we still don't have anything to return).
1157 * This function must handle any surprises the peer may have for us, such as
1158 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1159 * messages are treated as if they were handshake messages *if* the |recvd_type|
1160 * argument is non NULL.
1161 * Also if record payloads contain fragments too small to process, we store
1162 * them until there is enough for the respective protocol (the record protocol
1163 * may use arbitrary fragmentation and even interleaving):
1164 * Change cipher spec protocol
1165 * just 1 byte needed, no need for keeping anything stored
1167 * 2 bytes needed (AlertLevel, AlertDescription)
1168 * Handshake protocol
1169 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1170 * to detect unexpected Client Hello and Hello Request messages
1171 * here, anything else is handled by higher layers
1172 * Application data protocol
1173 * none of our business
1175 int ssl3_read_bytes(SSL
*ssl
, int type
, int *recvd_type
, unsigned char *buf
,
1176 size_t len
, int peek
, size_t *readbytes
)
1179 size_t n
, curr_rec
, totalbytes
;
1181 void (*cb
) (const SSL
*ssl
, int type2
, int val
) = NULL
;
1183 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
1185 is_tls13
= SSL_CONNECTION_IS_TLS13(s
);
1188 && (type
!= SSL3_RT_APPLICATION_DATA
)
1189 && (type
!= SSL3_RT_HANDSHAKE
))
1190 || (peek
&& (type
!= SSL3_RT_APPLICATION_DATA
))) {
1191 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1195 if ((type
== SSL3_RT_HANDSHAKE
) && (s
->rlayer
.handshake_fragment_len
> 0))
1196 /* (partially) satisfy request from storage */
1198 unsigned char *src
= s
->rlayer
.handshake_fragment
;
1199 unsigned char *dst
= buf
;
1204 while ((len
> 0) && (s
->rlayer
.handshake_fragment_len
> 0)) {
1207 s
->rlayer
.handshake_fragment_len
--;
1210 /* move any remaining fragment bytes: */
1211 for (k
= 0; k
< s
->rlayer
.handshake_fragment_len
; k
++)
1212 s
->rlayer
.handshake_fragment
[k
] = *src
++;
1214 if (recvd_type
!= NULL
)
1215 *recvd_type
= SSL3_RT_HANDSHAKE
;
1222 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1225 if (!ossl_statem_get_in_handshake(s
) && SSL_in_init(ssl
)) {
1226 /* type == SSL3_RT_APPLICATION_DATA */
1227 i
= s
->handshake_func(ssl
);
1228 /* SSLfatal() already called */
1235 s
->rwstate
= SSL_NOTHING
;
1238 * For each record 'i' up to |num_recs]
1239 * rr[i].type - is the type of record
1240 * rr[i].data, - data
1241 * rr[i].off, - offset into 'data' for next read
1242 * rr[i].length, - number of bytes.
1244 /* get new records if necessary */
1245 if (s
->rlayer
.curr_rec
>= s
->rlayer
.num_recs
) {
1246 s
->rlayer
.curr_rec
= s
->rlayer
.num_recs
= 0;
1248 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.num_recs
];
1250 ret
= HANDLE_RLAYER_RETURN(s
,
1251 s
->rlayer
.rrlmethod
->read_record(s
->rlayer
.rrl
,
1253 &rr
->version
, &rr
->type
,
1254 &rr
->data
, &rr
->length
,
1257 /* SSLfatal() already called if appropriate */
1261 s
->rlayer
.num_recs
++;
1262 } while (s
->rlayer
.rrlmethod
->processed_read_pending(s
->rlayer
.rrl
)
1263 && s
->rlayer
.num_recs
< SSL_MAX_PIPELINES
);
1265 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.curr_rec
];
1267 if (s
->rlayer
.handshake_fragment_len
> 0
1268 && rr
->type
!= SSL3_RT_HANDSHAKE
1269 && SSL_CONNECTION_IS_TLS13(s
)) {
1270 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
1271 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA
);
1276 * Reset the count of consecutive warning alerts if we've got a non-empty
1277 * record that isn't an alert.
1279 if (rr
->type
!= SSL3_RT_ALERT
&& rr
->length
!= 0)
1280 s
->rlayer
.alert_count
= 0;
1282 /* we now have a packet which can be read and processed */
1284 if (s
->s3
.change_cipher_spec
/* set when we receive ChangeCipherSpec,
1285 * reset by ssl3_get_finished */
1286 && (rr
->type
!= SSL3_RT_HANDSHAKE
)) {
1287 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
1288 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED
);
1293 * If the other end has shut down, throw anything we read away (even in
1296 if (s
->shutdown
& SSL_RECEIVED_SHUTDOWN
) {
1297 s
->rlayer
.curr_rec
++;
1298 s
->rwstate
= SSL_NOTHING
;
1302 if (type
== rr
->type
1303 || (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
1304 && type
== SSL3_RT_HANDSHAKE
&& recvd_type
!= NULL
1307 * SSL3_RT_APPLICATION_DATA or
1308 * SSL3_RT_HANDSHAKE or
1309 * SSL3_RT_CHANGE_CIPHER_SPEC
1312 * make sure that we are not getting application data when we are
1313 * doing a handshake for the first time
1315 if (SSL_in_init(ssl
) && type
== SSL3_RT_APPLICATION_DATA
1316 && s
->enc_read_ctx
== NULL
) {
1317 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_APP_DATA_IN_HANDSHAKE
);
1321 if (type
== SSL3_RT_HANDSHAKE
1322 && rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
1323 && s
->rlayer
.handshake_fragment_len
> 0) {
1324 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
1328 if (recvd_type
!= NULL
)
1329 *recvd_type
= rr
->type
;
1333 * Skip a zero length record. This ensures multiple calls to
1334 * SSL_read() with a zero length buffer will eventually cause
1335 * SSL_pending() to report data as being available.
1337 if (rr
->length
== 0)
1338 ssl_release_record(s
, rr
);
1344 curr_rec
= s
->rlayer
.curr_rec
;
1346 if (len
- totalbytes
> rr
->length
)
1349 n
= len
- totalbytes
;
1351 memcpy(buf
, &(rr
->data
[rr
->off
]), n
);
1354 /* Mark any zero length record as consumed CVE-2016-6305 */
1355 if (rr
->length
== 0)
1356 ssl_release_record(s
, rr
);
1358 if (s
->options
& SSL_OP_CLEANSE_PLAINTEXT
)
1359 OPENSSL_cleanse(&(rr
->data
[rr
->off
]), n
);
1362 if (rr
->length
== 0)
1363 ssl_release_record(s
, rr
);
1366 || (peek
&& n
== rr
->length
)) {
1371 } while (type
== SSL3_RT_APPLICATION_DATA
1372 && curr_rec
< s
->rlayer
.num_recs
1373 && totalbytes
< len
);
1374 if (totalbytes
== 0) {
1375 /* We must have read empty records. Get more data */
1378 *readbytes
= totalbytes
;
1383 * If we get here, then type != rr->type; if we have a handshake message,
1384 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1385 * were actually expecting a CCS).
1389 * Lets just double check that we've not got an SSLv2 record
1391 if (rr
->version
== SSL2_VERSION
) {
1393 * Should never happen. ssl3_get_record() should only give us an SSLv2
1394 * record back if this is the first packet and we are looking for an
1395 * initial ClientHello. Therefore |type| should always be equal to
1396 * |rr->type|. If not then something has gone horribly wrong
1398 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1402 if (ssl
->method
->version
== TLS_ANY_VERSION
1403 && (s
->server
|| rr
->type
!= SSL3_RT_ALERT
)) {
1405 * If we've got this far and still haven't decided on what version
1406 * we're using then this must be a client side alert we're dealing
1407 * with. We shouldn't be receiving anything other than a ClientHello
1408 * if we are a server.
1410 s
->version
= rr
->version
;
1411 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_MESSAGE
);
1416 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1417 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1420 if (rr
->type
== SSL3_RT_ALERT
) {
1421 unsigned int alert_level
, alert_descr
;
1422 unsigned char *alert_bytes
= rr
->data
1426 if (!PACKET_buf_init(&alert
, alert_bytes
, rr
->length
)
1427 || !PACKET_get_1(&alert
, &alert_level
)
1428 || !PACKET_get_1(&alert
, &alert_descr
)
1429 || PACKET_remaining(&alert
) != 0) {
1430 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_INVALID_ALERT
);
1434 if (s
->msg_callback
)
1435 s
->msg_callback(0, s
->version
, SSL3_RT_ALERT
, alert_bytes
, 2, ssl
,
1436 s
->msg_callback_arg
);
1438 if (s
->info_callback
!= NULL
)
1439 cb
= s
->info_callback
;
1440 else if (ssl
->ctx
->info_callback
!= NULL
)
1441 cb
= ssl
->ctx
->info_callback
;
1444 j
= (alert_level
<< 8) | alert_descr
;
1445 cb(ssl
, SSL_CB_READ_ALERT
, j
);
1448 if ((!is_tls13
&& alert_level
== SSL3_AL_WARNING
)
1449 || (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
)) {
1450 s
->s3
.warn_alert
= alert_descr
;
1451 ssl_release_record(s
, rr
);
1453 s
->rlayer
.alert_count
++;
1454 if (s
->rlayer
.alert_count
== MAX_WARN_ALERT_COUNT
) {
1455 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
1456 SSL_R_TOO_MANY_WARN_ALERTS
);
1462 * Apart from close_notify the only other warning alert in TLSv1.3
1463 * is user_cancelled - which we just ignore.
1465 if (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
) {
1467 } else if (alert_descr
== SSL_AD_CLOSE_NOTIFY
1468 && (is_tls13
|| alert_level
== SSL3_AL_WARNING
)) {
1469 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
1471 } else if (alert_level
== SSL3_AL_FATAL
|| is_tls13
) {
1472 s
->rwstate
= SSL_NOTHING
;
1473 s
->s3
.fatal_alert
= alert_descr
;
1474 SSLfatal_data(s
, SSL_AD_NO_ALERT
,
1475 SSL_AD_REASON_OFFSET
+ alert_descr
,
1476 "SSL alert number %d", alert_descr
);
1477 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
1478 ssl_release_record(s
, rr
);
1479 SSL_CTX_remove_session(s
->session_ctx
, s
->session
);
1481 } else if (alert_descr
== SSL_AD_NO_RENEGOTIATION
) {
1483 * This is a warning but we receive it if we requested
1484 * renegotiation and the peer denied it. Terminate with a fatal
1485 * alert because if application tried to renegotiate it
1486 * presumably had a good reason and expects it to succeed. In
1487 * future we might have a renegotiation where we don't care if
1488 * the peer refused it where we carry on.
1490 SSLfatal(s
, SSL_AD_HANDSHAKE_FAILURE
, SSL_R_NO_RENEGOTIATION
);
1492 } else if (alert_level
== SSL3_AL_WARNING
) {
1493 /* We ignore any other warning alert in TLSv1.2 and below */
1497 SSLfatal(s
, SSL_AD_ILLEGAL_PARAMETER
, SSL_R_UNKNOWN_ALERT_TYPE
);
1501 if ((s
->shutdown
& SSL_SENT_SHUTDOWN
) != 0) {
1502 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
1506 * We ignore any handshake messages sent to us unless they are
1507 * TLSv1.3 in which case we want to process them. For all other
1508 * handshake messages we can't do anything reasonable with them
1509 * because we are unable to write any response due to having already
1510 * sent close_notify.
1512 if (!SSL_CONNECTION_IS_TLS13(s
)) {
1513 ssl_release_record(s
, rr
);
1515 if ((s
->mode
& SSL_MODE_AUTO_RETRY
) != 0)
1518 s
->rwstate
= SSL_READING
;
1519 rbio
= SSL_get_rbio(ssl
);
1520 BIO_clear_retry_flags(rbio
);
1521 BIO_set_retry_read(rbio
);
1526 * The peer is continuing to send application data, but we have
1527 * already sent close_notify. If this was expected we should have
1528 * been called via SSL_read() and this would have been handled
1530 * No alert sent because we already sent close_notify
1532 ssl_release_record(s
, rr
);
1533 SSLfatal(s
, SSL_AD_NO_ALERT
,
1534 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY
);
1540 * For handshake data we have 'fragment' storage, so fill that so that we
1541 * can process the header at a fixed place. This is done after the
1542 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1543 * that we're just going to discard.
1545 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
1546 size_t dest_maxlen
= sizeof(s
->rlayer
.handshake_fragment
);
1547 unsigned char *dest
= s
->rlayer
.handshake_fragment
;
1548 size_t *dest_len
= &s
->rlayer
.handshake_fragment_len
;
1550 n
= dest_maxlen
- *dest_len
; /* available space in 'dest' */
1552 n
= rr
->length
; /* available bytes */
1554 /* now move 'n' bytes: */
1555 memcpy(dest
+ *dest_len
, rr
->data
+ rr
->off
, n
);
1559 if (rr
->length
== 0)
1560 ssl_release_record(s
, rr
);
1562 if (*dest_len
< dest_maxlen
)
1563 goto start
; /* fragment was too small */
1566 if (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
) {
1567 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
1572 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1573 * protocol violation)
1575 if ((s
->rlayer
.handshake_fragment_len
>= 4)
1576 && !ossl_statem_get_in_handshake(s
)) {
1577 int ined
= (s
->early_data_state
== SSL_EARLY_DATA_READING
);
1579 /* We found handshake data, so we're going back into init */
1580 ossl_statem_set_in_init(s
, 1);
1582 i
= s
->handshake_func(ssl
);
1583 /* SSLfatal() already called if appropriate */
1591 * If we were actually trying to read early data and we found a
1592 * handshake message, then we don't want to continue to try and read
1593 * the application data any more. It won't be "early" now.
1598 if (!(s
->mode
& SSL_MODE_AUTO_RETRY
)) {
1599 if (!RECORD_LAYER_read_pending(&s
->rlayer
)) {
1602 * In the case where we try to read application data, but we
1603 * trigger an SSL handshake, we return -1 with the retry
1604 * option set. Otherwise renegotiation may cause nasty
1605 * problems in the blocking world
1607 s
->rwstate
= SSL_READING
;
1608 bio
= SSL_get_rbio(ssl
);
1609 BIO_clear_retry_flags(bio
);
1610 BIO_set_retry_read(bio
);
1620 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1621 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1622 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1623 * no progress is being made and the peer continually sends unrecognised
1624 * record types, using up resources processing them.
1626 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
1628 case SSL3_RT_CHANGE_CIPHER_SPEC
:
1630 case SSL3_RT_HANDSHAKE
:
1632 * we already handled all of these, with the possible exception of
1633 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1634 * that should not happen when type != rr->type
1636 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, ERR_R_INTERNAL_ERROR
);
1638 case SSL3_RT_APPLICATION_DATA
:
1640 * At this point, we were expecting handshake data, but have
1641 * application data. If the library was running inside ssl3_read()
1642 * (i.e. in_read_app_data is set) and it makes sense to read
1643 * application data at this point (session renegotiation not yet
1644 * started), we will indulge it.
1646 if (ossl_statem_app_data_allowed(s
)) {
1647 s
->s3
.in_read_app_data
= 2;
1649 } else if (ossl_statem_skip_early_data(s
)) {
1651 * This can happen after a client sends a CH followed by early_data,
1652 * but the server responds with a HelloRetryRequest. The server
1653 * reads the next record from the client expecting to find a
1654 * plaintext ClientHello but gets a record which appears to be
1655 * application data. The trial decrypt "works" because null
1656 * decryption was applied. We just skip it and move on to the next
1659 if (!ossl_early_data_count_ok(s
, rr
->length
,
1660 EARLY_DATA_CIPHERTEXT_OVERHEAD
, 0)) {
1661 /* SSLfatal() already called */
1664 ssl_release_record(s
, rr
);
1667 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
1673 void ssl3_record_sequence_update(unsigned char *seq
)
1677 for (i
= 7; i
>= 0; i
--) {
1685 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1686 * format and false otherwise.
1688 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER
*rl
)
1690 if (SSL_CONNECTION_IS_DTLS(rl
->s
))
1692 return rl
->tlsrecs
[0].version
== SSL2_VERSION
;
1695 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper
;
1696 static void rlayer_msg_callback_wrapper(int write_p
, int version
,
1697 int content_type
, const void *buf
,
1698 size_t len
, void *cbarg
)
1700 SSL_CONNECTION
*s
= cbarg
;
1701 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1703 if (s
->msg_callback
!= NULL
)
1704 s
->msg_callback(write_p
, version
, content_type
, buf
, len
, ssl
,
1705 s
->msg_callback_arg
);
1708 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper
;
1709 static int rlayer_security_wrapper(void *cbarg
, int op
, int bits
, int nid
,
1712 SSL_CONNECTION
*s
= cbarg
;
1714 return ssl_security(s
, op
, bits
, nid
, other
);
1717 static const OSSL_DISPATCH rlayer_dispatch
[] = {
1718 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA
, (void (*)(void))ossl_statem_skip_early_data
},
1719 { OSSL_FUNC_RLAYER_MSG_CALLBACK
, (void (*)(void))rlayer_msg_callback_wrapper
},
1720 { OSSL_FUNC_RLAYER_SECURITY
, (void (*)(void))rlayer_security_wrapper
},
1724 static const OSSL_RECORD_METHOD
*ssl_select_next_record_layer(SSL_CONNECTION
*s
,
1728 if (level
== OSSL_RECORD_PROTECTION_LEVEL_NONE
) {
1729 if (SSL_CONNECTION_IS_DTLS(s
))
1730 return &ossl_dtls_record_method
;
1732 return &ossl_tls_record_method
;
1735 #ifndef OPENSSL_NO_KTLS
1736 /* KTLS does not support renegotiation */
1737 if (level
== OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1738 && (s
->options
& SSL_OP_ENABLE_KTLS
) != 0
1739 && (SSL_CONNECTION_IS_TLS13(s
) || SSL_IS_FIRST_HANDSHAKE(s
)))
1740 return &ossl_ktls_record_method
;
1743 /* Default to the current OSSL_RECORD_METHOD */
1744 return s
->rlayer
.rrlmethod
;
1747 static int ssl_post_record_layer_select(SSL_CONNECTION
*s
)
1749 #ifndef OPENSSL_NO_KTLS
1750 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1752 if (s
->rlayer
.rrlmethod
== &ossl_ktls_record_method
) {
1753 /* KTLS does not support renegotiation so disallow it */
1754 SSL_set_options(ssl
, SSL_OP_NO_RENEGOTIATION
);
1757 if (SSL_IS_FIRST_HANDSHAKE(s
) && s
->rlayer
.rrlmethod
->set_first_handshake
!= NULL
)
1758 s
->rlayer
.rrlmethod
->set_first_handshake(s
->rlayer
.rrl
, 1);
1760 if (s
->max_pipelines
!= 0 && s
->rlayer
.rrlmethod
->set_max_pipelines
!= NULL
)
1761 s
->rlayer
.rrlmethod
->set_max_pipelines(s
->rlayer
.rrl
, s
->max_pipelines
);
1766 int ssl_set_new_record_layer(SSL_CONNECTION
*s
, int version
,
1767 int direction
, int level
,
1768 unsigned char *key
, size_t keylen
,
1769 unsigned char *iv
, size_t ivlen
,
1770 unsigned char *mackey
, size_t mackeylen
,
1771 const EVP_CIPHER
*ciph
, size_t taglen
,
1772 int mactype
, const EVP_MD
*md
,
1773 const SSL_COMP
*comp
)
1775 OSSL_PARAM options
[5], *opts
= options
;
1776 OSSL_PARAM settings
[6], *set
= settings
;
1777 const OSSL_RECORD_METHOD
*origmeth
= s
->rlayer
.rrlmethod
;
1778 SSL_CTX
*sctx
= SSL_CONNECTION_GET_CTX(s
);
1779 const OSSL_RECORD_METHOD
*meth
;
1780 int use_etm
, stream_mac
= 0, tlstree
= 0;
1781 unsigned int maxfrag
= SSL3_RT_MAX_PLAIN_LENGTH
;
1782 int use_early_data
= 0;
1783 uint32_t max_early_data
;
1785 meth
= ssl_select_next_record_layer(s
, level
);
1787 if (s
->rlayer
.rrlmethod
!= NULL
&& !s
->rlayer
.rrlmethod
->free(s
->rlayer
.rrl
)) {
1788 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1792 s
->rlayer
.rrl
= NULL
;
1794 s
->rlayer
.rrlmethod
= meth
;
1796 if (!ossl_assert(s
->rlayer
.rrlmethod
!= NULL
)) {
1797 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1801 /* Parameters that *may* be supported by a record layer if passed */
1802 *opts
++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS
,
1804 *opts
++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE
,
1806 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN
,
1807 &s
->rlayer
.default_read_buf_len
);
1808 *opts
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD
,
1809 &s
->rlayer
.read_ahead
);
1810 *opts
= OSSL_PARAM_construct_end();
1812 /* Parameters that *must* be supported by a record layer if passed */
1813 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1814 use_etm
= SSL_READ_ETM(s
) ? 1 : 0;
1815 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_STREAM
) != 0)
1818 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_TLSTREE
) != 0)
1821 use_etm
= SSL_WRITE_ETM(s
) ? 1 : 0;
1822 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_STREAM
) != 0)
1825 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_TLSTREE
) != 0)
1830 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM
,
1834 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC
,
1838 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE
,
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
,
1849 * The record layer must check the amount of early data sent or received
1850 * using the early keys. A server also needs to worry about rejected early
1851 * data that might arrive when the handshake keys are in force.
1853 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1854 if (s
->server
&& direction
== OSSL_RECORD_DIRECTION_READ
) {
1855 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
1856 || level
== OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
);
1857 } else if (!s
->server
&& direction
== OSSL_RECORD_DIRECTION_WRITE
) {
1858 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
);
1860 if (use_early_data
) {
1861 max_early_data
= ossl_get_max_early_data(s
);
1863 if (max_early_data
!= 0)
1864 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA
,
1868 *set
= OSSL_PARAM_construct_end();
1872 BIO
*prev
= s
->rlayer
.rrlnext
;
1873 unsigned int epoch
= 0;;
1875 if (SSL_CONNECTION_IS_DTLS(s
)
1876 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1877 epoch
= DTLS_RECORD_LAYER_get_r_epoch(&s
->rlayer
) + 1; /* new epoch */
1879 if (SSL_CONNECTION_IS_DTLS(s
))
1880 s
->rlayer
.rrlnext
= BIO_new(BIO_s_dgram_mem());
1882 s
->rlayer
.rrlnext
= BIO_new(BIO_s_mem());
1884 if (s
->rlayer
.rrlnext
== NULL
) {
1886 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1890 rlret
= s
->rlayer
.rrlmethod
->new_record_layer(sctx
->libctx
,
1893 direction
, level
, epoch
,
1894 key
, keylen
, iv
, ivlen
,
1895 mackey
, mackeylen
, ciph
,
1896 taglen
, mactype
, md
, comp
,
1898 s
->rlayer
.rrlnext
, NULL
,
1899 NULL
, settings
, options
,
1904 case OSSL_RECORD_RETURN_FATAL
:
1905 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_RECORD_LAYER_FAILURE
);
1908 case OSSL_RECORD_RETURN_NON_FATAL_ERR
:
1909 if (s
->rlayer
.rrlmethod
!= origmeth
&& origmeth
!= NULL
) {
1911 * We tried a new record layer method, but it didn't work out,
1912 * so we fallback to the original method and try again
1914 s
->rlayer
.rrlmethod
= origmeth
;
1917 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_NO_SUITABLE_RECORD_LAYER
);
1920 case OSSL_RECORD_RETURN_SUCCESS
:
1924 /* Should not happen */
1925 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1931 return ssl_post_record_layer_select(s
);