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 ssl3_release_write_buffer(rl
->s
);
38 RECORD_LAYER_reset_write_sequence(rl
);
40 if (rl
->rrlmethod
!= NULL
)
41 rl
->rrlmethod
->free(rl
->rrl
); /* Ignore return value */
42 if (rl
->wrlmethod
!= NULL
)
43 rl
->wrlmethod
->free(rl
->wrl
); /* Ignore return value */
44 BIO_free(rl
->rrlnext
);
52 DTLS_RECORD_LAYER_clear(rl
);
55 void RECORD_LAYER_release(RECORD_LAYER
*rl
)
57 if (rl
->numwpipes
> 0)
58 ssl3_release_write_buffer(rl
->s
);
61 /* Checks if we have unprocessed read ahead data pending */
62 int RECORD_LAYER_read_pending(const RECORD_LAYER
*rl
)
64 return rl
->rrlmethod
->unprocessed_read_pending(rl
->rrl
);
67 /* Checks if we have decrypted unread record data pending */
68 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER
*rl
)
70 return (rl
->curr_rec
< rl
->num_recs
)
71 || rl
->rrlmethod
->processed_read_pending(rl
->rrl
);
74 int RECORD_LAYER_write_pending(const RECORD_LAYER
*rl
)
76 /* TODO(RECLAYER): Remove me when DTLS is moved to the write record layer */
77 if (SSL_CONNECTION_IS_DTLS(rl
->s
))
78 return (rl
->numwpipes
> 0)
79 && SSL3_BUFFER_get_left(&rl
->wbuf
[rl
->numwpipes
- 1]) != 0;
80 return rl
->wpend_tot
> 0;
83 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER
*rl
)
85 memset(rl
->write_sequence
, 0, sizeof(rl
->write_sequence
));
88 size_t ssl3_pending(const SSL
*s
)
91 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
96 if (SSL_CONNECTION_IS_DTLS(sc
)) {
100 iter
= pqueue_iterator(sc
->rlayer
.d
->buffered_app_data
.q
);
101 while ((item
= pqueue_next(&iter
)) != NULL
) {
103 num
+= rdata
->length
;
107 for (i
= 0; i
< sc
->rlayer
.num_recs
; i
++) {
108 if (sc
->rlayer
.tlsrecs
[i
].type
!= SSL3_RT_APPLICATION_DATA
)
110 num
+= sc
->rlayer
.tlsrecs
[i
].length
;
113 num
+= sc
->rlayer
.rrlmethod
->app_data_pending(sc
->rlayer
.rrl
);
118 void SSL_CTX_set_default_read_buffer_len(SSL_CTX
*ctx
, size_t len
)
120 ctx
->default_read_buf_len
= len
;
123 void SSL_set_default_read_buffer_len(SSL
*s
, size_t len
)
125 SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_SSL(s
);
129 sc
->rlayer
.default_read_buf_len
= len
;
132 const char *SSL_rstate_string_long(const SSL
*s
)
134 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
140 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
143 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, NULL
, &lng
);
148 const char *SSL_rstate_string(const SSL
*s
)
150 const SSL_CONNECTION
*sc
= SSL_CONNECTION_FROM_CONST_SSL(s
);
156 if (sc
->rlayer
.rrlmethod
== NULL
|| sc
->rlayer
.rrl
== NULL
)
159 sc
->rlayer
.rrlmethod
->get_state(sc
->rlayer
.rrl
, &shrt
, NULL
);
164 static int tls_write_check_pending(SSL_CONNECTION
*s
, int type
,
165 const unsigned char *buf
, size_t len
)
167 if (s
->rlayer
.wpend_tot
== 0)
170 /* We have pending data, so do some sanity checks */
171 if ((s
->rlayer
.wpend_tot
> len
)
172 || (!(s
->mode
& SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
)
173 && (s
->rlayer
.wpend_buf
!= buf
))
174 || (s
->rlayer
.wpend_type
!= type
)) {
175 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_WRITE_RETRY
);
182 * Call this to write data in records of type 'type' It will return <= 0 if
183 * not all data has been sent or non-blocking IO.
185 int ssl3_write_bytes(SSL
*ssl
, int type
, const void *buf_
, size_t len
,
188 const unsigned char *buf
= buf_
;
190 size_t n
, max_send_fragment
, split_send_fragment
, maxpipes
;
192 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
193 OSSL_RECORD_TEMPLATE tmpls
[SSL_MAX_PIPELINES
];
194 unsigned int recversion
;
199 s
->rwstate
= SSL_NOTHING
;
200 tot
= s
->rlayer
.wnum
;
202 * ensure that if we end up with a smaller value of data to write out
203 * than the original len from a write which didn't complete for
204 * non-blocking I/O and also somehow ended up avoiding the check for
205 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
206 * possible to end up with (len-tot) as a large number that will then
207 * promptly send beyond the end of the users buffer ... so we trap and
208 * report the error in a way the user will notice
210 if ((len
< s
->rlayer
.wnum
)
211 || ((s
->rlayer
.wpend_tot
!= 0)
212 && (len
< (s
->rlayer
.wnum
+ s
->rlayer
.wpend_tot
)))) {
213 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_LENGTH
);
217 if (s
->early_data_state
== SSL_EARLY_DATA_WRITING
218 && !ossl_early_data_count_ok(s
, len
, 0, 1)) {
219 /* SSLfatal() already called */
226 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
227 * into init unless we have writes pending - in which case we should finish
230 if (s
->rlayer
.wpend_tot
== 0 && (s
->key_update
!= SSL_KEY_UPDATE_NONE
231 || s
->ext
.extra_tickets_expected
> 0))
232 ossl_statem_set_in_init(s
, 1);
235 * When writing early data on the server side we could be "in_init" in
236 * between receiving the EoED and the CF - but we don't want to handle those
239 if (SSL_in_init(ssl
) && !ossl_statem_get_in_handshake(s
)
240 && s
->early_data_state
!= SSL_EARLY_DATA_UNAUTH_WRITING
) {
241 i
= s
->handshake_func(ssl
);
242 /* SSLfatal() already called */
250 i
= tls_write_check_pending(s
, type
, buf
, len
);
252 /* SSLfatal() already called */
256 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
257 s
->rlayer
.wrlmethod
->retry_write_records(s
->rlayer
.wrl
));
260 tot
+= s
->rlayer
.wpend_tot
;
261 s
->rlayer
.wpend_tot
= 0;
262 } /* else no retry required */
266 * We've not previously sent any data for this write so memorize
267 * arguments so that we can detect bad write retries later
269 s
->rlayer
.wpend_tot
= 0;
270 s
->rlayer
.wpend_type
= type
;
271 s
->rlayer
.wpend_buf
= buf
;
272 s
->rlayer
.wpend_ret
= len
;
275 if (tot
== len
) { /* done? */
280 /* If we have an alert to send, lets send it */
281 if (s
->s3
.alert_dispatch
) {
282 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
284 /* SSLfatal() already called if appropriate */
287 /* if it went, fall through and send more stuff */
292 max_send_fragment
= ssl_get_max_send_fragment(s
);
293 split_send_fragment
= ssl_get_split_send_fragment(s
);
296 * Ask the record layer how it would like to split the amount of data that
297 * we have, and how many of those records it would like in one go.
299 maxpipes
= s
->rlayer
.wrlmethod
->get_max_records(s
->rlayer
.wrl
, type
, n
,
301 &split_send_fragment
);
303 * If max_pipelines is 0 then this means "undefined" and we default to
304 * whatever the record layer wants to do. Otherwise we use the smallest
305 * value from the number requested by the record layer, and max number
306 * configured by the user.
308 if (s
->max_pipelines
> 0 && maxpipes
> s
->max_pipelines
)
309 maxpipes
= s
->max_pipelines
;
311 if (maxpipes
> SSL_MAX_PIPELINES
)
312 maxpipes
= SSL_MAX_PIPELINES
;
316 /* TODO(RECLAYER): FIX ME */
318 || s
->enc_write_ctx
== NULL
319 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s
->enc_write_ctx
))
320 & EVP_CIPH_FLAG_PIPELINE
) == 0
321 || !SSL_USE_EXPLICIT_IV(s
))
324 if (max_send_fragment
== 0
325 || split_send_fragment
== 0
326 || split_send_fragment
> max_send_fragment
) {
328 * We should have prevented this when we set/get the split and max send
329 * fragments so we shouldn't get here
331 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
336 * Some servers hang if initial client hello is larger than 256 bytes
337 * and record version number > TLS 1.0
339 /* TODO(RECLAYER): Does this also need to be in the DTLS equivalent code? */
340 recversion
= (s
->version
== TLS1_3_VERSION
) ? TLS1_2_VERSION
: s
->version
;
341 if (SSL_get_state(ssl
) == TLS_ST_CW_CLNT_HELLO
343 && TLS1_get_version(ssl
) > TLS1_VERSION
344 && s
->hello_retry_request
== SSL_HRR_NONE
)
345 recversion
= TLS1_VERSION
;
348 size_t tmppipelen
, remain
;
349 size_t numpipes
, j
, lensofar
= 0;
354 numpipes
= ((n
- 1) / split_send_fragment
) + 1;
355 if (numpipes
> maxpipes
)
358 if (n
/ numpipes
>= split_send_fragment
) {
360 * We have enough data to completely fill all available
363 for (j
= 0; j
< numpipes
; j
++) {
364 tmpls
[j
].type
= type
;
365 tmpls
[j
].version
= recversion
;
366 tmpls
[j
].buf
= &(buf
[tot
]) + (j
* split_send_fragment
);
367 tmpls
[j
].buflen
= split_send_fragment
;
369 /* Remember how much data we are going to be sending */
370 s
->rlayer
.wpend_tot
= numpipes
* split_send_fragment
;
372 /* We can partially fill all available pipelines */
373 tmppipelen
= n
/ numpipes
;
374 remain
= n
% numpipes
;
376 * If there is a remainder we add an extra byte to the first few
381 for (j
= 0; j
< numpipes
; j
++) {
382 tmpls
[j
].type
= type
;
383 tmpls
[j
].version
= recversion
;
384 tmpls
[j
].buf
= &(buf
[tot
]) + lensofar
;
385 tmpls
[j
].buflen
= tmppipelen
;
386 lensofar
+= tmppipelen
;
390 /* Remember how much data we are going to be sending */
391 s
->rlayer
.wpend_tot
= n
;
394 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
395 s
->rlayer
.wrlmethod
->write_records(s
->rlayer
.wrl
, tmpls
, numpipes
));
397 /* SSLfatal() already called if appropriate */
398 s
->rlayer
.wnum
= tot
;
402 if (s
->rlayer
.wpend_tot
== n
403 || (type
== SSL3_RT_APPLICATION_DATA
404 && (s
->mode
& SSL_MODE_ENABLE_PARTIAL_WRITE
) != 0)) {
405 *written
= tot
+ s
->rlayer
.wpend_tot
;
406 s
->rlayer
.wpend_tot
= 0;
410 n
-= s
->rlayer
.wpend_tot
;
411 tot
+= s
->rlayer
.wpend_tot
;
415 int ossl_tls_handle_rlayer_return(SSL_CONNECTION
*s
, int writing
, int ret
,
416 char *file
, int line
)
418 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
420 if (ret
== OSSL_RECORD_RETURN_RETRY
) {
421 s
->rwstate
= writing
? SSL_WRITING
: SSL_READING
;
424 s
->rwstate
= SSL_NOTHING
;
425 if (ret
== OSSL_RECORD_RETURN_EOF
) {
428 * This shouldn't happen with a writing operation. We treat it
432 ERR_set_debug(file
, line
, 0);
433 ossl_statem_fatal(s
, SSL_AD_INTERNAL_ERROR
,
434 ERR_R_INTERNAL_ERROR
, NULL
);
435 ret
= OSSL_RECORD_RETURN_FATAL
;
436 } else if ((s
->options
& SSL_OP_IGNORE_UNEXPECTED_EOF
) != 0) {
437 SSL_set_shutdown(ssl
, SSL_RECEIVED_SHUTDOWN
);
438 s
->s3
.warn_alert
= SSL_AD_CLOSE_NOTIFY
;
441 ERR_set_debug(file
, line
, 0);
442 ossl_statem_fatal(s
, SSL_AD_DECODE_ERROR
,
443 SSL_R_UNEXPECTED_EOF_WHILE_READING
, NULL
);
445 } else if (ret
== OSSL_RECORD_RETURN_FATAL
) {
446 int al
= s
->rlayer
.rrlmethod
->get_alert_code(s
->rlayer
.rrl
);
448 if (al
!= SSL_AD_NO_ALERT
) {
450 ERR_set_debug(file
, line
, 0);
451 ossl_statem_fatal(s
, al
, SSL_R_RECORD_LAYER_FAILURE
, NULL
);
454 * else some failure but there is no alert code. We don't log an
455 * error for this. The record layer should have logged an error
456 * already or, if not, its due to some sys call error which will be
457 * reported via SSL_ERROR_SYSCALL and errno.
461 * The record layer distinguishes the cases of EOF, non-fatal
462 * err and retry. Upper layers do not.
463 * If we got a retry or success then *ret is already correct,
464 * otherwise we need to convert the return value.
466 if (ret
== OSSL_RECORD_RETURN_NON_FATAL_ERR
|| ret
== OSSL_RECORD_RETURN_EOF
)
468 else if (ret
< OSSL_RECORD_RETURN_NON_FATAL_ERR
)
475 void ssl_release_record(SSL_CONNECTION
*s
, TLS_RECORD
*rr
)
477 if (rr
->rechandle
!= NULL
) {
478 /* The record layer allocated the buffers for this record */
479 s
->rlayer
.rrlmethod
->release_record(s
->rlayer
.rrl
, rr
->rechandle
);
481 /* We allocated the buffers for this record (only happens with DTLS) */
482 OPENSSL_free(rr
->data
);
484 s
->rlayer
.curr_rec
++;
488 * Return up to 'len' payload bytes received in 'type' records.
489 * 'type' is one of the following:
491 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
492 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
493 * - 0 (during a shutdown, no data has to be returned)
495 * If we don't have stored data to work from, read a SSL/TLS record first
496 * (possibly multiple records if we still don't have anything to return).
498 * This function must handle any surprises the peer may have for us, such as
499 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
500 * messages are treated as if they were handshake messages *if* the |recvd_type|
501 * argument is non NULL.
502 * Also if record payloads contain fragments too small to process, we store
503 * them until there is enough for the respective protocol (the record protocol
504 * may use arbitrary fragmentation and even interleaving):
505 * Change cipher spec protocol
506 * just 1 byte needed, no need for keeping anything stored
508 * 2 bytes needed (AlertLevel, AlertDescription)
510 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
511 * to detect unexpected Client Hello and Hello Request messages
512 * here, anything else is handled by higher layers
513 * Application data protocol
514 * none of our business
516 int ssl3_read_bytes(SSL
*ssl
, int type
, int *recvd_type
, unsigned char *buf
,
517 size_t len
, int peek
, size_t *readbytes
)
520 size_t n
, curr_rec
, totalbytes
;
522 void (*cb
) (const SSL
*ssl
, int type2
, int val
) = NULL
;
524 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
526 is_tls13
= SSL_CONNECTION_IS_TLS13(s
);
529 && (type
!= SSL3_RT_APPLICATION_DATA
)
530 && (type
!= SSL3_RT_HANDSHAKE
))
531 || (peek
&& (type
!= SSL3_RT_APPLICATION_DATA
))) {
532 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
536 if ((type
== SSL3_RT_HANDSHAKE
) && (s
->rlayer
.handshake_fragment_len
> 0))
537 /* (partially) satisfy request from storage */
539 unsigned char *src
= s
->rlayer
.handshake_fragment
;
540 unsigned char *dst
= buf
;
545 while ((len
> 0) && (s
->rlayer
.handshake_fragment_len
> 0)) {
548 s
->rlayer
.handshake_fragment_len
--;
551 /* move any remaining fragment bytes: */
552 for (k
= 0; k
< s
->rlayer
.handshake_fragment_len
; k
++)
553 s
->rlayer
.handshake_fragment
[k
] = *src
++;
555 if (recvd_type
!= NULL
)
556 *recvd_type
= SSL3_RT_HANDSHAKE
;
563 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
566 if (!ossl_statem_get_in_handshake(s
) && SSL_in_init(ssl
)) {
567 /* type == SSL3_RT_APPLICATION_DATA */
568 i
= s
->handshake_func(ssl
);
569 /* SSLfatal() already called */
576 s
->rwstate
= SSL_NOTHING
;
579 * For each record 'i' up to |num_recs]
580 * rr[i].type - is the type of record
582 * rr[i].off, - offset into 'data' for next read
583 * rr[i].length, - number of bytes.
585 /* get new records if necessary */
586 if (s
->rlayer
.curr_rec
>= s
->rlayer
.num_recs
) {
587 s
->rlayer
.curr_rec
= s
->rlayer
.num_recs
= 0;
589 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.num_recs
];
591 ret
= HANDLE_RLAYER_READ_RETURN(s
,
592 s
->rlayer
.rrlmethod
->read_record(s
->rlayer
.rrl
,
594 &rr
->version
, &rr
->type
,
595 &rr
->data
, &rr
->length
,
598 /* SSLfatal() already called if appropriate */
602 s
->rlayer
.num_recs
++;
603 } while (s
->rlayer
.rrlmethod
->processed_read_pending(s
->rlayer
.rrl
)
604 && s
->rlayer
.num_recs
< SSL_MAX_PIPELINES
);
606 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.curr_rec
];
608 if (s
->rlayer
.handshake_fragment_len
> 0
609 && rr
->type
!= SSL3_RT_HANDSHAKE
610 && SSL_CONNECTION_IS_TLS13(s
)) {
611 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
612 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA
);
617 * Reset the count of consecutive warning alerts if we've got a non-empty
618 * record that isn't an alert.
620 if (rr
->type
!= SSL3_RT_ALERT
&& rr
->length
!= 0)
621 s
->rlayer
.alert_count
= 0;
623 /* we now have a packet which can be read and processed */
625 if (s
->s3
.change_cipher_spec
/* set when we receive ChangeCipherSpec,
626 * reset by ssl3_get_finished */
627 && (rr
->type
!= SSL3_RT_HANDSHAKE
)) {
628 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
629 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED
);
634 * If the other end has shut down, throw anything we read away (even in
637 if (s
->shutdown
& SSL_RECEIVED_SHUTDOWN
) {
638 s
->rlayer
.curr_rec
++;
639 s
->rwstate
= SSL_NOTHING
;
644 || (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
645 && type
== SSL3_RT_HANDSHAKE
&& recvd_type
!= NULL
648 * SSL3_RT_APPLICATION_DATA or
649 * SSL3_RT_HANDSHAKE or
650 * SSL3_RT_CHANGE_CIPHER_SPEC
653 * make sure that we are not getting application data when we are
654 * doing a handshake for the first time
656 if (SSL_in_init(ssl
) && type
== SSL3_RT_APPLICATION_DATA
657 && s
->enc_read_ctx
== NULL
) {
658 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_APP_DATA_IN_HANDSHAKE
);
662 if (type
== SSL3_RT_HANDSHAKE
663 && rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
664 && s
->rlayer
.handshake_fragment_len
> 0) {
665 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
669 if (recvd_type
!= NULL
)
670 *recvd_type
= rr
->type
;
674 * Skip a zero length record. This ensures multiple calls to
675 * SSL_read() with a zero length buffer will eventually cause
676 * SSL_pending() to report data as being available.
679 ssl_release_record(s
, rr
);
685 curr_rec
= s
->rlayer
.curr_rec
;
687 if (len
- totalbytes
> rr
->length
)
690 n
= len
- totalbytes
;
692 memcpy(buf
, &(rr
->data
[rr
->off
]), n
);
695 /* Mark any zero length record as consumed CVE-2016-6305 */
697 ssl_release_record(s
, rr
);
699 if (s
->options
& SSL_OP_CLEANSE_PLAINTEXT
)
700 OPENSSL_cleanse(&(rr
->data
[rr
->off
]), n
);
704 ssl_release_record(s
, rr
);
707 || (peek
&& n
== rr
->length
)) {
712 } while (type
== SSL3_RT_APPLICATION_DATA
713 && curr_rec
< s
->rlayer
.num_recs
714 && totalbytes
< len
);
715 if (totalbytes
== 0) {
716 /* We must have read empty records. Get more data */
719 *readbytes
= totalbytes
;
724 * If we get here, then type != rr->type; if we have a handshake message,
725 * then it was unexpected (Hello Request or Client Hello) or invalid (we
726 * were actually expecting a CCS).
730 * Lets just double check that we've not got an SSLv2 record
732 if (rr
->version
== SSL2_VERSION
) {
734 * Should never happen. ssl3_get_record() should only give us an SSLv2
735 * record back if this is the first packet and we are looking for an
736 * initial ClientHello. Therefore |type| should always be equal to
737 * |rr->type|. If not then something has gone horribly wrong
739 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
743 if (ssl
->method
->version
== TLS_ANY_VERSION
744 && (s
->server
|| rr
->type
!= SSL3_RT_ALERT
)) {
746 * If we've got this far and still haven't decided on what version
747 * we're using then this must be a client side alert we're dealing
748 * with. We shouldn't be receiving anything other than a ClientHello
749 * if we are a server.
751 s
->version
= rr
->version
;
752 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_MESSAGE
);
757 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
758 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
761 if (rr
->type
== SSL3_RT_ALERT
) {
762 unsigned int alert_level
, alert_descr
;
763 unsigned char *alert_bytes
= rr
->data
767 if (!PACKET_buf_init(&alert
, alert_bytes
, rr
->length
)
768 || !PACKET_get_1(&alert
, &alert_level
)
769 || !PACKET_get_1(&alert
, &alert_descr
)
770 || PACKET_remaining(&alert
) != 0) {
771 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_INVALID_ALERT
);
776 s
->msg_callback(0, s
->version
, SSL3_RT_ALERT
, alert_bytes
, 2, ssl
,
777 s
->msg_callback_arg
);
779 if (s
->info_callback
!= NULL
)
780 cb
= s
->info_callback
;
781 else if (ssl
->ctx
->info_callback
!= NULL
)
782 cb
= ssl
->ctx
->info_callback
;
785 j
= (alert_level
<< 8) | alert_descr
;
786 cb(ssl
, SSL_CB_READ_ALERT
, j
);
789 if ((!is_tls13
&& alert_level
== SSL3_AL_WARNING
)
790 || (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
)) {
791 s
->s3
.warn_alert
= alert_descr
;
792 ssl_release_record(s
, rr
);
794 s
->rlayer
.alert_count
++;
795 if (s
->rlayer
.alert_count
== MAX_WARN_ALERT_COUNT
) {
796 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
797 SSL_R_TOO_MANY_WARN_ALERTS
);
803 * Apart from close_notify the only other warning alert in TLSv1.3
804 * is user_cancelled - which we just ignore.
806 if (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
) {
808 } else if (alert_descr
== SSL_AD_CLOSE_NOTIFY
809 && (is_tls13
|| alert_level
== SSL3_AL_WARNING
)) {
810 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
812 } else if (alert_level
== SSL3_AL_FATAL
|| is_tls13
) {
813 s
->rwstate
= SSL_NOTHING
;
814 s
->s3
.fatal_alert
= alert_descr
;
815 SSLfatal_data(s
, SSL_AD_NO_ALERT
,
816 SSL_AD_REASON_OFFSET
+ alert_descr
,
817 "SSL alert number %d", alert_descr
);
818 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
819 ssl_release_record(s
, rr
);
820 SSL_CTX_remove_session(s
->session_ctx
, s
->session
);
822 } else if (alert_descr
== SSL_AD_NO_RENEGOTIATION
) {
824 * This is a warning but we receive it if we requested
825 * renegotiation and the peer denied it. Terminate with a fatal
826 * alert because if application tried to renegotiate it
827 * presumably had a good reason and expects it to succeed. In
828 * future we might have a renegotiation where we don't care if
829 * the peer refused it where we carry on.
831 SSLfatal(s
, SSL_AD_HANDSHAKE_FAILURE
, SSL_R_NO_RENEGOTIATION
);
833 } else if (alert_level
== SSL3_AL_WARNING
) {
834 /* We ignore any other warning alert in TLSv1.2 and below */
838 SSLfatal(s
, SSL_AD_ILLEGAL_PARAMETER
, SSL_R_UNKNOWN_ALERT_TYPE
);
842 if ((s
->shutdown
& SSL_SENT_SHUTDOWN
) != 0) {
843 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
847 * We ignore any handshake messages sent to us unless they are
848 * TLSv1.3 in which case we want to process them. For all other
849 * handshake messages we can't do anything reasonable with them
850 * because we are unable to write any response due to having already
853 if (!SSL_CONNECTION_IS_TLS13(s
)) {
854 ssl_release_record(s
, rr
);
856 if ((s
->mode
& SSL_MODE_AUTO_RETRY
) != 0)
859 s
->rwstate
= SSL_READING
;
860 rbio
= SSL_get_rbio(ssl
);
861 BIO_clear_retry_flags(rbio
);
862 BIO_set_retry_read(rbio
);
867 * The peer is continuing to send application data, but we have
868 * already sent close_notify. If this was expected we should have
869 * been called via SSL_read() and this would have been handled
871 * No alert sent because we already sent close_notify
873 ssl_release_record(s
, rr
);
874 SSLfatal(s
, SSL_AD_NO_ALERT
,
875 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY
);
881 * For handshake data we have 'fragment' storage, so fill that so that we
882 * can process the header at a fixed place. This is done after the
883 * "SHUTDOWN" code above to avoid filling the fragment storage with data
884 * that we're just going to discard.
886 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
887 size_t dest_maxlen
= sizeof(s
->rlayer
.handshake_fragment
);
888 unsigned char *dest
= s
->rlayer
.handshake_fragment
;
889 size_t *dest_len
= &s
->rlayer
.handshake_fragment_len
;
891 n
= dest_maxlen
- *dest_len
; /* available space in 'dest' */
893 n
= rr
->length
; /* available bytes */
895 /* now move 'n' bytes: */
896 memcpy(dest
+ *dest_len
, rr
->data
+ rr
->off
, n
);
901 ssl_release_record(s
, rr
);
903 if (*dest_len
< dest_maxlen
)
904 goto start
; /* fragment was too small */
907 if (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
) {
908 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
913 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
914 * protocol violation)
916 if ((s
->rlayer
.handshake_fragment_len
>= 4)
917 && !ossl_statem_get_in_handshake(s
)) {
918 int ined
= (s
->early_data_state
== SSL_EARLY_DATA_READING
);
920 /* We found handshake data, so we're going back into init */
921 ossl_statem_set_in_init(s
, 1);
923 i
= s
->handshake_func(ssl
);
924 /* SSLfatal() already called if appropriate */
932 * If we were actually trying to read early data and we found a
933 * handshake message, then we don't want to continue to try and read
934 * the application data any more. It won't be "early" now.
939 if (!(s
->mode
& SSL_MODE_AUTO_RETRY
)) {
940 if (!RECORD_LAYER_read_pending(&s
->rlayer
)) {
943 * In the case where we try to read application data, but we
944 * trigger an SSL handshake, we return -1 with the retry
945 * option set. Otherwise renegotiation may cause nasty
946 * problems in the blocking world
948 s
->rwstate
= SSL_READING
;
949 bio
= SSL_get_rbio(ssl
);
950 BIO_clear_retry_flags(bio
);
951 BIO_set_retry_read(bio
);
961 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
962 * TLS 1.2 says you MUST send an unexpected message alert. We use the
963 * TLS 1.2 behaviour for all protocol versions to prevent issues where
964 * no progress is being made and the peer continually sends unrecognised
965 * record types, using up resources processing them.
967 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
969 case SSL3_RT_CHANGE_CIPHER_SPEC
:
971 case SSL3_RT_HANDSHAKE
:
973 * we already handled all of these, with the possible exception of
974 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
975 * that should not happen when type != rr->type
977 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, ERR_R_INTERNAL_ERROR
);
979 case SSL3_RT_APPLICATION_DATA
:
981 * At this point, we were expecting handshake data, but have
982 * application data. If the library was running inside ssl3_read()
983 * (i.e. in_read_app_data is set) and it makes sense to read
984 * application data at this point (session renegotiation not yet
985 * started), we will indulge it.
987 if (ossl_statem_app_data_allowed(s
)) {
988 s
->s3
.in_read_app_data
= 2;
990 } else if (ossl_statem_skip_early_data(s
)) {
992 * This can happen after a client sends a CH followed by early_data,
993 * but the server responds with a HelloRetryRequest. The server
994 * reads the next record from the client expecting to find a
995 * plaintext ClientHello but gets a record which appears to be
996 * application data. The trial decrypt "works" because null
997 * decryption was applied. We just skip it and move on to the next
1000 if (!ossl_early_data_count_ok(s
, rr
->length
,
1001 EARLY_DATA_CIPHERTEXT_OVERHEAD
, 0)) {
1002 /* SSLfatal() already called */
1005 ssl_release_record(s
, rr
);
1008 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
1014 void ssl3_record_sequence_update(unsigned char *seq
)
1018 for (i
= 7; i
>= 0; i
--) {
1026 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1027 * format and false otherwise.
1029 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER
*rl
)
1031 if (SSL_CONNECTION_IS_DTLS(rl
->s
))
1033 return rl
->tlsrecs
[0].version
== SSL2_VERSION
;
1036 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper
;
1037 static void rlayer_msg_callback_wrapper(int write_p
, int version
,
1038 int content_type
, const void *buf
,
1039 size_t len
, void *cbarg
)
1041 SSL_CONNECTION
*s
= cbarg
;
1042 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1044 if (s
->msg_callback
!= NULL
)
1045 s
->msg_callback(write_p
, version
, content_type
, buf
, len
, ssl
,
1046 s
->msg_callback_arg
);
1049 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper
;
1050 static int rlayer_security_wrapper(void *cbarg
, int op
, int bits
, int nid
,
1053 SSL_CONNECTION
*s
= cbarg
;
1055 return ssl_security(s
, op
, bits
, nid
, other
);
1058 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper
;
1059 static size_t rlayer_padding_wrapper(void *cbarg
, int type
, size_t len
)
1061 SSL_CONNECTION
*s
= cbarg
;
1062 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1064 return s
->rlayer
.record_padding_cb(ssl
, type
, len
,
1065 s
->rlayer
.record_padding_arg
);
1068 static const OSSL_DISPATCH rlayer_dispatch
[] = {
1069 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA
, (void (*)(void))ossl_statem_skip_early_data
},
1070 { OSSL_FUNC_RLAYER_MSG_CALLBACK
, (void (*)(void))rlayer_msg_callback_wrapper
},
1071 { OSSL_FUNC_RLAYER_SECURITY
, (void (*)(void))rlayer_security_wrapper
},
1072 { OSSL_FUNC_RLAYER_PADDING
, (void (*)(void))rlayer_padding_wrapper
},
1076 static const OSSL_RECORD_METHOD
*ssl_select_next_record_layer(SSL_CONNECTION
*s
,
1080 if (level
== OSSL_RECORD_PROTECTION_LEVEL_NONE
) {
1081 if (SSL_CONNECTION_IS_DTLS(s
))
1082 return &ossl_dtls_record_method
;
1084 return &ossl_tls_record_method
;
1087 #ifndef OPENSSL_NO_KTLS
1088 /* KTLS does not support renegotiation */
1089 if (level
== OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1090 && (s
->options
& SSL_OP_ENABLE_KTLS
) != 0
1091 && (SSL_CONNECTION_IS_TLS13(s
) || SSL_IS_FIRST_HANDSHAKE(s
)))
1092 return &ossl_ktls_record_method
;
1095 /* Default to the current OSSL_RECORD_METHOD */
1096 return s
->rlayer
.rrlmethod
;
1099 static int ssl_post_record_layer_select(SSL_CONNECTION
*s
, int direction
)
1101 const OSSL_RECORD_METHOD
*thismethod
;
1102 OSSL_RECORD_LAYER
*thisrl
;
1104 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1105 thismethod
= s
->rlayer
.rrlmethod
;
1106 thisrl
= s
->rlayer
.rrl
;
1108 thismethod
= s
->rlayer
.wrlmethod
;
1109 thisrl
= s
->rlayer
.wrl
;
1112 #ifndef OPENSSL_NO_KTLS
1114 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1116 if (s
->rlayer
.rrlmethod
== &ossl_ktls_record_method
) {
1117 /* KTLS does not support renegotiation so disallow it */
1118 SSL_set_options(ssl
, SSL_OP_NO_RENEGOTIATION
);
1122 if (SSL_IS_FIRST_HANDSHAKE(s
) && thismethod
->set_first_handshake
!= NULL
)
1123 thismethod
->set_first_handshake(thisrl
, 1);
1125 if (s
->max_pipelines
!= 0 && thismethod
->set_max_pipelines
!= NULL
)
1126 thismethod
->set_max_pipelines(thisrl
, s
->max_pipelines
);
1131 int ssl_set_new_record_layer(SSL_CONNECTION
*s
, int version
,
1132 int direction
, int level
,
1133 unsigned char *key
, size_t keylen
,
1134 unsigned char *iv
, size_t ivlen
,
1135 unsigned char *mackey
, size_t mackeylen
,
1136 const EVP_CIPHER
*ciph
, size_t taglen
,
1137 int mactype
, const EVP_MD
*md
,
1138 const SSL_COMP
*comp
)
1140 OSSL_PARAM options
[5], *opts
= options
;
1141 OSSL_PARAM settings
[6], *set
= settings
;
1142 const OSSL_RECORD_METHOD
**thismethod
;
1143 OSSL_RECORD_LAYER
**thisrl
, *newrl
= NULL
;
1145 SSL_CTX
*sctx
= SSL_CONNECTION_GET_CTX(s
);
1146 const OSSL_RECORD_METHOD
*meth
;
1147 int use_etm
, stream_mac
= 0, tlstree
= 0;
1148 unsigned int maxfrag
= SSL3_RT_MAX_PLAIN_LENGTH
;
1149 int use_early_data
= 0;
1150 uint32_t max_early_data
;
1152 meth
= ssl_select_next_record_layer(s
, level
);
1154 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1155 thismethod
= &s
->rlayer
.rrlmethod
;
1156 thisrl
= &s
->rlayer
.rrl
;
1159 thismethod
= &s
->rlayer
.wrlmethod
;
1160 thisrl
= &s
->rlayer
.wrl
;
1167 if (!ossl_assert(meth
!= NULL
)) {
1168 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1172 /* Parameters that *may* be supported by a record layer if passed */
1173 *opts
++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS
,
1175 *opts
++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE
,
1177 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1178 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN
,
1179 &s
->rlayer
.default_read_buf_len
);
1180 *opts
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD
,
1181 &s
->rlayer
.read_ahead
);
1183 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING
,
1184 &s
->rlayer
.block_padding
);
1186 *opts
= OSSL_PARAM_construct_end();
1188 /* Parameters that *must* be supported by a record layer if passed */
1189 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1190 use_etm
= SSL_READ_ETM(s
) ? 1 : 0;
1191 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_STREAM
) != 0)
1194 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_TLSTREE
) != 0)
1197 use_etm
= SSL_WRITE_ETM(s
) ? 1 : 0;
1198 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_STREAM
) != 0)
1201 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_TLSTREE
) != 0)
1206 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM
,
1210 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC
,
1214 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE
,
1217 if (s
->session
!= NULL
&& USE_MAX_FRAGMENT_LENGTH_EXT(s
->session
))
1218 maxfrag
= GET_MAX_FRAGMENT_LENGTH(s
->session
);
1220 if (maxfrag
!= SSL3_RT_MAX_PLAIN_LENGTH
)
1221 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN
,
1225 * The record layer must check the amount of early data sent or received
1226 * using the early keys. A server also needs to worry about rejected early
1227 * data that might arrive when the handshake keys are in force.
1229 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1230 if (s
->server
&& direction
== OSSL_RECORD_DIRECTION_READ
) {
1231 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
1232 || level
== OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
);
1233 } else if (!s
->server
&& direction
== OSSL_RECORD_DIRECTION_WRITE
) {
1234 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
);
1236 if (use_early_data
) {
1237 max_early_data
= ossl_get_max_early_data(s
);
1239 if (max_early_data
!= 0)
1240 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA
,
1244 *set
= OSSL_PARAM_construct_end();
1250 unsigned int epoch
= 0;
1251 OSSL_DISPATCH rlayer_dispatch_tmp
[OSSL_NELEM(rlayer_dispatch
)];
1254 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1255 prev
= s
->rlayer
.rrlnext
;
1256 if (SSL_CONNECTION_IS_DTLS(s
)
1257 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1258 epoch
= DTLS_RECORD_LAYER_get_r_epoch(&s
->rlayer
) + 1; /* new epoch */
1260 if (SSL_CONNECTION_IS_DTLS(s
))
1261 next
= BIO_new(BIO_s_dgram_mem());
1263 next
= BIO_new(BIO_s_mem());
1267 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1270 s
->rlayer
.rrlnext
= next
;
1274 * Create a copy of the dispatch array, missing out wrappers for
1275 * callbacks that we don't need.
1277 for (i
= 0, j
= 0; i
< OSSL_NELEM(rlayer_dispatch
); i
++) {
1278 switch (rlayer_dispatch
[i
].function_id
) {
1279 case OSSL_FUNC_RLAYER_MSG_CALLBACK
:
1280 if (s
->msg_callback
== NULL
)
1283 case OSSL_FUNC_RLAYER_PADDING
:
1284 if (s
->rlayer
.record_padding_cb
== NULL
)
1290 rlayer_dispatch_tmp
[j
++] = rlayer_dispatch
[i
];
1293 rlret
= meth
->new_record_layer(sctx
->libctx
, sctx
->propq
, version
,
1294 s
->server
, direction
, level
, epoch
,
1295 key
, keylen
, iv
, ivlen
, mackey
,
1296 mackeylen
, ciph
, taglen
, mactype
, md
,
1297 comp
, prev
, thisbio
, next
, NULL
, NULL
,
1298 settings
, options
, rlayer_dispatch_tmp
,
1302 case OSSL_RECORD_RETURN_FATAL
:
1303 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_RECORD_LAYER_FAILURE
);
1306 case OSSL_RECORD_RETURN_NON_FATAL_ERR
:
1307 if (*thismethod
!= meth
&& *thismethod
!= NULL
) {
1309 * We tried a new record layer method, but it didn't work out,
1310 * so we fallback to the original method and try again
1315 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_NO_SUITABLE_RECORD_LAYER
);
1318 case OSSL_RECORD_RETURN_SUCCESS
:
1322 /* Should not happen */
1323 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1329 if (*thismethod
!= NULL
&& !(*thismethod
)->free(*thisrl
)) {
1330 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1337 return ssl_post_record_layer_select(s
, direction
);
1340 int ssl_set_record_protocol_version(SSL_CONNECTION
*s
, int vers
)
1342 if (!ossl_assert(s
->rlayer
.rrlmethod
!= NULL
)
1343 || !ossl_assert(s
->rlayer
.wrlmethod
!= NULL
))
1345 s
->rlayer
.rrlmethod
->set_protocol_version(s
->rlayer
.rrl
, s
->version
);
1346 s
->rlayer
.wrlmethod
->set_protocol_version(s
->rlayer
.wrl
, s
->version
);