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 "record_local.h"
18 #include "internal/packet.h"
20 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
21 !( defined(AES_ASM) && ( \
22 defined(__x86_64) || defined(__x86_64__) || \
23 defined(_M_AMD64) || defined(_M_X64) ) \
25 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
26 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
29 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
32 RECORD_LAYER_set_first_record(&s->rlayer);
33 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
36 void RECORD_LAYER_clear(RECORD_LAYER *rl)
38 rl->rstate = SSL_ST_READ_HEADER;
41 * Do I need to clear read_ahead? As far as I can tell read_ahead did not
42 * previously get reset by SSL_clear...so I'll keep it that way..but is
47 rl->packet_length = 0;
49 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
50 rl->handshake_fragment_len = 0;
56 SSL3_BUFFER_clear(&rl->rbuf);
57 ssl3_release_write_buffer(rl->s);
59 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
61 RECORD_LAYER_reset_read_sequence(rl);
62 RECORD_LAYER_reset_write_sequence(rl);
65 DTLS_RECORD_LAYER_clear(rl);
68 void RECORD_LAYER_release(RECORD_LAYER *rl)
70 if (SSL3_BUFFER_is_initialised(&rl->rbuf))
71 ssl3_release_read_buffer(rl->s);
72 if (rl->numwpipes > 0)
73 ssl3_release_write_buffer(rl->s);
74 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
77 /* Checks if we have unprocessed read ahead data pending */
78 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
80 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
83 /* Checks if we have decrypted unread record data pending */
84 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
86 size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl);
87 const SSL3_RECORD *rr = rl->rrec;
89 while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]))
92 return curr_rec < num_recs;
95 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
97 return (rl->numwpipes > 0)
98 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
101 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
103 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
106 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
108 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
111 size_t ssl3_pending(const SSL *s)
114 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
119 if (sc->rlayer.rstate == SSL_ST_READ_BODY)
122 /* Take into account DTLS buffered app data */
123 if (SSL_CONNECTION_IS_DTLS(sc)) {
124 DTLS1_RECORD_DATA *rdata;
127 iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
128 while ((item = pqueue_next(&iter)) != NULL) {
130 num += rdata->rrec.length;
134 for (i = 0; i < RECORD_LAYER_get_numrpipes(&sc->rlayer); i++) {
135 if (SSL3_RECORD_get_type(&sc->rlayer.rrec[i])
136 != SSL3_RT_APPLICATION_DATA)
138 num += SSL3_RECORD_get_length(&sc->rlayer.rrec[i]);
144 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
146 ctx->default_read_buf_len = len;
149 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
151 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
156 SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&sc->rlayer), len);
159 const char *SSL_rstate_string_long(const SSL *s)
161 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
166 switch (sc->rlayer.rstate) {
167 case SSL_ST_READ_HEADER:
168 return "read header";
169 case SSL_ST_READ_BODY:
171 case SSL_ST_READ_DONE:
178 const char *SSL_rstate_string(const SSL *s)
180 const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
185 switch (sc->rlayer.rstate) {
186 case SSL_ST_READ_HEADER:
188 case SSL_ST_READ_BODY:
190 case SSL_ST_READ_DONE:
198 * Return values are as per SSL_read()
200 int ssl3_read_n(SSL_CONNECTION *s, size_t n, size_t max, int extend,
201 int clearold, size_t *readbytes)
204 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
205 * packet by another n bytes. The packet will be in the sub-array of
206 * s->rlayer.rbuf.buf specified by s->rlayer.packet and
207 * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
208 * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
209 * if clearold == 1, move the packet to the start of the buffer; if
210 * clearold == 0 then leave any old packets where they were
212 size_t len, left, align = 0;
219 rb = &s->rlayer.rbuf;
221 if (!ssl3_setup_read_buffer(s)) {
222 /* SSLfatal() already called */
227 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
228 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
229 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
233 /* start with empty packet ... */
236 else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
238 * check if next packet length is large enough to justify payload
241 pkt = rb->buf + rb->offset;
242 if (pkt[0] == SSL3_RT_APPLICATION_DATA
243 && (pkt[3] << 8 | pkt[4]) >= 128) {
245 * Note that even if packet is corrupted and its length field
246 * is insane, we can only be led to wrong decision about
247 * whether memmove will occur or not. Header values has no
248 * effect on memmove arguments and therefore no buffer
249 * overrun can be triggered.
251 memmove(rb->buf + align, pkt, left);
255 s->rlayer.packet = rb->buf + rb->offset;
256 s->rlayer.packet_length = 0;
257 /* ... now we can act as if 'extend' was set */
260 len = s->rlayer.packet_length;
261 pkt = rb->buf + align;
263 * Move any available bytes to front of buffer: 'len' bytes already
264 * pointed to by 'packet', 'left' extra ones at the end
266 if (s->rlayer.packet != pkt && clearold == 1) {
267 memmove(pkt, s->rlayer.packet, len + left);
268 s->rlayer.packet = pkt;
269 rb->offset = len + align;
273 * For DTLS/UDP reads should not span multiple packets because the read
274 * operation returns the whole packet at once (as long as it fits into
277 if (SSL_CONNECTION_IS_DTLS(s)) {
278 if (left == 0 && extend)
280 if (left > 0 && n > left)
284 /* if there is enough in the buffer from a previous read, take some */
286 s->rlayer.packet_length += n;
293 /* else we need to read more data */
295 if (n > rb->len - rb->offset) {
296 /* does not happen */
297 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
302 * Ktls always reads full records.
303 * Also, we always act like read_ahead is set for DTLS.
305 if (!BIO_get_ktls_recv(s->rbio) && !s->rlayer.read_ahead
306 && !SSL_CONNECTION_IS_DTLS(s)) {
307 /* ignore max parameter */
312 if (max > rb->len - rb->offset)
313 max = rb->len - rb->offset;
321 * Now we have len+left bytes at the front of s->s3.rbuf.buf and
322 * need to read in more until we have len+n (up to len+max if
327 if (s->rbio != NULL) {
328 s->rwstate = SSL_READING;
329 ret = BIO_read(s->rbio, pkt + len + left, max - left);
333 && !BIO_should_retry(s->rbio)
334 && BIO_eof(s->rbio)) {
335 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
336 SSL_set_shutdown(SSL_CONNECTION_GET_SSL(s),
337 SSL_RECEIVED_SHUTDOWN);
338 s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
340 SSLfatal(s, SSL_AD_DECODE_ERROR,
341 SSL_R_UNEXPECTED_EOF_WHILE_READING);
345 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
351 if ((s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
352 && !SSL_CONNECTION_IS_DTLS(s))
354 ssl3_release_read_buffer(s);
359 * reads should *never* span multiple packets for DTLS because the
360 * underlying transport protocol is message oriented as opposed to
361 * byte oriented as in the TLS case.
363 if (SSL_CONNECTION_IS_DTLS(s)) {
365 n = left; /* makes the while condition false */
369 /* done reading, now the book-keeping */
372 s->rlayer.packet_length += n;
373 s->rwstate = SSL_NOTHING;
379 * Call this to write data in records of type 'type' It will return <= 0 if
380 * not all data has been sent or non-blocking IO.
382 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
385 const unsigned char *buf = buf_;
387 size_t n, max_send_fragment, split_send_fragment, maxpipes;
388 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
394 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
399 wb = &s->rlayer.wbuf[0];
400 s->rwstate = SSL_NOTHING;
401 tot = s->rlayer.wnum;
403 * ensure that if we end up with a smaller value of data to write out
404 * than the original len from a write which didn't complete for
405 * non-blocking I/O and also somehow ended up avoiding the check for
406 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
407 * possible to end up with (len-tot) as a large number that will then
408 * promptly send beyond the end of the users buffer ... so we trap and
409 * report the error in a way the user will notice
411 if ((len < s->rlayer.wnum)
412 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
413 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
417 if (s->early_data_state == SSL_EARLY_DATA_WRITING
418 && !ossl_early_data_count_ok(s, len, 0, 1)) {
419 /* SSLfatal() already called */
426 * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
427 * into init unless we have writes pending - in which case we should finish
430 if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
431 || s->ext.extra_tickets_expected > 0))
432 ossl_statem_set_in_init(s, 1);
435 * When writing early data on the server side we could be "in_init" in
436 * between receiving the EoED and the CF - but we don't want to handle those
439 if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
440 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
441 i = s->handshake_func(ssl);
442 /* SSLfatal() already called */
451 * first check if there is a SSL3_BUFFER still being written out. This
452 * will happen with non blocking IO
455 /* SSLfatal() already called if appropriate */
456 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
459 /* XXX should we ssl3_release_write_buffer if i<0? */
460 s->rlayer.wnum = tot;
463 tot += tmpwrit; /* this might be last fragment */
465 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
467 * Depending on platform multi-block can deliver several *times*
468 * better performance. Downside is that it has to allocate
469 * jumbo buffer to accommodate up to 8 records, but the
470 * compromise is considered worthy.
472 if (type == SSL3_RT_APPLICATION_DATA
473 && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
474 && s->compress == NULL
475 && s->msg_callback == NULL
477 && SSL_USE_EXPLICIT_IV(s)
478 && !BIO_get_ktls_send(s->wbio)
479 && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
480 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
481 unsigned char aad[13];
482 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
486 /* minimize address aliasing conflicts */
487 if ((max_send_fragment & 0xfff) == 0)
488 max_send_fragment -= 512;
490 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
491 ssl3_release_write_buffer(s);
493 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
494 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
495 (int)max_send_fragment, NULL);
497 if (len >= 8 * max_send_fragment)
502 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
503 /* SSLfatal() already called */
506 } else if (tot == len) { /* done? */
507 /* free jumbo buffer */
508 ssl3_release_write_buffer(s);
515 if (n < 4 * max_send_fragment) {
516 /* free jumbo buffer */
517 ssl3_release_write_buffer(s);
521 if (s->s3.alert_dispatch) {
522 i = ssl->method->ssl_dispatch_alert(ssl);
524 /* SSLfatal() already called if appropriate */
525 s->rlayer.wnum = tot;
530 if (n >= 8 * max_send_fragment)
531 nw = max_send_fragment * (mb_param.interleave = 8);
533 nw = max_send_fragment * (mb_param.interleave = 4);
535 memcpy(aad, s->rlayer.write_sequence, 8);
537 aad[9] = (unsigned char)(s->version >> 8);
538 aad[10] = (unsigned char)(s->version);
545 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
546 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
547 sizeof(mb_param), &mb_param);
548 packlen = (size_t)packleni;
549 if (packleni <= 0 || packlen > wb->len) { /* never happens */
550 /* free jumbo buffer */
551 ssl3_release_write_buffer(s);
555 mb_param.out = wb->buf;
556 mb_param.inp = &buf[tot];
559 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
560 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
561 sizeof(mb_param), &mb_param) <= 0)
564 s->rlayer.write_sequence[7] += mb_param.interleave;
565 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
567 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
573 s->rlayer.wpend_tot = nw;
574 s->rlayer.wpend_buf = &buf[tot];
575 s->rlayer.wpend_type = type;
576 s->rlayer.wpend_ret = nw;
578 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
580 /* SSLfatal() already called if appropriate */
581 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
582 /* free jumbo buffer */
583 ssl3_release_write_buffer(s);
585 s->rlayer.wnum = tot;
589 /* free jumbo buffer */
590 ssl3_release_write_buffer(s);
591 *written = tot + tmpwrit;
598 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
599 if (tot == len) { /* done? */
600 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
601 ssl3_release_write_buffer(s);
609 max_send_fragment = ssl_get_max_send_fragment(s);
610 split_send_fragment = ssl_get_split_send_fragment(s);
612 * If max_pipelines is 0 then this means "undefined" and we default to
613 * 1 pipeline. Similarly if the cipher does not support pipelined
614 * processing then we also only use 1 pipeline, or if we're not using
617 maxpipes = s->max_pipelines;
618 if (maxpipes > SSL_MAX_PIPELINES) {
620 * We should have prevented this when we set max_pipelines so we
623 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
627 || s->enc_write_ctx == NULL
628 || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
629 & EVP_CIPH_FLAG_PIPELINE) == 0
630 || !SSL_USE_EXPLICIT_IV(s))
632 if (max_send_fragment == 0
633 || split_send_fragment == 0
634 || split_send_fragment > max_send_fragment) {
636 * We should have prevented this when we set/get the split and max send
637 * fragments so we shouldn't get here
639 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
644 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
650 numpipes = ((n - 1) / split_send_fragment) + 1;
651 if (numpipes > maxpipes)
654 if (n / numpipes >= max_send_fragment) {
656 * We have enough data to completely fill all available
659 for (j = 0; j < numpipes; j++) {
660 pipelens[j] = max_send_fragment;
663 /* We can partially fill all available pipelines */
664 tmppipelen = n / numpipes;
665 remain = n % numpipes;
666 for (j = 0; j < numpipes; j++) {
667 pipelens[j] = tmppipelen;
673 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
676 /* SSLfatal() already called if appropriate */
677 /* XXX should we ssl3_release_write_buffer if i<0? */
678 s->rlayer.wnum = tot;
683 (type == SSL3_RT_APPLICATION_DATA &&
684 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
686 * next chunk of data should get another prepended empty fragment
687 * in ciphersuites with known-IV weakness:
689 s->s3.empty_fragment_done = 0;
692 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
693 && !SSL_CONNECTION_IS_DTLS(s))
694 ssl3_release_write_buffer(s);
696 *written = tot + tmpwrit;
705 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
706 size_t *pipelens, size_t numpipes,
707 int create_empty_fragment, size_t *written)
709 WPACKET pkt[SSL_MAX_PIPELINES];
710 SSL3_RECORD wr[SSL_MAX_PIPELINES];
713 unsigned char *recordstart;
714 int i, mac_size, clear = 0;
715 size_t prefix_len = 0;
720 size_t totlen = 0, len, wpinited = 0;
723 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
725 for (j = 0; j < numpipes; j++)
726 totlen += pipelens[j];
728 * first check if there is a SSL3_BUFFER still being written out. This
729 * will happen with non blocking IO
731 if (RECORD_LAYER_write_pending(&s->rlayer)) {
732 /* Calls SSLfatal() as required */
733 return ssl3_write_pending(s, type, buf, totlen, written);
736 /* If we have an alert to send, lets send it */
737 if (s->s3.alert_dispatch) {
738 i = ssl->method->ssl_dispatch_alert(ssl);
740 /* SSLfatal() already called if appropriate */
743 /* if it went, fall through and send more stuff */
746 if (s->rlayer.numwpipes < numpipes) {
747 if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
748 /* SSLfatal() already called */
753 if (totlen == 0 && !create_empty_fragment)
759 || (s->enc_write_ctx == NULL)
760 || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
761 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
764 mac_size = EVP_MD_CTX_get_size(s->write_hash);
766 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
772 * 'create_empty_fragment' is true only when this function calls itself
774 if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
776 * countermeasure against known-IV weakness in CBC ciphersuites (see
777 * http://www.openssl.org/~bodo/tls-cbc.txt)
780 if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
782 * recursive function call with 'create_empty_fragment' set; this
783 * prepares and buffers the data for an empty fragment (these
784 * 'prefix_len' bytes are sent out later together with the actual
787 size_t tmppipelen = 0;
790 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
792 /* SSLfatal() already called if appropriate */
797 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
798 /* insufficient space */
799 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
804 s->s3.empty_fragment_done = 1;
807 using_ktls = BIO_get_ktls_send(s->wbio);
810 * ktls doesn't modify the buffer, but to avoid a warning we need to
811 * discard the const qualifier.
812 * This doesn't leak memory because the buffers have been released when
815 SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
816 SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
817 SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
818 goto wpacket_init_complete;
821 if (create_empty_fragment) {
822 wb = &s->rlayer.wbuf[0];
823 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
825 * extra fragment would be couple of cipher blocks, which would be
826 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
827 * payload, then we can just pretend we simply have two headers.
829 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
830 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
832 SSL3_BUFFER_set_offset(wb, align);
833 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
834 SSL3_BUFFER_get_len(wb), 0)
835 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
836 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
840 } else if (prefix_len) {
841 wb = &s->rlayer.wbuf[0];
842 if (!WPACKET_init_static_len(&pkt[0],
843 SSL3_BUFFER_get_buf(wb),
844 SSL3_BUFFER_get_len(wb), 0)
845 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
846 + prefix_len, NULL)) {
847 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
852 for (j = 0; j < numpipes; j++) {
855 wb = &s->rlayer.wbuf[j];
856 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
857 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
858 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
860 SSL3_BUFFER_set_offset(wb, align);
861 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
862 SSL3_BUFFER_get_len(wb), 0)
863 || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
864 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
871 /* Explicit IV length, block ciphers appropriate version flag */
872 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
873 && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
874 int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
875 if (mode == EVP_CIPH_CBC_MODE) {
876 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
878 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
883 } else if (mode == EVP_CIPH_GCM_MODE) {
884 /* Need explicit part of IV for GCM mode */
885 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
886 } else if (mode == EVP_CIPH_CCM_MODE) {
887 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
891 wpacket_init_complete:
894 /* Clear our SSL3_RECORD structures */
895 memset(wr, 0, sizeof(wr));
896 for (j = 0; j < numpipes; j++) {
897 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
899 unsigned char *compressdata = NULL;
901 unsigned int rectype;
907 * In TLSv1.3, once encrypting, we always use application data for the
910 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
911 && s->enc_write_ctx != NULL
912 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
913 || type != SSL3_RT_ALERT))
914 rectype = SSL3_RT_APPLICATION_DATA;
917 SSL3_RECORD_set_type(thiswr, rectype);
920 * Some servers hang if initial client hello is larger than 256 bytes
921 * and record version number > TLS 1.0
923 if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
925 && TLS1_get_version(ssl) > TLS1_VERSION
926 && s->hello_retry_request == SSL_HRR_NONE)
927 version = TLS1_VERSION;
928 SSL3_RECORD_set_rec_version(thiswr, version);
930 maxcomplen = pipelens[j];
931 if (s->compress != NULL)
932 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
935 * When using offload kernel will write the header.
936 * Otherwise write the header now
939 && (!WPACKET_put_bytes_u8(thispkt, rectype)
940 || !WPACKET_put_bytes_u16(thispkt, version)
941 || !WPACKET_start_sub_packet_u16(thispkt)
943 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
945 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
947 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
951 /* lets setup the record stuff. */
952 SSL3_RECORD_set_data(thiswr, compressdata);
953 SSL3_RECORD_set_length(thiswr, pipelens[j]);
954 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
955 totlen += pipelens[j];
958 * we now 'read' from thiswr->input, thiswr->length bytes into
962 /* first we compress */
963 if (s->compress != NULL) {
964 if (!ssl3_do_compress(s, thiswr)
965 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
966 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
971 SSL3_RECORD_reset_data(&wr[j]);
973 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
974 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
977 SSL3_RECORD_reset_input(&wr[j]);
981 if (SSL_CONNECTION_TREAT_AS_TLS13(s)
983 && s->enc_write_ctx != NULL
984 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
985 || type != SSL3_RT_ALERT)) {
986 size_t rlen, max_send_fragment;
988 if (!WPACKET_put_bytes_u8(thispkt, type)) {
989 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
992 SSL3_RECORD_add_length(thiswr, 1);
994 /* Add TLS1.3 padding */
995 max_send_fragment = ssl_get_max_send_fragment(s);
996 rlen = SSL3_RECORD_get_length(thiswr);
997 if (rlen < max_send_fragment) {
999 size_t max_padding = max_send_fragment - rlen;
1000 if (s->record_padding_cb != NULL) {
1001 padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
1002 } else if (s->block_padding > 0) {
1003 size_t mask = s->block_padding - 1;
1006 /* optimize for power of 2 */
1007 if ((s->block_padding & mask) == 0)
1008 remainder = rlen & mask;
1010 remainder = rlen % s->block_padding;
1011 /* don't want to add a block of padding if we don't have to */
1015 padding = s->block_padding - remainder;
1018 /* do not allow the record to exceed max plaintext length */
1019 if (padding > max_padding)
1020 padding = max_padding;
1021 if (!WPACKET_memset(thispkt, 0, padding)) {
1022 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1023 ERR_R_INTERNAL_ERROR);
1026 SSL3_RECORD_add_length(thiswr, padding);
1032 * we should still have the output to thiswr->data and the input from
1033 * wr->input. Length should be thiswr->length. thiswr->data still points
1037 if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
1040 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1041 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1042 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1048 * Reserve some bytes for any growth that may occur during encryption.
1049 * This will be at most one cipher block or the tag length if using
1050 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1053 if (!WPACKET_reserve_bytes(thispkt,
1054 SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1057 * We also need next the amount of bytes written to this
1060 || !WPACKET_get_length(thispkt, &len)) {
1061 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1065 /* Get a pointer to the start of this record excluding header */
1066 recordstart = WPACKET_get_curr(thispkt) - len;
1067 SSL3_RECORD_set_data(thiswr, recordstart);
1068 SSL3_RECORD_reset_input(thiswr);
1069 SSL3_RECORD_set_length(thiswr, len);
1073 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
1075 * We haven't actually negotiated the version yet, but we're trying to
1076 * send early data - so we need to use the tls13enc function.
1078 if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
1079 if (!ossl_statem_in_error(s)) {
1080 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1086 if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
1088 if (!ossl_statem_in_error(s)) {
1089 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1096 for (j = 0; j < numpipes; j++) {
1105 /* Allocate bytes for the encryption overhead */
1106 if (!WPACKET_get_length(thispkt, &origlen)
1107 /* Encryption should never shrink the data! */
1108 || origlen > thiswr->length
1109 || (thiswr->length > origlen
1110 && !WPACKET_allocate_bytes(thispkt,
1111 thiswr->length - origlen,
1113 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1116 if (SSL_WRITE_ETM(s) && mac_size != 0) {
1119 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1120 || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1121 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1124 SSL3_RECORD_add_length(thiswr, mac_size);
1127 if (!WPACKET_get_length(thispkt, &len)
1128 || !WPACKET_close(thispkt)) {
1129 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1133 if (s->msg_callback) {
1134 recordstart = WPACKET_get_curr(thispkt) - len
1135 - SSL3_RT_HEADER_LENGTH;
1136 s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1137 SSL3_RT_HEADER_LENGTH, ssl,
1138 s->msg_callback_arg);
1140 if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
1141 unsigned char ctype = type;
1143 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1144 &ctype, 1, ssl, s->msg_callback_arg);
1148 if (!WPACKET_finish(thispkt)) {
1149 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1153 /* header is added by the kernel when using offload */
1154 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1156 if (create_empty_fragment) {
1158 * we are in a recursive call; just return the length, don't write
1162 /* We should never be pipelining an empty fragment!! */
1163 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1166 *written = SSL3_RECORD_get_length(thiswr);
1172 * we should now have thiswr->data pointing to the encrypted data, which
1173 * is thiswr->length long
1175 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
1178 /* now let's set up wb */
1179 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
1180 prefix_len + SSL3_RECORD_get_length(thiswr));
1184 * memorize arguments so that ssl3_write_pending can detect bad write
1187 s->rlayer.wpend_tot = totlen;
1188 s->rlayer.wpend_buf = buf;
1189 s->rlayer.wpend_type = type;
1190 s->rlayer.wpend_ret = totlen;
1192 /* we now just need to write the buffer */
1193 return ssl3_write_pending(s, type, buf, totlen, written);
1195 for (j = 0; j < wpinited; j++)
1196 WPACKET_cleanup(&pkt[j]);
1200 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1202 * Return values are as per SSL_write()
1204 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1205 size_t len, size_t *written)
1208 SSL3_BUFFER *wb = s->rlayer.wbuf;
1212 if ((s->rlayer.wpend_tot > len)
1213 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1214 && (s->rlayer.wpend_buf != buf))
1215 || (s->rlayer.wpend_type != type)) {
1216 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1221 /* Loop until we find a buffer we haven't written out yet */
1222 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1223 && currbuf < s->rlayer.numwpipes - 1) {
1228 if (s->wbio != NULL) {
1229 s->rwstate = SSL_WRITING;
1232 * To prevent coalescing of control and data messages,
1233 * such as in buffer_write, we flush the BIO
1235 if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1236 i = BIO_flush(s->wbio);
1239 BIO_set_ktls_ctrl_msg(s->wbio, type);
1241 i = BIO_write(s->wbio, (char *)
1242 &(SSL3_BUFFER_get_buf(&wb[currbuf])
1243 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1244 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1248 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1253 * When an empty fragment is sent on a connection using KTLS,
1254 * it is sent as a write of zero bytes. If this zero byte
1255 * write succeeds, i will be 0 rather than a non-zero value.
1256 * Treat i == 0 as success rather than an error for zero byte
1257 * writes to permit this case.
1259 if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1260 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1261 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1262 if (currbuf + 1 < s->rlayer.numwpipes)
1264 s->rwstate = SSL_NOTHING;
1265 *written = s->rlayer.wpend_ret;
1267 } else if (i <= 0) {
1268 if (SSL_CONNECTION_IS_DTLS(s)) {
1270 * For DTLS, just drop it. That's kind of the whole point in
1271 * using a datagram service
1273 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1277 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1278 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1283 * Return up to 'len' payload bytes received in 'type' records.
1284 * 'type' is one of the following:
1286 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1287 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1288 * - 0 (during a shutdown, no data has to be returned)
1290 * If we don't have stored data to work from, read a SSL/TLS record first
1291 * (possibly multiple records if we still don't have anything to return).
1293 * This function must handle any surprises the peer may have for us, such as
1294 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1295 * messages are treated as if they were handshake messages *if* the |recvd_type|
1296 * argument is non NULL.
1297 * Also if record payloads contain fragments too small to process, we store
1298 * them until there is enough for the respective protocol (the record protocol
1299 * may use arbitrary fragmentation and even interleaving):
1300 * Change cipher spec protocol
1301 * just 1 byte needed, no need for keeping anything stored
1303 * 2 bytes needed (AlertLevel, AlertDescription)
1304 * Handshake protocol
1305 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
1306 * to detect unexpected Client Hello and Hello Request messages
1307 * here, anything else is handled by higher layers
1308 * Application data protocol
1309 * none of our business
1311 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1312 size_t len, int peek, size_t *readbytes)
1315 size_t n, curr_rec, num_recs, totalbytes;
1318 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1320 SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1322 is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1324 rbuf = &s->rlayer.rbuf;
1326 if (!SSL3_BUFFER_is_initialised(rbuf)) {
1327 /* Not initialized yet */
1328 if (!ssl3_setup_read_buffer(s)) {
1329 /* SSLfatal() already called */
1334 if ((type && (type != SSL3_RT_APPLICATION_DATA)
1335 && (type != SSL3_RT_HANDSHAKE)) || (peek
1337 SSL3_RT_APPLICATION_DATA))) {
1338 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1342 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1343 /* (partially) satisfy request from storage */
1345 unsigned char *src = s->rlayer.handshake_fragment;
1346 unsigned char *dst = buf;
1351 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1354 s->rlayer.handshake_fragment_len--;
1357 /* move any remaining fragment bytes: */
1358 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1359 s->rlayer.handshake_fragment[k] = *src++;
1361 if (recvd_type != NULL)
1362 *recvd_type = SSL3_RT_HANDSHAKE;
1369 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1372 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1373 /* type == SSL3_RT_APPLICATION_DATA */
1374 i = s->handshake_func(ssl);
1375 /* SSLfatal() already called */
1382 s->rwstate = SSL_NOTHING;
1385 * For each record 'i' up to |num_recs]
1386 * rr[i].type - is the type of record
1387 * rr[i].data, - data
1388 * rr[i].off, - offset into 'data' for next read
1389 * rr[i].length, - number of bytes.
1391 rr = s->rlayer.rrec;
1392 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1395 /* get new records if necessary */
1396 if (num_recs == 0) {
1397 ret = ssl3_get_record(s);
1399 /* SSLfatal() already called if appropriate */
1402 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1403 if (num_recs == 0) {
1404 /* Shouldn't happen */
1405 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1409 /* Skip over any records we have already read */
1411 curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
1413 if (curr_rec == num_recs) {
1414 RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1418 } while (num_recs == 0);
1421 if (s->rlayer.handshake_fragment_len > 0
1422 && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1423 && SSL_CONNECTION_IS_TLS13(s)) {
1424 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1425 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1430 * Reset the count of consecutive warning alerts if we've got a non-empty
1431 * record that isn't an alert.
1433 if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT
1434 && SSL3_RECORD_get_length(rr) != 0)
1435 s->rlayer.alert_count = 0;
1437 /* we now have a packet which can be read and processed */
1439 if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1440 * reset by ssl3_get_finished */
1441 && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1442 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1443 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1448 * If the other end has shut down, throw anything we read away (even in
1451 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1452 SSL3_RECORD_set_length(rr, 0);
1453 s->rwstate = SSL_NOTHING;
1457 if (type == SSL3_RECORD_get_type(rr)
1458 || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1459 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1462 * SSL3_RT_APPLICATION_DATA or
1463 * SSL3_RT_HANDSHAKE or
1464 * SSL3_RT_CHANGE_CIPHER_SPEC
1467 * make sure that we are not getting application data when we are
1468 * doing a handshake for the first time
1470 if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1471 && s->enc_read_ctx == NULL) {
1472 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1476 if (type == SSL3_RT_HANDSHAKE
1477 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1478 && s->rlayer.handshake_fragment_len > 0) {
1479 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1483 if (recvd_type != NULL)
1484 *recvd_type = SSL3_RECORD_get_type(rr);
1488 * Mark a zero length record as read. This ensures multiple calls to
1489 * SSL_read() with a zero length buffer will eventually cause
1490 * SSL_pending() to report data as being available.
1492 if (SSL3_RECORD_get_length(rr) == 0)
1493 SSL3_RECORD_set_read(rr);
1499 if (len - totalbytes > SSL3_RECORD_get_length(rr))
1500 n = SSL3_RECORD_get_length(rr);
1502 n = len - totalbytes;
1504 memcpy(buf, &(rr->data[rr->off]), n);
1507 /* Mark any zero length record as consumed CVE-2016-6305 */
1508 if (SSL3_RECORD_get_length(rr) == 0)
1509 SSL3_RECORD_set_read(rr);
1511 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1512 OPENSSL_cleanse(&(rr->data[rr->off]), n);
1513 SSL3_RECORD_sub_length(rr, n);
1514 SSL3_RECORD_add_off(rr, n);
1515 if (SSL3_RECORD_get_length(rr) == 0) {
1516 s->rlayer.rstate = SSL_ST_READ_HEADER;
1517 SSL3_RECORD_set_off(rr, 0);
1518 SSL3_RECORD_set_read(rr);
1521 if (SSL3_RECORD_get_length(rr) == 0
1522 || (peek && n == SSL3_RECORD_get_length(rr))) {
1527 } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1528 && totalbytes < len);
1529 if (totalbytes == 0) {
1530 /* We must have read empty records. Get more data */
1533 if (!peek && curr_rec == num_recs
1534 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1535 && SSL3_BUFFER_get_left(rbuf) == 0)
1536 ssl3_release_read_buffer(s);
1537 *readbytes = totalbytes;
1542 * If we get here, then type != rr->type; if we have a handshake message,
1543 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1544 * were actually expecting a CCS).
1548 * Lets just double check that we've not got an SSLv2 record
1550 if (rr->rec_version == SSL2_VERSION) {
1552 * Should never happen. ssl3_get_record() should only give us an SSLv2
1553 * record back if this is the first packet and we are looking for an
1554 * initial ClientHello. Therefore |type| should always be equal to
1555 * |rr->type|. If not then something has gone horribly wrong
1557 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1561 if (ssl->method->version == TLS_ANY_VERSION
1562 && (s->server || rr->type != SSL3_RT_ALERT)) {
1564 * If we've got this far and still haven't decided on what version
1565 * we're using then this must be a client side alert we're dealing
1566 * with. We shouldn't be receiving anything other than a ClientHello
1567 * if we are a server.
1569 s->version = rr->rec_version;
1570 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1575 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1576 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1579 if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1580 unsigned int alert_level, alert_descr;
1581 unsigned char *alert_bytes = SSL3_RECORD_get_data(rr)
1582 + SSL3_RECORD_get_off(rr);
1585 if (!PACKET_buf_init(&alert, alert_bytes, SSL3_RECORD_get_length(rr))
1586 || !PACKET_get_1(&alert, &alert_level)
1587 || !PACKET_get_1(&alert, &alert_descr)
1588 || PACKET_remaining(&alert) != 0) {
1589 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1593 if (s->msg_callback)
1594 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1595 s->msg_callback_arg);
1597 if (s->info_callback != NULL)
1598 cb = s->info_callback;
1599 else if (ssl->ctx->info_callback != NULL)
1600 cb = ssl->ctx->info_callback;
1603 j = (alert_level << 8) | alert_descr;
1604 cb(ssl, SSL_CB_READ_ALERT, j);
1607 if (alert_level == SSL3_AL_WARNING
1608 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1609 s->s3.warn_alert = alert_descr;
1610 SSL3_RECORD_set_read(rr);
1612 s->rlayer.alert_count++;
1613 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1614 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1615 SSL_R_TOO_MANY_WARN_ALERTS);
1621 * Apart from close_notify the only other warning alert in TLSv1.3
1622 * is user_cancelled - which we just ignore.
1624 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1626 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1627 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1628 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1630 } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1631 s->rwstate = SSL_NOTHING;
1632 s->s3.fatal_alert = alert_descr;
1633 SSLfatal_data(s, SSL_AD_NO_ALERT,
1634 SSL_AD_REASON_OFFSET + alert_descr,
1635 "SSL alert number %d", alert_descr);
1636 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1637 SSL3_RECORD_set_read(rr);
1638 SSL_CTX_remove_session(s->session_ctx, s->session);
1640 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1642 * This is a warning but we receive it if we requested
1643 * renegotiation and the peer denied it. Terminate with a fatal
1644 * alert because if application tried to renegotiate it
1645 * presumably had a good reason and expects it to succeed. In
1646 * future we might have a renegotiation where we don't care if
1647 * the peer refused it where we carry on.
1649 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1651 } else if (alert_level == SSL3_AL_WARNING) {
1652 /* We ignore any other warning alert in TLSv1.2 and below */
1656 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1660 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1661 if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1665 * We ignore any handshake messages sent to us unless they are
1666 * TLSv1.3 in which case we want to process them. For all other
1667 * handshake messages we can't do anything reasonable with them
1668 * because we are unable to write any response due to having already
1669 * sent close_notify.
1671 if (!SSL_CONNECTION_IS_TLS13(s)) {
1672 SSL3_RECORD_set_length(rr, 0);
1673 SSL3_RECORD_set_read(rr);
1675 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1678 s->rwstate = SSL_READING;
1679 rbio = SSL_get_rbio(ssl);
1680 BIO_clear_retry_flags(rbio);
1681 BIO_set_retry_read(rbio);
1686 * The peer is continuing to send application data, but we have
1687 * already sent close_notify. If this was expected we should have
1688 * been called via SSL_read() and this would have been handled
1690 * No alert sent because we already sent close_notify
1692 SSL3_RECORD_set_length(rr, 0);
1693 SSL3_RECORD_set_read(rr);
1694 SSLfatal(s, SSL_AD_NO_ALERT,
1695 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1701 * For handshake data we have 'fragment' storage, so fill that so that we
1702 * can process the header at a fixed place. This is done after the
1703 * "SHUTDOWN" code above to avoid filling the fragment storage with data
1704 * that we're just going to discard.
1706 if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1707 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1708 unsigned char *dest = s->rlayer.handshake_fragment;
1709 size_t *dest_len = &s->rlayer.handshake_fragment_len;
1711 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1712 if (SSL3_RECORD_get_length(rr) < n)
1713 n = SSL3_RECORD_get_length(rr); /* available bytes */
1715 /* now move 'n' bytes: */
1716 memcpy(dest + *dest_len,
1717 SSL3_RECORD_get_data(rr) + SSL3_RECORD_get_off(rr), n);
1718 SSL3_RECORD_add_off(rr, n);
1719 SSL3_RECORD_sub_length(rr, n);
1721 if (SSL3_RECORD_get_length(rr) == 0)
1722 SSL3_RECORD_set_read(rr);
1724 if (*dest_len < dest_maxlen)
1725 goto start; /* fragment was too small */
1728 if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1729 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1734 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1735 * protocol violation)
1737 if ((s->rlayer.handshake_fragment_len >= 4)
1738 && !ossl_statem_get_in_handshake(s)) {
1739 int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1741 /* We found handshake data, so we're going back into init */
1742 ossl_statem_set_in_init(s, 1);
1744 i = s->handshake_func(ssl);
1745 /* SSLfatal() already called if appropriate */
1753 * If we were actually trying to read early data and we found a
1754 * handshake message, then we don't want to continue to try and read
1755 * the application data any more. It won't be "early" now.
1760 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1761 if (SSL3_BUFFER_get_left(rbuf) == 0) {
1762 /* no read-ahead left? */
1765 * In the case where we try to read application data, but we
1766 * trigger an SSL handshake, we return -1 with the retry
1767 * option set. Otherwise renegotiation may cause nasty
1768 * problems in the blocking world
1770 s->rwstate = SSL_READING;
1771 bio = SSL_get_rbio(ssl);
1772 BIO_clear_retry_flags(bio);
1773 BIO_set_retry_read(bio);
1780 switch (SSL3_RECORD_get_type(rr)) {
1783 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1784 * TLS 1.2 says you MUST send an unexpected message alert. We use the
1785 * TLS 1.2 behaviour for all protocol versions to prevent issues where
1786 * no progress is being made and the peer continually sends unrecognised
1787 * record types, using up resources processing them.
1789 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1791 case SSL3_RT_CHANGE_CIPHER_SPEC:
1793 case SSL3_RT_HANDSHAKE:
1795 * we already handled all of these, with the possible exception of
1796 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1797 * that should not happen when type != rr->type
1799 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1801 case SSL3_RT_APPLICATION_DATA:
1803 * At this point, we were expecting handshake data, but have
1804 * application data. If the library was running inside ssl3_read()
1805 * (i.e. in_read_app_data is set) and it makes sense to read
1806 * application data at this point (session renegotiation not yet
1807 * started), we will indulge it.
1809 if (ossl_statem_app_data_allowed(s)) {
1810 s->s3.in_read_app_data = 2;
1812 } else if (ossl_statem_skip_early_data(s)) {
1814 * This can happen after a client sends a CH followed by early_data,
1815 * but the server responds with a HelloRetryRequest. The server
1816 * reads the next record from the client expecting to find a
1817 * plaintext ClientHello but gets a record which appears to be
1818 * application data. The trial decrypt "works" because null
1819 * decryption was applied. We just skip it and move on to the next
1822 if (!ossl_early_data_count_ok(s, rr->length,
1823 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1824 /* SSLfatal() already called */
1827 SSL3_RECORD_set_read(rr);
1830 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1836 void ssl3_record_sequence_update(unsigned char *seq)
1840 for (i = 7; i >= 0; i--) {
1848 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1849 * format and false otherwise.
1851 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1853 return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1857 * Returns the length in bytes of the current rrec
1859 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1861 return SSL3_RECORD_get_length(&rl->rrec[0]);