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 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
22 !( defined(AES_ASM) && ( \
23 defined(__x86_64) || defined(__x86_64__) || \
24 defined(_M_AMD64) || defined(_M_X64) ) \
26 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
27 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
30 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
35 void RECORD_LAYER_clear(RECORD_LAYER *rl)
38 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
39 rl->handshake_fragment_len = 0;
45 ssl3_release_write_buffer(rl->s);
47 RECORD_LAYER_reset_write_sequence(rl);
49 if (rl->rrlmethod != NULL)
50 rl->rrlmethod->free(rl->rrl); /* Ignore return value */
51 if (rl->wrlmethod != NULL)
52 rl->wrlmethod->free(rl->wrl); /* Ignore return value */
53 BIO_free(rl->rrlnext);
61 DTLS_RECORD_LAYER_clear(rl);
64 void RECORD_LAYER_release(RECORD_LAYER *rl)
66 if (rl->numwpipes > 0)
67 ssl3_release_write_buffer(rl->s);
70 /* Checks if we have unprocessed read ahead data pending */
71 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
73 return rl->rrlmethod->unprocessed_read_pending(rl->rrl);
76 /* Checks if we have decrypted unread record data pending */
77 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
79 return (rl->curr_rec < rl->num_recs)
80 || rl->rrlmethod->processed_read_pending(rl->rrl);
83 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
85 return (rl->numwpipes > 0)
86 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
89 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
91 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
94 size_t ssl3_pending(const SSL *s)
97 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
102 if (SSL_CONNECTION_IS_DTLS(sc)) {
106 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
107 while ((item = pqueue_next(&iter)) != NULL) {
109 num += rdata->length;
113 for (i = 0; i < sc->rlayer.num_recs; i++) {
114 if (sc->rlayer.tlsrecs[i].type != SSL3_RT_APPLICATION_DATA)
116 num += sc->rlayer.tlsrecs[i].length;
119 num += sc->rlayer.rrlmethod->app_data_pending(sc->rlayer.rrl);
124 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
126 ctx->default_read_buf_len = len;
129 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
131 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
135 sc->rlayer.default_read_buf_len = len;
138 const char *SSL_rstate_string_long(const SSL *s)
140 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
146 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
149 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, NULL, &lng);
154 const char *SSL_rstate_string(const SSL *s)
156 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
162 if (sc->rlayer.rrlmethod == NULL || sc->rlayer.rrl == NULL)
165 sc->rlayer.rrlmethod->get_state(sc->rlayer.rrl, &shrt, NULL);
170 static int tls_write_check_pending(SSL_CONNECTION *s, int type,
171 const unsigned char *buf, size_t len)
173 if (s->rlayer.wpend_tot == 0)
176 /* We have pending data, so do some sanity checks */
177 if ((s->rlayer.wpend_tot > len)
178 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
179 && (s->rlayer.wpend_buf != buf))
180 || (s->rlayer.wpend_type != type)) {
181 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
188 * Call this to write data in records of type 'type' It will return <= 0 if
189 * not all data has been sent or non-blocking IO.
191 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
194 const unsigned char *buf = buf_;
196 size_t n, max_send_fragment, split_send_fragment, maxpipes;
197 /* TODO(RECLAYER): Re-enable multiblock code */
198 #if 0 && !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
203 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
204 OSSL_RECORD_TEMPLATE tmpls[SSL_MAX_PIPELINES];
209 wb = &s->rlayer.wbuf[0];
210 s->rwstate = SSL_NOTHING;
211 tot = s->rlayer.wnum;
213 * ensure that if we end up with a smaller value of data to write out
214 * than the original len from a write which didn't complete for
215 * non-blocking I/O and also somehow ended up avoiding the check for
216 * this in tls_write_check_pending/SSL_R_BAD_WRITE_RETRY as it must never be
217 * possible to end up with (len-tot) as a large number that will then
218 * promptly send beyond the end of the users buffer ... so we trap and
219 * report the error in a way the user will notice
221 if ((len < s->rlayer.wnum)
222 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
223 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
227 if (s->early_data_state == SSL_EARLY_DATA_WRITING
228 && !ossl_early_data_count_ok(s, len, 0, 1)) {
229 /* SSLfatal() already called */
236 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
237 * into init unless we have writes pending - in which case we should finish
240 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
241 || s->ext.extra_tickets_expected > 0))
242 ossl_statem_set_in_init(s, 1);
245 * When writing early data on the server side we could be "in_init" in
246 * between receiving the EoED and the CF - but we don't want to handle those
249 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
250 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
251 i = s->handshake_func(ssl);
252 /* SSLfatal() already called */
260 i = tls_write_check_pending(s, type, buf, len);
262 /* SSLfatal() already called */
266 i = s->rlayer.wrlmethod->retry_write_records(s->rlayer.wrl);
269 tot += s->rlayer.wpend_tot;
270 s->rlayer.wpend_tot = 0;
271 } /* else no retry required */
275 * We've not previously sent any data for this write so memorize
276 * arguments so that we can detect bad write retries later
278 s->rlayer.wpend_tot = 0;
279 s->rlayer.wpend_type = type;
280 s->rlayer.wpend_buf = buf;
281 s->rlayer.wpend_ret = len;
284 /* TODO(RECLAYER): Re-enable multiblock code */
285 #if 0 && !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
287 * Depending on platform multi-block can deliver several *times*
288 * better performance. Downside is that it has to allocate
289 * jumbo buffer to accommodate up to 8 records, but the
290 * compromise is considered worthy.
292 if (type == SSL3_RT_APPLICATION_DATA
293 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
294 && s->compress == NULL
295 && s->msg_callback == NULL
297 && SSL_USE_EXPLICIT_IV(s)
298 && !BIO_get_ktls_send(s->wbio)
299 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
300 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
301 unsigned char aad[13];
302 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
306 /* minimize address aliasing conflicts */
307 if ((max_send_fragment & 0xfff) == 0)
308 max_send_fragment -= 512;
310 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
311 ssl3_release_write_buffer(s);
313 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
314 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
315 (int)max_send_fragment, NULL);
317 if (len >= 8 * max_send_fragment)
322 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
323 /* SSLfatal() already called */
326 } else if (tot == len) { /* done? */
327 /* free jumbo buffer */
328 ssl3_release_write_buffer(s);
335 if (n < 4 * max_send_fragment) {
336 /* free jumbo buffer */
337 ssl3_release_write_buffer(s);
341 if (s->s3.alert_dispatch) {
342 i = ssl->method->ssl_dispatch_alert(ssl);
344 /* SSLfatal() already called if appropriate */
345 s->rlayer.wnum = tot;
350 if (n >= 8 * max_send_fragment)
351 nw = max_send_fragment * (mb_param.interleave = 8);
353 nw = max_send_fragment * (mb_param.interleave = 4);
355 memcpy(aad, s->rlayer.write_sequence, 8);
357 aad[9] = (unsigned char)(s->version >> 8);
358 aad[10] = (unsigned char)(s->version);
365 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
366 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
367 sizeof(mb_param), &mb_param);
368 packlen = (size_t)packleni;
369 if (packleni <= 0 || packlen > wb->len) { /* never happens */
370 /* free jumbo buffer */
371 ssl3_release_write_buffer(s);
375 mb_param.out = wb->buf;
376 mb_param.inp = &buf[tot];
379 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
380 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
381 sizeof(mb_param), &mb_param) <= 0)
384 s->rlayer.write_sequence[7] += mb_param.interleave;
385 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
387 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
393 s->rlayer.wpend_tot = nw;
394 s->rlayer.wpend_buf = &buf[tot];
395 s->rlayer.wpend_type = type;
396 s->rlayer.wpend_ret = nw;
398 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
400 /* SSLfatal() already called if appropriate */
401 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
402 /* free jumbo buffer */
403 ssl3_release_write_buffer(s);
405 s->rlayer.wnum = tot;
409 /* free jumbo buffer */
410 ssl3_release_write_buffer(s);
411 *written = tot + tmpwrit;
418 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
419 if (tot == len) { /* done? */
420 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
421 ssl3_release_write_buffer(s);
429 max_send_fragment = ssl_get_max_send_fragment(s);
430 split_send_fragment = ssl_get_split_send_fragment(s);
432 * TODO(RECLAYER): This comment is now out-of-date and probably needs to
433 * move somewhere else
435 * If max_pipelines is 0 then this means "undefined" and we default to
436 * 1 pipeline. Similarly if the cipher does not support pipelined
437 * processing then we also only use 1 pipeline, or if we're not using
440 maxpipes = s->max_pipelines;
441 if (maxpipes > SSL_MAX_PIPELINES) {
443 * We should have prevented this when we set max_pipelines so we
446 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
449 /* If no explicit maxpipes configuration - default to 1 */
450 /* TODO(RECLAYER): Should we ask the record layer how many pipes it supports? */
454 /* TODO(RECLAYER): FIX ME */
456 || s->enc_write_ctx == NULL
457 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
458 & EVP_CIPH_FLAG_PIPELINE) == 0
459 || !SSL_USE_EXPLICIT_IV(s))
462 if (max_send_fragment == 0
463 || split_send_fragment == 0
464 || split_send_fragment > max_send_fragment) {
466 * We should have prevented this when we set/get the split and max send
467 * fragments so we shouldn't get here
469 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
474 size_t tmppipelen, remain;
475 size_t numpipes, j, lensofar = 0;
480 numpipes = ((n - 1) / split_send_fragment) + 1;
481 if (numpipes > maxpipes)
484 if (n / numpipes >= max_send_fragment) {
486 * We have enough data to completely fill all available
489 for (j = 0; j < numpipes; j++) {
490 tmpls[j].type = type;
491 tmpls[j].buf = &(buf[tot]) + (j * max_send_fragment);
492 tmpls[j].buflen = max_send_fragment;
494 /* Remember how much data we are going to be sending */
495 s->rlayer.wpend_tot = numpipes * max_send_fragment;
497 /* We can partially fill all available pipelines */
498 tmppipelen = n / numpipes;
499 remain = n % numpipes;
501 * If there is a remainder we add an extra byte to the first few
506 for (j = 0; j < numpipes; j++) {
507 tmpls[j].type = type;
508 tmpls[j].buf = &(buf[tot]) + lensofar;
509 tmpls[j].buflen = tmppipelen;
510 lensofar += tmppipelen;
514 /* Remember how much data we are going to be sending */
515 s->rlayer.wpend_tot = n;
518 i = s->rlayer.wrlmethod->write_records(s->rlayer.wrl, tmpls, numpipes);
520 /* SSLfatal() already called if appropriate */
521 s->rlayer.wnum = tot;
525 if (s->rlayer.wpend_tot == n ||
526 (type == SSL3_RT_APPLICATION_DATA &&
527 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
528 if (s->rlayer.wpend_tot == n
529 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
530 && !SSL_CONNECTION_IS_DTLS(s))
531 ssl3_release_write_buffer(s);
533 *written = tot + s->rlayer.wpend_tot;
534 s->rlayer.wpend_tot = 0;
538 n -= s->rlayer.wpend_tot;
539 tot += s->rlayer.wpend_tot;
543 int ossl_tls_handle_rlayer_return(SSL_CONNECTION *s, int ret, char *file,
546 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
548 if (ret == OSSL_RECORD_RETURN_RETRY) {
549 s->rwstate = SSL_READING;
552 s->rwstate = SSL_NOTHING;
553 if (ret == OSSL_RECORD_RETURN_EOF) {
554 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
555 SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN);
556 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
559 ERR_set_debug(file, line, 0);
560 ossl_statem_fatal(s, SSL_AD_DECODE_ERROR,
561 SSL_R_UNEXPECTED_EOF_WHILE_READING, NULL);
563 } else if (ret == OSSL_RECORD_RETURN_FATAL) {
564 int al = s->rlayer.rrlmethod->get_alert_code(s->rlayer.rrl);
566 if (al != SSL_AD_NO_ALERT) {
568 ERR_set_debug(file, line, 0);
569 ossl_statem_fatal(s, al, SSL_R_RECORD_LAYER_FAILURE, NULL);
572 * else some failure but there is no alert code. We don't log an
573 * error for this. The record layer should have logged an error
574 * already or, if not, its due to some sys call error which will be
575 * reported via SSL_ERROR_SYSCALL and errno.
579 * The record layer distinguishes the cases of EOF, non-fatal
580 * err and retry. Upper layers do not.
581 * If we got a retry or success then *ret is already correct,
582 * otherwise we need to convert the return value.
584 if (ret == OSSL_RECORD_RETURN_NON_FATAL_ERR || ret == OSSL_RECORD_RETURN_EOF)
586 else if (ret < OSSL_RECORD_RETURN_NON_FATAL_ERR)
593 void ssl_release_record(SSL_CONNECTION *s, TLS_RECORD *rr)
595 if (rr->rechandle != NULL) {
596 /* The record layer allocated the buffers for this record */
597 s->rlayer.rrlmethod->release_record(s->rlayer.rrl, rr->rechandle);
599 /* We allocated the buffers for this record (only happens with DTLS) */
600 OPENSSL_free(rr->data);
602 s->rlayer.curr_rec++;
606 * Return up to 'len' payload bytes received in 'type' records.
607 * 'type' is one of the following:
609 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
610 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
611 * - 0 (during a shutdown, no data has to be returned)
613 * If we don't have stored data to work from, read a SSL/TLS record first
614 * (possibly multiple records if we still don't have anything to return).
616 * This function must handle any surprises the peer may have for us, such as
617 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
618 * messages are treated as if they were handshake messages *if* the |recvd_type|
619 * argument is non NULL.
620 * Also if record payloads contain fragments too small to process, we store
621 * them until there is enough for the respective protocol (the record protocol
622 * may use arbitrary fragmentation and even interleaving):
623 * Change cipher spec protocol
624 * just 1 byte needed, no need for keeping anything stored
626 * 2 bytes needed (AlertLevel, AlertDescription)
628 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
629 * to detect unexpected Client Hello and Hello Request messages
630 * here, anything else is handled by higher layers
631 * Application data protocol
632 * none of our business
634 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
635 size_t len, int peek, size_t *readbytes)
638 size_t n, curr_rec, totalbytes;
640 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
642 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
644 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
647 && (type != SSL3_RT_APPLICATION_DATA)
648 && (type != SSL3_RT_HANDSHAKE))
649 || (peek && (type != SSL3_RT_APPLICATION_DATA))) {
650 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
654 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
655 /* (partially) satisfy request from storage */
657 unsigned char *src = s->rlayer.handshake_fragment;
658 unsigned char *dst = buf;
663 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
666 s->rlayer.handshake_fragment_len--;
669 /* move any remaining fragment bytes: */
670 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
671 s->rlayer.handshake_fragment[k] = *src++;
673 if (recvd_type != NULL)
674 *recvd_type = SSL3_RT_HANDSHAKE;
681 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
684 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
685 /* type == SSL3_RT_APPLICATION_DATA */
686 i = s->handshake_func(ssl);
687 /* SSLfatal() already called */
694 s->rwstate = SSL_NOTHING;
697 * For each record 'i' up to |num_recs]
698 * rr[i].type - is the type of record
700 * rr[i].off, - offset into 'data' for next read
701 * rr[i].length, - number of bytes.
703 /* get new records if necessary */
704 if (s->rlayer.curr_rec >= s->rlayer.num_recs) {
705 s->rlayer.curr_rec = s->rlayer.num_recs = 0;
707 rr = &s->rlayer.tlsrecs[s->rlayer.num_recs];
709 ret = HANDLE_RLAYER_RETURN(s,
710 s->rlayer.rrlmethod->read_record(s->rlayer.rrl,
712 &rr->version, &rr->type,
713 &rr->data, &rr->length,
716 /* SSLfatal() already called if appropriate */
720 s->rlayer.num_recs++;
721 } while (s->rlayer.rrlmethod->processed_read_pending(s->rlayer.rrl)
722 && s->rlayer.num_recs < SSL_MAX_PIPELINES);
724 rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
726 if (s->rlayer.handshake_fragment_len > 0
727 && rr->type != SSL3_RT_HANDSHAKE
728 && SSL_CONNECTION_IS_TLS13(s)) {
729 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
730 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
735 * Reset the count of consecutive warning alerts if we've got a non-empty
736 * record that isn't an alert.
738 if (rr->type != SSL3_RT_ALERT && rr->length != 0)
739 s->rlayer.alert_count = 0;
741 /* we now have a packet which can be read and processed */
743 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
744 * reset by ssl3_get_finished */
745 && (rr->type != SSL3_RT_HANDSHAKE)) {
746 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
747 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
752 * If the other end has shut down, throw anything we read away (even in
755 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
756 s->rlayer.curr_rec++;
757 s->rwstate = SSL_NOTHING;
762 || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
763 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
766 * SSL3_RT_APPLICATION_DATA or
767 * SSL3_RT_HANDSHAKE or
768 * SSL3_RT_CHANGE_CIPHER_SPEC
771 * make sure that we are not getting application data when we are
772 * doing a handshake for the first time
774 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
775 && s->enc_read_ctx == NULL) {
776 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
780 if (type == SSL3_RT_HANDSHAKE
781 && rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
782 && s->rlayer.handshake_fragment_len > 0) {
783 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
787 if (recvd_type != NULL)
788 *recvd_type = rr->type;
792 * Skip a zero length record. This ensures multiple calls to
793 * SSL_read() with a zero length buffer will eventually cause
794 * SSL_pending() to report data as being available.
797 ssl_release_record(s, rr);
803 curr_rec = s->rlayer.curr_rec;
805 if (len - totalbytes > rr->length)
808 n = len - totalbytes;
810 memcpy(buf, &(rr->data[rr->off]), n);
813 /* Mark any zero length record as consumed CVE-2016-6305 */
815 ssl_release_record(s, rr);
817 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
818 OPENSSL_cleanse(&(rr->data[rr->off]), n);
822 ssl_release_record(s, rr);
825 || (peek && n == rr->length)) {
830 } while (type == SSL3_RT_APPLICATION_DATA
831 && curr_rec < s->rlayer.num_recs
832 && totalbytes < len);
833 if (totalbytes == 0) {
834 /* We must have read empty records. Get more data */
837 *readbytes = totalbytes;
842 * If we get here, then type != rr->type; if we have a handshake message,
843 * then it was unexpected (Hello Request or Client Hello) or invalid (we
844 * were actually expecting a CCS).
848 * Lets just double check that we've not got an SSLv2 record
850 if (rr->version == SSL2_VERSION) {
852 * Should never happen. ssl3_get_record() should only give us an SSLv2
853 * record back if this is the first packet and we are looking for an
854 * initial ClientHello. Therefore |type| should always be equal to
855 * |rr->type|. If not then something has gone horribly wrong
857 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
861 if (ssl->method->version == TLS_ANY_VERSION
862 && (s->server || rr->type != SSL3_RT_ALERT)) {
864 * If we've got this far and still haven't decided on what version
865 * we're using then this must be a client side alert we're dealing
866 * with. We shouldn't be receiving anything other than a ClientHello
867 * if we are a server.
869 s->version = rr->version;
870 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
875 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
876 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
879 if (rr->type == SSL3_RT_ALERT) {
880 unsigned int alert_level, alert_descr;
881 unsigned char *alert_bytes = rr->data
885 if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
886 || !PACKET_get_1(&alert, &alert_level)
887 || !PACKET_get_1(&alert, &alert_descr)
888 || PACKET_remaining(&alert) != 0) {
889 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
894 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
895 s->msg_callback_arg);
897 if (s->info_callback != NULL)
898 cb = s->info_callback;
899 else if (ssl->ctx->info_callback != NULL)
900 cb = ssl->ctx->info_callback;
903 j = (alert_level << 8) | alert_descr;
904 cb(ssl, SSL_CB_READ_ALERT, j);
907 if ((!is_tls13 && alert_level == SSL3_AL_WARNING)
908 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
909 s->s3.warn_alert = alert_descr;
910 ssl_release_record(s, rr);
912 s->rlayer.alert_count++;
913 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
914 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
915 SSL_R_TOO_MANY_WARN_ALERTS);
921 * Apart from close_notify the only other warning alert in TLSv1.3
922 * is user_cancelled - which we just ignore.
924 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
926 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
927 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
928 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
930 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
931 s->rwstate = SSL_NOTHING;
932 s->s3.fatal_alert = alert_descr;
933 SSLfatal_data(s, SSL_AD_NO_ALERT,
934 SSL_AD_REASON_OFFSET + alert_descr,
935 "SSL alert number %d", alert_descr);
936 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
937 ssl_release_record(s, rr);
938 SSL_CTX_remove_session(s->session_ctx, s->session);
940 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
942 * This is a warning but we receive it if we requested
943 * renegotiation and the peer denied it. Terminate with a fatal
944 * alert because if application tried to renegotiate it
945 * presumably had a good reason and expects it to succeed. In
946 * future we might have a renegotiation where we don't care if
947 * the peer refused it where we carry on.
949 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
951 } else if (alert_level == SSL3_AL_WARNING) {
952 /* We ignore any other warning alert in TLSv1.2 and below */
956 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
960 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
961 if (rr->type == SSL3_RT_HANDSHAKE) {
965 * We ignore any handshake messages sent to us unless they are
966 * TLSv1.3 in which case we want to process them. For all other
967 * handshake messages we can't do anything reasonable with them
968 * because we are unable to write any response due to having already
971 if (!SSL_CONNECTION_IS_TLS13(s)) {
972 ssl_release_record(s, rr);
974 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
977 s->rwstate = SSL_READING;
978 rbio = SSL_get_rbio(ssl);
979 BIO_clear_retry_flags(rbio);
980 BIO_set_retry_read(rbio);
985 * The peer is continuing to send application data, but we have
986 * already sent close_notify. If this was expected we should have
987 * been called via SSL_read() and this would have been handled
989 * No alert sent because we already sent close_notify
991 ssl_release_record(s, rr);
992 SSLfatal(s, SSL_AD_NO_ALERT,
993 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
999 * For handshake data we have 'fragment' storage, so fill that so that we
1000 * can process the header at a fixed place. This is done after the
1001 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1002 * that we're just going to discard.
1004 if (rr->type == SSL3_RT_HANDSHAKE) {
1005 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1006 unsigned char *dest = s->rlayer.handshake_fragment;
1007 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1009 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1011 n = rr->length; /* available bytes */
1013 /* now move 'n' bytes: */
1014 memcpy(dest + *dest_len, rr->data + rr->off, n);
1018 if (rr->length == 0)
1019 ssl_release_record(s, rr);
1021 if (*dest_len < dest_maxlen)
1022 goto start; /* fragment was too small */
1025 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1026 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1031 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1032 * protocol violation)
1034 if ((s->rlayer.handshake_fragment_len >= 4)
1035 && !ossl_statem_get_in_handshake(s)) {
1036 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1038 /* We found handshake data, so we're going back into init */
1039 ossl_statem_set_in_init(s, 1);
1041 i = s->handshake_func(ssl);
1042 /* SSLfatal() already called if appropriate */
1050 * If we were actually trying to read early data and we found a
1051 * handshake message, then we don't want to continue to try and read
1052 * the application data any more. It won't be "early" now.
1057 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1058 if (!RECORD_LAYER_read_pending(&s->rlayer)) {
1061 * In the case where we try to read application data, but we
1062 * trigger an SSL handshake, we return -1 with the retry
1063 * option set. Otherwise renegotiation may cause nasty
1064 * problems in the blocking world
1066 s->rwstate = SSL_READING;
1067 bio = SSL_get_rbio(ssl);
1068 BIO_clear_retry_flags(bio);
1069 BIO_set_retry_read(bio);
1079 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1080 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1081 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1082 * no progress is being made and the peer continually sends unrecognised
1083 * record types, using up resources processing them.
1085 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1087 case SSL3_RT_CHANGE_CIPHER_SPEC:
1089 case SSL3_RT_HANDSHAKE:
1091 * we already handled all of these, with the possible exception of
1092 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1093 * that should not happen when type != rr->type
1095 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1097 case SSL3_RT_APPLICATION_DATA:
1099 * At this point, we were expecting handshake data, but have
1100 * application data. If the library was running inside ssl3_read()
1101 * (i.e. in_read_app_data is set) and it makes sense to read
1102 * application data at this point (session renegotiation not yet
1103 * started), we will indulge it.
1105 if (ossl_statem_app_data_allowed(s)) {
1106 s->s3.in_read_app_data = 2;
1108 } else if (ossl_statem_skip_early_data(s)) {
1110 * This can happen after a client sends a CH followed by early_data,
1111 * but the server responds with a HelloRetryRequest. The server
1112 * reads the next record from the client expecting to find a
1113 * plaintext ClientHello but gets a record which appears to be
1114 * application data. The trial decrypt "works" because null
1115 * decryption was applied. We just skip it and move on to the next
1118 if (!ossl_early_data_count_ok(s, rr->length,
1119 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1120 /* SSLfatal() already called */
1123 ssl_release_record(s, rr);
1126 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1132 void ssl3_record_sequence_update(unsigned char *seq)
1136 for (i = 7; i >= 0; i--) {
1144 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1145 * format and false otherwise.
1147 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1149 if (SSL_CONNECTION_IS_DTLS(rl->s))
1151 return rl->tlsrecs[0].version == SSL2_VERSION;
1154 static OSSL_FUNC_rlayer_msg_callback_fn rlayer_msg_callback_wrapper;
1155 static void rlayer_msg_callback_wrapper(int write_p, int version,
1156 int content_type, const void *buf,
1157 size_t len, void *cbarg)
1159 SSL_CONNECTION *s = cbarg;
1160 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1162 if (s->msg_callback != NULL)
1163 s->msg_callback(write_p, version, content_type, buf, len, ssl,
1164 s->msg_callback_arg);
1167 static OSSL_FUNC_rlayer_security_fn rlayer_security_wrapper;
1168 static int rlayer_security_wrapper(void *cbarg, int op, int bits, int nid,
1171 SSL_CONNECTION *s = cbarg;
1173 return ssl_security(s, op, bits, nid, other);
1176 static const OSSL_DISPATCH rlayer_dispatch[] = {
1177 { OSSL_FUNC_RLAYER_SKIP_EARLY_DATA, (void (*)(void))ossl_statem_skip_early_data },
1178 { OSSL_FUNC_RLAYER_MSG_CALLBACK, (void (*)(void))rlayer_msg_callback_wrapper },
1179 { OSSL_FUNC_RLAYER_SECURITY, (void (*)(void))rlayer_security_wrapper },
1183 static const OSSL_RECORD_METHOD *ssl_select_next_record_layer(SSL_CONNECTION *s,
1187 if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE) {
1188 if (SSL_CONNECTION_IS_DTLS(s))
1189 return &ossl_dtls_record_method;
1191 return &ossl_tls_record_method;
1194 #ifndef OPENSSL_NO_KTLS
1195 /* KTLS does not support renegotiation */
1196 if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION
1197 && (s->options & SSL_OP_ENABLE_KTLS) != 0
1198 && (SSL_CONNECTION_IS_TLS13(s) || SSL_IS_FIRST_HANDSHAKE(s)))
1199 return &ossl_ktls_record_method;
1202 /* Default to the current OSSL_RECORD_METHOD */
1203 return s->rlayer.rrlmethod;
1206 static int ssl_post_record_layer_select(SSL_CONNECTION *s, int direction)
1208 const OSSL_RECORD_METHOD *thismethod;
1209 OSSL_RECORD_LAYER *thisrl;
1211 if (direction == OSSL_RECORD_DIRECTION_READ) {
1212 thismethod = s->rlayer.rrlmethod;
1213 thisrl = s->rlayer.rrl;
1215 thismethod = s->rlayer.wrlmethod;
1216 thisrl = s->rlayer.wrl;
1219 #ifndef OPENSSL_NO_KTLS
1221 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1223 if (s->rlayer.rrlmethod == &ossl_ktls_record_method) {
1224 /* KTLS does not support renegotiation so disallow it */
1225 SSL_set_options(ssl, SSL_OP_NO_RENEGOTIATION);
1229 if (SSL_IS_FIRST_HANDSHAKE(s) && thismethod->set_first_handshake != NULL)
1230 thismethod->set_first_handshake(thisrl, 1);
1232 if (s->max_pipelines != 0 && thismethod->set_max_pipelines != NULL)
1233 thismethod->set_max_pipelines(thisrl, s->max_pipelines);
1238 int ssl_set_new_record_layer(SSL_CONNECTION *s, int version,
1239 int direction, int level,
1240 unsigned char *key, size_t keylen,
1241 unsigned char *iv, size_t ivlen,
1242 unsigned char *mackey, size_t mackeylen,
1243 const EVP_CIPHER *ciph, size_t taglen,
1244 int mactype, const EVP_MD *md,
1245 const SSL_COMP *comp)
1247 OSSL_PARAM options[5], *opts = options;
1248 OSSL_PARAM settings[6], *set = settings;
1249 const OSSL_RECORD_METHOD *origmeth = s->rlayer.rrlmethod;
1250 const OSSL_RECORD_METHOD **thismethod;
1251 OSSL_RECORD_LAYER **thisrl;
1253 SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1254 const OSSL_RECORD_METHOD *meth;
1255 int use_etm, stream_mac = 0, tlstree = 0;
1256 unsigned int maxfrag = SSL3_RT_MAX_PLAIN_LENGTH;
1257 int use_early_data = 0;
1258 uint32_t max_early_data;
1260 meth = ssl_select_next_record_layer(s, level);
1262 if (direction == OSSL_RECORD_DIRECTION_READ) {
1263 thismethod = &s->rlayer.rrlmethod;
1264 thisrl = &s->rlayer.rrl;
1267 thismethod = &s->rlayer.wrlmethod;
1268 thisrl = &s->rlayer.wrl;
1272 if (*thismethod != NULL && !(*thismethod)->free(*thisrl)) {
1273 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1281 if (!ossl_assert(*thismethod != NULL)) {
1282 ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1286 /* Parameters that *may* be supported by a record layer if passed */
1287 *opts++ = OSSL_PARAM_construct_uint64(OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS,
1289 *opts++ = OSSL_PARAM_construct_uint32(OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE,
1291 if (direction == OSSL_RECORD_DIRECTION_READ) {
1292 *opts++ = OSSL_PARAM_construct_size_t(OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN,
1293 &s->rlayer.default_read_buf_len);
1294 *opts++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD,
1295 &s->rlayer.read_ahead);
1297 *opts = OSSL_PARAM_construct_end();
1299 /* Parameters that *must* be supported by a record layer if passed */
1300 if (direction == OSSL_RECORD_DIRECTION_READ) {
1301 use_etm = SSL_READ_ETM(s) ? 1 : 0;
1302 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM) != 0)
1305 if ((s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE) != 0)
1308 use_etm = SSL_WRITE_ETM(s) ? 1 : 0;
1309 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) != 0)
1312 if ((s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE) != 0)
1317 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM,
1321 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC,
1325 *set++ = OSSL_PARAM_construct_int(OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE,
1328 if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1329 maxfrag = GET_MAX_FRAGMENT_LENGTH(s->session);
1331 if (maxfrag != SSL3_RT_MAX_PLAIN_LENGTH)
1332 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN,
1336 * The record layer must check the amount of early data sent or received
1337 * using the early keys. A server also needs to worry about rejected early
1338 * data that might arrive when the handshake keys are in force.
1340 /* TODO(RECLAYER): Check this when doing the "write" record layer */
1341 if (s->server && direction == OSSL_RECORD_DIRECTION_READ) {
1342 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY
1343 || level == OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE);
1344 } else if (!s->server && direction == OSSL_RECORD_DIRECTION_WRITE) {
1345 use_early_data = (level == OSSL_RECORD_PROTECTION_LEVEL_EARLY);
1347 if (use_early_data) {
1348 max_early_data = ossl_get_max_early_data(s);
1350 if (max_early_data != 0)
1351 *set++ = OSSL_PARAM_construct_uint(OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA,
1355 *set = OSSL_PARAM_construct_end();
1361 unsigned int epoch = 0;;
1364 if (direction == OSSL_RECORD_DIRECTION_READ) {
1365 prev = s->rlayer.rrlnext;
1366 if (SSL_CONNECTION_IS_DTLS(s)
1367 && level != OSSL_RECORD_PROTECTION_LEVEL_NONE)
1368 epoch = DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer) + 1; /* new epoch */
1370 if (SSL_CONNECTION_IS_DTLS(s))
1371 next = BIO_new(BIO_s_dgram_mem());
1373 next = BIO_new(BIO_s_mem());
1377 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1380 s->rlayer.rrlnext = next;
1383 rlret = (*thismethod)->new_record_layer(sctx->libctx,
1386 direction, level, epoch,
1387 key, keylen, iv, ivlen,
1388 mackey, mackeylen, ciph,
1389 taglen, mactype, md, comp,
1392 NULL, settings, options,
1397 case OSSL_RECORD_RETURN_FATAL:
1398 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_RECORD_LAYER_FAILURE);
1401 case OSSL_RECORD_RETURN_NON_FATAL_ERR:
1402 if (*thismethod != origmeth && origmeth != NULL) {
1404 * We tried a new record layer method, but it didn't work out,
1405 * so we fallback to the original method and try again
1407 *thismethod = origmeth;
1410 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_SUITABLE_RECORD_LAYER);
1413 case OSSL_RECORD_RETURN_SUCCESS:
1417 /* Should not happen */
1418 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1424 return ssl_post_record_layer_select(s, direction);