2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
14 #include "../ssl_locl.h"
15 #include <openssl/evp.h>
16 #include <openssl/buffer.h>
17 #include <openssl/rand.h>
18 #include "record_locl.h"
20 #ifndef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
21 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
24 #if defined(OPENSSL_SMALL_FOOTPRINT) || \
25 !( defined(AES_ASM) && ( \
26 defined(__x86_64) || defined(__x86_64__) || \
27 defined(_M_AMD64) || defined(_M_X64) ) \
29 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
30 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
33 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s)
36 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
39 void RECORD_LAYER_clear(RECORD_LAYER *rl)
43 rl->rstate = SSL_ST_READ_HEADER;
45 /* Do I need to clear read_ahead? As far as I can tell read_ahead did not
46 * previously get reset by SSL_clear...so I'll keep it that way..but is
51 rl->packet_length = 0;
53 memset(rl->alert_fragment, 0, sizeof(rl->alert_fragment));
54 rl->alert_fragment_len = 0;
55 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
56 rl->handshake_fragment_len = 0;
62 SSL3_BUFFER_clear(&rl->rbuf);
63 for (pipes = 0; pipes < rl->numwpipes; pipes++)
64 SSL3_BUFFER_clear(&rl->wbuf[pipes]);
67 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
69 RECORD_LAYER_reset_read_sequence(rl);
70 RECORD_LAYER_reset_write_sequence(rl);
73 DTLS_RECORD_LAYER_clear(rl);
76 void RECORD_LAYER_release(RECORD_LAYER *rl)
78 if (SSL3_BUFFER_is_initialised(&rl->rbuf))
79 ssl3_release_read_buffer(rl->s);
80 if (rl->numwpipes > 0)
81 ssl3_release_write_buffer(rl->s);
82 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
85 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
87 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
90 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
92 return (rl->numwpipes > 0)
93 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes-1]) != 0;
96 int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf, int len)
98 rl->packet_length = len;
100 rl->rstate = SSL_ST_READ_HEADER;
101 if (!SSL3_BUFFER_is_initialised(&rl->rbuf))
102 if (!ssl3_setup_read_buffer(rl->s))
106 rl->packet = SSL3_BUFFER_get_buf(&rl->rbuf);
107 SSL3_BUFFER_set_data(&rl->rbuf, buf, len);
112 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
114 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
117 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
119 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
122 int ssl3_pending(const SSL *s)
127 if (s->rlayer.rstate == SSL_ST_READ_BODY)
130 for (i = 0; i < RECORD_LAYER_get_numrpipes(&s->rlayer); i++) {
131 if (SSL3_RECORD_get_type(&s->rlayer.rrec[i])
132 != SSL3_RT_APPLICATION_DATA)
134 num += SSL3_RECORD_get_length(&s->rlayer.rrec[i]);
140 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
142 ctx->default_read_buf_len = len;
145 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
147 SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&s->rlayer), len);
150 const char *SSL_rstate_string_long(const SSL *s)
152 switch (s->rlayer.rstate) {
153 case SSL_ST_READ_HEADER:
154 return "read header";
155 case SSL_ST_READ_BODY:
157 case SSL_ST_READ_DONE:
164 const char *SSL_rstate_string(const SSL *s)
166 switch (s->rlayer.rstate) {
167 case SSL_ST_READ_HEADER:
169 case SSL_ST_READ_BODY:
171 case SSL_ST_READ_DONE:
178 int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
181 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
182 * packet by another n bytes. The packet will be in the sub-array of
183 * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
184 * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus
185 * s->packet_length bytes if extend == 1].)
186 * if clearold == 1, move the packet to the start of the buffer; if
187 * clearold == 0 then leave any old packets where they were
197 rb = &s->rlayer.rbuf;
199 if (!ssl3_setup_read_buffer(s))
203 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
204 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
205 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
209 /* start with empty packet ... */
212 else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
214 * check if next packet length is large enough to justify payload
217 pkt = rb->buf + rb->offset;
218 if (pkt[0] == SSL3_RT_APPLICATION_DATA
219 && (pkt[3] << 8 | pkt[4]) >= 128) {
221 * Note that even if packet is corrupted and its length field
222 * is insane, we can only be led to wrong decision about
223 * whether memmove will occur or not. Header values has no
224 * effect on memmove arguments and therefore no buffer
225 * overrun can be triggered.
227 memmove(rb->buf + align, pkt, left);
231 s->rlayer.packet = rb->buf + rb->offset;
232 s->rlayer.packet_length = 0;
233 /* ... now we can act as if 'extend' was set */
237 * For DTLS/UDP reads should not span multiple packets because the read
238 * operation returns the whole packet at once (as long as it fits into
241 if (SSL_IS_DTLS(s)) {
242 if (left == 0 && extend)
244 if (left > 0 && n > left)
248 /* if there is enough in the buffer from a previous read, take some */
250 s->rlayer.packet_length += n;
256 /* else we need to read more data */
258 len = s->rlayer.packet_length;
259 pkt = rb->buf + align;
261 * Move any available bytes to front of buffer: 'len' bytes already
262 * pointed to by 'packet', 'left' extra ones at the end
264 if (s->rlayer.packet != pkt && clearold == 1) { /* len > 0 */
265 memmove(pkt, s->rlayer.packet, len + left);
266 s->rlayer.packet = pkt;
267 rb->offset = len + align;
270 if (n > (int)(rb->len - rb->offset)) { /* does not happen */
271 SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
275 /* We always act like read_ahead is set for DTLS */
276 if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s))
277 /* ignore max parameter */
282 if (max > (int)(rb->len - rb->offset))
283 max = rb->len - rb->offset;
288 * Now we have len+left bytes at the front of s->s3->rbuf.buf and
289 * need to read in more until we have len+n (up to len+max if
294 if (s->rbio != NULL) {
295 s->rwstate = SSL_READING;
296 i = BIO_read(s->rbio, pkt + len + left, max - left);
298 SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
304 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
306 ssl3_release_read_buffer(s);
311 * reads should *never* span multiple packets for DTLS because the
312 * underlying transport protocol is message oriented as opposed to
313 * byte oriented as in the TLS case.
315 if (SSL_IS_DTLS(s)) {
317 n = left; /* makes the while condition false */
321 /* done reading, now the book-keeping */
324 s->rlayer.packet_length += n;
325 s->rwstate = SSL_NOTHING;
331 * Call this to write data in records of type 'type' It will return <= 0 if
332 * not all data has been sent or non-blocking IO.
334 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
336 const unsigned char *buf = buf_;
338 unsigned int n, split_send_fragment, maxpipes;
339 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
340 unsigned int max_send_fragment, nw;
341 unsigned int u_len = (unsigned int)len;
343 SSL3_BUFFER *wb = &s->rlayer.wbuf[0];
347 SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH);
351 s->rwstate = SSL_NOTHING;
352 tot = s->rlayer.wnum;
354 * ensure that if we end up with a smaller value of data to write out
355 * than the the original len from a write which didn't complete for
356 * non-blocking I/O and also somehow ended up avoiding the check for
357 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
358 * possible to end up with (len-tot) as a large number that will then
359 * promptly send beyond the end of the users buffer ... so we trap and
360 * report the error in a way the user will notice
362 if ((unsigned int)len < s->rlayer.wnum) {
363 SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
370 if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)) {
371 i = s->handshake_func(s);
375 SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
381 * first check if there is a SSL3_BUFFER still being written out. This
382 * will happen with non blocking IO
385 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot);
387 /* XXX should we ssl3_release_write_buffer if i<0? */
388 s->rlayer.wnum = tot;
391 tot += i; /* this might be last fragment */
393 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
395 * Depending on platform multi-block can deliver several *times*
396 * better performance. Downside is that it has to allocate
397 * jumbo buffer to accommodate up to 8 records, but the
398 * compromise is considered worthy.
400 if (type == SSL3_RT_APPLICATION_DATA &&
401 u_len >= 4 * (max_send_fragment = s->max_send_fragment) &&
402 s->compress == NULL && s->msg_callback == NULL &&
403 !SSL_USE_ETM(s) && SSL_USE_EXPLICIT_IV(s) &&
404 EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) &
405 EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) {
406 unsigned char aad[13];
407 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
410 /* minimize address aliasing conflicts */
411 if ((max_send_fragment & 0xfff) == 0)
412 max_send_fragment -= 512;
414 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
415 ssl3_release_write_buffer(s);
417 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
418 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
419 max_send_fragment, NULL);
421 if (u_len >= 8 * max_send_fragment)
426 wb->buf = OPENSSL_malloc(packlen);
427 if (wb->buf == NULL) {
428 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
432 } else if (tot == len) { /* done? */
433 OPENSSL_free(wb->buf); /* free jumbo buffer */
440 if (n < 4 * max_send_fragment) {
441 OPENSSL_free(wb->buf); /* free jumbo buffer */
446 if (s->s3->alert_dispatch) {
447 i = s->method->ssl_dispatch_alert(s);
449 s->rlayer.wnum = tot;
454 if (n >= 8 * max_send_fragment)
455 nw = max_send_fragment * (mb_param.interleave = 8);
457 nw = max_send_fragment * (mb_param.interleave = 4);
459 memcpy(aad, s->rlayer.write_sequence, 8);
461 aad[9] = (unsigned char)(s->version >> 8);
462 aad[10] = (unsigned char)(s->version);
469 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
470 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
471 sizeof(mb_param), &mb_param);
473 if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
474 OPENSSL_free(wb->buf); /* free jumbo buffer */
479 mb_param.out = wb->buf;
480 mb_param.inp = &buf[tot];
483 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
484 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
485 sizeof(mb_param), &mb_param) <= 0)
488 s->rlayer.write_sequence[7] += mb_param.interleave;
489 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
491 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
497 s->rlayer.wpend_tot = nw;
498 s->rlayer.wpend_buf = &buf[tot];
499 s->rlayer.wpend_type = type;
500 s->rlayer.wpend_ret = nw;
502 i = ssl3_write_pending(s, type, &buf[tot], nw);
504 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
505 OPENSSL_free(wb->buf);
508 s->rlayer.wnum = tot;
512 OPENSSL_free(wb->buf); /* free jumbo buffer */
521 if (tot == len) { /* done? */
522 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
523 ssl3_release_write_buffer(s);
530 split_send_fragment = s->split_send_fragment;
532 * If max_pipelines is 0 then this means "undefined" and we default to
533 * 1 pipeline. Similarly if the cipher does not support pipelined
534 * processing then we also only use 1 pipeline, or if we're not using
537 maxpipes = s->max_pipelines;
538 if (maxpipes > SSL_MAX_PIPELINES) {
540 * We should have prevented this when we set max_pipelines so we
543 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
547 || s->enc_write_ctx == NULL
548 || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx))
549 & EVP_CIPH_FLAG_PIPELINE)
550 || !SSL_USE_EXPLICIT_IV(s))
552 if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment
553 || split_send_fragment == 0) {
555 * We should have prevented this when we set the split and max send
556 * fragments so we shouldn't get here
558 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
563 unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
564 unsigned int numpipes, j;
569 numpipes = ((n - 1) / split_send_fragment) + 1;
570 if (numpipes > maxpipes)
573 if (n / numpipes >= s->max_send_fragment) {
575 * We have enough data to completely fill all available
578 for (j = 0; j < numpipes; j++) {
579 pipelens[j] = s->max_send_fragment;
582 /* We can partially fill all available pipelines */
583 tmppipelen = n / numpipes;
584 remain = n % numpipes;
585 for (j = 0; j < numpipes; j++) {
586 pipelens[j] = tmppipelen;
592 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);
594 /* XXX should we ssl3_release_write_buffer if i<0? */
595 s->rlayer.wnum = tot;
600 (type == SSL3_RT_APPLICATION_DATA &&
601 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
603 * next chunk of data should get another prepended empty fragment
604 * in ciphersuites with known-IV weakness:
606 s->s3->empty_fragment_done = 0;
608 if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
610 ssl3_release_write_buffer(s);
620 int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
621 unsigned int *pipelens, unsigned int numpipes,
622 int create_empty_fragment)
624 unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
625 SSL3_RECORD wr[SSL_MAX_PIPELINES];
626 int i, mac_size, clear = 0;
632 unsigned int totlen = 0;
635 for (j = 0; j < numpipes; j++)
636 totlen += pipelens[j];
638 * first check if there is a SSL3_BUFFER still being written out. This
639 * will happen with non blocking IO
641 if (RECORD_LAYER_write_pending(&s->rlayer))
642 return (ssl3_write_pending(s, type, buf, totlen));
644 /* If we have an alert to send, lets send it */
645 if (s->s3->alert_dispatch) {
646 i = s->method->ssl_dispatch_alert(s);
649 /* if it went, fall through and send more stuff */
652 if (s->rlayer.numwpipes < numpipes)
653 if (!ssl3_setup_write_buffer(s, numpipes))
656 if (totlen == 0 && !create_empty_fragment)
661 if ((sess == NULL) ||
662 (s->enc_write_ctx == NULL) ||
663 (EVP_MD_CTX_md(s->write_hash) == NULL)) {
664 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
667 mac_size = EVP_MD_CTX_size(s->write_hash);
673 * 'create_empty_fragment' is true only when this function calls itself
675 if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
677 * countermeasure against known-IV weakness in CBC ciphersuites (see
678 * http://www.openssl.org/~bodo/tls-cbc.txt)
681 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
683 * recursive function call with 'create_empty_fragment' set; this
684 * prepares and buffers the data for an empty fragment (these
685 * 'prefix_len' bytes are sent out later together with the actual
688 unsigned int tmppipelen = 0;
690 prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
695 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
697 /* insufficient space */
698 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
703 s->s3->empty_fragment_done = 1;
706 if (create_empty_fragment) {
707 wb = &s->rlayer.wbuf[0];
708 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
710 * extra fragment would be couple of cipher blocks, which would be
711 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
712 * payload, then we can just pretend we simply have two headers.
714 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
715 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
717 outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
718 SSL3_BUFFER_set_offset(wb, align);
719 } else if (prefix_len) {
720 wb = &s->rlayer.wbuf[0];
721 outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
724 for (j=0; j < numpipes; j++) {
725 wb = &s->rlayer.wbuf[j];
726 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
727 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
728 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
730 outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
731 SSL3_BUFFER_set_offset(wb, align);
735 /* Explicit IV length, block ciphers appropriate version flag */
736 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
737 int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
738 if (mode == EVP_CIPH_CBC_MODE) {
739 eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
743 /* Need explicit part of IV for GCM mode */
744 else if (mode == EVP_CIPH_GCM_MODE)
745 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
746 else if (mode == EVP_CIPH_CCM_MODE)
747 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
755 /* Clear our SSL3_RECORD structures */
756 memset(wr, 0, sizeof wr);
757 for (j=0; j < numpipes; j++) {
758 /* write the header */
759 *(outbuf[j]++) = type & 0xff;
760 SSL3_RECORD_set_type(&wr[j], type);
762 *(outbuf[j]++) = (s->version >> 8);
764 * Some servers hang if initial client hello is larger than 256 bytes
765 * and record version number > TLS 1.0
767 if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
768 && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
769 *(outbuf[j]++) = 0x1;
771 *(outbuf[j]++) = s->version & 0xff;
773 /* field where we are to write out packet length */
777 /* lets setup the record stuff. */
778 SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
779 SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
780 SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
781 totlen += pipelens[j];
784 * we now 'read' from wr->input, wr->length bytes into wr->data
787 /* first we compress */
788 if (s->compress != NULL) {
789 if (!ssl3_do_compress(s, &wr[j])) {
790 SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
794 memcpy(wr[j].data, wr[j].input, wr[j].length);
795 SSL3_RECORD_reset_input(&wr[j]);
799 * we should still have the output to wr->data and the input from
800 * wr->input. Length should be wr->length. wr->data still points in the
804 if (!SSL_USE_ETM(s) && mac_size != 0) {
805 if (s->method->ssl3_enc->mac(s, &wr[j],
806 &(outbuf[j][wr[j].length + eivlen]), 1) < 0)
808 SSL3_RECORD_add_length(&wr[j], mac_size);
812 SSL3_RECORD_set_data(&wr[j], outbuf[j]);
813 SSL3_RECORD_reset_input(&wr[j]);
817 * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
819 SSL3_RECORD_add_length(&wr[j], eivlen);
823 if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
826 for (j=0; j < numpipes; j++) {
827 if (SSL_USE_ETM(s) && mac_size != 0) {
828 if (s->method->ssl3_enc->mac(s, &wr[j],
829 outbuf[j] + wr[j].length, 1) < 0)
831 SSL3_RECORD_add_length(&wr[j], mac_size);
834 /* record length after mac and block padding */
835 s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
838 s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
839 s->msg_callback_arg);
842 * we should now have wr->data pointing to the encrypted data, which is
845 SSL3_RECORD_set_type(&wr[j], type); /* not needed but helps for debugging */
846 SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
848 if (create_empty_fragment) {
850 * we are in a recursive call; just return the length, don't write
854 /* We should never be pipelining an empty fragment!! */
855 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
858 return SSL3_RECORD_get_length(wr);
861 /* now let's set up wb */
862 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
863 prefix_len + SSL3_RECORD_get_length(&wr[j]));
869 * memorize arguments so that ssl3_write_pending can detect bad write
872 s->rlayer.wpend_tot = totlen;
873 s->rlayer.wpend_buf = buf;
874 s->rlayer.wpend_type = type;
875 s->rlayer.wpend_ret = totlen;
877 /* we now just need to write the buffer */
878 return ssl3_write_pending(s, type, buf, totlen);
883 /* if s->s3->wbuf.left != 0, we need to call this */
884 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
888 SSL3_BUFFER *wb = s->rlayer.wbuf;
889 unsigned int currbuf = 0;
892 if ((s->rlayer.wpend_tot > (int)len)
893 || ((s->rlayer.wpend_buf != buf) &&
894 !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
895 || (s->rlayer.wpend_type != type)) {
896 SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
901 /* Loop until we find a buffer we haven't written out yet */
902 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
903 && currbuf < s->rlayer.numwpipes - 1) {
908 if (s->wbio != NULL) {
909 s->rwstate = SSL_WRITING;
910 i = BIO_write(s->wbio,
911 (char *)&(SSL3_BUFFER_get_buf(&wb[currbuf])[
912 SSL3_BUFFER_get_offset(&wb[currbuf])]),
913 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
915 SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
918 if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
919 SSL3_BUFFER_set_left(&wb[currbuf], 0);
920 SSL3_BUFFER_add_offset(&wb[currbuf], i);
921 if (currbuf + 1 < s->rlayer.numwpipes)
923 s->rwstate = SSL_NOTHING;
924 return (s->rlayer.wpend_ret);
926 if (SSL_IS_DTLS(s)) {
928 * For DTLS, just drop it. That's kind of the whole point in
929 * using a datagram service
931 SSL3_BUFFER_set_left(&wb[currbuf], 0);
935 SSL3_BUFFER_add_offset(&wb[currbuf], i);
936 SSL3_BUFFER_add_left(&wb[currbuf], -i);
941 * Return up to 'len' payload bytes received in 'type' records.
942 * 'type' is one of the following:
944 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
945 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
946 * - 0 (during a shutdown, no data has to be returned)
948 * If we don't have stored data to work from, read a SSL/TLS record first
949 * (possibly multiple records if we still don't have anything to return).
951 * This function must handle any surprises the peer may have for us, such as
952 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
953 * messages are treated as if they were handshake messages *if* the |recd_type|
954 * argument is non NULL.
955 * Also if record payloads contain fragments too small to process, we store
956 * them until there is enough for the respective protocol (the record protocol
957 * may use arbitrary fragmentation and even interleaving):
958 * Change cipher spec protocol
959 * just 1 byte needed, no need for keeping anything stored
961 * 2 bytes needed (AlertLevel, AlertDescription)
963 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
964 * to detect unexpected Client Hello and Hello Request messages
965 * here, anything else is handled by higher layers
966 * Application data protocol
967 * none of our business
969 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
973 unsigned int n, curr_rec, num_recs, read_bytes;
976 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
978 rbuf = &s->rlayer.rbuf;
980 if (!SSL3_BUFFER_is_initialised(rbuf)) {
981 /* Not initialized yet */
982 if (!ssl3_setup_read_buffer(s))
986 if ((type && (type != SSL3_RT_APPLICATION_DATA)
987 && (type != SSL3_RT_HANDSHAKE)) || (peek
989 SSL3_RT_APPLICATION_DATA))) {
990 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
994 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
995 /* (partially) satisfy request from storage */
997 unsigned char *src = s->rlayer.handshake_fragment;
998 unsigned char *dst = buf;
1003 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1006 s->rlayer.handshake_fragment_len--;
1009 /* move any remaining fragment bytes: */
1010 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1011 s->rlayer.handshake_fragment[k] = *src++;
1013 if (recvd_type != NULL)
1014 *recvd_type = SSL3_RT_HANDSHAKE;
1020 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1023 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
1024 /* type == SSL3_RT_APPLICATION_DATA */
1025 i = s->handshake_func(s);
1029 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1034 s->rwstate = SSL_NOTHING;
1037 * For each record 'i' up to |num_recs]
1038 * rr[i].type - is the type of record
1039 * rr[i].data, - data
1040 * rr[i].off, - offset into 'data' for next read
1041 * rr[i].length, - number of bytes.
1043 rr = s->rlayer.rrec;
1044 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1047 /* get new records if necessary */
1048 if (num_recs == 0) {
1049 ret = ssl3_get_record(s);
1052 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1053 if (num_recs == 0) {
1054 /* Shouldn't happen */
1055 al = SSL_AD_INTERNAL_ERROR;
1056 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1060 /* Skip over any records we have already read */
1062 curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
1064 if (curr_rec == num_recs) {
1065 RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1069 } while (num_recs == 0);
1072 /* we now have a packet which can be read and processed */
1074 if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1075 * reset by ssl3_get_finished */
1076 && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1077 al = SSL_AD_UNEXPECTED_MESSAGE;
1078 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1083 * If the other end has shut down, throw anything we read away (even in
1086 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1087 SSL3_RECORD_set_length(rr, 0);
1088 s->rwstate = SSL_NOTHING;
1092 if (type == SSL3_RECORD_get_type(rr)
1093 || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1094 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
1096 * SSL3_RT_APPLICATION_DATA or
1097 * SSL3_RT_HANDSHAKE or
1098 * SSL3_RT_CHANGE_CIPHER_SPEC
1101 * make sure that we are not getting application data when we are
1102 * doing a handshake for the first time
1104 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1105 (s->enc_read_ctx == NULL)) {
1106 al = SSL_AD_UNEXPECTED_MESSAGE;
1107 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1111 if (type == SSL3_RT_HANDSHAKE
1112 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1113 && s->rlayer.handshake_fragment_len > 0) {
1114 al = SSL_AD_UNEXPECTED_MESSAGE;
1115 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1119 if (recvd_type != NULL)
1120 *recvd_type = SSL3_RECORD_get_type(rr);
1127 if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
1128 n = SSL3_RECORD_get_length(rr);
1130 n = (unsigned int)len - read_bytes;
1132 memcpy(buf, &(rr->data[rr->off]), n);
1135 SSL3_RECORD_sub_length(rr, n);
1136 SSL3_RECORD_add_off(rr, n);
1137 if (SSL3_RECORD_get_length(rr) == 0) {
1138 s->rlayer.rstate = SSL_ST_READ_HEADER;
1139 SSL3_RECORD_set_off(rr, 0);
1140 SSL3_RECORD_set_read(rr);
1143 if (SSL3_RECORD_get_length(rr) == 0
1144 || (peek && n == SSL3_RECORD_get_length(rr))) {
1149 } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1150 && read_bytes < (unsigned int)len);
1151 if (read_bytes == 0) {
1152 /* We must have read empty records. Get more data */
1155 if (!peek && curr_rec == num_recs
1156 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1157 && SSL3_BUFFER_get_left(rbuf) == 0)
1158 ssl3_release_read_buffer(s);
1163 * If we get here, then type != rr->type; if we have a handshake message,
1164 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1165 * were actually expecting a CCS).
1168 if (rr->type == SSL3_RT_HANDSHAKE && type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1169 al = SSL_AD_UNEXPECTED_MESSAGE;
1170 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1175 * Lets just double check that we've not got an SSLv2 record
1177 if (rr->rec_version == SSL2_VERSION) {
1179 * Should never happen. ssl3_get_record() should only give us an SSLv2
1180 * record back if this is the first packet and we are looking for an
1181 * initial ClientHello. Therefore |type| should always be equal to
1182 * |rr->type|. If not then something has gone horribly wrong
1184 al = SSL_AD_INTERNAL_ERROR;
1185 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1189 if (s->method->version == TLS_ANY_VERSION
1190 && (s->server || rr->type != SSL3_RT_ALERT)) {
1192 * If we've got this far and still haven't decided on what version
1193 * we're using then this must be a client side alert we're dealing with
1194 * (we don't allow heartbeats yet). We shouldn't be receiving anything
1195 * other than a ClientHello if we are a server.
1197 s->version = rr->rec_version;
1198 al = SSL_AD_UNEXPECTED_MESSAGE;
1199 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1204 * In case of record types for which we have 'fragment' storage, fill
1205 * that so that we can process the data at a fixed place.
1208 unsigned int dest_maxlen = 0;
1209 unsigned char *dest = NULL;
1210 unsigned int *dest_len = NULL;
1212 if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1213 dest_maxlen = sizeof s->rlayer.handshake_fragment;
1214 dest = s->rlayer.handshake_fragment;
1215 dest_len = &s->rlayer.handshake_fragment_len;
1216 } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1217 dest_maxlen = sizeof s->rlayer.alert_fragment;
1218 dest = s->rlayer.alert_fragment;
1219 dest_len = &s->rlayer.alert_fragment_len;
1222 if (dest_maxlen > 0) {
1223 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1224 if (SSL3_RECORD_get_length(rr) < n)
1225 n = SSL3_RECORD_get_length(rr); /* available bytes */
1227 /* now move 'n' bytes: */
1229 dest[(*dest_len)++] =
1230 SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
1231 SSL3_RECORD_add_off(rr, 1);
1232 SSL3_RECORD_add_length(rr, -1);
1235 if (*dest_len < dest_maxlen) {
1236 SSL3_RECORD_set_read(rr);
1237 goto start; /* fragment was too small */
1243 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1244 * s->rlayer.alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
1245 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1248 /* If we are a client, check for an incoming 'Hello Request': */
1250 (s->rlayer.handshake_fragment_len >= 4) &&
1251 (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1252 (s->session != NULL) && (s->session->cipher != NULL)) {
1253 s->rlayer.handshake_fragment_len = 0;
1255 if ((s->rlayer.handshake_fragment[1] != 0) ||
1256 (s->rlayer.handshake_fragment[2] != 0) ||
1257 (s->rlayer.handshake_fragment[3] != 0)) {
1258 al = SSL_AD_DECODE_ERROR;
1259 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1263 if (s->msg_callback)
1264 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1265 s->rlayer.handshake_fragment, 4, s,
1266 s->msg_callback_arg);
1268 if (SSL_is_init_finished(s) &&
1269 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1270 !s->s3->renegotiate) {
1271 ssl3_renegotiate(s);
1272 if (ssl3_renegotiate_check(s)) {
1273 i = s->handshake_func(s);
1277 SSLerr(SSL_F_SSL3_READ_BYTES,
1278 SSL_R_SSL_HANDSHAKE_FAILURE);
1282 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1283 if (SSL3_BUFFER_get_left(rbuf) == 0) {
1284 /* no read-ahead left? */
1287 * In the case where we try to read application data,
1288 * but we trigger an SSL handshake, we return -1 with
1289 * the retry option set. Otherwise renegotiation may
1290 * cause nasty problems in the blocking world
1292 s->rwstate = SSL_READING;
1293 bio = SSL_get_rbio(s);
1294 BIO_clear_retry_flags(bio);
1295 BIO_set_retry_read(bio);
1302 * we either finished a handshake or ignored the request, now try
1303 * again to obtain the (application) data we were asked for
1308 * If we are a server and get a client hello when renegotiation isn't
1309 * allowed send back a no renegotiation alert and carry on. WARNING:
1310 * experimental code, needs reviewing (steve)
1313 SSL_is_init_finished(s) &&
1314 !s->s3->send_connection_binding &&
1315 (s->version > SSL3_VERSION) &&
1316 (s->rlayer.handshake_fragment_len >= 4) &&
1317 (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1318 (s->session != NULL) && (s->session->cipher != NULL) &&
1319 !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1320 SSL3_RECORD_set_length(rr, 0);
1321 SSL3_RECORD_set_read(rr);
1322 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1325 if (s->rlayer.alert_fragment_len >= 2) {
1326 int alert_level = s->rlayer.alert_fragment[0];
1327 int alert_descr = s->rlayer.alert_fragment[1];
1329 s->rlayer.alert_fragment_len = 0;
1331 if (s->msg_callback)
1332 s->msg_callback(0, s->version, SSL3_RT_ALERT,
1333 s->rlayer.alert_fragment, 2, s,
1334 s->msg_callback_arg);
1336 if (s->info_callback != NULL)
1337 cb = s->info_callback;
1338 else if (s->ctx->info_callback != NULL)
1339 cb = s->ctx->info_callback;
1342 j = (alert_level << 8) | alert_descr;
1343 cb(s, SSL_CB_READ_ALERT, j);
1346 if (alert_level == SSL3_AL_WARNING) {
1347 s->s3->warn_alert = alert_descr;
1348 SSL3_RECORD_set_read(rr);
1349 if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1350 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1354 * This is a warning but we receive it if we requested
1355 * renegotiation and the peer denied it. Terminate with a fatal
1356 * alert because if application tried to renegotiate it
1357 * presumably had a good reason and expects it to succeed. In
1358 * future we might have a renegotiation where we don't care if
1359 * the peer refused it where we carry on.
1361 else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1362 al = SSL_AD_HANDSHAKE_FAILURE;
1363 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1366 #ifdef SSL_AD_MISSING_SRP_USERNAME
1367 else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1370 } else if (alert_level == SSL3_AL_FATAL) {
1373 s->rwstate = SSL_NOTHING;
1374 s->s3->fatal_alert = alert_descr;
1375 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1376 BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1377 ERR_add_error_data(2, "SSL alert number ", tmp);
1378 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1379 SSL3_RECORD_set_read(rr);
1380 SSL_CTX_remove_session(s->session_ctx, s->session);
1383 al = SSL_AD_ILLEGAL_PARAMETER;
1384 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1391 if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1393 s->rwstate = SSL_NOTHING;
1394 SSL3_RECORD_set_length(rr, 0);
1395 SSL3_RECORD_set_read(rr);
1399 if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1400 al = SSL_AD_UNEXPECTED_MESSAGE;
1401 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1406 * Unexpected handshake message (Client Hello, or protocol violation)
1408 if ((s->rlayer.handshake_fragment_len >= 4)
1409 && !ossl_statem_get_in_handshake(s)) {
1410 if (SSL_is_init_finished(s) &&
1411 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1412 ossl_statem_set_in_init(s, 1);
1416 i = s->handshake_func(s);
1420 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1424 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1425 if (SSL3_BUFFER_get_left(rbuf) == 0) {
1426 /* no read-ahead left? */
1429 * In the case where we try to read application data, but we
1430 * trigger an SSL handshake, we return -1 with the retry
1431 * option set. Otherwise renegotiation may cause nasty
1432 * problems in the blocking world
1434 s->rwstate = SSL_READING;
1435 bio = SSL_get_rbio(s);
1436 BIO_clear_retry_flags(bio);
1437 BIO_set_retry_read(bio);
1444 switch (SSL3_RECORD_get_type(rr)) {
1447 * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1448 * an unexpected message alert.
1450 if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1451 SSL3_RECORD_set_length(rr, 0);
1452 SSL3_RECORD_set_read(rr);
1455 al = SSL_AD_UNEXPECTED_MESSAGE;
1456 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1458 case SSL3_RT_CHANGE_CIPHER_SPEC:
1460 case SSL3_RT_HANDSHAKE:
1462 * we already handled all of these, with the possible exception of
1463 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1464 * that should not happen when type != rr->type
1466 al = SSL_AD_UNEXPECTED_MESSAGE;
1467 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1469 case SSL3_RT_APPLICATION_DATA:
1471 * At this point, we were expecting handshake data, but have
1472 * application data. If the library was running inside ssl3_read()
1473 * (i.e. in_read_app_data is set) and it makes sense to read
1474 * application data at this point (session renegotiation not yet
1475 * started), we will indulge it.
1477 if (ossl_statem_app_data_allowed(s)) {
1478 s->s3->in_read_app_data = 2;
1481 al = SSL_AD_UNEXPECTED_MESSAGE;
1482 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1489 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1493 void ssl3_record_sequence_update(unsigned char *seq)
1497 for (i = 7; i >= 0; i--) {
1505 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1506 * format and false otherwise.
1508 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1510 return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1514 * Returns the length in bytes of the current rrec
1516 unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1518 return SSL3_RECORD_get_length(&rl->rrec[0]);