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
14 #include "../ssl_local.h"
15 #include "../quic/quic_local.h"
16 #include <openssl/evp.h>
17 #include <openssl/buffer.h>
18 #include <openssl/rand.h>
19 #include <openssl/core_names.h>
20 #include "record_local.h"
21 #include "internal/packet.h"
23 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
28 void RECORD_LAYER_clear(RECORD_LAYER *rl)
31 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
32 rl->handshake_fragment_len = 0;
38 if (rl->rrlmethod != NULL)
39 rl->rrlmethod->free(rl->rrl); /* Ignore return value */
40 if (rl->wrlmethod != NULL)
41 rl->wrlmethod->free(rl->wrl); /* Ignore return value */
42 BIO_free(rl->rrlnext);
50 DTLS_RECORD_LAYER_clear(rl);
53 /* Checks if we have unprocessed read ahead data pending */
54 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
56 return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
59 /* Checks if we have decrypted unread record data pending */
60 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
62 return (rl->curr_rec < rl->num_recs)
63 || rl->rrlmethod->processed_read_pending(rl->rrl);
66 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
68 return rl->wpend_tot > 0;
71 static uint32_t ossl_get_max_early_data(SSL_CONNECTION *s)
73 uint32_t max_early_data;
74 SSL_SESSION *sess = s->session;
77 * If we are a client then we always use the max_early_data from the
78 * session/psksession. Otherwise we go with the lowest out of the max early
79 * data set in the session and the configured max_early_data.
81 if (!s->server && sess->ext.max_early_data == 0) {
82 if (!ossl_assert(s->psksession != NULL
83 && s->psksession->ext.max_early_data > 0)) {
84 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
91 max_early_data = sess->ext.max_early_data;
92 else if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
93 max_early_data = s->recv_max_early_data;
95 max_early_data = s->recv_max_early_data < sess->ext.max_early_data
96 ? s->recv_max_early_data : sess->ext.max_early_data;
98 return max_early_data;
101 static int ossl_early_data_count_ok(SSL_CONNECTION *s, size_t length,
102 size_t overhead, int send)
104 uint32_t max_early_data;
106 max_early_data = ossl_get_max_early_data(s);
108 if (max_early_data == 0) {
109 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
110 SSL_R_TOO_MUCH_EARLY_DATA);
114 /* If we are dealing with ciphertext we need to allow for the overhead */
115 max_early_data += overhead;
117 if (s->early_data_count + length > max_early_data) {
118 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
119 SSL_R_TOO_MUCH_EARLY_DATA);
122 s->early_data_count += length;
127 size_t ssl3_pending(const SSL *s)
130 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
135 if (SSL_CONNECTION_IS_DTLS(sc)) {
139 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
140 while ((item = pqueue_next(&iter)) != NULL) {
142 num += rdata->length;
146 for (i = 0; i < sc->rlayer.num_recs; i++) {
147 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
149 num += sc->rlayer.tlsrecs[i].length;
152 num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
157 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
159 ctx->default_read_buf_len = len;
162 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
164 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
166 if (sc == NULL || IS_QUIC(s))
168 sc->rlayer.default_read_buf_len = len;
171 const char *SSL_rstate_string_long(const SSL *s)
173 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
179 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
182 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
187 const char *SSL_rstate_string(const SSL *s)
189 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
195 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
198 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
203 static int tls_write_check_pending(SSL_CONNECTION *s, int type,
204 const unsigned char *buf, size_t len)
206 if (s->rlayer.wpend_tot == 0)
209 /* We have pending data, so do some sanity checks */
210 if ((s->rlayer.wpend_tot > len)
211 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
212 && (s->rlayer.wpend_buf != buf))
213 || (s->rlayer.wpend_type != type)) {
214 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
221 * Call this to write data in records of type 'type' It will return <= 0 if
222 * not all data has been sent or non-blocking IO.
224 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
227 const unsigned char *buf = buf_;
229 size_t n, max_send_fragment, split_send_fragment, maxpipes;
231 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
232 OSSL_RECORD_TEMPLATE tmpls[SSL_MAX_PIPELINES];
233 unsigned int recversion;
238 s->rwstate = SSL_NOTHING;
239 tot = s->rlayer.wnum;
241 * ensure that if we end up with a smaller value of data to write out
242 * than the original len from a write which didn't complete for
243 * non-blocking I/O and also somehow ended up avoiding the check for
244 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
245 * possible to end up with (len-tot) as a large number that will then
246 * promptly send beyond the end of the users buffer ... so we trap and
247 * report the error in a way the user will notice
249 if ((len < s->rlayer.wnum)
250 || ((s->rlayer.wpend_tot != 0)
251 && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
252 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
256 if (s->early_data_state == SSL_EARLY_DATA_WRITING
257 && !ossl_early_data_count_ok(s, len, 0, 1)) {
258 /* SSLfatal() already called */
265 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
266 * into init unless we have writes pending - in which case we should finish
269 if (s->rlayer.wpend_tot == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
270 || s->ext.extra_tickets_expected > 0))
271 ossl_statem_set_in_init(s, 1);
274 * When writing early data on the server side we could be "in_init" in
275 * between receiving the EoED and the CF - but we don't want to handle those
278 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
279 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
280 i = s->handshake_func(ssl);
281 /* SSLfatal() already called */
289 i = tls_write_check_pending(s, type, buf, len);
291 /* SSLfatal() already called */
295 i = HANDLE_RLAYER_WRITE_RETURN(s,
296 s->rlayer.wrlmethod->retry_write_records(s->rlayer.wrl));
299 tot += s->rlayer.wpend_tot;
300 s->rlayer.wpend_tot = 0;
301 } /* else no retry required */
305 * We've not previously sent any data for this write so memorize
306 * arguments so that we can detect bad write retries later
308 s->rlayer.wpend_tot = 0;
309 s->rlayer.wpend_type = type;
310 s->rlayer.wpend_buf = buf;
311 s->rlayer.wpend_ret = len;
314 if (tot == len) { /* done? */
319 /* If we have an alert to send, lets send it */
320 if (s->s3.alert_dispatch > 0) {
321 i = ssl->method->ssl_dispatch_alert(ssl);
323 /* SSLfatal() already called if appropriate */
326 /* if it went, fall through and send more stuff */
331 max_send_fragment = ssl_get_max_send_fragment(s);
332 split_send_fragment = ssl_get_split_send_fragment(s);
334 if (max_send_fragment == 0
335 || split_send_fragment == 0
336 || split_send_fragment > max_send_fragment) {
338 * We should have prevented this when we set/get the split and max send
339 * fragments so we shouldn't get here
341 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
346 * Some servers hang if initial client hello is larger than 256 bytes
347 * and record version number > TLS 1.0
349 recversion = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION : s->version;
350 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
352 && TLS1_get_version(ssl) > TLS1_VERSION
353 && s->hello_retry_request == SSL_HRR_NONE)
354 recversion = TLS1_VERSION;
357 size_t tmppipelen, remain;
358 size_t j, lensofar = 0;
361 * Ask the record layer how it would like to split the amount of data
362 * that we have, and how many of those records it would like in one go.
364 maxpipes = s->rlayer.wrlmethod->get_max_records(s->rlayer.wrl, type, n,
366 &split_send_fragment);
368 * If max_pipelines is 0 then this means "undefined" and we default to
369 * whatever the record layer wants to do. Otherwise we use the smallest
370 * value from the number requested by the record layer, and max number
371 * configured by the user.
373 if (s->max_pipelines > 0 && maxpipes > s->max_pipelines)
374 maxpipes = s->max_pipelines;
376 if (maxpipes > SSL_MAX_PIPELINES)
377 maxpipes = SSL_MAX_PIPELINES;
379 if (split_send_fragment > max_send_fragment) {
380 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
384 if (n / maxpipes >= split_send_fragment) {
386 * We have enough data to completely fill all available
389 for (j = 0; j < maxpipes; j++) {
390 tmpls[j].type = type;
391 tmpls[j].version = recversion;
392 tmpls[j].buf = &(buf[tot]) + (j * split_send_fragment);
393 tmpls[j].buflen = split_send_fragment;
395 /* Remember how much data we are going to be sending */
396 s->rlayer.wpend_tot = maxpipes * split_send_fragment;
398 /* We can partially fill all available pipelines */
399 tmppipelen = n / maxpipes;
400 remain = n % maxpipes;
402 * If there is a remainder we add an extra byte to the first few
407 for (j = 0; j < maxpipes; j++) {
408 tmpls[j].type = type;
409 tmpls[j].version = recversion;
410 tmpls[j].buf = &(buf[tot]) + lensofar;
411 tmpls[j].buflen = tmppipelen;
412 lensofar += tmppipelen;
416 /* Remember how much data we are going to be sending */
417 s->rlayer.wpend_tot = n;
420 i = HANDLE_RLAYER_WRITE_RETURN(s,
421 s->rlayer.wrlmethod->write_records(s->rlayer.wrl, tmpls, maxpipes));
423 /* SSLfatal() already called if appropriate */
424 s->rlayer.wnum = tot;
428 if (s->rlayer.wpend_tot == n
429 || (type == SSL3_RT_APPLICATION_DATA
430 && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0)) {
431 *written = tot + s->rlayer.wpend_tot;
432 s->rlayer.wpend_tot = 0;
436 n -= s->rlayer.wpend_tot;
437 tot += s->rlayer.wpend_tot;
441 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int writing, int ret,
442 char *file, int line)
444 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
446 if (ret == OSSL_RECORD_RETURN_RETRY) {
447 s->rwstate = writing ? SSL_WRITING : SSL_READING;
450 s->rwstate = SSL_NOTHING;
451 if (ret == OSSL_RECORD_RETURN_EOF) {
454 * This shouldn't happen with a writing operation. We treat it
458 ERR_set_debug(file, line, 0);
459 ossl_statem_fatal(s, SSL_AD_INTERNAL_ERROR,
460 ERR_R_INTERNAL_ERROR, NULL);
461 ret = OSSL_RECORD_RETURN_FATAL;
462 } else if ((s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) != 0) {
463 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
464 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
467 ERR_set_debug(file, line, 0);
468 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
469 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
471 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
472 int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
474 if (al != SSL_AD_NO_ALERT) {
476 ERR_set_debug(file, line, 0);
477 ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
480 * else some failure but there is no alert code. We don't log an
481 * error for this. The record layer should have logged an error
482 * already or, if not, its due to some sys call error which will be
483 * reported via SSL_ERROR_SYSCALL and errno.
487 * The record layer distinguishes the cases of EOF, non-fatal
488 * err and retry. Upper layers do not.
489 * If we got a retry or success then *ret is already correct,
490 * otherwise we need to convert the return value.
492 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
494 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
501 int ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr, size_t length)
503 assert(rr->length >= length);
504 if (rr->rechandle != NULL) {
507 /* The record layer allocated the buffers for this record */
508 if (HANDLE_RLAYER_READ_RETURN(s,
509 s->rlayer.rrlmethod->release_record(s->rlayer.rrl,
512 /* RLAYER_fatal already called */
516 if (length == rr->length)
517 s->rlayer.curr_rec++;
518 } else if (length == 0 || length == rr->length) {
519 /* We allocated the buffers for this record (only happens with DTLS) */
520 OPENSSL_free(rr->allocdata);
521 rr->allocdata = NULL;
523 rr->length -= length;
533 * Return up to 'len' payload bytes received in 'type' records.
534 * 'type' is one of the following:
536 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
537 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
538 * - 0 (during a shutdown, no data has to be returned)
540 * If we don't have stored data to work from, read a SSL/TLS record first
541 * (possibly multiple records if we still don't have anything to return).
543 * This function must handle any surprises the peer may have for us, such as
544 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
545 * messages are treated as if they were handshake messages *if* the |recvd_type|
546 * argument is non NULL.
547 * Also if record payloads contain fragments too small to process, we store
548 * them until there is enough for the respective protocol (the record protocol
549 * may use arbitrary fragmentation and even interleaving):
550 * Change cipher spec protocol
551 * just 1 byte needed, no need for keeping anything stored
553 * 2 bytes needed (AlertLevel, AlertDescription)
555 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
556 * to detect unexpected Client Hello and Hello Request messages
557 * here, anything else is handled by higher layers
558 * Application data protocol
559 * none of our business
561 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
562 size_t len, int peek, size_t *readbytes)
565 size_t n, curr_rec, totalbytes;
567 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
569 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
571 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
574 && (type != SSL3_RT_APPLICATION_DATA)
575 && (type != SSL3_RT_HANDSHAKE))
576 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
577 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
581 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
582 /* (partially) satisfy request from storage */
584 unsigned char *src = s->rlayer.handshake_fragment;
585 unsigned char *dst = buf;
590 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
593 s->rlayer.handshake_fragment_len--;
596 /* move any remaining fragment bytes: */
597 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
598 s->rlayer.handshake_fragment[k] = *src++;
600 if (recvd_type != NULL)
601 *recvd_type = SSL3_RT_HANDSHAKE;
608 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
611 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
612 /* type == SSL3_RT_APPLICATION_DATA */
613 i = s->handshake_func(ssl);
614 /* SSLfatal() already called */
621 s->rwstate = SSL_NOTHING;
624 * For each record 'i' up to |num_recs]
625 * rr[i].type - is the type of record
627 * rr[i].off, - offset into 'data' for next read
628 * rr[i].length, - number of bytes.
630 /* get new records if necessary */
631 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
632 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
634 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
636 ret = HANDLE_RLAYER_READ_RETURN(s,
637 s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
639 &rr->version, &rr->type,
640 &rr->data, &rr->length,
643 /* SSLfatal() already called if appropriate */
647 s->rlayer.num_recs++;
648 } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
649 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
651 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
653 if (s->rlayer.handshake_fragment_len > 0
654 && rr->type != SSL3_RT_HANDSHAKE
655 && SSL_CONNECTION_IS_TLS13(s)) {
656 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
657 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
662 * Reset the count of consecutive warning alerts if we've got a non-empty
663 * record that isn't an alert.
665 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
666 s->rlayer.alert_count = 0;
668 /* we now have a packet which can be read and processed */
670 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
671 * reset by ssl3_get_finished */
672 && (rr->type != SSL3_RT_HANDSHAKE)) {
673 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
674 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
679 * If the other end has shut down, throw anything we read away (even in
682 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
683 s->rlayer.curr_rec++;
684 s->rwstate = SSL_NOTHING;
689 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
690 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
693 * SSL3_RT_APPLICATION_DATA or
694 * SSL3_RT_HANDSHAKE or
695 * SSL3_RT_CHANGE_CIPHER_SPEC
698 * make sure that we are not getting application data when we are
699 * doing a handshake for the first time
701 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
702 && SSL_IS_FIRST_HANDSHAKE(s)) {
703 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
707 if (type == SSL3_RT_HANDSHAKE
708 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
709 && s->rlayer.handshake_fragment_len > 0) {
710 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
714 if (recvd_type != NULL)
715 *recvd_type = rr->type;
719 * Skip a zero length record. This ensures multiple calls to
720 * SSL_read() with a zero length buffer will eventually cause
721 * SSL_pending() to report data as being available.
723 if (rr->length == 0 && !ssl_release_record(s, rr, 0))
730 curr_rec = s->rlayer.curr_rec;
732 if (len - totalbytes > rr->length)
735 n = len - totalbytes;
737 memcpy(buf, &(rr->data[rr->off]), n);
740 /* Mark any zero length record as consumed CVE-2016-6305 */
741 if (rr->length == 0 && !ssl_release_record(s, rr, 0))
744 if (!ssl_release_record(s, rr, n))
748 || (peek && n == rr->length)) {
753 } while (type == SSL3_RT_APPLICATION_DATA
754 && curr_rec < s->rlayer.num_recs
755 && totalbytes < len);
756 if (totalbytes == 0) {
757 /* We must have read empty records. Get more data */
760 *readbytes = totalbytes;
765 * If we get here, then type != rr->type; if we have a handshake message,
766 * then it was unexpected (Hello Request or Client Hello) or invalid (we
767 * were actually expecting a CCS).
771 * Lets just double check that we've not got an SSLv2 record
773 if (rr->version == SSL2_VERSION) {
775 * Should never happen. ssl3_get_record() should only give us an SSLv2
776 * record back if this is the first packet and we are looking for an
777 * initial ClientHello. Therefore |type| should always be equal to
778 * |rr->type|. If not then something has gone horribly wrong
780 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
784 if (ssl->method->version == TLS_ANY_VERSION
785 && (s->server || rr->type != SSL3_RT_ALERT)) {
787 * If we've got this far and still haven't decided on what version
788 * we're using then this must be a client side alert we're dealing
789 * with. We shouldn't be receiving anything other than a ClientHello
790 * if we are a server.
792 s->version = rr->version;
793 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
798 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
799 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
802 if (rr->type == SSL3_RT_ALERT) {
803 unsigned int alert_level, alert_descr;
804 const unsigned char *alert_bytes = rr->data + rr->off;
807 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
808 || !PACKET_get_1(&alert, &alert_level)
809 || !PACKET_get_1(&alert, &alert_descr)
810 || PACKET_remaining(&alert) != 0) {
811 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
816 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
817 s->msg_callback_arg);
819 if (s->info_callback != NULL)
820 cb = s->info_callback;
821 else if (ssl->ctx->info_callback != NULL)
822 cb = ssl->ctx->info_callback;
825 j = (alert_level << 8) | alert_descr;
826 cb(ssl, SSL_CB_READ_ALERT, j);
829 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
830 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
831 s->s3.warn_alert = alert_descr;
832 if (!ssl_release_record(s, rr, 0))
835 s->rlayer.alert_count++;
836 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
837 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
838 SSL_R_TOO_MANY_WARN_ALERTS);
844 * Apart from close_notify the only other warning alert in TLSv1.3
845 * is user_cancelled - which we just ignore.
847 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
849 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
850 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
851 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
853 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
854 s->rwstate = SSL_NOTHING;
855 s->s3.fatal_alert = alert_descr;
856 SSLfatal_data(s, SSL_AD_NO_ALERT,
857 SSL_AD_REASON_OFFSET + alert_descr,
858 "SSL alert number %d", alert_descr);
859 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
860 if (!ssl_release_record(s, rr, 0))
862 SSL_CTX_remove_session(s->session_ctx, s->session);
864 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
866 * This is a warning but we receive it if we requested
867 * renegotiation and the peer denied it. Terminate with a fatal
868 * alert because if application tried to renegotiate it
869 * presumably had a good reason and expects it to succeed. In
870 * future we might have a renegotiation where we don't care if
871 * the peer refused it where we carry on.
873 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
875 } else if (alert_level == SSL3_AL_WARNING) {
876 /* We ignore any other warning alert in TLSv1.2 and below */
880 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
884 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
885 if (rr->type == SSL3_RT_HANDSHAKE) {
889 * We ignore any handshake messages sent to us unless they are
890 * TLSv1.3 in which case we want to process them. For all other
891 * handshake messages we can't do anything reasonable with them
892 * because we are unable to write any response due to having already
895 if (!SSL_CONNECTION_IS_TLS13(s)) {
896 if (!ssl_release_record(s, rr, 0))
899 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
902 s->rwstate = SSL_READING;
903 rbio = SSL_get_rbio(ssl);
904 BIO_clear_retry_flags(rbio);
905 BIO_set_retry_read(rbio);
910 * The peer is continuing to send application data, but we have
911 * already sent close_notify. If this was expected we should have
912 * been called via SSL_read() and this would have been handled
914 * No alert sent because we already sent close_notify
916 if (!ssl_release_record(s, rr, 0))
918 SSLfatal(s, SSL_AD_NO_ALERT,
919 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
925 * For handshake data we have 'fragment' storage, so fill that so that we
926 * can process the header at a fixed place. This is done after the
927 * "SHUTDOWN" code above to avoid filling the fragment storage with data
928 * that we're just going to discard.
930 if (rr->type == SSL3_RT_HANDSHAKE) {
931 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
932 unsigned char *dest = s->rlayer.handshake_fragment;
933 size_t *dest_len = &s->rlayer.handshake_fragment_len;
935 n = dest_maxlen - *dest_len; /* available space in 'dest' */
937 n = rr->length; /* available bytes */
939 /* now move 'n' bytes: */
941 memcpy(dest + *dest_len, rr->data + rr->off, n);
945 * We release the number of bytes consumed, or the whole record if it
948 if ((n > 0 || rr->length == 0) && !ssl_release_record(s, rr, n))
951 if (*dest_len < dest_maxlen)
952 goto start; /* fragment was too small */
955 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
956 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
961 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
962 * protocol violation)
964 if ((s->rlayer.handshake_fragment_len >= 4)
965 && !ossl_statem_get_in_handshake(s)) {
966 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
968 /* We found handshake data, so we're going back into init */
969 ossl_statem_set_in_init(s, 1);
971 i = s->handshake_func(ssl);
972 /* SSLfatal() already called if appropriate */
980 * If we were actually trying to read early data and we found a
981 * handshake message, then we don't want to continue to try and read
982 * the application data any more. It won't be "early" now.
987 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
988 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
991 * In the case where we try to read application data, but we
992 * trigger an SSL handshake, we return -1 with the retry
993 * option set. Otherwise renegotiation may cause nasty
994 * problems in the blocking world
996 s->rwstate = SSL_READING;
997 bio = SSL_get_rbio(ssl);
998 BIO_clear_retry_flags(bio);
999 BIO_set_retry_read(bio);
1009 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1010 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1011 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1012 * no progress is being made and the peer continually sends unrecognised
1013 * record types, using up resources processing them.
1015 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1017 case SSL3_RT_CHANGE_CIPHER_SPEC:
1019 case SSL3_RT_HANDSHAKE:
1021 * we already handled all of these, with the possible exception of
1022 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1023 * that should not happen when type != rr->type
1025 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1027 case SSL3_RT_APPLICATION_DATA:
1029 * At this point, we were expecting handshake data, but have
1030 * application data. If the library was running inside ssl3_read()
1031 * (i.e. in_read_app_data is set) and it makes sense to read
1032 * application data at this point (session renegotiation not yet
1033 * started), we will indulge it.
1035 if (ossl_statem_app_data_allowed(s)) {
1036 s->s3.in_read_app_data = 2;
1038 } else if (ossl_statem_skip_early_data(s)) {
1040 * This can happen after a client sends a CH followed by early_data,
1041 * but the server responds with a HelloRetryRequest. The server
1042 * reads the next record from the client expecting to find a
1043 * plaintext ClientHello but gets a record which appears to be
1044 * application data. The trial decrypt "works" because null
1045 * decryption was applied. We just skip it and move on to the next
1048 if (!ossl_early_data_count_ok(s, rr->length,
1049 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1050 /* SSLfatal() already called */
1053 if (!ssl_release_record(s, rr, 0))
1057 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1064 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1065 * format and false otherwise.
1067 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1069 if (SSL_CONNECTION_IS_DTLS(rl->s))
1071 return rl->tlsrecs[0].version == SSL2_VERSION;
1074 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1075 static void rlayer_msg_callback_wrapper(int write_p, int version,
1076 int content_type, const void *buf,
1077 size_t len, void *cbarg)
1079 SSL_CONNECTION *s = cbarg;
1080 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1082 if (s->msg_callback != NULL)
1083 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1084 s->msg_callback_arg);
1087 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1088 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1091 SSL_CONNECTION *s = cbarg;
1093 return ssl_security(s, op, bits, nid, other);
1096 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper;
1097 static size_t rlayer_padding_wrapper(void *cbarg, int type, size_t len)
1099 SSL_CONNECTION *s = cbarg;
1100 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1102 return s->rlayer.record_padding_cb(ssl, type, len,
1103 s->rlayer.record_padding_arg);
1106 static const OSSL_DISPATCH rlayer_dispatch[] = {
1107 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1108 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1109 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1110 { OSSL_FUNC_RLAYER_PADDING, (void (*)(void))rlayer_padding_wrapper },
1114 void ossl_ssl_set_custom_record_layer(SSL_CONNECTION *s,
1115 const OSSL_RECORD_METHOD *meth,
1118 s->rlayer.custom_rlmethod = meth;
1119 s->rlayer.rlarg = rlarg;
1122 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1126 if (s->rlayer.custom_rlmethod != NULL)
1127 return s->rlayer.custom_rlmethod;
1129 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1130 if (SSL_CONNECTION_IS_DTLS(s))
1131 return &ossl_dtls_record_method;
1133 return &ossl_tls_record_method;
1136 #ifndef OPENSSL_NO_KTLS
1137 /* KTLS does not support renegotiation */
1138 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1139 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1140 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1141 return &ossl_ktls_record_method;
1144 /* Default to the current OSSL_RECORD_METHOD */
1145 return direction == OSSL_RECORD_DIRECTION_READ ? s->rlayer.rrlmethod
1146 : s->rlayer.wrlmethod;
1149 static int ssl_post_record_layer_select(SSL_CONNECTION *s, int direction)
1151 const OSSL_RECORD_METHOD *thismethod;
1152 OSSL_RECORD_LAYER *thisrl;
1154 if (direction == OSSL_RECORD_DIRECTION_READ) {
1155 thismethod = s->rlayer.rrlmethod;
1156 thisrl = s->rlayer.rrl;
1158 thismethod = s->rlayer.wrlmethod;
1159 thisrl = s->rlayer.wrl;
1162 #ifndef OPENSSL_NO_KTLS
1164 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1166 if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1167 /* KTLS does not support renegotiation so disallow it */
1168 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1172 if (SSL_IS_FIRST_HANDSHAKE(s) && thismethod->set_first_handshake != NULL)
1173 thismethod->set_first_handshake(thisrl, 1);
1175 if (s->max_pipelines != 0 && thismethod->set_max_pipelines != NULL)
1176 thismethod->set_max_pipelines(thisrl, s->max_pipelines);
1181 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1182 int direction, int level,
1183 unsigned char *secret, size_t secretlen,
1184 unsigned char *key, size_t keylen,
1185 unsigned char *iv, size_t ivlen,
1186 unsigned char *mackey, size_t mackeylen,
1187 const EVP_CIPHER *ciph, size_t taglen,
1188 int mactype, const EVP_MD *md,
1189 const SSL_COMP *comp, const EVP_MD *kdfdigest)
1191 OSSL_PARAM options[5], *opts = options;
1192 OSSL_PARAM settings[6], *set = settings;
1193 const OSSL_RECORD_METHOD **thismethod;
1194 OSSL_RECORD_LAYER **thisrl, *newrl = NULL;
1196 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1197 const OSSL_RECORD_METHOD *meth;
1198 int use_etm, stream_mac = 0, tlstree = 0;
1199 unsigned int maxfrag = (direction == OSSL_RECORD_DIRECTION_WRITE)
1200 ? ssl_get_max_send_fragment(s)
1201 : SSL3_RT_MAX_PLAIN_LENGTH;
1202 int use_early_data = 0;
1203 uint32_t max_early_data;
1204 COMP_METHOD *compm = (comp == NULL) ? NULL : comp->method;
1206 meth = ssl_select_next_record_layer(s, direction, level);
1208 if (direction == OSSL_RECORD_DIRECTION_READ) {
1209 thismethod = &s->rlayer.rrlmethod;
1210 thisrl = &s->rlayer.rrl;
1213 thismethod = &s->rlayer.wrlmethod;
1214 thisrl = &s->rlayer.wrl;
1221 if (!ossl_assert(meth != NULL)) {
1222 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1226 /* Parameters that *may* be supported by a record layer if passed */
1227 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1229 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1231 if (direction == OSSL_RECORD_DIRECTION_READ) {
1232 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1233 &s->rlayer.default_read_buf_len);
1234 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1235 &s->rlayer.read_ahead);
1237 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING,
1238 &s->rlayer.block_padding);
1240 *opts = OSSL_PARAM_construct_end();
1242 /* Parameters that *must* be supported by a record layer if passed */
1243 if (direction == OSSL_RECORD_DIRECTION_READ) {
1244 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1245 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1248 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1251 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1252 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1255 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1260 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1264 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1268 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1272 * We only need to do this for the read side. The write side should already
1273 * have the correct value due to the ssl_get_max_send_fragment() call above
1275 if (direction == OSSL_RECORD_DIRECTION_READ
1276 && s->session != NULL
1277 && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1278 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1281 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1282 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1286 * The record layer must check the amount of early data sent or received
1287 * using the early keys. A server also needs to worry about rejected early
1288 * data that might arrive when the handshake keys are in force.
1290 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1291 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1292 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1293 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1294 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1296 if (use_early_data) {
1297 max_early_data = ossl_get_max_early_data(s);
1299 if (max_early_data != 0)
1300 *set++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1304 *set = OSSL_PARAM_construct_end();
1310 unsigned int epoch = 0;
1311 OSSL_DISPATCH rlayer_dispatch_tmp[OSSL_NELEM(rlayer_dispatch)];
1314 if (direction == OSSL_RECORD_DIRECTION_READ) {
1315 prev = s->rlayer.rrlnext;
1316 if (SSL_CONNECTION_IS_DTLS(s)
1317 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1318 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1320 #ifndef OPENSSL_NO_DGRAM
1321 if (SSL_CONNECTION_IS_DTLS(s))
1322 next = BIO_new(BIO_s_dgram_mem());
1325 next = BIO_new(BIO_s_mem());
1329 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1332 s->rlayer.rrlnext = next;
1334 if (SSL_CONNECTION_IS_DTLS(s)
1335 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1336 epoch = DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) + 1; /* new epoch */
1340 * Create a copy of the dispatch array, missing out wrappers for
1341 * callbacks that we don't need.
1343 for (i = 0, j = 0; i < OSSL_NELEM(rlayer_dispatch); i++) {
1344 switch (rlayer_dispatch[i].function_id) {
1345 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1346 if (s->msg_callback == NULL)
1349 case OSSL_FUNC_RLAYER_PADDING:
1350 if (s->rlayer.record_padding_cb == NULL)
1356 rlayer_dispatch_tmp[j++] = rlayer_dispatch[i];
1359 rlret = meth->new_record_layer(sctx->libctx, sctx->propq, version,
1360 s->server, direction, level, epoch,
1361 secret, secretlen, key, keylen, iv,
1362 ivlen, mackey, mackeylen, ciph, taglen,
1363 mactype, md, compm, kdfdigest, prev,
1364 thisbio, next, NULL, NULL, settings,
1365 options, rlayer_dispatch_tmp, s,
1366 s->rlayer.rlarg, &newrl);
1369 case OSSL_RECORD_RETURN_FATAL:
1370 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1373 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1374 if (*thismethod != meth && *thismethod != NULL) {
1376 * We tried a new record layer method, but it didn't work out,
1377 * so we fallback to the original method and try again
1382 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1385 case OSSL_RECORD_RETURN_SUCCESS:
1389 /* Should not happen */
1390 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1397 * Free the old record layer if we have one except in the case of DTLS when
1398 * writing and there are still buffered sent messages in our queue. In that
1399 * case the record layer is still referenced by those buffered messages for
1400 * potential retransmit. Only when those buffered messages get freed do we
1401 * free the record layer object (see dtls1_hm_fragment_free)
1403 if (!SSL_CONNECTION_IS_DTLS(s)
1404 || direction == OSSL_RECORD_DIRECTION_READ
1405 || pqueue_peek(s->d1->sent_messages) == NULL) {
1406 if (*thismethod != NULL && !(*thismethod)->free(*thisrl)) {
1407 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1415 return ssl_post_record_layer_select(s, direction);
1418 int ssl_set_record_protocol_version(SSL_CONNECTION *s, int vers)
1420 if (!ossl_assert(s->rlayer.rrlmethod != NULL)
1421 || !ossl_assert(s->rlayer.wrlmethod != NULL))
1423 s->rlayer.rrlmethod->set_protocol_version(s->rlayer.rrl, s->version);
1424 s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, s->version);