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 void RECORD_LAYER_init(RECORD_LAYER
*rl
, SSL_CONNECTION
*s
)
26 void RECORD_LAYER_clear(RECORD_LAYER
*rl
)
29 memset(rl
->handshake_fragment
, 0, sizeof(rl
->handshake_fragment
));
30 rl
->handshake_fragment_len
= 0;
36 if (rl
->rrlmethod
!= NULL
)
37 rl
->rrlmethod
->free(rl
->rrl
); /* Ignore return value */
38 if (rl
->wrlmethod
!= NULL
)
39 rl
->wrlmethod
->free(rl
->wrl
); /* Ignore return value */
40 BIO_free(rl
->rrlnext
);
48 DTLS_RECORD_LAYER_clear(rl
);
51 /* Checks if we have unprocessed read ahead data pending */
52 int RECORD_LAYER_read_pending(const RECORD_LAYER
*rl
)
54 return rl
->rrlmethod
->unprocessed_read_pending(rl
->rrl
);
57 /* Checks if we have decrypted unread record data pending */
58 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER
*rl
)
60 return (rl
->curr_rec
< rl
->num_recs
)
61 || rl
->rrlmethod
->processed_read_pending(rl
->rrl
);
64 int RECORD_LAYER_write_pending(const RECORD_LAYER
*rl
)
66 return rl
->wpend_tot
> 0;
69 size_t ssl3_pending(const SSL
*s
)
72 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
77 if (SSL_CONNECTION_IS_DTLS(sc
)) {
81 iter
= pqueue_iterator(sc
->rlayer
.d
->buffered_app_data
.q
);
82 while ((item
= pqueue_next(&iter
)) != NULL
) {
88 for (i
= 0; i
< sc
->rlayer
.num_recs
; i
++) {
89 if (sc
->rlayer
.tlsrecs
[i
].type
!= SSL3_RT_APPLICATION_DATA
)
91 num
+= sc
->rlayer
.tlsrecs
[i
].length
;
94 num
+= sc
->rlayer
.rrlmethod
->app_data_pending(sc
->rlayer
.rrl
);
99 void SSL_CTX_set_default_read_buffer_len(SSL_CTX
*ctx
, size_t len
)
101 ctx
->default_read_buf_len
= len
;
104 void SSL_set_default_read_buffer_len(SSL
*s
, size_t len
)
106 SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_SSL(s
);
110 sc
->rlayer
.default_read_buf_len
= len
;
113 const char *SSL_rstate_string_long(const SSL
*s
)
115 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
121 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
124 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, NULL
, &lng
);
129 const char *SSL_rstate_string(const SSL
*s
)
131 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
137 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
140 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, &shrt
, NULL
);
145 static int tls_write_check_pending(SSL_CONNECTION
*s
, int type
,
146 const unsigned char *buf
, size_t len
)
148 if (s
->rlayer
.wpend_tot
== 0)
151 /* We have pending data, so do some sanity checks */
152 if ((s
->rlayer
.wpend_tot
> len
)
153 || (!(s
->mode
& SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
)
154 && (s
->rlayer
.wpend_buf
!= buf
))
155 || (s
->rlayer
.wpend_type
!= type
)) {
156 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_WRITE_RETRY
);
163 * Call this to write data in records of type 'type' It will return <= 0 if
164 * not all data has been sent or non-blocking IO.
166 int ssl3_write_bytes(SSL
*ssl
, int type
, const void *buf_
, size_t len
,
169 const unsigned char *buf
= buf_
;
171 size_t n
, max_send_fragment
, split_send_fragment
, maxpipes
;
173 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
174 OSSL_RECORD_TEMPLATE tmpls
[SSL_MAX_PIPELINES
];
175 unsigned int recversion
;
180 s
->rwstate
= SSL_NOTHING
;
181 tot
= s
->rlayer
.wnum
;
183 * ensure that if we end up with a smaller value of data to write out
184 * than the original len from a write which didn't complete for
185 * non-blocking I/O and also somehow ended up avoiding the check for
186 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
187 * possible to end up with (len-tot) as a large number that will then
188 * promptly send beyond the end of the users buffer ... so we trap and
189 * report the error in a way the user will notice
191 if ((len
< s
->rlayer
.wnum
)
192 || ((s
->rlayer
.wpend_tot
!= 0)
193 && (len
< (s
->rlayer
.wnum
+ s
->rlayer
.wpend_tot
)))) {
194 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_LENGTH
);
198 if (s
->early_data_state
== SSL_EARLY_DATA_WRITING
199 && !ossl_early_data_count_ok(s
, len
, 0, 1)) {
200 /* SSLfatal() already called */
207 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
208 * into init unless we have writes pending - in which case we should finish
211 if (s
->rlayer
.wpend_tot
== 0 && (s
->key_update
!= SSL_KEY_UPDATE_NONE
212 || s
->ext
.extra_tickets_expected
> 0))
213 ossl_statem_set_in_init(s
, 1);
216 * When writing early data on the server side we could be "in_init" in
217 * between receiving the EoED and the CF - but we don't want to handle those
220 if (SSL_in_init(ssl
) && !ossl_statem_get_in_handshake(s
)
221 && s
->early_data_state
!= SSL_EARLY_DATA_UNAUTH_WRITING
) {
222 i
= s
->handshake_func(ssl
);
223 /* SSLfatal() already called */
231 i
= tls_write_check_pending(s
, type
, buf
, len
);
233 /* SSLfatal() already called */
237 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
238 s
->rlayer
.wrlmethod
->retry_write_records(s
->rlayer
.wrl
));
241 tot
+= s
->rlayer
.wpend_tot
;
242 s
->rlayer
.wpend_tot
= 0;
243 } /* else no retry required */
247 * We've not previously sent any data for this write so memorize
248 * arguments so that we can detect bad write retries later
250 s
->rlayer
.wpend_tot
= 0;
251 s
->rlayer
.wpend_type
= type
;
252 s
->rlayer
.wpend_buf
= buf
;
253 s
->rlayer
.wpend_ret
= len
;
256 if (tot
== len
) { /* done? */
261 /* If we have an alert to send, lets send it */
262 if (s
->s3
.alert_dispatch
) {
263 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
265 /* SSLfatal() already called if appropriate */
268 /* if it went, fall through and send more stuff */
273 max_send_fragment
= ssl_get_max_send_fragment(s
);
274 split_send_fragment
= ssl_get_split_send_fragment(s
);
276 if (max_send_fragment
== 0
277 || split_send_fragment
== 0
278 || split_send_fragment
> max_send_fragment
) {
280 * We should have prevented this when we set/get the split and max send
281 * fragments so we shouldn't get here
283 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
288 * Some servers hang if initial client hello is larger than 256 bytes
289 * and record version number > TLS 1.0
291 recversion
= (s
->version
== TLS1_3_VERSION
) ? TLS1_2_VERSION
: s
->version
;
292 if (SSL_get_state(ssl
) == TLS_ST_CW_CLNT_HELLO
294 && TLS1_get_version(ssl
) > TLS1_VERSION
295 && s
->hello_retry_request
== SSL_HRR_NONE
)
296 recversion
= TLS1_VERSION
;
299 size_t tmppipelen
, remain
;
300 size_t j
, lensofar
= 0;
303 * Ask the record layer how it would like to split the amount of data
304 * that we have, and how many of those records it would like in one go.
306 maxpipes
= s
->rlayer
.wrlmethod
->get_max_records(s
->rlayer
.wrl
, type
, n
,
308 &split_send_fragment
);
310 * If max_pipelines is 0 then this means "undefined" and we default to
311 * whatever the record layer wants to do. Otherwise we use the smallest
312 * value from the number requested by the record layer, and max number
313 * configured by the user.
315 if (s
->max_pipelines
> 0 && maxpipes
> s
->max_pipelines
)
316 maxpipes
= s
->max_pipelines
;
318 if (maxpipes
> SSL_MAX_PIPELINES
)
319 maxpipes
= SSL_MAX_PIPELINES
;
321 if (split_send_fragment
> max_send_fragment
) {
322 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
326 if (n
/ maxpipes
>= split_send_fragment
) {
328 * We have enough data to completely fill all available
331 for (j
= 0; j
< maxpipes
; j
++) {
332 tmpls
[j
].type
= type
;
333 tmpls
[j
].version
= recversion
;
334 tmpls
[j
].buf
= &(buf
[tot
]) + (j
* split_send_fragment
);
335 tmpls
[j
].buflen
= split_send_fragment
;
337 /* Remember how much data we are going to be sending */
338 s
->rlayer
.wpend_tot
= maxpipes
* split_send_fragment
;
340 /* We can partially fill all available pipelines */
341 tmppipelen
= n
/ maxpipes
;
342 remain
= n
% maxpipes
;
344 * If there is a remainder we add an extra byte to the first few
349 for (j
= 0; j
< maxpipes
; j
++) {
350 tmpls
[j
].type
= type
;
351 tmpls
[j
].version
= recversion
;
352 tmpls
[j
].buf
= &(buf
[tot
]) + lensofar
;
353 tmpls
[j
].buflen
= tmppipelen
;
354 lensofar
+= tmppipelen
;
358 /* Remember how much data we are going to be sending */
359 s
->rlayer
.wpend_tot
= n
;
362 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
363 s
->rlayer
.wrlmethod
->write_records(s
->rlayer
.wrl
, tmpls
, maxpipes
));
365 /* SSLfatal() already called if appropriate */
366 s
->rlayer
.wnum
= tot
;
370 if (s
->rlayer
.wpend_tot
== n
371 || (type
== SSL3_RT_APPLICATION_DATA
372 && (s
->mode
& SSL_MODE_ENABLE_PARTIAL_WRITE
) != 0)) {
373 *written
= tot
+ s
->rlayer
.wpend_tot
;
374 s
->rlayer
.wpend_tot
= 0;
378 n
-= s
->rlayer
.wpend_tot
;
379 tot
+= s
->rlayer
.wpend_tot
;
383 int ossl_tls_handle_rlayer_return(SSL_CONNECTION
*s
, int writing
, int ret
,
384 char *file
, int line
)
386 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
388 if (ret
== OSSL_RECORD_RETURN_RETRY
) {
389 s
->rwstate
= writing
? SSL_WRITING
: SSL_READING
;
392 s
->rwstate
= SSL_NOTHING
;
393 if (ret
== OSSL_RECORD_RETURN_EOF
) {
396 * This shouldn't happen with a writing operation. We treat it
400 ERR_set_debug(file
, line
, 0);
401 ossl_statem_fatal(s
, SSL_AD_INTERNAL_ERROR
,
402 ERR_R_INTERNAL_ERROR
, NULL
);
403 ret
= OSSL_RECORD_RETURN_FATAL
;
404 } else if ((s
->options
& SSL_OP_IGNORE_UNEXPECTED_EOF
) != 0) {
405 SSL_set_shutdown(ssl
, SSL_RECEIVED_SHUTDOWN
);
406 s
->s3
.warn_alert
= SSL_AD_CLOSE_NOTIFY
;
409 ERR_set_debug(file
, line
, 0);
410 ossl_statem_fatal(s
, SSL_AD_DECODE_ERROR
,
411 SSL_R_UNEXPECTED_EOF_WHILE_READING
, NULL
);
413 } else if (ret
== OSSL_RECORD_RETURN_FATAL
) {
414 int al
= s
->rlayer
.rrlmethod
->get_alert_code(s
->rlayer
.rrl
);
416 if (al
!= SSL_AD_NO_ALERT
) {
418 ERR_set_debug(file
, line
, 0);
419 ossl_statem_fatal(s
, al
, SSL_R_RECORD_LAYER_FAILURE
, NULL
);
422 * else some failure but there is no alert code. We don't log an
423 * error for this. The record layer should have logged an error
424 * already or, if not, its due to some sys call error which will be
425 * reported via SSL_ERROR_SYSCALL and errno.
429 * The record layer distinguishes the cases of EOF, non-fatal
430 * err and retry. Upper layers do not.
431 * If we got a retry or success then *ret is already correct,
432 * otherwise we need to convert the return value.
434 if (ret
== OSSL_RECORD_RETURN_NON_FATAL_ERR
|| ret
== OSSL_RECORD_RETURN_EOF
)
436 else if (ret
< OSSL_RECORD_RETURN_NON_FATAL_ERR
)
443 void ssl_release_record(SSL_CONNECTION
*s
, TLS_RECORD
*rr
)
445 if (rr
->rechandle
!= NULL
) {
446 /* The record layer allocated the buffers for this record */
447 s
->rlayer
.rrlmethod
->release_record(s
->rlayer
.rrl
, rr
->rechandle
);
449 /* We allocated the buffers for this record (only happens with DTLS) */
450 OPENSSL_free(rr
->data
);
452 s
->rlayer
.curr_rec
++;
456 * Return up to 'len' payload bytes received in 'type' records.
457 * 'type' is one of the following:
459 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
460 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
461 * - 0 (during a shutdown, no data has to be returned)
463 * If we don't have stored data to work from, read a SSL/TLS record first
464 * (possibly multiple records if we still don't have anything to return).
466 * This function must handle any surprises the peer may have for us, such as
467 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
468 * messages are treated as if they were handshake messages *if* the |recvd_type|
469 * argument is non NULL.
470 * Also if record payloads contain fragments too small to process, we store
471 * them until there is enough for the respective protocol (the record protocol
472 * may use arbitrary fragmentation and even interleaving):
473 * Change cipher spec protocol
474 * just 1 byte needed, no need for keeping anything stored
476 * 2 bytes needed (AlertLevel, AlertDescription)
478 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
479 * to detect unexpected Client Hello and Hello Request messages
480 * here, anything else is handled by higher layers
481 * Application data protocol
482 * none of our business
484 int ssl3_read_bytes(SSL
*ssl
, int type
, int *recvd_type
, unsigned char *buf
,
485 size_t len
, int peek
, size_t *readbytes
)
488 size_t n
, curr_rec
, totalbytes
;
490 void (*cb
) (const SSL
*ssl
, int type2
, int val
) = NULL
;
492 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
494 is_tls13
= SSL_CONNECTION_IS_TLS13(s
);
497 && (type
!= SSL3_RT_APPLICATION_DATA
)
498 && (type
!= SSL3_RT_HANDSHAKE
))
499 || (peek
&& (type
!= SSL3_RT_APPLICATION_DATA
))) {
500 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
504 if ((type
== SSL3_RT_HANDSHAKE
) && (s
->rlayer
.handshake_fragment_len
> 0))
505 /* (partially) satisfy request from storage */
507 unsigned char *src
= s
->rlayer
.handshake_fragment
;
508 unsigned char *dst
= buf
;
513 while ((len
> 0) && (s
->rlayer
.handshake_fragment_len
> 0)) {
516 s
->rlayer
.handshake_fragment_len
--;
519 /* move any remaining fragment bytes: */
520 for (k
= 0; k
< s
->rlayer
.handshake_fragment_len
; k
++)
521 s
->rlayer
.handshake_fragment
[k
] = *src
++;
523 if (recvd_type
!= NULL
)
524 *recvd_type
= SSL3_RT_HANDSHAKE
;
531 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
534 if (!ossl_statem_get_in_handshake(s
) && SSL_in_init(ssl
)) {
535 /* type == SSL3_RT_APPLICATION_DATA */
536 i
= s
->handshake_func(ssl
);
537 /* SSLfatal() already called */
544 s
->rwstate
= SSL_NOTHING
;
547 * For each record 'i' up to |num_recs]
548 * rr[i].type - is the type of record
550 * rr[i].off, - offset into 'data' for next read
551 * rr[i].length, - number of bytes.
553 /* get new records if necessary */
554 if (s
->rlayer
.curr_rec
>= s
->rlayer
.num_recs
) {
555 s
->rlayer
.curr_rec
= s
->rlayer
.num_recs
= 0;
557 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.num_recs
];
559 ret
= HANDLE_RLAYER_READ_RETURN(s
,
560 s
->rlayer
.rrlmethod
->read_record(s
->rlayer
.rrl
,
562 &rr
->version
, &rr
->type
,
563 &rr
->data
, &rr
->length
,
566 /* SSLfatal() already called if appropriate */
570 s
->rlayer
.num_recs
++;
571 } while (s
->rlayer
.rrlmethod
->processed_read_pending(s
->rlayer
.rrl
)
572 && s
->rlayer
.num_recs
< SSL_MAX_PIPELINES
);
574 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.curr_rec
];
576 if (s
->rlayer
.handshake_fragment_len
> 0
577 && rr
->type
!= SSL3_RT_HANDSHAKE
578 && SSL_CONNECTION_IS_TLS13(s
)) {
579 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
580 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA
);
585 * Reset the count of consecutive warning alerts if we've got a non-empty
586 * record that isn't an alert.
588 if (rr
->type
!= SSL3_RT_ALERT
&& rr
->length
!= 0)
589 s
->rlayer
.alert_count
= 0;
591 /* we now have a packet which can be read and processed */
593 if (s
->s3
.change_cipher_spec
/* set when we receive ChangeCipherSpec,
594 * reset by ssl3_get_finished */
595 && (rr
->type
!= SSL3_RT_HANDSHAKE
)) {
596 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
597 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED
);
602 * If the other end has shut down, throw anything we read away (even in
605 if (s
->shutdown
& SSL_RECEIVED_SHUTDOWN
) {
606 s
->rlayer
.curr_rec
++;
607 s
->rwstate
= SSL_NOTHING
;
612 || (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
613 && type
== SSL3_RT_HANDSHAKE
&& recvd_type
!= NULL
616 * SSL3_RT_APPLICATION_DATA or
617 * SSL3_RT_HANDSHAKE or
618 * SSL3_RT_CHANGE_CIPHER_SPEC
621 * make sure that we are not getting application data when we are
622 * doing a handshake for the first time
624 if (SSL_in_init(ssl
) && type
== SSL3_RT_APPLICATION_DATA
625 && s
->enc_read_ctx
== NULL
) {
626 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_APP_DATA_IN_HANDSHAKE
);
630 if (type
== SSL3_RT_HANDSHAKE
631 && rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
632 && s
->rlayer
.handshake_fragment_len
> 0) {
633 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
637 if (recvd_type
!= NULL
)
638 *recvd_type
= rr
->type
;
642 * Skip a zero length record. This ensures multiple calls to
643 * SSL_read() with a zero length buffer will eventually cause
644 * SSL_pending() to report data as being available.
647 ssl_release_record(s
, rr
);
653 curr_rec
= s
->rlayer
.curr_rec
;
655 if (len
- totalbytes
> rr
->length
)
658 n
= len
- totalbytes
;
660 memcpy(buf
, &(rr
->data
[rr
->off
]), n
);
663 /* Mark any zero length record as consumed CVE-2016-6305 */
665 ssl_release_record(s
, rr
);
667 if (s
->options
& SSL_OP_CLEANSE_PLAINTEXT
)
668 OPENSSL_cleanse(&(rr
->data
[rr
->off
]), n
);
672 ssl_release_record(s
, rr
);
675 || (peek
&& n
== rr
->length
)) {
680 } while (type
== SSL3_RT_APPLICATION_DATA
681 && curr_rec
< s
->rlayer
.num_recs
682 && totalbytes
< len
);
683 if (totalbytes
== 0) {
684 /* We must have read empty records. Get more data */
687 *readbytes
= totalbytes
;
692 * If we get here, then type != rr->type; if we have a handshake message,
693 * then it was unexpected (Hello Request or Client Hello) or invalid (we
694 * were actually expecting a CCS).
698 * Lets just double check that we've not got an SSLv2 record
700 if (rr
->version
== SSL2_VERSION
) {
702 * Should never happen. ssl3_get_record() should only give us an SSLv2
703 * record back if this is the first packet and we are looking for an
704 * initial ClientHello. Therefore |type| should always be equal to
705 * |rr->type|. If not then something has gone horribly wrong
707 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
711 if (ssl
->method
->version
== TLS_ANY_VERSION
712 && (s
->server
|| rr
->type
!= SSL3_RT_ALERT
)) {
714 * If we've got this far and still haven't decided on what version
715 * we're using then this must be a client side alert we're dealing
716 * with. We shouldn't be receiving anything other than a ClientHello
717 * if we are a server.
719 s
->version
= rr
->version
;
720 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_MESSAGE
);
725 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
726 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
729 if (rr
->type
== SSL3_RT_ALERT
) {
730 unsigned int alert_level
, alert_descr
;
731 unsigned char *alert_bytes
= rr
->data
735 if (!PACKET_buf_init(&alert
, alert_bytes
, rr
->length
)
736 || !PACKET_get_1(&alert
, &alert_level
)
737 || !PACKET_get_1(&alert
, &alert_descr
)
738 || PACKET_remaining(&alert
) != 0) {
739 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_INVALID_ALERT
);
744 s
->msg_callback(0, s
->version
, SSL3_RT_ALERT
, alert_bytes
, 2, ssl
,
745 s
->msg_callback_arg
);
747 if (s
->info_callback
!= NULL
)
748 cb
= s
->info_callback
;
749 else if (ssl
->ctx
->info_callback
!= NULL
)
750 cb
= ssl
->ctx
->info_callback
;
753 j
= (alert_level
<< 8) | alert_descr
;
754 cb(ssl
, SSL_CB_READ_ALERT
, j
);
757 if ((!is_tls13
&& alert_level
== SSL3_AL_WARNING
)
758 || (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
)) {
759 s
->s3
.warn_alert
= alert_descr
;
760 ssl_release_record(s
, rr
);
762 s
->rlayer
.alert_count
++;
763 if (s
->rlayer
.alert_count
== MAX_WARN_ALERT_COUNT
) {
764 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
765 SSL_R_TOO_MANY_WARN_ALERTS
);
771 * Apart from close_notify the only other warning alert in TLSv1.3
772 * is user_cancelled - which we just ignore.
774 if (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
) {
776 } else if (alert_descr
== SSL_AD_CLOSE_NOTIFY
777 && (is_tls13
|| alert_level
== SSL3_AL_WARNING
)) {
778 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
780 } else if (alert_level
== SSL3_AL_FATAL
|| is_tls13
) {
781 s
->rwstate
= SSL_NOTHING
;
782 s
->s3
.fatal_alert
= alert_descr
;
783 SSLfatal_data(s
, SSL_AD_NO_ALERT
,
784 SSL_AD_REASON_OFFSET
+ alert_descr
,
785 "SSL alert number %d", alert_descr
);
786 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
787 ssl_release_record(s
, rr
);
788 SSL_CTX_remove_session(s
->session_ctx
, s
->session
);
790 } else if (alert_descr
== SSL_AD_NO_RENEGOTIATION
) {
792 * This is a warning but we receive it if we requested
793 * renegotiation and the peer denied it. Terminate with a fatal
794 * alert because if application tried to renegotiate it
795 * presumably had a good reason and expects it to succeed. In
796 * future we might have a renegotiation where we don't care if
797 * the peer refused it where we carry on.
799 SSLfatal(s
, SSL_AD_HANDSHAKE_FAILURE
, SSL_R_NO_RENEGOTIATION
);
801 } else if (alert_level
== SSL3_AL_WARNING
) {
802 /* We ignore any other warning alert in TLSv1.2 and below */
806 SSLfatal(s
, SSL_AD_ILLEGAL_PARAMETER
, SSL_R_UNKNOWN_ALERT_TYPE
);
810 if ((s
->shutdown
& SSL_SENT_SHUTDOWN
) != 0) {
811 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
815 * We ignore any handshake messages sent to us unless they are
816 * TLSv1.3 in which case we want to process them. For all other
817 * handshake messages we can't do anything reasonable with them
818 * because we are unable to write any response due to having already
821 if (!SSL_CONNECTION_IS_TLS13(s
)) {
822 ssl_release_record(s
, rr
);
824 if ((s
->mode
& SSL_MODE_AUTO_RETRY
) != 0)
827 s
->rwstate
= SSL_READING
;
828 rbio
= SSL_get_rbio(ssl
);
829 BIO_clear_retry_flags(rbio
);
830 BIO_set_retry_read(rbio
);
835 * The peer is continuing to send application data, but we have
836 * already sent close_notify. If this was expected we should have
837 * been called via SSL_read() and this would have been handled
839 * No alert sent because we already sent close_notify
841 ssl_release_record(s
, rr
);
842 SSLfatal(s
, SSL_AD_NO_ALERT
,
843 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY
);
849 * For handshake data we have 'fragment' storage, so fill that so that we
850 * can process the header at a fixed place. This is done after the
851 * "SHUTDOWN" code above to avoid filling the fragment storage with data
852 * that we're just going to discard.
854 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
855 size_t dest_maxlen
= sizeof(s
->rlayer
.handshake_fragment
);
856 unsigned char *dest
= s
->rlayer
.handshake_fragment
;
857 size_t *dest_len
= &s
->rlayer
.handshake_fragment_len
;
859 n
= dest_maxlen
- *dest_len
; /* available space in 'dest' */
861 n
= rr
->length
; /* available bytes */
863 /* now move 'n' bytes: */
864 memcpy(dest
+ *dest_len
, rr
->data
+ rr
->off
, n
);
869 ssl_release_record(s
, rr
);
871 if (*dest_len
< dest_maxlen
)
872 goto start
; /* fragment was too small */
875 if (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
) {
876 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
881 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
882 * protocol violation)
884 if ((s
->rlayer
.handshake_fragment_len
>= 4)
885 && !ossl_statem_get_in_handshake(s
)) {
886 int ined
= (s
->early_data_state
== SSL_EARLY_DATA_READING
);
888 /* We found handshake data, so we're going back into init */
889 ossl_statem_set_in_init(s
, 1);
891 i
= s
->handshake_func(ssl
);
892 /* SSLfatal() already called if appropriate */
900 * If we were actually trying to read early data and we found a
901 * handshake message, then we don't want to continue to try and read
902 * the application data any more. It won't be "early" now.
907 if (!(s
->mode
& SSL_MODE_AUTO_RETRY
)) {
908 if (!RECORD_LAYER_read_pending(&s
->rlayer
)) {
911 * In the case where we try to read application data, but we
912 * trigger an SSL handshake, we return -1 with the retry
913 * option set. Otherwise renegotiation may cause nasty
914 * problems in the blocking world
916 s
->rwstate
= SSL_READING
;
917 bio
= SSL_get_rbio(ssl
);
918 BIO_clear_retry_flags(bio
);
919 BIO_set_retry_read(bio
);
929 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
930 * TLS 1.2 says you MUST send an unexpected message alert. We use the
931 * TLS 1.2 behaviour for all protocol versions to prevent issues where
932 * no progress is being made and the peer continually sends unrecognised
933 * record types, using up resources processing them.
935 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
937 case SSL3_RT_CHANGE_CIPHER_SPEC
:
939 case SSL3_RT_HANDSHAKE
:
941 * we already handled all of these, with the possible exception of
942 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
943 * that should not happen when type != rr->type
945 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, ERR_R_INTERNAL_ERROR
);
947 case SSL3_RT_APPLICATION_DATA
:
949 * At this point, we were expecting handshake data, but have
950 * application data. If the library was running inside ssl3_read()
951 * (i.e. in_read_app_data is set) and it makes sense to read
952 * application data at this point (session renegotiation not yet
953 * started), we will indulge it.
955 if (ossl_statem_app_data_allowed(s
)) {
956 s
->s3
.in_read_app_data
= 2;
958 } else if (ossl_statem_skip_early_data(s
)) {
960 * This can happen after a client sends a CH followed by early_data,
961 * but the server responds with a HelloRetryRequest. The server
962 * reads the next record from the client expecting to find a
963 * plaintext ClientHello but gets a record which appears to be
964 * application data. The trial decrypt "works" because null
965 * decryption was applied. We just skip it and move on to the next
968 if (!ossl_early_data_count_ok(s
, rr
->length
,
969 EARLY_DATA_CIPHERTEXT_OVERHEAD
, 0)) {
970 /* SSLfatal() already called */
973 ssl_release_record(s
, rr
);
976 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
983 * Returns true if the current rrec was sent in SSLv2 backwards compatible
984 * format and false otherwise.
986 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER
*rl
)
988 if (SSL_CONNECTION_IS_DTLS(rl
->s
))
990 return rl
->tlsrecs
[0].version
== SSL2_VERSION
;
993 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper
;
994 static void rlayer_msg_callback_wrapper(int write_p
, int version
,
995 int content_type
, const void *buf
,
996 size_t len
, void *cbarg
)
998 SSL_CONNECTION
*s
= cbarg
;
999 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1001 if (s
->msg_callback
!= NULL
)
1002 s
->msg_callback(write_p
, version
, content_type
, buf
, len
, ssl
,
1003 s
->msg_callback_arg
);
1006 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper
;
1007 static int rlayer_security_wrapper(void *cbarg
, int op
, int bits
, int nid
,
1010 SSL_CONNECTION
*s
= cbarg
;
1012 return ssl_security(s
, op
, bits
, nid
, other
);
1015 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper
;
1016 static size_t rlayer_padding_wrapper(void *cbarg
, int type
, size_t len
)
1018 SSL_CONNECTION
*s
= cbarg
;
1019 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1021 return s
->rlayer
.record_padding_cb(ssl
, type
, len
,
1022 s
->rlayer
.record_padding_arg
);
1025 static const OSSL_DISPATCH rlayer_dispatch
[] = {
1026 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA
, (void (*)(void))ossl_statem_skip_early_data
},
1027 { OSSL_FUNC_RLAYER_MSG_CALLBACK
, (void (*)(void))rlayer_msg_callback_wrapper
},
1028 { OSSL_FUNC_RLAYER_SECURITY
, (void (*)(void))rlayer_security_wrapper
},
1029 { OSSL_FUNC_RLAYER_PADDING
, (void (*)(void))rlayer_padding_wrapper
},
1033 static const OSSL_RECORD_METHOD
*ssl_select_next_record_layer(SSL_CONNECTION
*s
,
1038 if (level
== OSSL_RECORD_PROTECTION_LEVEL_NONE
) {
1039 if (SSL_CONNECTION_IS_DTLS(s
))
1040 return &ossl_dtls_record_method
;
1042 return &ossl_tls_record_method
;
1045 #ifndef OPENSSL_NO_KTLS
1046 /* KTLS does not support renegotiation */
1047 if (level
== OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1048 && (s
->options
& SSL_OP_ENABLE_KTLS
) != 0
1049 && (SSL_CONNECTION_IS_TLS13(s
) || SSL_IS_FIRST_HANDSHAKE(s
)))
1050 return &ossl_ktls_record_method
;
1053 /* Default to the current OSSL_RECORD_METHOD */
1054 return direction
== OSSL_RECORD_DIRECTION_READ
? s
->rlayer
.rrlmethod
1055 : s
->rlayer
.wrlmethod
;
1058 static int ssl_post_record_layer_select(SSL_CONNECTION
*s
, int direction
)
1060 const OSSL_RECORD_METHOD
*thismethod
;
1061 OSSL_RECORD_LAYER
*thisrl
;
1063 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1064 thismethod
= s
->rlayer
.rrlmethod
;
1065 thisrl
= s
->rlayer
.rrl
;
1067 thismethod
= s
->rlayer
.wrlmethod
;
1068 thisrl
= s
->rlayer
.wrl
;
1071 #ifndef OPENSSL_NO_KTLS
1073 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1075 if (s
->rlayer
.rrlmethod
== &ossl_ktls_record_method
) {
1076 /* KTLS does not support renegotiation so disallow it */
1077 SSL_set_options(ssl
, SSL_OP_NO_RENEGOTIATION
);
1081 if (SSL_IS_FIRST_HANDSHAKE(s
) && thismethod
->set_first_handshake
!= NULL
)
1082 thismethod
->set_first_handshake(thisrl
, 1);
1084 if (s
->max_pipelines
!= 0 && thismethod
->set_max_pipelines
!= NULL
)
1085 thismethod
->set_max_pipelines(thisrl
, s
->max_pipelines
);
1090 int ssl_set_new_record_layer(SSL_CONNECTION
*s
, int version
,
1091 int direction
, int level
,
1092 unsigned char *key
, size_t keylen
,
1093 unsigned char *iv
, size_t ivlen
,
1094 unsigned char *mackey
, size_t mackeylen
,
1095 const EVP_CIPHER
*ciph
, size_t taglen
,
1096 int mactype
, const EVP_MD
*md
,
1097 const SSL_COMP
*comp
)
1099 OSSL_PARAM options
[5], *opts
= options
;
1100 OSSL_PARAM settings
[6], *set
= settings
;
1101 const OSSL_RECORD_METHOD
**thismethod
;
1102 OSSL_RECORD_LAYER
**thisrl
, *newrl
= NULL
;
1104 SSL_CTX
*sctx
= SSL_CONNECTION_GET_CTX(s
);
1105 const OSSL_RECORD_METHOD
*meth
;
1106 int use_etm
, stream_mac
= 0, tlstree
= 0;
1107 unsigned int maxfrag
= (direction
== OSSL_RECORD_DIRECTION_WRITE
)
1108 ? ssl_get_max_send_fragment(s
)
1109 : SSL3_RT_MAX_PLAIN_LENGTH
;
1110 int use_early_data
= 0;
1111 uint32_t max_early_data
;
1112 COMP_METHOD
*compm
= (comp
== NULL
) ? NULL
: comp
->method
;
1114 meth
= ssl_select_next_record_layer(s
, direction
, level
);
1116 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1117 thismethod
= &s
->rlayer
.rrlmethod
;
1118 thisrl
= &s
->rlayer
.rrl
;
1121 thismethod
= &s
->rlayer
.wrlmethod
;
1122 thisrl
= &s
->rlayer
.wrl
;
1129 if (!ossl_assert(meth
!= NULL
)) {
1130 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1134 /* Parameters that *may* be supported by a record layer if passed */
1135 *opts
++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS
,
1137 *opts
++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE
,
1139 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1140 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN
,
1141 &s
->rlayer
.default_read_buf_len
);
1142 *opts
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD
,
1143 &s
->rlayer
.read_ahead
);
1145 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING
,
1146 &s
->rlayer
.block_padding
);
1148 *opts
= OSSL_PARAM_construct_end();
1150 /* Parameters that *must* be supported by a record layer if passed */
1151 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1152 use_etm
= SSL_READ_ETM(s
) ? 1 : 0;
1153 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_STREAM
) != 0)
1156 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_TLSTREE
) != 0)
1159 use_etm
= SSL_WRITE_ETM(s
) ? 1 : 0;
1160 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_STREAM
) != 0)
1163 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_TLSTREE
) != 0)
1168 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM
,
1172 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC
,
1176 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE
,
1180 * We only need to do this for the read side. The write side should already
1181 * have the correct value due to the ssl_get_max_send_fragment() call above
1183 if (direction
== OSSL_RECORD_DIRECTION_READ
1184 && s
->session
!= NULL
1185 && USE_MAX_FRAGMENT_LENGTH_EXT(s
->session
))
1186 maxfrag
= GET_MAX_FRAGMENT_LENGTH(s
->session
);
1189 if (maxfrag
!= SSL3_RT_MAX_PLAIN_LENGTH
)
1190 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN
,
1194 * The record layer must check the amount of early data sent or received
1195 * using the early keys. A server also needs to worry about rejected early
1196 * data that might arrive when the handshake keys are in force.
1198 if (s
->server
&& direction
== OSSL_RECORD_DIRECTION_READ
) {
1199 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
1200 || level
== OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
);
1201 } else if (!s
->server
&& direction
== OSSL_RECORD_DIRECTION_WRITE
) {
1202 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
);
1204 if (use_early_data
) {
1205 max_early_data
= ossl_get_max_early_data(s
);
1207 if (max_early_data
!= 0)
1208 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA
,
1212 *set
= OSSL_PARAM_construct_end();
1218 unsigned int epoch
= 0;
1219 OSSL_DISPATCH rlayer_dispatch_tmp
[OSSL_NELEM(rlayer_dispatch
)];
1222 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1223 prev
= s
->rlayer
.rrlnext
;
1224 if (SSL_CONNECTION_IS_DTLS(s
)
1225 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1226 epoch
= DTLS_RECORD_LAYER_get_r_epoch(&s
->rlayer
) + 1; /* new epoch */
1228 if (SSL_CONNECTION_IS_DTLS(s
))
1229 next
= BIO_new(BIO_s_dgram_mem());
1231 next
= BIO_new(BIO_s_mem());
1235 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1238 s
->rlayer
.rrlnext
= next
;
1240 if (SSL_CONNECTION_IS_DTLS(s
)
1241 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1242 epoch
= DTLS_RECORD_LAYER_get_w_epoch(&s
->rlayer
) + 1; /* new epoch */
1246 * Create a copy of the dispatch array, missing out wrappers for
1247 * callbacks that we don't need.
1249 for (i
= 0, j
= 0; i
< OSSL_NELEM(rlayer_dispatch
); i
++) {
1250 switch (rlayer_dispatch
[i
].function_id
) {
1251 case OSSL_FUNC_RLAYER_MSG_CALLBACK
:
1252 if (s
->msg_callback
== NULL
)
1255 case OSSL_FUNC_RLAYER_PADDING
:
1256 if (s
->rlayer
.record_padding_cb
== NULL
)
1262 rlayer_dispatch_tmp
[j
++] = rlayer_dispatch
[i
];
1265 rlret
= meth
->new_record_layer(sctx
->libctx
, sctx
->propq
, version
,
1266 s
->server
, direction
, level
, epoch
,
1267 key
, keylen
, iv
, ivlen
, mackey
,
1268 mackeylen
, ciph
, taglen
, mactype
, md
,
1269 compm
, prev
, thisbio
, next
, NULL
, NULL
,
1270 settings
, options
, rlayer_dispatch_tmp
,
1274 case OSSL_RECORD_RETURN_FATAL
:
1275 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_RECORD_LAYER_FAILURE
);
1278 case OSSL_RECORD_RETURN_NON_FATAL_ERR
:
1279 if (*thismethod
!= meth
&& *thismethod
!= NULL
) {
1281 * We tried a new record layer method, but it didn't work out,
1282 * so we fallback to the original method and try again
1287 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_NO_SUITABLE_RECORD_LAYER
);
1290 case OSSL_RECORD_RETURN_SUCCESS
:
1294 /* Should not happen */
1295 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1302 * Free the old record layer if we have one except in the case of DTLS when
1303 * writing. In that case the record layer is still referenced by buffered
1304 * messages for potential retransmit. Only when those buffered messages get
1305 * freed do we free the record layer object (see dtls1_hm_fragment_free)
1307 if (!SSL_CONNECTION_IS_DTLS(s
) || direction
== OSSL_RECORD_DIRECTION_READ
) {
1308 if (*thismethod
!= NULL
&& !(*thismethod
)->free(*thisrl
)) {
1309 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1317 return ssl_post_record_layer_select(s
, direction
);
1320 int ssl_set_record_protocol_version(SSL_CONNECTION
*s
, int vers
)
1322 if (!ossl_assert(s
->rlayer
.rrlmethod
!= NULL
)
1323 || !ossl_assert(s
->rlayer
.wrlmethod
!= NULL
))
1325 s
->rlayer
.rrlmethod
->set_protocol_version(s
->rlayer
.rrl
, s
->version
);
1326 s
->rlayer
.wrlmethod
->set_protocol_version(s
->rlayer
.wrl
, s
->version
);