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
;
191 /* TODO(RECLAYER): Re-enable multiblock code */
192 #if 0 && !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
196 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
197 OSSL_RECORD_TEMPLATE tmpls
[SSL_MAX_PIPELINES
];
198 unsigned int recversion
;
203 s
->rwstate
= SSL_NOTHING
;
204 tot
= s
->rlayer
.wnum
;
206 * ensure that if we end up with a smaller value of data to write out
207 * than the original len from a write which didn't complete for
208 * non-blocking I/O and also somehow ended up avoiding the check for
209 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
210 * possible to end up with (len-tot) as a large number that will then
211 * promptly send beyond the end of the users buffer ... so we trap and
212 * report the error in a way the user will notice
214 if ((len
< s
->rlayer
.wnum
)
215 || ((s
->rlayer
.wpend_tot
!= 0)
216 && (len
< (s
->rlayer
.wnum
+ s
->rlayer
.wpend_tot
)))) {
217 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_BAD_LENGTH
);
221 if (s
->early_data_state
== SSL_EARLY_DATA_WRITING
222 && !ossl_early_data_count_ok(s
, len
, 0, 1)) {
223 /* SSLfatal() already called */
230 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
231 * into init unless we have writes pending - in which case we should finish
234 if (s
->rlayer
.wpend_tot
== 0 && (s
->key_update
!= SSL_KEY_UPDATE_NONE
235 || s
->ext
.extra_tickets_expected
> 0))
236 ossl_statem_set_in_init(s
, 1);
239 * When writing early data on the server side we could be "in_init" in
240 * between receiving the EoED and the CF - but we don't want to handle those
243 if (SSL_in_init(ssl
) && !ossl_statem_get_in_handshake(s
)
244 && s
->early_data_state
!= SSL_EARLY_DATA_UNAUTH_WRITING
) {
245 i
= s
->handshake_func(ssl
);
246 /* SSLfatal() already called */
254 i
= tls_write_check_pending(s
, type
, buf
, len
);
256 /* SSLfatal() already called */
260 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
261 s
->rlayer
.wrlmethod
->retry_write_records(s
->rlayer
.wrl
));
264 tot
+= s
->rlayer
.wpend_tot
;
265 s
->rlayer
.wpend_tot
= 0;
266 } /* else no retry required */
270 * We've not previously sent any data for this write so memorize
271 * arguments so that we can detect bad write retries later
273 s
->rlayer
.wpend_tot
= 0;
274 s
->rlayer
.wpend_type
= type
;
275 s
->rlayer
.wpend_buf
= buf
;
276 s
->rlayer
.wpend_ret
= len
;
279 /* TODO(RECLAYER): Is this needed any more? */
280 if (tot
== len
) { /* done? */
285 /* If we have an alert to send, lets send it */
286 if (s
->s3
.alert_dispatch
) {
287 i
= ssl
->method
->ssl_dispatch_alert(ssl
);
289 /* SSLfatal() already called if appropriate */
292 /* if it went, fall through and send more stuff */
297 max_send_fragment
= ssl_get_max_send_fragment(s
);
298 split_send_fragment
= ssl_get_split_send_fragment(s
);
300 * TODO(RECLAYER): This comment is now out-of-date and probably needs to
301 * move somewhere else
303 * If max_pipelines is 0 then this means "undefined" and we default to
304 * 1 pipeline. Similarly if the cipher does not support pipelined
305 * processing then we also only use 1 pipeline, or if we're not using
309 maxpipes
= s
->rlayer
.wrlmethod
->get_max_records(s
->rlayer
.wrl
, type
, n
,
311 &split_send_fragment
);
312 if (s
->max_pipelines
> 0 && maxpipes
> s
->max_pipelines
)
313 maxpipes
= s
->max_pipelines
;
315 if (maxpipes
> SSL_MAX_PIPELINES
)
316 maxpipes
= SSL_MAX_PIPELINES
;
320 /* TODO(RECLAYER): FIX ME */
322 || s
->enc_write_ctx
== NULL
323 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s
->enc_write_ctx
))
324 & EVP_CIPH_FLAG_PIPELINE
) == 0
325 || !SSL_USE_EXPLICIT_IV(s
))
328 if (max_send_fragment
== 0
329 || split_send_fragment
== 0
330 || split_send_fragment
> max_send_fragment
) {
332 * We should have prevented this when we set/get the split and max send
333 * fragments so we shouldn't get here
335 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
340 * Some servers hang if initial client hello is larger than 256 bytes
341 * and record version number > TLS 1.0
343 /* TODO(RECLAYER): Does this also need to be in the DTLS equivalent code? */
344 recversion
= (s
->version
== TLS1_3_VERSION
) ? TLS1_2_VERSION
: s
->version
;
345 if (SSL_get_state(ssl
) == TLS_ST_CW_CLNT_HELLO
347 && TLS1_get_version(ssl
) > TLS1_VERSION
348 && s
->hello_retry_request
== SSL_HRR_NONE
)
349 recversion
= TLS1_VERSION
;
352 size_t tmppipelen
, remain
;
353 size_t numpipes
, j
, lensofar
= 0;
358 numpipes
= ((n
- 1) / split_send_fragment
) + 1;
359 if (numpipes
> maxpipes
)
362 if (n
/ numpipes
>= split_send_fragment
) {
364 * We have enough data to completely fill all available
367 for (j
= 0; j
< numpipes
; j
++) {
368 tmpls
[j
].type
= type
;
369 tmpls
[j
].version
= recversion
;
370 tmpls
[j
].buf
= &(buf
[tot
]) + (j
* split_send_fragment
);
371 tmpls
[j
].buflen
= split_send_fragment
;
373 /* Remember how much data we are going to be sending */
374 s
->rlayer
.wpend_tot
= numpipes
* split_send_fragment
;
376 /* We can partially fill all available pipelines */
377 tmppipelen
= n
/ numpipes
;
378 remain
= n
% numpipes
;
380 * If there is a remainder we add an extra byte to the first few
385 for (j
= 0; j
< numpipes
; j
++) {
386 tmpls
[j
].type
= type
;
387 tmpls
[j
].version
= recversion
;
388 tmpls
[j
].buf
= &(buf
[tot
]) + lensofar
;
389 tmpls
[j
].buflen
= tmppipelen
;
390 lensofar
+= tmppipelen
;
394 /* Remember how much data we are going to be sending */
395 s
->rlayer
.wpend_tot
= n
;
398 i
= HANDLE_RLAYER_WRITE_RETURN(s
,
399 s
->rlayer
.wrlmethod
->write_records(s
->rlayer
.wrl
, tmpls
, numpipes
));
401 /* SSLfatal() already called if appropriate */
402 s
->rlayer
.wnum
= tot
;
406 if (s
->rlayer
.wpend_tot
== n
407 || (type
== SSL3_RT_APPLICATION_DATA
408 && (s
->mode
& SSL_MODE_ENABLE_PARTIAL_WRITE
) != 0)) {
409 *written
= tot
+ s
->rlayer
.wpend_tot
;
410 s
->rlayer
.wpend_tot
= 0;
414 n
-= s
->rlayer
.wpend_tot
;
415 tot
+= s
->rlayer
.wpend_tot
;
419 int ossl_tls_handle_rlayer_return(SSL_CONNECTION
*s
, int writing
, int ret
,
420 char *file
, int line
)
422 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
424 if (ret
== OSSL_RECORD_RETURN_RETRY
) {
425 s
->rwstate
= writing
? SSL_WRITING
: SSL_READING
;
428 s
->rwstate
= SSL_NOTHING
;
429 if (ret
== OSSL_RECORD_RETURN_EOF
) {
432 * This shouldn't happen with a writing operation. We treat it
436 ERR_set_debug(file
, line
, 0);
437 ossl_statem_fatal(s
, SSL_AD_INTERNAL_ERROR
,
438 ERR_R_INTERNAL_ERROR
, NULL
);
439 ret
= OSSL_RECORD_RETURN_FATAL
;
440 } else if ((s
->options
& SSL_OP_IGNORE_UNEXPECTED_EOF
) != 0) {
441 SSL_set_shutdown(ssl
, SSL_RECEIVED_SHUTDOWN
);
442 s
->s3
.warn_alert
= SSL_AD_CLOSE_NOTIFY
;
445 ERR_set_debug(file
, line
, 0);
446 ossl_statem_fatal(s
, SSL_AD_DECODE_ERROR
,
447 SSL_R_UNEXPECTED_EOF_WHILE_READING
, NULL
);
449 } else if (ret
== OSSL_RECORD_RETURN_FATAL
) {
450 int al
= s
->rlayer
.rrlmethod
->get_alert_code(s
->rlayer
.rrl
);
452 if (al
!= SSL_AD_NO_ALERT
) {
454 ERR_set_debug(file
, line
, 0);
455 ossl_statem_fatal(s
, al
, SSL_R_RECORD_LAYER_FAILURE
, NULL
);
458 * else some failure but there is no alert code. We don't log an
459 * error for this. The record layer should have logged an error
460 * already or, if not, its due to some sys call error which will be
461 * reported via SSL_ERROR_SYSCALL and errno.
465 * The record layer distinguishes the cases of EOF, non-fatal
466 * err and retry. Upper layers do not.
467 * If we got a retry or success then *ret is already correct,
468 * otherwise we need to convert the return value.
470 if (ret
== OSSL_RECORD_RETURN_NON_FATAL_ERR
|| ret
== OSSL_RECORD_RETURN_EOF
)
472 else if (ret
< OSSL_RECORD_RETURN_NON_FATAL_ERR
)
479 void ssl_release_record(SSL_CONNECTION
*s
, TLS_RECORD
*rr
)
481 if (rr
->rechandle
!= NULL
) {
482 /* The record layer allocated the buffers for this record */
483 s
->rlayer
.rrlmethod
->release_record(s
->rlayer
.rrl
, rr
->rechandle
);
485 /* We allocated the buffers for this record (only happens with DTLS) */
486 OPENSSL_free(rr
->data
);
488 s
->rlayer
.curr_rec
++;
492 * Return up to 'len' payload bytes received in 'type' records.
493 * 'type' is one of the following:
495 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
496 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
497 * - 0 (during a shutdown, no data has to be returned)
499 * If we don't have stored data to work from, read a SSL/TLS record first
500 * (possibly multiple records if we still don't have anything to return).
502 * This function must handle any surprises the peer may have for us, such as
503 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
504 * messages are treated as if they were handshake messages *if* the |recvd_type|
505 * argument is non NULL.
506 * Also if record payloads contain fragments too small to process, we store
507 * them until there is enough for the respective protocol (the record protocol
508 * may use arbitrary fragmentation and even interleaving):
509 * Change cipher spec protocol
510 * just 1 byte needed, no need for keeping anything stored
512 * 2 bytes needed (AlertLevel, AlertDescription)
514 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
515 * to detect unexpected Client Hello and Hello Request messages
516 * here, anything else is handled by higher layers
517 * Application data protocol
518 * none of our business
520 int ssl3_read_bytes(SSL
*ssl
, int type
, int *recvd_type
, unsigned char *buf
,
521 size_t len
, int peek
, size_t *readbytes
)
524 size_t n
, curr_rec
, totalbytes
;
526 void (*cb
) (const SSL
*ssl
, int type2
, int val
) = NULL
;
528 SSL_CONNECTION
*s
= SSL_CONNECTION_FROM_SSL_ONLY(ssl
);
530 is_tls13
= SSL_CONNECTION_IS_TLS13(s
);
533 && (type
!= SSL3_RT_APPLICATION_DATA
)
534 && (type
!= SSL3_RT_HANDSHAKE
))
535 || (peek
&& (type
!= SSL3_RT_APPLICATION_DATA
))) {
536 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
540 if ((type
== SSL3_RT_HANDSHAKE
) && (s
->rlayer
.handshake_fragment_len
> 0))
541 /* (partially) satisfy request from storage */
543 unsigned char *src
= s
->rlayer
.handshake_fragment
;
544 unsigned char *dst
= buf
;
549 while ((len
> 0) && (s
->rlayer
.handshake_fragment_len
> 0)) {
552 s
->rlayer
.handshake_fragment_len
--;
555 /* move any remaining fragment bytes: */
556 for (k
= 0; k
< s
->rlayer
.handshake_fragment_len
; k
++)
557 s
->rlayer
.handshake_fragment
[k
] = *src
++;
559 if (recvd_type
!= NULL
)
560 *recvd_type
= SSL3_RT_HANDSHAKE
;
567 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
570 if (!ossl_statem_get_in_handshake(s
) && SSL_in_init(ssl
)) {
571 /* type == SSL3_RT_APPLICATION_DATA */
572 i
= s
->handshake_func(ssl
);
573 /* SSLfatal() already called */
580 s
->rwstate
= SSL_NOTHING
;
583 * For each record 'i' up to |num_recs]
584 * rr[i].type - is the type of record
586 * rr[i].off, - offset into 'data' for next read
587 * rr[i].length, - number of bytes.
589 /* get new records if necessary */
590 if (s
->rlayer
.curr_rec
>= s
->rlayer
.num_recs
) {
591 s
->rlayer
.curr_rec
= s
->rlayer
.num_recs
= 0;
593 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.num_recs
];
595 ret
= HANDLE_RLAYER_READ_RETURN(s
,
596 s
->rlayer
.rrlmethod
->read_record(s
->rlayer
.rrl
,
598 &rr
->version
, &rr
->type
,
599 &rr
->data
, &rr
->length
,
602 /* SSLfatal() already called if appropriate */
606 s
->rlayer
.num_recs
++;
607 } while (s
->rlayer
.rrlmethod
->processed_read_pending(s
->rlayer
.rrl
)
608 && s
->rlayer
.num_recs
< SSL_MAX_PIPELINES
);
610 rr
= &s
->rlayer
.tlsrecs
[s
->rlayer
.curr_rec
];
612 if (s
->rlayer
.handshake_fragment_len
> 0
613 && rr
->type
!= SSL3_RT_HANDSHAKE
614 && SSL_CONNECTION_IS_TLS13(s
)) {
615 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
616 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA
);
621 * Reset the count of consecutive warning alerts if we've got a non-empty
622 * record that isn't an alert.
624 if (rr
->type
!= SSL3_RT_ALERT
&& rr
->length
!= 0)
625 s
->rlayer
.alert_count
= 0;
627 /* we now have a packet which can be read and processed */
629 if (s
->s3
.change_cipher_spec
/* set when we receive ChangeCipherSpec,
630 * reset by ssl3_get_finished */
631 && (rr
->type
!= SSL3_RT_HANDSHAKE
)) {
632 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
633 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED
);
638 * If the other end has shut down, throw anything we read away (even in
641 if (s
->shutdown
& SSL_RECEIVED_SHUTDOWN
) {
642 s
->rlayer
.curr_rec
++;
643 s
->rwstate
= SSL_NOTHING
;
648 || (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
649 && type
== SSL3_RT_HANDSHAKE
&& recvd_type
!= NULL
652 * SSL3_RT_APPLICATION_DATA or
653 * SSL3_RT_HANDSHAKE or
654 * SSL3_RT_CHANGE_CIPHER_SPEC
657 * make sure that we are not getting application data when we are
658 * doing a handshake for the first time
660 if (SSL_in_init(ssl
) && type
== SSL3_RT_APPLICATION_DATA
661 && s
->enc_read_ctx
== NULL
) {
662 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_APP_DATA_IN_HANDSHAKE
);
666 if (type
== SSL3_RT_HANDSHAKE
667 && rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
668 && s
->rlayer
.handshake_fragment_len
> 0) {
669 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
673 if (recvd_type
!= NULL
)
674 *recvd_type
= rr
->type
;
678 * Skip a zero length record. This ensures multiple calls to
679 * SSL_read() with a zero length buffer will eventually cause
680 * SSL_pending() to report data as being available.
683 ssl_release_record(s
, rr
);
689 curr_rec
= s
->rlayer
.curr_rec
;
691 if (len
- totalbytes
> rr
->length
)
694 n
= len
- totalbytes
;
696 memcpy(buf
, &(rr
->data
[rr
->off
]), n
);
699 /* Mark any zero length record as consumed CVE-2016-6305 */
701 ssl_release_record(s
, rr
);
703 if (s
->options
& SSL_OP_CLEANSE_PLAINTEXT
)
704 OPENSSL_cleanse(&(rr
->data
[rr
->off
]), n
);
708 ssl_release_record(s
, rr
);
711 || (peek
&& n
== rr
->length
)) {
716 } while (type
== SSL3_RT_APPLICATION_DATA
717 && curr_rec
< s
->rlayer
.num_recs
718 && totalbytes
< len
);
719 if (totalbytes
== 0) {
720 /* We must have read empty records. Get more data */
723 *readbytes
= totalbytes
;
728 * If we get here, then type != rr->type; if we have a handshake message,
729 * then it was unexpected (Hello Request or Client Hello) or invalid (we
730 * were actually expecting a CCS).
734 * Lets just double check that we've not got an SSLv2 record
736 if (rr
->version
== SSL2_VERSION
) {
738 * Should never happen. ssl3_get_record() should only give us an SSLv2
739 * record back if this is the first packet and we are looking for an
740 * initial ClientHello. Therefore |type| should always be equal to
741 * |rr->type|. If not then something has gone horribly wrong
743 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
747 if (ssl
->method
->version
== TLS_ANY_VERSION
748 && (s
->server
|| rr
->type
!= SSL3_RT_ALERT
)) {
750 * If we've got this far and still haven't decided on what version
751 * we're using then this must be a client side alert we're dealing
752 * with. We shouldn't be receiving anything other than a ClientHello
753 * if we are a server.
755 s
->version
= rr
->version
;
756 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_MESSAGE
);
761 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
762 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
765 if (rr
->type
== SSL3_RT_ALERT
) {
766 unsigned int alert_level
, alert_descr
;
767 unsigned char *alert_bytes
= rr
->data
771 if (!PACKET_buf_init(&alert
, alert_bytes
, rr
->length
)
772 || !PACKET_get_1(&alert
, &alert_level
)
773 || !PACKET_get_1(&alert
, &alert_descr
)
774 || PACKET_remaining(&alert
) != 0) {
775 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_INVALID_ALERT
);
780 s
->msg_callback(0, s
->version
, SSL3_RT_ALERT
, alert_bytes
, 2, ssl
,
781 s
->msg_callback_arg
);
783 if (s
->info_callback
!= NULL
)
784 cb
= s
->info_callback
;
785 else if (ssl
->ctx
->info_callback
!= NULL
)
786 cb
= ssl
->ctx
->info_callback
;
789 j
= (alert_level
<< 8) | alert_descr
;
790 cb(ssl
, SSL_CB_READ_ALERT
, j
);
793 if ((!is_tls13
&& alert_level
== SSL3_AL_WARNING
)
794 || (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
)) {
795 s
->s3
.warn_alert
= alert_descr
;
796 ssl_release_record(s
, rr
);
798 s
->rlayer
.alert_count
++;
799 if (s
->rlayer
.alert_count
== MAX_WARN_ALERT_COUNT
) {
800 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
,
801 SSL_R_TOO_MANY_WARN_ALERTS
);
807 * Apart from close_notify the only other warning alert in TLSv1.3
808 * is user_cancelled - which we just ignore.
810 if (is_tls13
&& alert_descr
== SSL_AD_USER_CANCELLED
) {
812 } else if (alert_descr
== SSL_AD_CLOSE_NOTIFY
813 && (is_tls13
|| alert_level
== SSL3_AL_WARNING
)) {
814 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
816 } else if (alert_level
== SSL3_AL_FATAL
|| is_tls13
) {
817 s
->rwstate
= SSL_NOTHING
;
818 s
->s3
.fatal_alert
= alert_descr
;
819 SSLfatal_data(s
, SSL_AD_NO_ALERT
,
820 SSL_AD_REASON_OFFSET
+ alert_descr
,
821 "SSL alert number %d", alert_descr
);
822 s
->shutdown
|= SSL_RECEIVED_SHUTDOWN
;
823 ssl_release_record(s
, rr
);
824 SSL_CTX_remove_session(s
->session_ctx
, s
->session
);
826 } else if (alert_descr
== SSL_AD_NO_RENEGOTIATION
) {
828 * This is a warning but we receive it if we requested
829 * renegotiation and the peer denied it. Terminate with a fatal
830 * alert because if application tried to renegotiate it
831 * presumably had a good reason and expects it to succeed. In
832 * future we might have a renegotiation where we don't care if
833 * the peer refused it where we carry on.
835 SSLfatal(s
, SSL_AD_HANDSHAKE_FAILURE
, SSL_R_NO_RENEGOTIATION
);
837 } else if (alert_level
== SSL3_AL_WARNING
) {
838 /* We ignore any other warning alert in TLSv1.2 and below */
842 SSLfatal(s
, SSL_AD_ILLEGAL_PARAMETER
, SSL_R_UNKNOWN_ALERT_TYPE
);
846 if ((s
->shutdown
& SSL_SENT_SHUTDOWN
) != 0) {
847 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
851 * We ignore any handshake messages sent to us unless they are
852 * TLSv1.3 in which case we want to process them. For all other
853 * handshake messages we can't do anything reasonable with them
854 * because we are unable to write any response due to having already
857 if (!SSL_CONNECTION_IS_TLS13(s
)) {
858 ssl_release_record(s
, rr
);
860 if ((s
->mode
& SSL_MODE_AUTO_RETRY
) != 0)
863 s
->rwstate
= SSL_READING
;
864 rbio
= SSL_get_rbio(ssl
);
865 BIO_clear_retry_flags(rbio
);
866 BIO_set_retry_read(rbio
);
871 * The peer is continuing to send application data, but we have
872 * already sent close_notify. If this was expected we should have
873 * been called via SSL_read() and this would have been handled
875 * No alert sent because we already sent close_notify
877 ssl_release_record(s
, rr
);
878 SSLfatal(s
, SSL_AD_NO_ALERT
,
879 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY
);
885 * For handshake data we have 'fragment' storage, so fill that so that we
886 * can process the header at a fixed place. This is done after the
887 * "SHUTDOWN" code above to avoid filling the fragment storage with data
888 * that we're just going to discard.
890 if (rr
->type
== SSL3_RT_HANDSHAKE
) {
891 size_t dest_maxlen
= sizeof(s
->rlayer
.handshake_fragment
);
892 unsigned char *dest
= s
->rlayer
.handshake_fragment
;
893 size_t *dest_len
= &s
->rlayer
.handshake_fragment_len
;
895 n
= dest_maxlen
- *dest_len
; /* available space in 'dest' */
897 n
= rr
->length
; /* available bytes */
899 /* now move 'n' bytes: */
900 memcpy(dest
+ *dest_len
, rr
->data
+ rr
->off
, n
);
905 ssl_release_record(s
, rr
);
907 if (*dest_len
< dest_maxlen
)
908 goto start
; /* fragment was too small */
911 if (rr
->type
== SSL3_RT_CHANGE_CIPHER_SPEC
) {
912 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_CCS_RECEIVED_EARLY
);
917 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
918 * protocol violation)
920 if ((s
->rlayer
.handshake_fragment_len
>= 4)
921 && !ossl_statem_get_in_handshake(s
)) {
922 int ined
= (s
->early_data_state
== SSL_EARLY_DATA_READING
);
924 /* We found handshake data, so we're going back into init */
925 ossl_statem_set_in_init(s
, 1);
927 i
= s
->handshake_func(ssl
);
928 /* SSLfatal() already called if appropriate */
936 * If we were actually trying to read early data and we found a
937 * handshake message, then we don't want to continue to try and read
938 * the application data any more. It won't be "early" now.
943 if (!(s
->mode
& SSL_MODE_AUTO_RETRY
)) {
944 if (!RECORD_LAYER_read_pending(&s
->rlayer
)) {
947 * In the case where we try to read application data, but we
948 * trigger an SSL handshake, we return -1 with the retry
949 * option set. Otherwise renegotiation may cause nasty
950 * problems in the blocking world
952 s
->rwstate
= SSL_READING
;
953 bio
= SSL_get_rbio(ssl
);
954 BIO_clear_retry_flags(bio
);
955 BIO_set_retry_read(bio
);
965 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
966 * TLS 1.2 says you MUST send an unexpected message alert. We use the
967 * TLS 1.2 behaviour for all protocol versions to prevent issues where
968 * no progress is being made and the peer continually sends unrecognised
969 * record types, using up resources processing them.
971 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
973 case SSL3_RT_CHANGE_CIPHER_SPEC
:
975 case SSL3_RT_HANDSHAKE
:
977 * we already handled all of these, with the possible exception of
978 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
979 * that should not happen when type != rr->type
981 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, ERR_R_INTERNAL_ERROR
);
983 case SSL3_RT_APPLICATION_DATA
:
985 * At this point, we were expecting handshake data, but have
986 * application data. If the library was running inside ssl3_read()
987 * (i.e. in_read_app_data is set) and it makes sense to read
988 * application data at this point (session renegotiation not yet
989 * started), we will indulge it.
991 if (ossl_statem_app_data_allowed(s
)) {
992 s
->s3
.in_read_app_data
= 2;
994 } else if (ossl_statem_skip_early_data(s
)) {
996 * This can happen after a client sends a CH followed by early_data,
997 * but the server responds with a HelloRetryRequest. The server
998 * reads the next record from the client expecting to find a
999 * plaintext ClientHello but gets a record which appears to be
1000 * application data. The trial decrypt "works" because null
1001 * decryption was applied. We just skip it and move on to the next
1004 if (!ossl_early_data_count_ok(s
, rr
->length
,
1005 EARLY_DATA_CIPHERTEXT_OVERHEAD
, 0)) {
1006 /* SSLfatal() already called */
1009 ssl_release_record(s
, rr
);
1012 SSLfatal(s
, SSL_AD_UNEXPECTED_MESSAGE
, SSL_R_UNEXPECTED_RECORD
);
1018 void ssl3_record_sequence_update(unsigned char *seq
)
1022 for (i
= 7; i
>= 0; i
--) {
1030 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1031 * format and false otherwise.
1033 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER
*rl
)
1035 if (SSL_CONNECTION_IS_DTLS(rl
->s
))
1037 return rl
->tlsrecs
[0].version
== SSL2_VERSION
;
1040 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper
;
1041 static void rlayer_msg_callback_wrapper(int write_p
, int version
,
1042 int content_type
, const void *buf
,
1043 size_t len
, void *cbarg
)
1045 SSL_CONNECTION
*s
= cbarg
;
1046 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1048 if (s
->msg_callback
!= NULL
)
1049 s
->msg_callback(write_p
, version
, content_type
, buf
, len
, ssl
,
1050 s
->msg_callback_arg
);
1053 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper
;
1054 static int rlayer_security_wrapper(void *cbarg
, int op
, int bits
, int nid
,
1057 SSL_CONNECTION
*s
= cbarg
;
1059 return ssl_security(s
, op
, bits
, nid
, other
);
1062 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper
;
1063 static size_t rlayer_padding_wrapper(void *cbarg
, int type
, size_t len
)
1065 SSL_CONNECTION
*s
= cbarg
;
1066 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1068 return s
->rlayer
.record_padding_cb(ssl
, type
, len
,
1069 s
->rlayer
.record_padding_arg
);
1072 static const OSSL_DISPATCH rlayer_dispatch
[] = {
1073 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA
, (void (*)(void))ossl_statem_skip_early_data
},
1074 { OSSL_FUNC_RLAYER_MSG_CALLBACK
, (void (*)(void))rlayer_msg_callback_wrapper
},
1075 { OSSL_FUNC_RLAYER_SECURITY
, (void (*)(void))rlayer_security_wrapper
},
1076 { OSSL_FUNC_RLAYER_PADDING
, (void (*)(void))rlayer_padding_wrapper
},
1080 static const OSSL_RECORD_METHOD
*ssl_select_next_record_layer(SSL_CONNECTION
*s
,
1084 if (level
== OSSL_RECORD_PROTECTION_LEVEL_NONE
) {
1085 if (SSL_CONNECTION_IS_DTLS(s
))
1086 return &ossl_dtls_record_method
;
1088 return &ossl_tls_record_method
;
1091 #ifndef OPENSSL_NO_KTLS
1092 /* KTLS does not support renegotiation */
1093 if (level
== OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1094 && (s
->options
& SSL_OP_ENABLE_KTLS
) != 0
1095 && (SSL_CONNECTION_IS_TLS13(s
) || SSL_IS_FIRST_HANDSHAKE(s
)))
1096 return &ossl_ktls_record_method
;
1099 /* Default to the current OSSL_RECORD_METHOD */
1100 return s
->rlayer
.rrlmethod
;
1103 static int ssl_post_record_layer_select(SSL_CONNECTION
*s
, int direction
)
1105 const OSSL_RECORD_METHOD
*thismethod
;
1106 OSSL_RECORD_LAYER
*thisrl
;
1108 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1109 thismethod
= s
->rlayer
.rrlmethod
;
1110 thisrl
= s
->rlayer
.rrl
;
1112 thismethod
= s
->rlayer
.wrlmethod
;
1113 thisrl
= s
->rlayer
.wrl
;
1116 #ifndef OPENSSL_NO_KTLS
1118 SSL
*ssl
= SSL_CONNECTION_GET_SSL(s
);
1120 if (s
->rlayer
.rrlmethod
== &ossl_ktls_record_method
) {
1121 /* KTLS does not support renegotiation so disallow it */
1122 SSL_set_options(ssl
, SSL_OP_NO_RENEGOTIATION
);
1126 if (SSL_IS_FIRST_HANDSHAKE(s
) && thismethod
->set_first_handshake
!= NULL
)
1127 thismethod
->set_first_handshake(thisrl
, 1);
1129 if (s
->max_pipelines
!= 0 && thismethod
->set_max_pipelines
!= NULL
)
1130 thismethod
->set_max_pipelines(thisrl
, s
->max_pipelines
);
1135 int ssl_set_new_record_layer(SSL_CONNECTION
*s
, int version
,
1136 int direction
, int level
,
1137 unsigned char *key
, size_t keylen
,
1138 unsigned char *iv
, size_t ivlen
,
1139 unsigned char *mackey
, size_t mackeylen
,
1140 const EVP_CIPHER
*ciph
, size_t taglen
,
1141 int mactype
, const EVP_MD
*md
,
1142 const SSL_COMP
*comp
)
1144 OSSL_PARAM options
[5], *opts
= options
;
1145 OSSL_PARAM settings
[6], *set
= settings
;
1146 const OSSL_RECORD_METHOD
**thismethod
;
1147 OSSL_RECORD_LAYER
**thisrl
, *newrl
= NULL
;
1149 SSL_CTX
*sctx
= SSL_CONNECTION_GET_CTX(s
);
1150 const OSSL_RECORD_METHOD
*meth
;
1151 int use_etm
, stream_mac
= 0, tlstree
= 0;
1152 unsigned int maxfrag
= SSL3_RT_MAX_PLAIN_LENGTH
;
1153 int use_early_data
= 0;
1154 uint32_t max_early_data
;
1156 meth
= ssl_select_next_record_layer(s
, level
);
1158 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1159 thismethod
= &s
->rlayer
.rrlmethod
;
1160 thisrl
= &s
->rlayer
.rrl
;
1163 thismethod
= &s
->rlayer
.wrlmethod
;
1164 thisrl
= &s
->rlayer
.wrl
;
1171 if (!ossl_assert(meth
!= NULL
)) {
1172 ERR_raise(ERR_LIB_SSL
, ERR_R_INTERNAL_ERROR
);
1176 /* Parameters that *may* be supported by a record layer if passed */
1177 *opts
++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS
,
1179 *opts
++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE
,
1181 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1182 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN
,
1183 &s
->rlayer
.default_read_buf_len
);
1184 *opts
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD
,
1185 &s
->rlayer
.read_ahead
);
1187 *opts
++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING
,
1188 &s
->rlayer
.block_padding
);
1190 *opts
= OSSL_PARAM_construct_end();
1192 /* Parameters that *must* be supported by a record layer if passed */
1193 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1194 use_etm
= SSL_READ_ETM(s
) ? 1 : 0;
1195 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_STREAM
) != 0)
1198 if ((s
->mac_flags
& SSL_MAC_FLAG_READ_MAC_TLSTREE
) != 0)
1201 use_etm
= SSL_WRITE_ETM(s
) ? 1 : 0;
1202 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_STREAM
) != 0)
1205 if ((s
->mac_flags
& SSL_MAC_FLAG_WRITE_MAC_TLSTREE
) != 0)
1210 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM
,
1214 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC
,
1218 *set
++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE
,
1221 if (s
->session
!= NULL
&& USE_MAX_FRAGMENT_LENGTH_EXT(s
->session
))
1222 maxfrag
= GET_MAX_FRAGMENT_LENGTH(s
->session
);
1224 if (maxfrag
!= SSL3_RT_MAX_PLAIN_LENGTH
)
1225 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN
,
1229 * The record layer must check the amount of early data sent or received
1230 * using the early keys. A server also needs to worry about rejected early
1231 * data that might arrive when the handshake keys are in force.
1233 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1234 if (s
->server
&& direction
== OSSL_RECORD_DIRECTION_READ
) {
1235 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
1236 || level
== OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
);
1237 } else if (!s
->server
&& direction
== OSSL_RECORD_DIRECTION_WRITE
) {
1238 use_early_data
= (level
== OSSL_RECORD_PROTECTION_LEVEL_EARLY
);
1240 if (use_early_data
) {
1241 max_early_data
= ossl_get_max_early_data(s
);
1243 if (max_early_data
!= 0)
1244 *set
++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA
,
1248 *set
= OSSL_PARAM_construct_end();
1254 unsigned int epoch
= 0;
1255 OSSL_DISPATCH rlayer_dispatch_tmp
[OSSL_NELEM(rlayer_dispatch
)];
1258 if (direction
== OSSL_RECORD_DIRECTION_READ
) {
1259 prev
= s
->rlayer
.rrlnext
;
1260 if (SSL_CONNECTION_IS_DTLS(s
)
1261 && level
!= OSSL_RECORD_PROTECTION_LEVEL_NONE
)
1262 epoch
= DTLS_RECORD_LAYER_get_r_epoch(&s
->rlayer
) + 1; /* new epoch */
1264 if (SSL_CONNECTION_IS_DTLS(s
))
1265 next
= BIO_new(BIO_s_dgram_mem());
1267 next
= BIO_new(BIO_s_mem());
1271 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1274 s
->rlayer
.rrlnext
= next
;
1278 * Create a copy of the dispatch array, missing out wrappers for
1279 * callbacks that we don't need.
1281 for (i
= 0, j
= 0; i
< OSSL_NELEM(rlayer_dispatch
); i
++) {
1282 switch (rlayer_dispatch
[i
].function_id
) {
1283 case OSSL_FUNC_RLAYER_MSG_CALLBACK
:
1284 if (s
->msg_callback
== NULL
)
1287 case OSSL_FUNC_RLAYER_PADDING
:
1288 if (s
->rlayer
.record_padding_cb
== NULL
)
1294 rlayer_dispatch_tmp
[j
++] = rlayer_dispatch
[i
];
1297 rlret
= meth
->new_record_layer(sctx
->libctx
, sctx
->propq
, version
,
1298 s
->server
, direction
, level
, epoch
,
1299 key
, keylen
, iv
, ivlen
, mackey
,
1300 mackeylen
, ciph
, taglen
, mactype
, md
,
1301 comp
, prev
, thisbio
, next
, NULL
, NULL
,
1302 settings
, options
, rlayer_dispatch_tmp
,
1306 case OSSL_RECORD_RETURN_FATAL
:
1307 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_RECORD_LAYER_FAILURE
);
1310 case OSSL_RECORD_RETURN_NON_FATAL_ERR
:
1311 if (*thismethod
!= meth
&& *thismethod
!= NULL
) {
1313 * We tried a new record layer method, but it didn't work out,
1314 * so we fallback to the original method and try again
1319 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, SSL_R_NO_SUITABLE_RECORD_LAYER
);
1322 case OSSL_RECORD_RETURN_SUCCESS
:
1326 /* Should not happen */
1327 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1333 if (*thismethod
!= NULL
&& !(*thismethod
)->free(*thisrl
)) {
1334 SSLfatal(s
, SSL_AD_INTERNAL_ERROR
, ERR_R_INTERNAL_ERROR
);
1341 return ssl_post_record_layer_select(s
, direction
);
1344 int ssl_set_record_protocol_version(SSL_CONNECTION
*s
, int vers
)
1346 if (!ossl_assert(s
->rlayer
.rrlmethod
!= NULL
)
1347 || !ossl_assert(s
->rlayer
.wrlmethod
!= NULL
))
1349 s
->rlayer
.rrlmethod
->set_protocol_version(s
->rlayer
.rrl
, s
->version
);
1350 s
->rlayer
.wrlmethod
->set_protocol_version(s
->rlayer
.wrl
, s
->version
);