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 void RECORD_LAYER_release(RECORD_LAYER
*rl
)
54 * TODO(RECLAYER): Need a way to release the write buffers in the record
59 /* Checks if we have unprocessed read ahead data pending */
60 int RECORD_LAYER_read_pending(const RECORD_LAYER
*rl
)
62 return rl
->rrlmethod
->unprocessed_read_pending(rl
->rrl
);
65 /* Checks if we have decrypted unread record data pending */
66 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER
*rl
)
68 return (rl
->curr_rec
< rl
->num_recs
)
69 || rl
->rrlmethod
->processed_read_pending(rl
->rrl
);
72 int RECORD_LAYER_write_pending(const RECORD_LAYER
*rl
)
74 return rl
->wpend_tot
> 0;
77 size_t ssl3_pending(const SSL
*s
)
80 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
85 if (SSL_CONNECTION_IS_DTLS(sc
)) {
89 iter
= pqueue_iterator(sc
->rlayer
.d
->buffered_app_data
.q
);
90 while ((item
= pqueue_next(&iter
)) != NULL
) {
96 for (i
= 0; i
< sc
->rlayer
.num_recs
; i
++) {
97 if (sc
->rlayer
.tlsrecs
[i
].type
!= SSL3_RT_APPLICATION_DATA
)
99 num
+= sc
->rlayer
.tlsrecs
[i
].length
;
102 num
+= sc
->rlayer
.rrlmethod
->app_data_pending(sc
->rlayer
.rrl
);
107 void SSL_CTX_set_default_read_buffer_len(SSL_CTX
*ctx
, size_t len
)
109 ctx
->default_read_buf_len
= len
;
112 void SSL_set_default_read_buffer_len(SSL
*s
, size_t len
)
114 SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_SSL(s
);
118 sc
->rlayer
.default_read_buf_len
= len
;
121 const char *SSL_rstate_string_long(const SSL
*s
)
123 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
129 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
132 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, NULL
, &lng
);
137 const char *SSL_rstate_string(const SSL
*s
)
139 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
145 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
148 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, &shrt
, NULL
);
153 static int tls_write_check_pending(SSL_CONNECTION
*s
, int type
,
154 const unsigned char *buf
, size_t len
)
156 if (s
->rlayer
.wpend_tot
== 0)
159 /* We have pending data, so do some sanity checks */
160 if ((s
->rlayer
.wpend_tot
> len
)
161 || (!(s
->mode
& SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
)
162 && (s
->rlayer
.wpend_buf
!= buf
))
163 || (s
->rlayer
.wpend_type
!= type
)) {
164 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_WRITE_RETRY
);
171 * Call this to write data in records of type 'type' It will return <= 0 if
172 * not all data has been sent or non-blocking IO.
174 int ssl3_write_bytes(SSL
*ssl
, int type
, const void *buf_
, size_t len
,
177 const unsigned char *buf
= buf_
;
179 size_t n
, max_send_fragment
, split_send_fragment
, maxpipes
;
181 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
182 OSSL_RECORD_TEMPLATE tmpls
[SSL_MAX_PIPELINES
];
183 unsigned int recversion
;
188 s
->rwstate
= SSL_NOTHING
;
189 tot
= s
->rlayer
.wnum
;
191 * ensure that if we end up with a smaller value of data to write out
192 * than the original len from a write which didn't complete for
193 * non-blocking I/O and also somehow ended up avoiding the check for
194 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
195 * possible to end up with (len-tot) as a large number that will then
196 * promptly send beyond the end of the users buffer ... so we trap and
197 * report the error in a way the user will notice
199 if ((len
< s
->rlayer
.wnum
)
200 || ((s
->rlayer
.wpend_tot
!= 0)
201 && (len
< (s
->rlayer
.wnum
+ s
->rlayer
.wpend_tot
)))) {
202 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_LENGTH
);
206 if (s
->early_data_state
== SSL_EARLY_DATA_WRITING
207 && !ossl_early_data_count_ok(s
, len
, 0, 1)) {
208 /* SSLfatal() already called */
215 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
216 * into init unless we have writes pending - in which case we should finish
219 if (s
->rlayer
.wpend_tot
== 0 && (s
->key_update
!= SSL_KEY_UPDATE_NONE
220 || s
->ext
.extra_tickets_expected
> 0))
221 ossl_statem_set_in_init(s
, 1);
224 * When writing early data on the server side we could be "in_init" in
225 * between receiving the EoED and the CF - but we don't want to handle those
228 if (SSL_in_init(ssl
) && !ossl_statem_get_in_handshake(s
)
229 && s
->early_data_state
!= SSL_EARLY_DATA_UNAUTH_WRITING
) {
230 i
= s
->handshake_func(ssl
);
231 /* SSLfatal() already called */
239 i
= tls_write_check_pending(s
, type
, buf
, len
);
241 /* SSLfatal() already called */
245 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
246 s
->rlayer
.wrlmethod
->retry_write_records(s
->rlayer
.wrl
));
249 tot
+= s
->rlayer
.wpend_tot
;
250 s
->rlayer
.wpend_tot
= 0;
251 } /* else no retry required */
255 * We've not previously sent any data for this write so memorize
256 * arguments so that we can detect bad write retries later
258 s
->rlayer
.wpend_tot
= 0;
259 s
->rlayer
.wpend_type
= type
;
260 s
->rlayer
.wpend_buf
= buf
;
261 s
->rlayer
.wpend_ret
= len
;
264 if (tot
== len
) { /* done? */
269 /* If we have an alert to send, lets send it */
270 if (s
->s3
.alert_dispatch
) {
271 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
273 /* SSLfatal() already called if appropriate */
276 /* if it went, fall through and send more stuff */
281 max_send_fragment
= ssl_get_max_send_fragment(s
);
282 split_send_fragment
= ssl_get_split_send_fragment(s
);
284 if (max_send_fragment
== 0
285 || split_send_fragment
== 0
286 || split_send_fragment
> max_send_fragment
) {
288 * We should have prevented this when we set/get the split and max send
289 * fragments so we shouldn't get here
291 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
296 * Some servers hang if initial client hello is larger than 256 bytes
297 * and record version number > TLS 1.0
299 recversion
= (s
->version
== TLS1_3_VERSION
) ? TLS1_2_VERSION
: s
->version
;
300 if (SSL_get_state(ssl
) == TLS_ST_CW_CLNT_HELLO
302 && TLS1_get_version(ssl
) > TLS1_VERSION
303 && s
->hello_retry_request
== SSL_HRR_NONE
)
304 recversion
= TLS1_VERSION
;
307 size_t tmppipelen
, remain
;
308 size_t j
, lensofar
= 0;
311 * Ask the record layer how it would like to split the amount of data
312 * that we have, and how many of those records it would like in one go.
314 maxpipes
= s
->rlayer
.wrlmethod
->get_max_records(s
->rlayer
.wrl
, type
, n
,
316 &split_send_fragment
);
318 * If max_pipelines is 0 then this means "undefined" and we default to
319 * whatever the record layer wants to do. Otherwise we use the smallest
320 * value from the number requested by the record layer, and max number
321 * configured by the user.
323 if (s
->max_pipelines
> 0 && maxpipes
> s
->max_pipelines
)
324 maxpipes
= s
->max_pipelines
;
326 if (maxpipes
> SSL_MAX_PIPELINES
)
327 maxpipes
= SSL_MAX_PIPELINES
;
329 if (split_send_fragment
> max_send_fragment
) {
330 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
334 if (n
/ maxpipes
>= split_send_fragment
) {
336 * We have enough data to completely fill all available
339 for (j
= 0; j
< maxpipes
; j
++) {
340 tmpls
[j
].type
= type
;
341 tmpls
[j
].version
= recversion
;
342 tmpls
[j
].buf
= &(buf
[tot
]) + (j
* split_send_fragment
);
343 tmpls
[j
].buflen
= split_send_fragment
;
345 /* Remember how much data we are going to be sending */
346 s
->rlayer
.wpend_tot
= maxpipes
* split_send_fragment
;
348 /* We can partially fill all available pipelines */
349 tmppipelen
= n
/ maxpipes
;
350 remain
= n
% maxpipes
;
352 * If there is a remainder we add an extra byte to the first few
357 for (j
= 0; j
< maxpipes
; j
++) {
358 tmpls
[j
].type
= type
;
359 tmpls
[j
].version
= recversion
;
360 tmpls
[j
].buf
= &(buf
[tot
]) + lensofar
;
361 tmpls
[j
].buflen
= tmppipelen
;
362 lensofar
+= tmppipelen
;
366 /* Remember how much data we are going to be sending */
367 s
->rlayer
.wpend_tot
= n
;
370 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
371 s
->rlayer
.wrlmethod
->write_records(s
->rlayer
.wrl
, tmpls
, maxpipes
));
373 /* SSLfatal() already called if appropriate */
374 s
->rlayer
.wnum
= tot
;
378 if (s
->rlayer
.wpend_tot
== n
379 || (type
== SSL3_RT_APPLICATION_DATA
380 && (s
->mode
& SSL_MODE_ENABLE_PARTIAL_WRITE
) != 0)) {
381 *written
= tot
+ s
->rlayer
.wpend_tot
;
382 s
->rlayer
.wpend_tot
= 0;
386 n
-= s
->rlayer
.wpend_tot
;
387 tot
+= s
->rlayer
.wpend_tot
;
391 int ossl_tls_handle_rlayer_return(SSL_CONNECTION
*s
, int writing
, int ret
,
392 char *file
, int line
)
394 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
396 if (ret
== OSSL_RECORD_RETURN_RETRY
) {
397 s
->rwstate
= writing
? SSL_WRITING
: SSL_READING
;
400 s
->rwstate
= SSL_NOTHING
;
401 if (ret
== OSSL_RECORD_RETURN_EOF
) {
404 * This shouldn't happen with a writing operation. We treat it
408 ERR_set_debug(file
, line
, 0);
409 ossl_statem_fatal(s
, SSL_AD_INTERNAL_ERROR
,
410 ERR_R_INTERNAL_ERROR
, NULL
);
411 ret
= OSSL_RECORD_RETURN_FATAL
;
412 } else if ((s
->options
& SSL_OP_IGNORE_UNEXPECTED_EOF
) != 0) {
413 SSL_set_shutdown(ssl
, SSL_RECEIVED_SHUTDOWN
);
414 s
->s3
.warn_alert
= SSL_AD_CLOSE_NOTIFY
;
417 ERR_set_debug(file
, line
, 0);
418 ossl_statem_fatal(s
, SSL_AD_DECODE_ERROR
,
419 SSL_R_UNEXPECTED_EOF_WHILE_READING
, NULL
);
421 } else if (ret
== OSSL_RECORD_RETURN_FATAL
) {
422 int al
= s
->rlayer
.rrlmethod
->get_alert_code(s
->rlayer
.rrl
);
424 if (al
!= SSL_AD_NO_ALERT
) {
426 ERR_set_debug(file
, line
, 0);
427 ossl_statem_fatal(s
, al
, SSL_R_RECORD_LAYER_FAILURE
, NULL
);
430 * else some failure but there is no alert code. We don't log an
431 * error for this. The record layer should have logged an error
432 * already or, if not, its due to some sys call error which will be
433 * reported via SSL_ERROR_SYSCALL and errno.
437 * The record layer distinguishes the cases of EOF, non-fatal
438 * err and retry. Upper layers do not.
439 * If we got a retry or success then *ret is already correct,
440 * otherwise we need to convert the return value.
442 if (ret
== OSSL_RECORD_RETURN_NON_FATAL_ERR
|| ret
== OSSL_RECORD_RETURN_EOF
)
444 else if (ret
< OSSL_RECORD_RETURN_NON_FATAL_ERR
)
451 void ssl_release_record(SSL_CONNECTION
*s
, TLS_RECORD
*rr
)
453 if (rr
->rechandle
!= NULL
) {
454 /* The record layer allocated the buffers for this record */
455 s
->rlayer
.rrlmethod
->release_record(s
->rlayer
.rrl
, rr
->rechandle
);
457 /* We allocated the buffers for this record (only happens with DTLS) */
458 OPENSSL_free(rr
->data
);
460 s
->rlayer
.curr_rec
++;
464 * Return up to 'len' payload bytes received in 'type' records.
465 * 'type' is one of the following:
467 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
468 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
469 * - 0 (during a shutdown, no data has to be returned)
471 * If we don't have stored data to work from, read a SSL/TLS record first
472 * (possibly multiple records if we still don't have anything to return).
474 * This function must handle any surprises the peer may have for us, such as
475 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
476 * messages are treated as if they were handshake messages *if* the |recvd_type|
477 * argument is non NULL.
478 * Also if record payloads contain fragments too small to process, we store
479 * them until there is enough for the respective protocol (the record protocol
480 * may use arbitrary fragmentation and even interleaving):
481 * Change cipher spec protocol
482 * just 1 byte needed, no need for keeping anything stored
484 * 2 bytes needed (AlertLevel, AlertDescription)
486 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
487 * to detect unexpected Client Hello and Hello Request messages
488 * here, anything else is handled by higher layers
489 * Application data protocol
490 * none of our business
492 int ssl3_read_bytes(SSL
*ssl
, int type
, int *recvd_type
, unsigned char *buf
,
493 size_t len
, int peek
, size_t *readbytes
)
496 size_t n
, curr_rec
, totalbytes
;
498 void (*cb
) (const SSL
*ssl
, int type2
, int val
) = NULL
;
500 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
502 is_tls13
= SSL_CONNECTION_IS_TLS13(s
);
505 && (type
!= SSL3_RT_APPLICATION_DATA
)
506 && (type
!= SSL3_RT_HANDSHAKE
))
507 || (peek
&& (type
!= SSL3_RT_APPLICATION_DATA
))) {
508 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
512 if ((type
== SSL3_RT_HANDSHAKE
) && (s
->rlayer
.handshake_fragment_len
> 0))
513 /* (partially) satisfy request from storage */
515 unsigned char *src
= s
->rlayer
.handshake_fragment
;
516 unsigned char *dst
= buf
;
521 while ((len
> 0) && (s
->rlayer
.handshake_fragment_len
> 0)) {
524 s
->rlayer
.handshake_fragment_len
--;
527 /* move any remaining fragment bytes: */
528 for (k
= 0; k
< s
->rlayer
.handshake_fragment_len
; k
++)
529 s
->rlayer
.handshake_fragment
[k
] = *src
++;
531 if (recvd_type
!= NULL
)
532 *recvd_type
= SSL3_RT_HANDSHAKE
;
539 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
542 if (!ossl_statem_get_in_handshake(s
) && SSL_in_init(ssl
)) {
543 /* type == SSL3_RT_APPLICATION_DATA */
544 i
= s
->handshake_func(ssl
);
545 /* SSLfatal() already called */
552 s
->rwstate
= SSL_NOTHING
;
555 * For each record 'i' up to |num_recs]
556 * rr[i].type - is the type of record
558 * rr[i].off, - offset into 'data' for next read
559 * rr[i].length, - number of bytes.
561 /* get new records if necessary */
562 if (s
->rlayer
.curr_rec
>= s
->rlayer
.num_recs
) {
563 s
->rlayer
.curr_rec
= s
->rlayer
.num_recs
= 0;
565 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.num_recs
];
567 ret
= HANDLE_RLAYER_READ_RETURN(s
,
568 s
->rlayer
.rrlmethod
->read_record(s
->rlayer
.rrl
,
570 &rr
->version
, &rr
->type
,
571 &rr
->data
, &rr
->length
,
574 /* SSLfatal() already called if appropriate */
578 s
->rlayer
.num_recs
++;
579 } while (s
->rlayer
.rrlmethod
->processed_read_pending(s
->rlayer
.rrl
)
580 && s
->rlayer
.num_recs
< SSL_MAX_PIPELINES
);
582 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.curr_rec
];
584 if (s
->rlayer
.handshake_fragment_len
> 0
585 && rr
->type
!= SSL3_RT_HANDSHAKE
586 && SSL_CONNECTION_IS_TLS13(s
)) {
587 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
588 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA
);
593 * Reset the count of consecutive warning alerts if we've got a non-empty
594 * record that isn't an alert.
596 if (rr
->type
!= SSL3_RT_ALERT
&& rr
->length
!= 0)
597 s
->rlayer
.alert_count
= 0;
599 /* we now have a packet which can be read and processed */
601 if (s
->s3
.change_cipher_spec
/* set when we receive ChangeCipherSpec,
602 * reset by ssl3_get_finished */
603 && (rr
->type
!= SSL3_RT_HANDSHAKE
)) {
604 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
605 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED
);
610 * If the other end has shut down, throw anything we read away (even in
613 if (s
->shutdown
& SSL_RECEIVED_SHUTDOWN
) {
614 s
->rlayer
.curr_rec
++;
615 s
->rwstate
= SSL_NOTHING
;
620 || (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
621 && type
== SSL3_RT_HANDSHAKE
&& recvd_type
!= NULL
624 * SSL3_RT_APPLICATION_DATA or
625 * SSL3_RT_HANDSHAKE or
626 * SSL3_RT_CHANGE_CIPHER_SPEC
629 * make sure that we are not getting application data when we are
630 * doing a handshake for the first time
632 if (SSL_in_init(ssl
) && type
== SSL3_RT_APPLICATION_DATA
633 && s
->enc_read_ctx
== NULL
) {
634 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_APP_DATA_IN_HANDSHAKE
);
638 if (type
== SSL3_RT_HANDSHAKE
639 && rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
640 && s
->rlayer
.handshake_fragment_len
> 0) {
641 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
645 if (recvd_type
!= NULL
)
646 *recvd_type
= rr
->type
;
650 * Skip a zero length record. This ensures multiple calls to
651 * SSL_read() with a zero length buffer will eventually cause
652 * SSL_pending() to report data as being available.
655 ssl_release_record(s
, rr
);
661 curr_rec
= s
->rlayer
.curr_rec
;
663 if (len
- totalbytes
> rr
->length
)
666 n
= len
- totalbytes
;
668 memcpy(buf
, &(rr
->data
[rr
->off
]), n
);
671 /* Mark any zero length record as consumed CVE-2016-6305 */
673 ssl_release_record(s
, rr
);
675 if (s
->options
& SSL_OP_CLEANSE_PLAINTEXT
)
676 OPENSSL_cleanse(&(rr
->data
[rr
->off
]), n
);
680 ssl_release_record(s
, rr
);
683 || (peek
&& n
== rr
->length
)) {
688 } while (type
== SSL3_RT_APPLICATION_DATA
689 && curr_rec
< s
->rlayer
.num_recs
690 && totalbytes
< len
);
691 if (totalbytes
== 0) {
692 /* We must have read empty records. Get more data */
695 *readbytes
= totalbytes
;
700 * If we get here, then type != rr->type; if we have a handshake message,
701 * then it was unexpected (Hello Request or Client Hello) or invalid (we
702 * were actually expecting a CCS).
706 * Lets just double check that we've not got an SSLv2 record
708 if (rr
->version
== SSL2_VERSION
) {
710 * Should never happen. ssl3_get_record() should only give us an SSLv2
711 * record back if this is the first packet and we are looking for an
712 * initial ClientHello. Therefore |type| should always be equal to
713 * |rr->type|. If not then something has gone horribly wrong
715 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
719 if (ssl
->method
->version
== TLS_ANY_VERSION
720 && (s
->server
|| rr
->type
!= SSL3_RT_ALERT
)) {
722 * If we've got this far and still haven't decided on what version
723 * we're using then this must be a client side alert we're dealing
724 * with. We shouldn't be receiving anything other than a ClientHello
725 * if we are a server.
727 s
->version
= rr
->version
;
728 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_MESSAGE
);
733 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
734 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
737 if (rr
->type
== SSL3_RT_ALERT
) {
738 unsigned int alert_level
, alert_descr
;
739 unsigned char *alert_bytes
= rr
->data
743 if (!PACKET_buf_init(&alert
, alert_bytes
, rr
->length
)
744 || !PACKET_get_1(&alert
, &alert_level
)
745 || !PACKET_get_1(&alert
, &alert_descr
)
746 || PACKET_remaining(&alert
) != 0) {
747 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_INVALID_ALERT
);
752 s
->msg_callback(0, s
->version
, SSL3_RT_ALERT
, alert_bytes
, 2, ssl
,
753 s
->msg_callback_arg
);
755 if (s
->info_callback
!= NULL
)
756 cb
= s
->info_callback
;
757 else if (ssl
->ctx
->info_callback
!= NULL
)
758 cb
= ssl
->ctx
->info_callback
;
761 j
= (alert_level
<< 8) | alert_descr
;
762 cb(ssl
, SSL_CB_READ_ALERT
, j
);
765 if ((!is_tls13
&& alert_level
== SSL3_AL_WARNING
)
766 || (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
)) {
767 s
->s3
.warn_alert
= alert_descr
;
768 ssl_release_record(s
, rr
);
770 s
->rlayer
.alert_count
++;
771 if (s
->rlayer
.alert_count
== MAX_WARN_ALERT_COUNT
) {
772 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
773 SSL_R_TOO_MANY_WARN_ALERTS
);
779 * Apart from close_notify the only other warning alert in TLSv1.3
780 * is user_cancelled - which we just ignore.
782 if (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
) {
784 } else if (alert_descr
== SSL_AD_CLOSE_NOTIFY
785 && (is_tls13
|| alert_level
== SSL3_AL_WARNING
)) {
786 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
788 } else if (alert_level
== SSL3_AL_FATAL
|| is_tls13
) {
789 s
->rwstate
= SSL_NOTHING
;
790 s
->s3
.fatal_alert
= alert_descr
;
791 SSLfatal_data(s
, SSL_AD_NO_ALERT
,
792 SSL_AD_REASON_OFFSET
+ alert_descr
,
793 "SSL alert number %d", alert_descr
);
794 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
795 ssl_release_record(s
, rr
);
796 SSL_CTX_remove_session(s
->session_ctx
, s
->session
);
798 } else if (alert_descr
== SSL_AD_NO_RENEGOTIATION
) {
800 * This is a warning but we receive it if we requested
801 * renegotiation and the peer denied it. Terminate with a fatal
802 * alert because if application tried to renegotiate it
803 * presumably had a good reason and expects it to succeed. In
804 * future we might have a renegotiation where we don't care if
805 * the peer refused it where we carry on.
807 SSLfatal(s
, SSL_AD_HANDSHAKE_FAILURE
, SSL_R_NO_RENEGOTIATION
);
809 } else if (alert_level
== SSL3_AL_WARNING
) {
810 /* We ignore any other warning alert in TLSv1.2 and below */
814 SSLfatal(s
, SSL_AD_ILLEGAL_PARAMETER
, SSL_R_UNKNOWN_ALERT_TYPE
);
818 if ((s
->shutdown
& SSL_SENT_SHUTDOWN
) != 0) {
819 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
823 * We ignore any handshake messages sent to us unless they are
824 * TLSv1.3 in which case we want to process them. For all other
825 * handshake messages we can't do anything reasonable with them
826 * because we are unable to write any response due to having already
829 if (!SSL_CONNECTION_IS_TLS13(s
)) {
830 ssl_release_record(s
, rr
);
832 if ((s
->mode
& SSL_MODE_AUTO_RETRY
) != 0)
835 s
->rwstate
= SSL_READING
;
836 rbio
= SSL_get_rbio(ssl
);
837 BIO_clear_retry_flags(rbio
);
838 BIO_set_retry_read(rbio
);
843 * The peer is continuing to send application data, but we have
844 * already sent close_notify. If this was expected we should have
845 * been called via SSL_read() and this would have been handled
847 * No alert sent because we already sent close_notify
849 ssl_release_record(s
, rr
);
850 SSLfatal(s
, SSL_AD_NO_ALERT
,
851 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY
);
857 * For handshake data we have 'fragment' storage, so fill that so that we
858 * can process the header at a fixed place. This is done after the
859 * "SHUTDOWN" code above to avoid filling the fragment storage with data
860 * that we're just going to discard.
862 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
863 size_t dest_maxlen
= sizeof(s
->rlayer
.handshake_fragment
);
864 unsigned char *dest
= s
->rlayer
.handshake_fragment
;
865 size_t *dest_len
= &s
->rlayer
.handshake_fragment_len
;
867 n
= dest_maxlen
- *dest_len
; /* available space in 'dest' */
869 n
= rr
->length
; /* available bytes */
871 /* now move 'n' bytes: */
872 memcpy(dest
+ *dest_len
, rr
->data
+ rr
->off
, n
);
877 ssl_release_record(s
, rr
);
879 if (*dest_len
< dest_maxlen
)
880 goto start
; /* fragment was too small */
883 if (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
) {
884 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
889 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
890 * protocol violation)
892 if ((s
->rlayer
.handshake_fragment_len
>= 4)
893 && !ossl_statem_get_in_handshake(s
)) {
894 int ined
= (s
->early_data_state
== SSL_EARLY_DATA_READING
);
896 /* We found handshake data, so we're going back into init */
897 ossl_statem_set_in_init(s
, 1);
899 i
= s
->handshake_func(ssl
);
900 /* SSLfatal() already called if appropriate */
908 * If we were actually trying to read early data and we found a
909 * handshake message, then we don't want to continue to try and read
910 * the application data any more. It won't be "early" now.
915 if (!(s
->mode
& SSL_MODE_AUTO_RETRY
)) {
916 if (!RECORD_LAYER_read_pending(&s
->rlayer
)) {
919 * In the case where we try to read application data, but we
920 * trigger an SSL handshake, we return -1 with the retry
921 * option set. Otherwise renegotiation may cause nasty
922 * problems in the blocking world
924 s
->rwstate
= SSL_READING
;
925 bio
= SSL_get_rbio(ssl
);
926 BIO_clear_retry_flags(bio
);
927 BIO_set_retry_read(bio
);
937 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
938 * TLS 1.2 says you MUST send an unexpected message alert. We use the
939 * TLS 1.2 behaviour for all protocol versions to prevent issues where
940 * no progress is being made and the peer continually sends unrecognised
941 * record types, using up resources processing them.
943 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
945 case SSL3_RT_CHANGE_CIPHER_SPEC
:
947 case SSL3_RT_HANDSHAKE
:
949 * we already handled all of these, with the possible exception of
950 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
951 * that should not happen when type != rr->type
953 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, ERR_R_INTERNAL_ERROR
);
955 case SSL3_RT_APPLICATION_DATA
:
957 * At this point, we were expecting handshake data, but have
958 * application data. If the library was running inside ssl3_read()
959 * (i.e. in_read_app_data is set) and it makes sense to read
960 * application data at this point (session renegotiation not yet
961 * started), we will indulge it.
963 if (ossl_statem_app_data_allowed(s
)) {
964 s
->s3
.in_read_app_data
= 2;
966 } else if (ossl_statem_skip_early_data(s
)) {
968 * This can happen after a client sends a CH followed by early_data,
969 * but the server responds with a HelloRetryRequest. The server
970 * reads the next record from the client expecting to find a
971 * plaintext ClientHello but gets a record which appears to be
972 * application data. The trial decrypt "works" because null
973 * decryption was applied. We just skip it and move on to the next
976 if (!ossl_early_data_count_ok(s
, rr
->length
,
977 EARLY_DATA_CIPHERTEXT_OVERHEAD
, 0)) {
978 /* SSLfatal() already called */
981 ssl_release_record(s
, rr
);
984 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
991 * Returns true if the current rrec was sent in SSLv2 backwards compatible
992 * format and false otherwise.
994 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER
*rl
)
996 if (SSL_CONNECTION_IS_DTLS(rl
->s
))
998 return rl
->tlsrecs
[0].version
== SSL2_VERSION
;
1001 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper
;
1002 static void rlayer_msg_callback_wrapper(int write_p
, int version
,
1003 int content_type
, const void *buf
,
1004 size_t len
, void *cbarg
)
1006 SSL_CONNECTION
*s
= cbarg
;
1007 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1009 if (s
->msg_callback
!= NULL
)
1010 s
->msg_callback(write_p
, version
, content_type
, buf
, len
, ssl
,
1011 s
->msg_callback_arg
);
1014 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper
;
1015 static int rlayer_security_wrapper(void *cbarg
, int op
, int bits
, int nid
,
1018 SSL_CONNECTION
*s
= cbarg
;
1020 return ssl_security(s
, op
, bits
, nid
, other
);
1023 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper
;
1024 static size_t rlayer_padding_wrapper(void *cbarg
, int type
, size_t len
)
1026 SSL_CONNECTION
*s
= cbarg
;
1027 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1029 return s
->rlayer
.record_padding_cb(ssl
, type
, len
,
1030 s
->rlayer
.record_padding_arg
);
1033 static const OSSL_DISPATCH rlayer_dispatch
[] = {
1034 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA
, (void (*)(void))ossl_statem_skip_early_data
},
1035 { OSSL_FUNC_RLAYER_MSG_CALLBACK
, (void (*)(void))rlayer_msg_callback_wrapper
},
1036 { OSSL_FUNC_RLAYER_SECURITY
, (void (*)(void))rlayer_security_wrapper
},
1037 { OSSL_FUNC_RLAYER_PADDING
, (void (*)(void))rlayer_padding_wrapper
},
1041 static const OSSL_RECORD_METHOD
*ssl_select_next_record_layer(SSL_CONNECTION
*s
,
1046 if (level
== OSSL_RECORD_PROTECTION_LEVEL_NONE
) {
1047 if (SSL_CONNECTION_IS_DTLS(s
))
1048 return &ossl_dtls_record_method
;
1050 return &ossl_tls_record_method
;
1053 #ifndef OPENSSL_NO_KTLS
1054 /* KTLS does not support renegotiation */
1055 if (level
== OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1056 && (s
->options
& SSL_OP_ENABLE_KTLS
) != 0
1057 && (SSL_CONNECTION_IS_TLS13(s
) || SSL_IS_FIRST_HANDSHAKE(s
)))
1058 return &ossl_ktls_record_method
;
1061 /* Default to the current OSSL_RECORD_METHOD */
1062 return direction
== OSSL_RECORD_DIRECTION_READ
? s
->rlayer
.rrlmethod
1063 : s
->rlayer
.wrlmethod
;
1066 static int ssl_post_record_layer_select(SSL_CONNECTION
*s
, int direction
)
1068 const OSSL_RECORD_METHOD
*thismethod
;
1069 OSSL_RECORD_LAYER
*thisrl
;
1071 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1072 thismethod
= s
->rlayer
.rrlmethod
;
1073 thisrl
= s
->rlayer
.rrl
;
1075 thismethod
= s
->rlayer
.wrlmethod
;
1076 thisrl
= s
->rlayer
.wrl
;
1079 #ifndef OPENSSL_NO_KTLS
1081 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1083 if (s
->rlayer
.rrlmethod
== &ossl_ktls_record_method
) {
1084 /* KTLS does not support renegotiation so disallow it */
1085 SSL_set_options(ssl
, SSL_OP_NO_RENEGOTIATION
);
1089 if (SSL_IS_FIRST_HANDSHAKE(s
) && thismethod
->set_first_handshake
!= NULL
)
1090 thismethod
->set_first_handshake(thisrl
, 1);
1092 if (s
->max_pipelines
!= 0 && thismethod
->set_max_pipelines
!= NULL
)
1093 thismethod
->set_max_pipelines(thisrl
, s
->max_pipelines
);
1098 int ssl_set_new_record_layer(SSL_CONNECTION
*s
, int version
,
1099 int direction
, int level
,
1100 unsigned char *key
, size_t keylen
,
1101 unsigned char *iv
, size_t ivlen
,
1102 unsigned char *mackey
, size_t mackeylen
,
1103 const EVP_CIPHER
*ciph
, size_t taglen
,
1104 int mactype
, const EVP_MD
*md
,
1105 const SSL_COMP
*comp
)
1107 OSSL_PARAM options
[5], *opts
= options
;
1108 OSSL_PARAM settings
[6], *set
= settings
;
1109 const OSSL_RECORD_METHOD
**thismethod
;
1110 OSSL_RECORD_LAYER
**thisrl
, *newrl
= NULL
;
1112 SSL_CTX
*sctx
= SSL_CONNECTION_GET_CTX(s
);
1113 const OSSL_RECORD_METHOD
*meth
;
1114 int use_etm
, stream_mac
= 0, tlstree
= 0;
1115 unsigned int maxfrag
= (direction
== OSSL_RECORD_DIRECTION_WRITE
)
1116 ? ssl_get_max_send_fragment(s
)
1117 : SSL3_RT_MAX_PLAIN_LENGTH
;
1118 int use_early_data
= 0;
1119 uint32_t max_early_data
;
1120 COMP_METHOD
*compm
= (comp
== NULL
) ? NULL
: comp
->method
;
1122 meth
= ssl_select_next_record_layer(s
, direction
, level
);
1124 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1125 thismethod
= &s
->rlayer
.rrlmethod
;
1126 thisrl
= &s
->rlayer
.rrl
;
1129 thismethod
= &s
->rlayer
.wrlmethod
;
1130 thisrl
= &s
->rlayer
.wrl
;
1137 if (!ossl_assert(meth
!= NULL
)) {
1138 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1142 /* Parameters that *may* be supported by a record layer if passed */
1143 *opts
++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS
,
1145 *opts
++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE
,
1147 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1148 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN
,
1149 &s
->rlayer
.default_read_buf_len
);
1150 *opts
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD
,
1151 &s
->rlayer
.read_ahead
);
1153 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING
,
1154 &s
->rlayer
.block_padding
);
1156 *opts
= OSSL_PARAM_construct_end();
1158 /* Parameters that *must* be supported by a record layer if passed */
1159 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1160 use_etm
= SSL_READ_ETM(s
) ? 1 : 0;
1161 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_STREAM
) != 0)
1164 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_TLSTREE
) != 0)
1167 use_etm
= SSL_WRITE_ETM(s
) ? 1 : 0;
1168 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_STREAM
) != 0)
1171 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_TLSTREE
) != 0)
1176 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM
,
1180 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC
,
1184 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE
,
1188 * We only need to do this for the read side. The write side should already
1189 * have the correct value due to the ssl_get_max_send_fragment() call above
1191 if (direction
== OSSL_RECORD_DIRECTION_READ
1192 && s
->session
!= NULL
1193 && USE_MAX_FRAGMENT_LENGTH_EXT(s
->session
))
1194 maxfrag
= GET_MAX_FRAGMENT_LENGTH(s
->session
);
1197 if (maxfrag
!= SSL3_RT_MAX_PLAIN_LENGTH
)
1198 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN
,
1202 * The record layer must check the amount of early data sent or received
1203 * using the early keys. A server also needs to worry about rejected early
1204 * data that might arrive when the handshake keys are in force.
1206 if (s
->server
&& direction
== OSSL_RECORD_DIRECTION_READ
) {
1207 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
1208 || level
== OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
);
1209 } else if (!s
->server
&& direction
== OSSL_RECORD_DIRECTION_WRITE
) {
1210 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
);
1212 if (use_early_data
) {
1213 max_early_data
= ossl_get_max_early_data(s
);
1215 if (max_early_data
!= 0)
1216 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA
,
1220 *set
= OSSL_PARAM_construct_end();
1226 unsigned int epoch
= 0;
1227 OSSL_DISPATCH rlayer_dispatch_tmp
[OSSL_NELEM(rlayer_dispatch
)];
1230 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1231 prev
= s
->rlayer
.rrlnext
;
1232 if (SSL_CONNECTION_IS_DTLS(s
)
1233 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1234 epoch
= DTLS_RECORD_LAYER_get_r_epoch(&s
->rlayer
) + 1; /* new epoch */
1236 if (SSL_CONNECTION_IS_DTLS(s
))
1237 next
= BIO_new(BIO_s_dgram_mem());
1239 next
= BIO_new(BIO_s_mem());
1243 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1246 s
->rlayer
.rrlnext
= next
;
1248 if (SSL_CONNECTION_IS_DTLS(s
)
1249 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1250 epoch
= DTLS_RECORD_LAYER_get_w_epoch(&s
->rlayer
) + 1; /* new epoch */
1254 * Create a copy of the dispatch array, missing out wrappers for
1255 * callbacks that we don't need.
1257 for (i
= 0, j
= 0; i
< OSSL_NELEM(rlayer_dispatch
); i
++) {
1258 switch (rlayer_dispatch
[i
].function_id
) {
1259 case OSSL_FUNC_RLAYER_MSG_CALLBACK
:
1260 if (s
->msg_callback
== NULL
)
1263 case OSSL_FUNC_RLAYER_PADDING
:
1264 if (s
->rlayer
.record_padding_cb
== NULL
)
1270 rlayer_dispatch_tmp
[j
++] = rlayer_dispatch
[i
];
1273 rlret
= meth
->new_record_layer(sctx
->libctx
, sctx
->propq
, version
,
1274 s
->server
, direction
, level
, epoch
,
1275 key
, keylen
, iv
, ivlen
, mackey
,
1276 mackeylen
, ciph
, taglen
, mactype
, md
,
1277 compm
, prev
, thisbio
, next
, NULL
, NULL
,
1278 settings
, options
, rlayer_dispatch_tmp
,
1282 case OSSL_RECORD_RETURN_FATAL
:
1283 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_RECORD_LAYER_FAILURE
);
1286 case OSSL_RECORD_RETURN_NON_FATAL_ERR
:
1287 if (*thismethod
!= meth
&& *thismethod
!= NULL
) {
1289 * We tried a new record layer method, but it didn't work out,
1290 * so we fallback to the original method and try again
1295 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_NO_SUITABLE_RECORD_LAYER
);
1298 case OSSL_RECORD_RETURN_SUCCESS
:
1302 /* Should not happen */
1303 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1310 * Free the old record layer if we have one except in the case of DTLS when
1311 * writing. In that case the record layer is still referenced by buffered
1312 * messages for potential retransmit. Only when those buffered messages get
1313 * freed do we free the record layer object (see dtls1_hm_fragment_free)
1315 if (!SSL_CONNECTION_IS_DTLS(s
) || direction
== OSSL_RECORD_DIRECTION_READ
) {
1316 if (*thismethod
!= NULL
&& !(*thismethod
)->free(*thisrl
)) {
1317 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1325 return ssl_post_record_layer_select(s
, direction
);
1328 int ssl_set_record_protocol_version(SSL_CONNECTION
*s
, int vers
)
1330 if (!ossl_assert(s
->rlayer
.rrlmethod
!= NULL
)
1331 || !ossl_assert(s
->rlayer
.wrlmethod
!= NULL
))
1333 s
->rlayer
.rrlmethod
->set_protocol_version(s
->rlayer
.rrl
, s
->version
);
1334 s
->rlayer
.wrlmethod
->set_protocol_version(s
->rlayer
.wrl
, s
->version
);