2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include <openssl/core_names.h>
18 #include "record_local.h"
19 #include "internal/packet.h"
21 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
26 void RECORD_LAYER_clear(RECORD_LAYER *rl)
29 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
30 rl->handshake_fragment_len = 0;
36 if (rl->rrlmethod != NULL)
37 rl->rrlmethod->free(rl->rrl); /* Ignore return value */
38 if (rl->wrlmethod != NULL)
39 rl->wrlmethod->free(rl->wrl); /* Ignore return value */
40 BIO_free(rl->rrlnext);
48 DTLS_RECORD_LAYER_clear(rl);
51 /* Checks if we have unprocessed read ahead data pending */
52 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
54 return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
57 /* Checks if we have decrypted unread record data pending */
58 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
60 return (rl->curr_rec < rl->num_recs)
61 || rl->rrlmethod->processed_read_pending(rl->rrl);
64 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
66 return rl->wpend_tot > 0;
69 static uint32_t ossl_get_max_early_data(SSL_CONNECTION *s)
71 uint32_t max_early_data;
72 SSL_SESSION *sess = s->session;
75 * If we are a client then we always use the max_early_data from the
76 * session/psksession. Otherwise we go with the lowest out of the max early
77 * data set in the session and the configured max_early_data.
79 if (!s->server && sess->ext.max_early_data == 0) {
80 if (!ossl_assert(s->psksession != NULL
81 && s->psksession->ext.max_early_data > 0)) {
82 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
89 max_early_data = sess->ext.max_early_data;
90 else if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
91 max_early_data = s->recv_max_early_data;
93 max_early_data = s->recv_max_early_data < sess->ext.max_early_data
94 ? s->recv_max_early_data : sess->ext.max_early_data;
96 return max_early_data;
99 static int ossl_early_data_count_ok(SSL_CONNECTION *s, size_t length,
100 size_t overhead, int send)
102 uint32_t max_early_data;
104 max_early_data = ossl_get_max_early_data(s);
106 if (max_early_data == 0) {
107 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
108 SSL_R_TOO_MUCH_EARLY_DATA);
112 /* If we are dealing with ciphertext we need to allow for the overhead */
113 max_early_data += overhead;
115 if (s->early_data_count + length > max_early_data) {
116 SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
117 SSL_R_TOO_MUCH_EARLY_DATA);
120 s->early_data_count += length;
125 size_t ssl3_pending(const SSL *s)
128 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
133 if (SSL_CONNECTION_IS_DTLS(sc)) {
137 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
138 while ((item = pqueue_next(&iter)) != NULL) {
140 num += rdata->length;
144 for (i = 0; i < sc->rlayer.num_recs; i++) {
145 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
147 num += sc->rlayer.tlsrecs[i].length;
150 num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
155 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
157 ctx->default_read_buf_len = len;
160 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
162 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
166 sc->rlayer.default_read_buf_len = len;
169 const char *SSL_rstate_string_long(const SSL *s)
171 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
177 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
180 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
185 const char *SSL_rstate_string(const SSL *s)
187 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
193 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
196 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
201 static int tls_write_check_pending(SSL_CONNECTION *s, int type,
202 const unsigned char *buf, size_t len)
204 if (s->rlayer.wpend_tot == 0)
207 /* We have pending data, so do some sanity checks */
208 if ((s->rlayer.wpend_tot > len)
209 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
210 && (s->rlayer.wpend_buf != buf))
211 || (s->rlayer.wpend_type != type)) {
212 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
219 * Call this to write data in records of type 'type' It will return <= 0 if
220 * not all data has been sent or non-blocking IO.
222 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
225 const unsigned char *buf = buf_;
227 size_t n, max_send_fragment, split_send_fragment, maxpipes;
229 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
230 OSSL_RECORD_TEMPLATE tmpls[SSL_MAX_PIPELINES];
231 unsigned int recversion;
236 s->rwstate = SSL_NOTHING;
237 tot = s->rlayer.wnum;
239 * ensure that if we end up with a smaller value of data to write out
240 * than the original len from a write which didn't complete for
241 * non-blocking I/O and also somehow ended up avoiding the check for
242 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
243 * possible to end up with (len-tot) as a large number that will then
244 * promptly send beyond the end of the users buffer ... so we trap and
245 * report the error in a way the user will notice
247 if ((len < s->rlayer.wnum)
248 || ((s->rlayer.wpend_tot != 0)
249 && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
250 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
254 if (s->early_data_state == SSL_EARLY_DATA_WRITING
255 && !ossl_early_data_count_ok(s, len, 0, 1)) {
256 /* SSLfatal() already called */
263 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
264 * into init unless we have writes pending - in which case we should finish
267 if (s->rlayer.wpend_tot == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
268 || s->ext.extra_tickets_expected > 0))
269 ossl_statem_set_in_init(s, 1);
272 * When writing early data on the server side we could be "in_init" in
273 * between receiving the EoED and the CF - but we don't want to handle those
276 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
277 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
278 i = s->handshake_func(ssl);
279 /* SSLfatal() already called */
287 i = tls_write_check_pending(s, type, buf, len);
289 /* SSLfatal() already called */
293 i = HANDLE_RLAYER_WRITE_RETURN(s,
294 s->rlayer.wrlmethod->retry_write_records(s->rlayer.wrl));
297 tot += s->rlayer.wpend_tot;
298 s->rlayer.wpend_tot = 0;
299 } /* else no retry required */
303 * We've not previously sent any data for this write so memorize
304 * arguments so that we can detect bad write retries later
306 s->rlayer.wpend_tot = 0;
307 s->rlayer.wpend_type = type;
308 s->rlayer.wpend_buf = buf;
309 s->rlayer.wpend_ret = len;
312 if (tot == len) { /* done? */
317 /* If we have an alert to send, lets send it */
318 if (s->s3.alert_dispatch) {
319 i = ssl->method->ssl_dispatch_alert(ssl);
321 /* SSLfatal() already called if appropriate */
324 /* if it went, fall through and send more stuff */
329 max_send_fragment = ssl_get_max_send_fragment(s);
330 split_send_fragment = ssl_get_split_send_fragment(s);
332 if (max_send_fragment == 0
333 || split_send_fragment == 0
334 || split_send_fragment > max_send_fragment) {
336 * We should have prevented this when we set/get the split and max send
337 * fragments so we shouldn't get here
339 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
344 * Some servers hang if initial client hello is larger than 256 bytes
345 * and record version number > TLS 1.0
347 recversion = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION : s->version;
348 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
350 && TLS1_get_version(ssl) > TLS1_VERSION
351 && s->hello_retry_request == SSL_HRR_NONE)
352 recversion = TLS1_VERSION;
355 size_t tmppipelen, remain;
356 size_t j, lensofar = 0;
359 * Ask the record layer how it would like to split the amount of data
360 * that we have, and how many of those records it would like in one go.
362 maxpipes = s->rlayer.wrlmethod->get_max_records(s->rlayer.wrl, type, n,
364 &split_send_fragment);
366 * If max_pipelines is 0 then this means "undefined" and we default to
367 * whatever the record layer wants to do. Otherwise we use the smallest
368 * value from the number requested by the record layer, and max number
369 * configured by the user.
371 if (s->max_pipelines > 0 && maxpipes > s->max_pipelines)
372 maxpipes = s->max_pipelines;
374 if (maxpipes > SSL_MAX_PIPELINES)
375 maxpipes = SSL_MAX_PIPELINES;
377 if (split_send_fragment > max_send_fragment) {
378 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
382 if (n / maxpipes >= split_send_fragment) {
384 * We have enough data to completely fill all available
387 for (j = 0; j < maxpipes; j++) {
388 tmpls[j].type = type;
389 tmpls[j].version = recversion;
390 tmpls[j].buf = &(buf[tot]) + (j * split_send_fragment);
391 tmpls[j].buflen = split_send_fragment;
393 /* Remember how much data we are going to be sending */
394 s->rlayer.wpend_tot = maxpipes * split_send_fragment;
396 /* We can partially fill all available pipelines */
397 tmppipelen = n / maxpipes;
398 remain = n % maxpipes;
400 * If there is a remainder we add an extra byte to the first few
405 for (j = 0; j < maxpipes; j++) {
406 tmpls[j].type = type;
407 tmpls[j].version = recversion;
408 tmpls[j].buf = &(buf[tot]) + lensofar;
409 tmpls[j].buflen = tmppipelen;
410 lensofar += tmppipelen;
414 /* Remember how much data we are going to be sending */
415 s->rlayer.wpend_tot = n;
418 i = HANDLE_RLAYER_WRITE_RETURN(s,
419 s->rlayer.wrlmethod->write_records(s->rlayer.wrl, tmpls, maxpipes));
421 /* SSLfatal() already called if appropriate */
422 s->rlayer.wnum = tot;
426 if (s->rlayer.wpend_tot == n
427 || (type == SSL3_RT_APPLICATION_DATA
428 && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0)) {
429 *written = tot + s->rlayer.wpend_tot;
430 s->rlayer.wpend_tot = 0;
434 n -= s->rlayer.wpend_tot;
435 tot += s->rlayer.wpend_tot;
439 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int writing, int ret,
440 char *file, int line)
442 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
444 if (ret == OSSL_RECORD_RETURN_RETRY) {
445 s->rwstate = writing ? SSL_WRITING : SSL_READING;
448 s->rwstate = SSL_NOTHING;
449 if (ret == OSSL_RECORD_RETURN_EOF) {
452 * This shouldn't happen with a writing operation. We treat it
456 ERR_set_debug(file, line, 0);
457 ossl_statem_fatal(s, SSL_AD_INTERNAL_ERROR,
458 ERR_R_INTERNAL_ERROR, NULL);
459 ret = OSSL_RECORD_RETURN_FATAL;
460 } else if ((s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) != 0) {
461 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
462 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
465 ERR_set_debug(file, line, 0);
466 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
467 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
469 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
470 int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
472 if (al != SSL_AD_NO_ALERT) {
474 ERR_set_debug(file, line, 0);
475 ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
478 * else some failure but there is no alert code. We don't log an
479 * error for this. The record layer should have logged an error
480 * already or, if not, its due to some sys call error which will be
481 * reported via SSL_ERROR_SYSCALL and errno.
485 * The record layer distinguishes the cases of EOF, non-fatal
486 * err and retry. Upper layers do not.
487 * If we got a retry or success then *ret is already correct,
488 * otherwise we need to convert the return value.
490 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
492 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
499 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
501 if (rr->rechandle != NULL) {
502 /* The record layer allocated the buffers for this record */
503 s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
505 /* We allocated the buffers for this record (only happens with DTLS) */
506 OPENSSL_free(rr->data);
508 s->rlayer.curr_rec++;
512 * Return up to 'len' payload bytes received in 'type' records.
513 * 'type' is one of the following:
515 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
516 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
517 * - 0 (during a shutdown, no data has to be returned)
519 * If we don't have stored data to work from, read a SSL/TLS record first
520 * (possibly multiple records if we still don't have anything to return).
522 * This function must handle any surprises the peer may have for us, such as
523 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
524 * messages are treated as if they were handshake messages *if* the |recvd_type|
525 * argument is non NULL.
526 * Also if record payloads contain fragments too small to process, we store
527 * them until there is enough for the respective protocol (the record protocol
528 * may use arbitrary fragmentation and even interleaving):
529 * Change cipher spec protocol
530 * just 1 byte needed, no need for keeping anything stored
532 * 2 bytes needed (AlertLevel, AlertDescription)
534 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
535 * to detect unexpected Client Hello and Hello Request messages
536 * here, anything else is handled by higher layers
537 * Application data protocol
538 * none of our business
540 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
541 size_t len, int peek, size_t *readbytes)
544 size_t n, curr_rec, totalbytes;
546 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
548 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
550 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
553 && (type != SSL3_RT_APPLICATION_DATA)
554 && (type != SSL3_RT_HANDSHAKE))
555 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
556 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
560 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
561 /* (partially) satisfy request from storage */
563 unsigned char *src = s->rlayer.handshake_fragment;
564 unsigned char *dst = buf;
569 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
572 s->rlayer.handshake_fragment_len--;
575 /* move any remaining fragment bytes: */
576 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
577 s->rlayer.handshake_fragment[k] = *src++;
579 if (recvd_type != NULL)
580 *recvd_type = SSL3_RT_HANDSHAKE;
587 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
590 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
591 /* type == SSL3_RT_APPLICATION_DATA */
592 i = s->handshake_func(ssl);
593 /* SSLfatal() already called */
600 s->rwstate = SSL_NOTHING;
603 * For each record 'i' up to |num_recs]
604 * rr[i].type - is the type of record
606 * rr[i].off, - offset into 'data' for next read
607 * rr[i].length, - number of bytes.
609 /* get new records if necessary */
610 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
611 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
613 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
615 ret = HANDLE_RLAYER_READ_RETURN(s,
616 s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
618 &rr->version, &rr->type,
619 &rr->data, &rr->length,
622 /* SSLfatal() already called if appropriate */
626 s->rlayer.num_recs++;
627 } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
628 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
630 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
632 if (s->rlayer.handshake_fragment_len > 0
633 && rr->type != SSL3_RT_HANDSHAKE
634 && SSL_CONNECTION_IS_TLS13(s)) {
635 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
636 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
641 * Reset the count of consecutive warning alerts if we've got a non-empty
642 * record that isn't an alert.
644 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
645 s->rlayer.alert_count = 0;
647 /* we now have a packet which can be read and processed */
649 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
650 * reset by ssl3_get_finished */
651 && (rr->type != SSL3_RT_HANDSHAKE)) {
652 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
653 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
658 * If the other end has shut down, throw anything we read away (even in
661 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
662 s->rlayer.curr_rec++;
663 s->rwstate = SSL_NOTHING;
668 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
669 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
672 * SSL3_RT_APPLICATION_DATA or
673 * SSL3_RT_HANDSHAKE or
674 * SSL3_RT_CHANGE_CIPHER_SPEC
677 * make sure that we are not getting application data when we are
678 * doing a handshake for the first time
680 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
681 && SSL_IS_FIRST_HANDSHAKE(s)) {
682 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
686 if (type == SSL3_RT_HANDSHAKE
687 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
688 && s->rlayer.handshake_fragment_len > 0) {
689 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
693 if (recvd_type != NULL)
694 *recvd_type = rr->type;
698 * Skip a zero length record. This ensures multiple calls to
699 * SSL_read() with a zero length buffer will eventually cause
700 * SSL_pending() to report data as being available.
703 ssl_release_record(s, rr);
709 curr_rec = s->rlayer.curr_rec;
711 if (len - totalbytes > rr->length)
714 n = len - totalbytes;
716 memcpy(buf, &(rr->data[rr->off]), n);
719 /* Mark any zero length record as consumed CVE-2016-6305 */
721 ssl_release_record(s, rr);
723 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
724 OPENSSL_cleanse(&(rr->data[rr->off]), n);
728 ssl_release_record(s, rr);
731 || (peek && n == rr->length)) {
736 } while (type == SSL3_RT_APPLICATION_DATA
737 && curr_rec < s->rlayer.num_recs
738 && totalbytes < len);
739 if (totalbytes == 0) {
740 /* We must have read empty records. Get more data */
743 *readbytes = totalbytes;
748 * If we get here, then type != rr->type; if we have a handshake message,
749 * then it was unexpected (Hello Request or Client Hello) or invalid (we
750 * were actually expecting a CCS).
754 * Lets just double check that we've not got an SSLv2 record
756 if (rr->version == SSL2_VERSION) {
758 * Should never happen. ssl3_get_record() should only give us an SSLv2
759 * record back if this is the first packet and we are looking for an
760 * initial ClientHello. Therefore |type| should always be equal to
761 * |rr->type|. If not then something has gone horribly wrong
763 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
767 if (ssl->method->version == TLS_ANY_VERSION
768 && (s->server || rr->type != SSL3_RT_ALERT)) {
770 * If we've got this far and still haven't decided on what version
771 * we're using then this must be a client side alert we're dealing
772 * with. We shouldn't be receiving anything other than a ClientHello
773 * if we are a server.
775 s->version = rr->version;
776 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
781 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
782 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
785 if (rr->type == SSL3_RT_ALERT) {
786 unsigned int alert_level, alert_descr;
787 unsigned char *alert_bytes = rr->data
791 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
792 || !PACKET_get_1(&alert, &alert_level)
793 || !PACKET_get_1(&alert, &alert_descr)
794 || PACKET_remaining(&alert) != 0) {
795 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
800 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
801 s->msg_callback_arg);
803 if (s->info_callback != NULL)
804 cb = s->info_callback;
805 else if (ssl->ctx->info_callback != NULL)
806 cb = ssl->ctx->info_callback;
809 j = (alert_level << 8) | alert_descr;
810 cb(ssl, SSL_CB_READ_ALERT, j);
813 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
814 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
815 s->s3.warn_alert = alert_descr;
816 ssl_release_record(s, rr);
818 s->rlayer.alert_count++;
819 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
820 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
821 SSL_R_TOO_MANY_WARN_ALERTS);
827 * Apart from close_notify the only other warning alert in TLSv1.3
828 * is user_cancelled - which we just ignore.
830 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
832 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
833 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
834 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
836 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
837 s->rwstate = SSL_NOTHING;
838 s->s3.fatal_alert = alert_descr;
839 SSLfatal_data(s, SSL_AD_NO_ALERT,
840 SSL_AD_REASON_OFFSET + alert_descr,
841 "SSL alert number %d", alert_descr);
842 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
843 ssl_release_record(s, rr);
844 SSL_CTX_remove_session(s->session_ctx, s->session);
846 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
848 * This is a warning but we receive it if we requested
849 * renegotiation and the peer denied it. Terminate with a fatal
850 * alert because if application tried to renegotiate it
851 * presumably had a good reason and expects it to succeed. In
852 * future we might have a renegotiation where we don't care if
853 * the peer refused it where we carry on.
855 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
857 } else if (alert_level == SSL3_AL_WARNING) {
858 /* We ignore any other warning alert in TLSv1.2 and below */
862 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
866 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
867 if (rr->type == SSL3_RT_HANDSHAKE) {
871 * We ignore any handshake messages sent to us unless they are
872 * TLSv1.3 in which case we want to process them. For all other
873 * handshake messages we can't do anything reasonable with them
874 * because we are unable to write any response due to having already
877 if (!SSL_CONNECTION_IS_TLS13(s)) {
878 ssl_release_record(s, rr);
880 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
883 s->rwstate = SSL_READING;
884 rbio = SSL_get_rbio(ssl);
885 BIO_clear_retry_flags(rbio);
886 BIO_set_retry_read(rbio);
891 * The peer is continuing to send application data, but we have
892 * already sent close_notify. If this was expected we should have
893 * been called via SSL_read() and this would have been handled
895 * No alert sent because we already sent close_notify
897 ssl_release_record(s, rr);
898 SSLfatal(s, SSL_AD_NO_ALERT,
899 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
905 * For handshake data we have 'fragment' storage, so fill that so that we
906 * can process the header at a fixed place. This is done after the
907 * "SHUTDOWN" code above to avoid filling the fragment storage with data
908 * that we're just going to discard.
910 if (rr->type == SSL3_RT_HANDSHAKE) {
911 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
912 unsigned char *dest = s->rlayer.handshake_fragment;
913 size_t *dest_len = &s->rlayer.handshake_fragment_len;
915 n = dest_maxlen - *dest_len; /* available space in 'dest' */
917 n = rr->length; /* available bytes */
919 /* now move 'n' bytes: */
920 memcpy(dest + *dest_len, rr->data + rr->off, n);
925 ssl_release_record(s, rr);
927 if (*dest_len < dest_maxlen)
928 goto start; /* fragment was too small */
931 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
932 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
937 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
938 * protocol violation)
940 if ((s->rlayer.handshake_fragment_len >= 4)
941 && !ossl_statem_get_in_handshake(s)) {
942 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
944 /* We found handshake data, so we're going back into init */
945 ossl_statem_set_in_init(s, 1);
947 i = s->handshake_func(ssl);
948 /* SSLfatal() already called if appropriate */
956 * If we were actually trying to read early data and we found a
957 * handshake message, then we don't want to continue to try and read
958 * the application data any more. It won't be "early" now.
963 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
964 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
967 * In the case where we try to read application data, but we
968 * trigger an SSL handshake, we return -1 with the retry
969 * option set. Otherwise renegotiation may cause nasty
970 * problems in the blocking world
972 s->rwstate = SSL_READING;
973 bio = SSL_get_rbio(ssl);
974 BIO_clear_retry_flags(bio);
975 BIO_set_retry_read(bio);
985 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
986 * TLS 1.2 says you MUST send an unexpected message alert. We use the
987 * TLS 1.2 behaviour for all protocol versions to prevent issues where
988 * no progress is being made and the peer continually sends unrecognised
989 * record types, using up resources processing them.
991 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
993 case SSL3_RT_CHANGE_CIPHER_SPEC:
995 case SSL3_RT_HANDSHAKE:
997 * we already handled all of these, with the possible exception of
998 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
999 * that should not happen when type != rr->type
1001 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1003 case SSL3_RT_APPLICATION_DATA:
1005 * At this point, we were expecting handshake data, but have
1006 * application data. If the library was running inside ssl3_read()
1007 * (i.e. in_read_app_data is set) and it makes sense to read
1008 * application data at this point (session renegotiation not yet
1009 * started), we will indulge it.
1011 if (ossl_statem_app_data_allowed(s)) {
1012 s->s3.in_read_app_data = 2;
1014 } else if (ossl_statem_skip_early_data(s)) {
1016 * This can happen after a client sends a CH followed by early_data,
1017 * but the server responds with a HelloRetryRequest. The server
1018 * reads the next record from the client expecting to find a
1019 * plaintext ClientHello but gets a record which appears to be
1020 * application data. The trial decrypt "works" because null
1021 * decryption was applied. We just skip it and move on to the next
1024 if (!ossl_early_data_count_ok(s, rr->length,
1025 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1026 /* SSLfatal() already called */
1029 ssl_release_record(s, rr);
1032 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1039 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1040 * format and false otherwise.
1042 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1044 if (SSL_CONNECTION_IS_DTLS(rl->s))
1046 return rl->tlsrecs[0].version == SSL2_VERSION;
1049 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1050 static void rlayer_msg_callback_wrapper(int write_p, int version,
1051 int content_type, const void *buf,
1052 size_t len, void *cbarg)
1054 SSL_CONNECTION *s = cbarg;
1055 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1057 if (s->msg_callback != NULL)
1058 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1059 s->msg_callback_arg);
1062 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1063 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1066 SSL_CONNECTION *s = cbarg;
1068 return ssl_security(s, op, bits, nid, other);
1071 static OSSL_FUNC_rlayer_padding_fn rlayer_padding_wrapper;
1072 static size_t rlayer_padding_wrapper(void *cbarg, int type, size_t len)
1074 SSL_CONNECTION *s = cbarg;
1075 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1077 return s->rlayer.record_padding_cb(ssl, type, len,
1078 s->rlayer.record_padding_arg);
1081 static const OSSL_DISPATCH rlayer_dispatch[] = {
1082 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1083 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1084 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1085 { OSSL_FUNC_RLAYER_PADDING, (void (*)(void))rlayer_padding_wrapper },
1089 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1094 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1095 if (SSL_CONNECTION_IS_DTLS(s))
1096 return &ossl_dtls_record_method;
1098 return &ossl_tls_record_method;
1101 #ifndef OPENSSL_NO_KTLS
1102 /* KTLS does not support renegotiation */
1103 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1104 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1105 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1106 return &ossl_ktls_record_method;
1109 /* Default to the current OSSL_RECORD_METHOD */
1110 return direction == OSSL_RECORD_DIRECTION_READ ? s->rlayer.rrlmethod
1111 : s->rlayer.wrlmethod;
1114 static int ssl_post_record_layer_select(SSL_CONNECTION *s, int direction)
1116 const OSSL_RECORD_METHOD *thismethod;
1117 OSSL_RECORD_LAYER *thisrl;
1119 if (direction == OSSL_RECORD_DIRECTION_READ) {
1120 thismethod = s->rlayer.rrlmethod;
1121 thisrl = s->rlayer.rrl;
1123 thismethod = s->rlayer.wrlmethod;
1124 thisrl = s->rlayer.wrl;
1127 #ifndef OPENSSL_NO_KTLS
1129 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1131 if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1132 /* KTLS does not support renegotiation so disallow it */
1133 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1137 if (SSL_IS_FIRST_HANDSHAKE(s) && thismethod->set_first_handshake != NULL)
1138 thismethod->set_first_handshake(thisrl, 1);
1140 if (s->max_pipelines != 0 && thismethod->set_max_pipelines != NULL)
1141 thismethod->set_max_pipelines(thisrl, s->max_pipelines);
1146 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1147 int direction, int level,
1148 unsigned char *key, size_t keylen,
1149 unsigned char *iv, size_t ivlen,
1150 unsigned char *mackey, size_t mackeylen,
1151 const EVP_CIPHER *ciph, size_t taglen,
1152 int mactype, const EVP_MD *md,
1153 const SSL_COMP *comp)
1155 OSSL_PARAM options[5], *opts = options;
1156 OSSL_PARAM settings[6], *set = settings;
1157 const OSSL_RECORD_METHOD **thismethod;
1158 OSSL_RECORD_LAYER **thisrl, *newrl = NULL;
1160 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1161 const OSSL_RECORD_METHOD *meth;
1162 int use_etm, stream_mac = 0, tlstree = 0;
1163 unsigned int maxfrag = (direction == OSSL_RECORD_DIRECTION_WRITE)
1164 ? ssl_get_max_send_fragment(s)
1165 : SSL3_RT_MAX_PLAIN_LENGTH;
1166 int use_early_data = 0;
1167 uint32_t max_early_data;
1168 COMP_METHOD *compm = (comp == NULL) ? NULL : comp->method;
1170 meth = ssl_select_next_record_layer(s, direction, level);
1172 if (direction == OSSL_RECORD_DIRECTION_READ) {
1173 thismethod = &s->rlayer.rrlmethod;
1174 thisrl = &s->rlayer.rrl;
1177 thismethod = &s->rlayer.wrlmethod;
1178 thisrl = &s->rlayer.wrl;
1185 if (!ossl_assert(meth != NULL)) {
1186 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1190 /* Parameters that *may* be supported by a record layer if passed */
1191 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1193 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1195 if (direction == OSSL_RECORD_DIRECTION_READ) {
1196 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1197 &s->rlayer.default_read_buf_len);
1198 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1199 &s->rlayer.read_ahead);
1201 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING,
1202 &s->rlayer.block_padding);
1204 *opts = OSSL_PARAM_construct_end();
1206 /* Parameters that *must* be supported by a record layer if passed */
1207 if (direction == OSSL_RECORD_DIRECTION_READ) {
1208 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1209 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1212 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1215 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1216 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1219 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1224 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1228 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1232 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1236 * We only need to do this for the read side. The write side should already
1237 * have the correct value due to the ssl_get_max_send_fragment() call above
1239 if (direction == OSSL_RECORD_DIRECTION_READ
1240 && s->session != NULL
1241 && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1242 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1245 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1246 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1250 * The record layer must check the amount of early data sent or received
1251 * using the early keys. A server also needs to worry about rejected early
1252 * data that might arrive when the handshake keys are in force.
1254 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1255 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1256 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1257 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1258 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1260 if (use_early_data) {
1261 max_early_data = ossl_get_max_early_data(s);
1263 if (max_early_data != 0)
1264 *set++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1268 *set = OSSL_PARAM_construct_end();
1274 unsigned int epoch = 0;
1275 OSSL_DISPATCH rlayer_dispatch_tmp[OSSL_NELEM(rlayer_dispatch)];
1278 if (direction == OSSL_RECORD_DIRECTION_READ) {
1279 prev = s->rlayer.rrlnext;
1280 if (SSL_CONNECTION_IS_DTLS(s)
1281 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1282 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1284 if (SSL_CONNECTION_IS_DTLS(s))
1285 next = BIO_new(BIO_s_dgram_mem());
1287 next = BIO_new(BIO_s_mem());
1291 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1294 s->rlayer.rrlnext = next;
1296 if (SSL_CONNECTION_IS_DTLS(s)
1297 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1298 epoch = DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) + 1; /* new epoch */
1302 * Create a copy of the dispatch array, missing out wrappers for
1303 * callbacks that we don't need.
1305 for (i = 0, j = 0; i < OSSL_NELEM(rlayer_dispatch); i++) {
1306 switch (rlayer_dispatch[i].function_id) {
1307 case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1308 if (s->msg_callback == NULL)
1311 case OSSL_FUNC_RLAYER_PADDING:
1312 if (s->rlayer.record_padding_cb == NULL)
1318 rlayer_dispatch_tmp[j++] = rlayer_dispatch[i];
1321 rlret = meth->new_record_layer(sctx->libctx, sctx->propq, version,
1322 s->server, direction, level, epoch,
1323 key, keylen, iv, ivlen, mackey,
1324 mackeylen, ciph, taglen, mactype, md,
1325 compm, prev, thisbio, next, NULL, NULL,
1326 settings, options, rlayer_dispatch_tmp,
1330 case OSSL_RECORD_RETURN_FATAL:
1331 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1334 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1335 if (*thismethod != meth && *thismethod != NULL) {
1337 * We tried a new record layer method, but it didn't work out,
1338 * so we fallback to the original method and try again
1343 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1346 case OSSL_RECORD_RETURN_SUCCESS:
1350 /* Should not happen */
1351 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1358 * Free the old record layer if we have one except in the case of DTLS when
1359 * writing and there are still buffered sent messages in our queue. In that
1360 * case the record layer is still referenced by those buffered messages for
1361 * potential retransmit. Only when those buffered messages get freed do we
1362 * free the record layer object (see dtls1_hm_fragment_free)
1364 if (!SSL_CONNECTION_IS_DTLS(s)
1365 || direction == OSSL_RECORD_DIRECTION_READ
1366 || pqueue_peek(s->d1->sent_messages) == NULL) {
1367 if (*thismethod != NULL && !(*thismethod)->free(*thisrl)) {
1368 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1376 return ssl_post_record_layer_select(s, direction);
1379 int ssl_set_record_protocol_version(SSL_CONNECTION *s, int vers)
1381 if (!ossl_assert(s->rlayer.rrlmethod != NULL)
1382 || !ossl_assert(s->rlayer.wrlmethod != NULL))
1384 s->rlayer.rrlmethod->set_protocol_version(s->rlayer.rrl, s->version);
1385 s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, s->version);