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 if (!ssl3_setup_write_buffer(s, 1, packlen)) {
427 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE);
430 } else if (tot == len) { /* done? */
431 /* free jumbo buffer */
432 ssl3_release_write_buffer(s);
438 if (n < 4 * max_send_fragment) {
439 /* free jumbo buffer */
440 ssl3_release_write_buffer(s);
444 if (s->s3->alert_dispatch) {
445 i = s->method->ssl_dispatch_alert(s);
447 s->rlayer.wnum = tot;
452 if (n >= 8 * max_send_fragment)
453 nw = max_send_fragment * (mb_param.interleave = 8);
455 nw = max_send_fragment * (mb_param.interleave = 4);
457 memcpy(aad, s->rlayer.write_sequence, 8);
459 aad[9] = (unsigned char)(s->version >> 8);
460 aad[10] = (unsigned char)(s->version);
467 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
468 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
469 sizeof(mb_param), &mb_param);
471 if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */
472 /* free jumbo buffer */
473 ssl3_release_write_buffer(s);
477 mb_param.out = wb->buf;
478 mb_param.inp = &buf[tot];
481 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
482 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
483 sizeof(mb_param), &mb_param) <= 0)
486 s->rlayer.write_sequence[7] += mb_param.interleave;
487 if (s->rlayer.write_sequence[7] < mb_param.interleave) {
489 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
495 s->rlayer.wpend_tot = nw;
496 s->rlayer.wpend_buf = &buf[tot];
497 s->rlayer.wpend_type = type;
498 s->rlayer.wpend_ret = nw;
500 i = ssl3_write_pending(s, type, &buf[tot], nw);
502 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
503 /* free jumbo buffer */
504 ssl3_release_write_buffer(s);
506 s->rlayer.wnum = tot;
510 /* free jumbo buffer */
511 ssl3_release_write_buffer(s);
519 if (tot == len) { /* done? */
520 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
521 ssl3_release_write_buffer(s);
528 split_send_fragment = s->split_send_fragment;
530 * If max_pipelines is 0 then this means "undefined" and we default to
531 * 1 pipeline. Similarly if the cipher does not support pipelined
532 * processing then we also only use 1 pipeline, or if we're not using
535 maxpipes = s->max_pipelines;
536 if (maxpipes > SSL_MAX_PIPELINES) {
538 * We should have prevented this when we set max_pipelines so we
541 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
545 || s->enc_write_ctx == NULL
546 || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx))
547 & EVP_CIPH_FLAG_PIPELINE)
548 || !SSL_USE_EXPLICIT_IV(s))
550 if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment
551 || split_send_fragment == 0) {
553 * We should have prevented this when we set the split and max send
554 * fragments so we shouldn't get here
556 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
561 unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
562 unsigned int numpipes, j;
567 numpipes = ((n - 1) / split_send_fragment) + 1;
568 if (numpipes > maxpipes)
571 if (n / numpipes >= s->max_send_fragment) {
573 * We have enough data to completely fill all available
576 for (j = 0; j < numpipes; j++) {
577 pipelens[j] = s->max_send_fragment;
580 /* We can partially fill all available pipelines */
581 tmppipelen = n / numpipes;
582 remain = n % numpipes;
583 for (j = 0; j < numpipes; j++) {
584 pipelens[j] = tmppipelen;
590 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0);
592 /* XXX should we ssl3_release_write_buffer if i<0? */
593 s->rlayer.wnum = tot;
598 (type == SSL3_RT_APPLICATION_DATA &&
599 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
601 * next chunk of data should get another prepended empty fragment
602 * in ciphersuites with known-IV weakness:
604 s->s3->empty_fragment_done = 0;
606 if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS &&
608 ssl3_release_write_buffer(s);
618 int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
619 unsigned int *pipelens, unsigned int numpipes,
620 int create_empty_fragment)
622 unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
623 SSL3_RECORD wr[SSL_MAX_PIPELINES];
624 int i, mac_size, clear = 0;
630 unsigned int totlen = 0;
633 for (j = 0; j < numpipes; j++)
634 totlen += pipelens[j];
636 * first check if there is a SSL3_BUFFER still being written out. This
637 * will happen with non blocking IO
639 if (RECORD_LAYER_write_pending(&s->rlayer))
640 return (ssl3_write_pending(s, type, buf, totlen));
642 /* If we have an alert to send, lets send it */
643 if (s->s3->alert_dispatch) {
644 i = s->method->ssl_dispatch_alert(s);
647 /* if it went, fall through and send more stuff */
650 if (s->rlayer.numwpipes < numpipes)
651 if (!ssl3_setup_write_buffer(s, numpipes, 0))
654 if (totlen == 0 && !create_empty_fragment)
659 if ((sess == NULL) ||
660 (s->enc_write_ctx == NULL) ||
661 (EVP_MD_CTX_md(s->write_hash) == NULL)) {
662 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
665 mac_size = EVP_MD_CTX_size(s->write_hash);
671 * 'create_empty_fragment' is true only when this function calls itself
673 if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
675 * countermeasure against known-IV weakness in CBC ciphersuites (see
676 * http://www.openssl.org/~bodo/tls-cbc.txt)
679 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
681 * recursive function call with 'create_empty_fragment' set; this
682 * prepares and buffers the data for an empty fragment (these
683 * 'prefix_len' bytes are sent out later together with the actual
686 unsigned int tmppipelen = 0;
688 prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
693 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
695 /* insufficient space */
696 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
701 s->s3->empty_fragment_done = 1;
704 if (create_empty_fragment) {
705 wb = &s->rlayer.wbuf[0];
706 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
708 * extra fragment would be couple of cipher blocks, which would be
709 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
710 * payload, then we can just pretend we simply have two headers.
712 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
713 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
715 outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
716 SSL3_BUFFER_set_offset(wb, align);
717 } else if (prefix_len) {
718 wb = &s->rlayer.wbuf[0];
719 outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
722 for (j=0; j < numpipes; j++) {
723 wb = &s->rlayer.wbuf[j];
724 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
725 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
726 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
728 outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
729 SSL3_BUFFER_set_offset(wb, align);
733 /* Explicit IV length, block ciphers appropriate version flag */
734 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
735 int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
736 if (mode == EVP_CIPH_CBC_MODE) {
737 eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
741 /* Need explicit part of IV for GCM mode */
742 else if (mode == EVP_CIPH_GCM_MODE)
743 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
744 else if (mode == EVP_CIPH_CCM_MODE)
745 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
753 /* Clear our SSL3_RECORD structures */
754 memset(wr, 0, sizeof wr);
755 for (j=0; j < numpipes; j++) {
756 /* write the header */
757 *(outbuf[j]++) = type & 0xff;
758 SSL3_RECORD_set_type(&wr[j], type);
760 *(outbuf[j]++) = (s->version >> 8);
762 * Some servers hang if initial client hello is larger than 256 bytes
763 * and record version number > TLS 1.0
765 if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
766 && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
767 *(outbuf[j]++) = 0x1;
769 *(outbuf[j]++) = s->version & 0xff;
771 /* field where we are to write out packet length */
775 /* lets setup the record stuff. */
776 SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
777 SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
778 SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
779 totlen += pipelens[j];
782 * we now 'read' from wr->input, wr->length bytes into wr->data
785 /* first we compress */
786 if (s->compress != NULL) {
787 if (!ssl3_do_compress(s, &wr[j])) {
788 SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
792 memcpy(wr[j].data, wr[j].input, wr[j].length);
793 SSL3_RECORD_reset_input(&wr[j]);
797 * we should still have the output to wr->data and the input from
798 * wr->input. Length should be wr->length. wr->data still points in the
802 if (!SSL_USE_ETM(s) && mac_size != 0) {
803 if (s->method->ssl3_enc->mac(s, &wr[j],
804 &(outbuf[j][wr[j].length + eivlen]), 1) < 0)
806 SSL3_RECORD_add_length(&wr[j], mac_size);
810 SSL3_RECORD_set_data(&wr[j], outbuf[j]);
811 SSL3_RECORD_reset_input(&wr[j]);
815 * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
817 SSL3_RECORD_add_length(&wr[j], eivlen);
821 if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
824 for (j=0; j < numpipes; j++) {
825 if (SSL_USE_ETM(s) && mac_size != 0) {
826 if (s->method->ssl3_enc->mac(s, &wr[j],
827 outbuf[j] + wr[j].length, 1) < 0)
829 SSL3_RECORD_add_length(&wr[j], mac_size);
832 /* record length after mac and block padding */
833 s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
836 s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
837 s->msg_callback_arg);
840 * we should now have wr->data pointing to the encrypted data, which is
843 SSL3_RECORD_set_type(&wr[j], type); /* not needed but helps for debugging */
844 SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
846 if (create_empty_fragment) {
848 * we are in a recursive call; just return the length, don't write
852 /* We should never be pipelining an empty fragment!! */
853 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
856 return SSL3_RECORD_get_length(wr);
859 /* now let's set up wb */
860 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
861 prefix_len + SSL3_RECORD_get_length(&wr[j]));
867 * memorize arguments so that ssl3_write_pending can detect bad write
870 s->rlayer.wpend_tot = totlen;
871 s->rlayer.wpend_buf = buf;
872 s->rlayer.wpend_type = type;
873 s->rlayer.wpend_ret = totlen;
875 /* we now just need to write the buffer */
876 return ssl3_write_pending(s, type, buf, totlen);
881 /* if s->s3->wbuf.left != 0, we need to call this */
882 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
886 SSL3_BUFFER *wb = s->rlayer.wbuf;
887 unsigned int currbuf = 0;
890 if ((s->rlayer.wpend_tot > (int)len)
891 || ((s->rlayer.wpend_buf != buf) &&
892 !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
893 || (s->rlayer.wpend_type != type)) {
894 SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
899 /* Loop until we find a buffer we haven't written out yet */
900 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
901 && currbuf < s->rlayer.numwpipes - 1) {
906 if (s->wbio != NULL) {
907 s->rwstate = SSL_WRITING;
908 i = BIO_write(s->wbio,
909 (char *)&(SSL3_BUFFER_get_buf(&wb[currbuf])[
910 SSL3_BUFFER_get_offset(&wb[currbuf])]),
911 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
913 SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
916 if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
917 SSL3_BUFFER_set_left(&wb[currbuf], 0);
918 SSL3_BUFFER_add_offset(&wb[currbuf], i);
919 if (currbuf + 1 < s->rlayer.numwpipes)
921 s->rwstate = SSL_NOTHING;
922 return (s->rlayer.wpend_ret);
924 if (SSL_IS_DTLS(s)) {
926 * For DTLS, just drop it. That's kind of the whole point in
927 * using a datagram service
929 SSL3_BUFFER_set_left(&wb[currbuf], 0);
933 SSL3_BUFFER_add_offset(&wb[currbuf], i);
934 SSL3_BUFFER_add_left(&wb[currbuf], -i);
939 * Return up to 'len' payload bytes received in 'type' records.
940 * 'type' is one of the following:
942 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
943 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
944 * - 0 (during a shutdown, no data has to be returned)
946 * If we don't have stored data to work from, read a SSL/TLS record first
947 * (possibly multiple records if we still don't have anything to return).
949 * This function must handle any surprises the peer may have for us, such as
950 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
951 * messages are treated as if they were handshake messages *if* the |recd_type|
952 * argument is non NULL.
953 * Also if record payloads contain fragments too small to process, we store
954 * them until there is enough for the respective protocol (the record protocol
955 * may use arbitrary fragmentation and even interleaving):
956 * Change cipher spec protocol
957 * just 1 byte needed, no need for keeping anything stored
959 * 2 bytes needed (AlertLevel, AlertDescription)
961 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
962 * to detect unexpected Client Hello and Hello Request messages
963 * here, anything else is handled by higher layers
964 * Application data protocol
965 * none of our business
967 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
971 unsigned int n, curr_rec, num_recs, read_bytes;
974 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
976 rbuf = &s->rlayer.rbuf;
978 if (!SSL3_BUFFER_is_initialised(rbuf)) {
979 /* Not initialized yet */
980 if (!ssl3_setup_read_buffer(s))
984 if ((type && (type != SSL3_RT_APPLICATION_DATA)
985 && (type != SSL3_RT_HANDSHAKE)) || (peek
987 SSL3_RT_APPLICATION_DATA))) {
988 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
992 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
993 /* (partially) satisfy request from storage */
995 unsigned char *src = s->rlayer.handshake_fragment;
996 unsigned char *dst = buf;
1001 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1004 s->rlayer.handshake_fragment_len--;
1007 /* move any remaining fragment bytes: */
1008 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1009 s->rlayer.handshake_fragment[k] = *src++;
1011 if (recvd_type != NULL)
1012 *recvd_type = SSL3_RT_HANDSHAKE;
1018 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1021 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
1022 /* type == SSL3_RT_APPLICATION_DATA */
1023 i = s->handshake_func(s);
1027 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1032 s->rwstate = SSL_NOTHING;
1035 * For each record 'i' up to |num_recs]
1036 * rr[i].type - is the type of record
1037 * rr[i].data, - data
1038 * rr[i].off, - offset into 'data' for next read
1039 * rr[i].length, - number of bytes.
1041 rr = s->rlayer.rrec;
1042 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1045 /* get new records if necessary */
1046 if (num_recs == 0) {
1047 ret = ssl3_get_record(s);
1050 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1051 if (num_recs == 0) {
1052 /* Shouldn't happen */
1053 al = SSL_AD_INTERNAL_ERROR;
1054 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1058 /* Skip over any records we have already read */
1060 curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
1062 if (curr_rec == num_recs) {
1063 RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1067 } while (num_recs == 0);
1070 /* we now have a packet which can be read and processed */
1072 if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1073 * reset by ssl3_get_finished */
1074 && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1075 al = SSL_AD_UNEXPECTED_MESSAGE;
1076 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1081 * If the other end has shut down, throw anything we read away (even in
1084 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1085 SSL3_RECORD_set_length(rr, 0);
1086 s->rwstate = SSL_NOTHING;
1090 if (type == SSL3_RECORD_get_type(rr)
1091 || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1092 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
1094 * SSL3_RT_APPLICATION_DATA or
1095 * SSL3_RT_HANDSHAKE or
1096 * SSL3_RT_CHANGE_CIPHER_SPEC
1099 * make sure that we are not getting application data when we are
1100 * doing a handshake for the first time
1102 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1103 (s->enc_read_ctx == NULL)) {
1104 al = SSL_AD_UNEXPECTED_MESSAGE;
1105 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1109 if (type == SSL3_RT_HANDSHAKE
1110 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1111 && s->rlayer.handshake_fragment_len > 0) {
1112 al = SSL_AD_UNEXPECTED_MESSAGE;
1113 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1117 if (recvd_type != NULL)
1118 *recvd_type = SSL3_RECORD_get_type(rr);
1125 if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
1126 n = SSL3_RECORD_get_length(rr);
1128 n = (unsigned int)len - read_bytes;
1130 memcpy(buf, &(rr->data[rr->off]), n);
1133 SSL3_RECORD_sub_length(rr, n);
1134 SSL3_RECORD_add_off(rr, n);
1135 if (SSL3_RECORD_get_length(rr) == 0) {
1136 s->rlayer.rstate = SSL_ST_READ_HEADER;
1137 SSL3_RECORD_set_off(rr, 0);
1138 SSL3_RECORD_set_read(rr);
1141 if (SSL3_RECORD_get_length(rr) == 0
1142 || (peek && n == SSL3_RECORD_get_length(rr))) {
1147 } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1148 && read_bytes < (unsigned int)len);
1149 if (read_bytes == 0) {
1150 /* We must have read empty records. Get more data */
1153 if (!peek && curr_rec == num_recs
1154 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1155 && SSL3_BUFFER_get_left(rbuf) == 0)
1156 ssl3_release_read_buffer(s);
1161 * If we get here, then type != rr->type; if we have a handshake message,
1162 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1163 * were actually expecting a CCS).
1166 if (rr->type == SSL3_RT_HANDSHAKE && type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1167 al = SSL_AD_UNEXPECTED_MESSAGE;
1168 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1173 * Lets just double check that we've not got an SSLv2 record
1175 if (rr->rec_version == SSL2_VERSION) {
1177 * Should never happen. ssl3_get_record() should only give us an SSLv2
1178 * record back if this is the first packet and we are looking for an
1179 * initial ClientHello. Therefore |type| should always be equal to
1180 * |rr->type|. If not then something has gone horribly wrong
1182 al = SSL_AD_INTERNAL_ERROR;
1183 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1187 if (s->method->version == TLS_ANY_VERSION
1188 && (s->server || rr->type != SSL3_RT_ALERT)) {
1190 * If we've got this far and still haven't decided on what version
1191 * we're using then this must be a client side alert we're dealing with
1192 * (we don't allow heartbeats yet). We shouldn't be receiving anything
1193 * other than a ClientHello if we are a server.
1195 s->version = rr->rec_version;
1196 al = SSL_AD_UNEXPECTED_MESSAGE;
1197 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1202 * In case of record types for which we have 'fragment' storage, fill
1203 * that so that we can process the data at a fixed place.
1206 unsigned int dest_maxlen = 0;
1207 unsigned char *dest = NULL;
1208 unsigned int *dest_len = NULL;
1210 if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1211 dest_maxlen = sizeof s->rlayer.handshake_fragment;
1212 dest = s->rlayer.handshake_fragment;
1213 dest_len = &s->rlayer.handshake_fragment_len;
1214 } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1215 dest_maxlen = sizeof s->rlayer.alert_fragment;
1216 dest = s->rlayer.alert_fragment;
1217 dest_len = &s->rlayer.alert_fragment_len;
1220 if (dest_maxlen > 0) {
1221 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1222 if (SSL3_RECORD_get_length(rr) < n)
1223 n = SSL3_RECORD_get_length(rr); /* available bytes */
1225 /* now move 'n' bytes: */
1227 dest[(*dest_len)++] =
1228 SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
1229 SSL3_RECORD_add_off(rr, 1);
1230 SSL3_RECORD_add_length(rr, -1);
1233 if (*dest_len < dest_maxlen) {
1234 SSL3_RECORD_set_read(rr);
1235 goto start; /* fragment was too small */
1241 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1242 * s->rlayer.alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
1243 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1246 /* If we are a client, check for an incoming 'Hello Request': */
1248 (s->rlayer.handshake_fragment_len >= 4) &&
1249 (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1250 (s->session != NULL) && (s->session->cipher != NULL)) {
1251 s->rlayer.handshake_fragment_len = 0;
1253 if ((s->rlayer.handshake_fragment[1] != 0) ||
1254 (s->rlayer.handshake_fragment[2] != 0) ||
1255 (s->rlayer.handshake_fragment[3] != 0)) {
1256 al = SSL_AD_DECODE_ERROR;
1257 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1261 if (s->msg_callback)
1262 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1263 s->rlayer.handshake_fragment, 4, s,
1264 s->msg_callback_arg);
1266 if (SSL_is_init_finished(s) &&
1267 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1268 !s->s3->renegotiate) {
1269 ssl3_renegotiate(s);
1270 if (ssl3_renegotiate_check(s)) {
1271 i = s->handshake_func(s);
1275 SSLerr(SSL_F_SSL3_READ_BYTES,
1276 SSL_R_SSL_HANDSHAKE_FAILURE);
1280 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1281 if (SSL3_BUFFER_get_left(rbuf) == 0) {
1282 /* no read-ahead left? */
1285 * In the case where we try to read application data,
1286 * but we trigger an SSL handshake, we return -1 with
1287 * the retry option set. Otherwise renegotiation may
1288 * cause nasty problems in the blocking world
1290 s->rwstate = SSL_READING;
1291 bio = SSL_get_rbio(s);
1292 BIO_clear_retry_flags(bio);
1293 BIO_set_retry_read(bio);
1300 * we either finished a handshake or ignored the request, now try
1301 * again to obtain the (application) data we were asked for
1306 * If we are a server and get a client hello when renegotiation isn't
1307 * allowed send back a no renegotiation alert and carry on. WARNING:
1308 * experimental code, needs reviewing (steve)
1311 SSL_is_init_finished(s) &&
1312 !s->s3->send_connection_binding &&
1313 (s->version > SSL3_VERSION) &&
1314 (s->rlayer.handshake_fragment_len >= 4) &&
1315 (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1316 (s->session != NULL) && (s->session->cipher != NULL) &&
1317 !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1318 SSL3_RECORD_set_length(rr, 0);
1319 SSL3_RECORD_set_read(rr);
1320 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1323 if (s->rlayer.alert_fragment_len >= 2) {
1324 int alert_level = s->rlayer.alert_fragment[0];
1325 int alert_descr = s->rlayer.alert_fragment[1];
1327 s->rlayer.alert_fragment_len = 0;
1329 if (s->msg_callback)
1330 s->msg_callback(0, s->version, SSL3_RT_ALERT,
1331 s->rlayer.alert_fragment, 2, s,
1332 s->msg_callback_arg);
1334 if (s->info_callback != NULL)
1335 cb = s->info_callback;
1336 else if (s->ctx->info_callback != NULL)
1337 cb = s->ctx->info_callback;
1340 j = (alert_level << 8) | alert_descr;
1341 cb(s, SSL_CB_READ_ALERT, j);
1344 if (alert_level == SSL3_AL_WARNING) {
1345 s->s3->warn_alert = alert_descr;
1346 SSL3_RECORD_set_read(rr);
1347 if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1348 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1352 * This is a warning but we receive it if we requested
1353 * renegotiation and the peer denied it. Terminate with a fatal
1354 * alert because if application tried to renegotiate it
1355 * presumably had a good reason and expects it to succeed. In
1356 * future we might have a renegotiation where we don't care if
1357 * the peer refused it where we carry on.
1359 else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1360 al = SSL_AD_HANDSHAKE_FAILURE;
1361 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1364 #ifdef SSL_AD_MISSING_SRP_USERNAME
1365 else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1368 } else if (alert_level == SSL3_AL_FATAL) {
1371 s->rwstate = SSL_NOTHING;
1372 s->s3->fatal_alert = alert_descr;
1373 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1374 BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1375 ERR_add_error_data(2, "SSL alert number ", tmp);
1376 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1377 SSL3_RECORD_set_read(rr);
1378 SSL_CTX_remove_session(s->session_ctx, s->session);
1381 al = SSL_AD_ILLEGAL_PARAMETER;
1382 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1389 if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1391 s->rwstate = SSL_NOTHING;
1392 SSL3_RECORD_set_length(rr, 0);
1393 SSL3_RECORD_set_read(rr);
1397 if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1398 al = SSL_AD_UNEXPECTED_MESSAGE;
1399 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1404 * Unexpected handshake message (Client Hello, or protocol violation)
1406 if ((s->rlayer.handshake_fragment_len >= 4)
1407 && !ossl_statem_get_in_handshake(s)) {
1408 if (SSL_is_init_finished(s) &&
1409 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1410 ossl_statem_set_in_init(s, 1);
1414 i = s->handshake_func(s);
1418 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1422 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1423 if (SSL3_BUFFER_get_left(rbuf) == 0) {
1424 /* no read-ahead left? */
1427 * In the case where we try to read application data, but we
1428 * trigger an SSL handshake, we return -1 with the retry
1429 * option set. Otherwise renegotiation may cause nasty
1430 * problems in the blocking world
1432 s->rwstate = SSL_READING;
1433 bio = SSL_get_rbio(s);
1434 BIO_clear_retry_flags(bio);
1435 BIO_set_retry_read(bio);
1442 switch (SSL3_RECORD_get_type(rr)) {
1445 * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1446 * an unexpected message alert.
1448 if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1449 SSL3_RECORD_set_length(rr, 0);
1450 SSL3_RECORD_set_read(rr);
1453 al = SSL_AD_UNEXPECTED_MESSAGE;
1454 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1456 case SSL3_RT_CHANGE_CIPHER_SPEC:
1458 case SSL3_RT_HANDSHAKE:
1460 * we already handled all of these, with the possible exception of
1461 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1462 * that should not happen when type != rr->type
1464 al = SSL_AD_UNEXPECTED_MESSAGE;
1465 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1467 case SSL3_RT_APPLICATION_DATA:
1469 * At this point, we were expecting handshake data, but have
1470 * application data. If the library was running inside ssl3_read()
1471 * (i.e. in_read_app_data is set) and it makes sense to read
1472 * application data at this point (session renegotiation not yet
1473 * started), we will indulge it.
1475 if (ossl_statem_app_data_allowed(s)) {
1476 s->s3->in_read_app_data = 2;
1479 al = SSL_AD_UNEXPECTED_MESSAGE;
1480 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1487 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1491 void ssl3_record_sequence_update(unsigned char *seq)
1495 for (i = 7; i >= 0; i--) {
1503 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1504 * format and false otherwise.
1506 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1508 return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1512 * Returns the length in bytes of the current rrec
1514 unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1516 return SSL3_RECORD_get_length(&rl->rrec[0]);