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 RECORD_LAYER_set_first_record(&s->rlayer);
37 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
40 void RECORD_LAYER_clear(RECORD_LAYER *rl)
44 rl->rstate = SSL_ST_READ_HEADER;
47 * Do I need to clear read_ahead? As far as I can tell read_ahead did not
48 * previously get reset by SSL_clear...so I'll keep it that way..but is
53 rl->packet_length = 0;
55 memset(rl->alert_fragment, 0, sizeof(rl->alert_fragment));
56 rl->alert_fragment_len = 0;
57 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
58 rl->handshake_fragment_len = 0;
64 SSL3_BUFFER_clear(&rl->rbuf);
65 for (pipes = 0; pipes < rl->numwpipes; pipes++)
66 SSL3_BUFFER_clear(&rl->wbuf[pipes]);
69 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
71 RECORD_LAYER_reset_read_sequence(rl);
72 RECORD_LAYER_reset_write_sequence(rl);
75 DTLS_RECORD_LAYER_clear(rl);
78 void RECORD_LAYER_release(RECORD_LAYER *rl)
80 if (SSL3_BUFFER_is_initialised(&rl->rbuf))
81 ssl3_release_read_buffer(rl->s);
82 if (rl->numwpipes > 0)
83 ssl3_release_write_buffer(rl->s);
84 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
87 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
89 return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
92 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
94 return (rl->numwpipes > 0)
95 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
98 int RECORD_LAYER_set_data(RECORD_LAYER *rl, const unsigned char *buf, int len)
100 rl->packet_length = len;
102 rl->rstate = SSL_ST_READ_HEADER;
103 if (!SSL3_BUFFER_is_initialised(&rl->rbuf))
104 if (!ssl3_setup_read_buffer(rl->s))
108 rl->packet = SSL3_BUFFER_get_buf(&rl->rbuf);
109 SSL3_BUFFER_set_data(&rl->rbuf, buf, len);
114 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
116 memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
119 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
121 memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
124 int ssl3_pending(const SSL *s)
129 if (s->rlayer.rstate == SSL_ST_READ_BODY)
132 for (i = 0; i < RECORD_LAYER_get_numrpipes(&s->rlayer); i++) {
133 if (SSL3_RECORD_get_type(&s->rlayer.rrec[i])
134 != SSL3_RT_APPLICATION_DATA)
136 num += SSL3_RECORD_get_length(&s->rlayer.rrec[i]);
142 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
144 ctx->default_read_buf_len = len;
147 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
149 SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&s->rlayer), len);
152 const char *SSL_rstate_string_long(const SSL *s)
154 switch (s->rlayer.rstate) {
155 case SSL_ST_READ_HEADER:
156 return "read header";
157 case SSL_ST_READ_BODY:
159 case SSL_ST_READ_DONE:
166 const char *SSL_rstate_string(const SSL *s)
168 switch (s->rlayer.rstate) {
169 case SSL_ST_READ_HEADER:
171 case SSL_ST_READ_BODY:
173 case SSL_ST_READ_DONE:
180 int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold)
183 * If extend == 0, obtain new n-byte packet; if extend == 1, increase
184 * packet by another n bytes. The packet will be in the sub-array of
185 * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
186 * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus
187 * s->packet_length bytes if extend == 1].)
188 * if clearold == 1, move the packet to the start of the buffer; if
189 * clearold == 0 then leave any old packets where they were
199 rb = &s->rlayer.rbuf;
201 if (!ssl3_setup_read_buffer(s))
205 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
206 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
207 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
211 /* start with empty packet ... */
214 else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
216 * check if next packet length is large enough to justify payload
219 pkt = rb->buf + rb->offset;
220 if (pkt[0] == SSL3_RT_APPLICATION_DATA
221 && (pkt[3] << 8 | pkt[4]) >= 128) {
223 * Note that even if packet is corrupted and its length field
224 * is insane, we can only be led to wrong decision about
225 * whether memmove will occur or not. Header values has no
226 * effect on memmove arguments and therefore no buffer
227 * overrun can be triggered.
229 memmove(rb->buf + align, pkt, left);
233 s->rlayer.packet = rb->buf + rb->offset;
234 s->rlayer.packet_length = 0;
235 /* ... now we can act as if 'extend' was set */
239 * For DTLS/UDP reads should not span multiple packets because the read
240 * operation returns the whole packet at once (as long as it fits into
243 if (SSL_IS_DTLS(s)) {
244 if (left == 0 && extend)
246 if (left > 0 && n > left)
250 /* if there is enough in the buffer from a previous read, take some */
252 s->rlayer.packet_length += n;
258 /* else we need to read more data */
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) { /* len > 0 */
267 memmove(pkt, s->rlayer.packet, len + left);
268 s->rlayer.packet = pkt;
269 rb->offset = len + align;
272 if (n > (int)(rb->len - rb->offset)) { /* does not happen */
273 SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
277 /* We always act like read_ahead is set for DTLS */
278 if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s))
279 /* ignore max parameter */
284 if (max > (int)(rb->len - rb->offset))
285 max = rb->len - rb->offset;
290 * Now we have len+left bytes at the front of s->s3->rbuf.buf and
291 * need to read in more until we have len+n (up to len+max if
296 if (s->rbio != NULL) {
297 s->rwstate = SSL_READING;
298 i = BIO_read(s->rbio, pkt + len + left, max - left);
300 SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
306 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s))
308 ssl3_release_read_buffer(s);
313 * reads should *never* span multiple packets for DTLS because the
314 * underlying transport protocol is message oriented as opposed to
315 * byte oriented as in the TLS case.
317 if (SSL_IS_DTLS(s)) {
319 n = left; /* makes the while condition false */
323 /* done reading, now the book-keeping */
326 s->rlayer.packet_length += n;
327 s->rwstate = SSL_NOTHING;
332 * Call this to write data in records of type 'type' It will return <= 0 if
333 * not all data has been sent or non-blocking IO.
335 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
337 const unsigned char *buf = buf_;
339 unsigned int n, split_send_fragment, maxpipes;
340 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
341 unsigned int max_send_fragment, nw;
342 unsigned int u_len = (unsigned int)len;
344 SSL3_BUFFER *wb = &s->rlayer.wbuf[0];
348 SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH);
352 s->rwstate = SSL_NOTHING;
353 tot = s->rlayer.wnum;
355 * ensure that if we end up with a smaller value of data to write out
356 * than the the original len from a write which didn't complete for
357 * non-blocking I/O and also somehow ended up avoiding the check for
358 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
359 * possible to end up with (len-tot) as a large number that will then
360 * promptly send beyond the end of the users buffer ... so we trap and
361 * report the error in a way the user will notice
363 if ((unsigned int)len < s->rlayer.wnum) {
364 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) || (EVP_MD_CTX_md(s->write_hash) == NULL)) {
661 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
664 mac_size = EVP_MD_CTX_size(s->write_hash);
670 * 'create_empty_fragment' is true only when this function calls itself
672 if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
674 * countermeasure against known-IV weakness in CBC ciphersuites (see
675 * http://www.openssl.org/~bodo/tls-cbc.txt)
678 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
680 * recursive function call with 'create_empty_fragment' set; this
681 * prepares and buffers the data for an empty fragment (these
682 * 'prefix_len' bytes are sent out later together with the actual
685 unsigned int tmppipelen = 0;
687 prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
692 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
693 /* insufficient space */
694 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
699 s->s3->empty_fragment_done = 1;
702 if (create_empty_fragment) {
703 wb = &s->rlayer.wbuf[0];
704 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
706 * extra fragment would be couple of cipher blocks, which would be
707 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
708 * payload, then we can just pretend we simply have two headers.
710 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
711 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
713 outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
714 SSL3_BUFFER_set_offset(wb, align);
715 } else if (prefix_len) {
716 wb = &s->rlayer.wbuf[0];
717 outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
720 for (j = 0; j < numpipes; j++) {
721 wb = &s->rlayer.wbuf[j];
722 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
723 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
724 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
726 outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
727 SSL3_BUFFER_set_offset(wb, align);
731 /* Explicit IV length, block ciphers appropriate version flag */
732 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
733 int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
734 if (mode == EVP_CIPH_CBC_MODE) {
735 eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
739 /* Need explicit part of IV for GCM mode */
740 else if (mode == EVP_CIPH_GCM_MODE)
741 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
742 else if (mode == EVP_CIPH_CCM_MODE)
743 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
750 /* Clear our SSL3_RECORD structures */
751 memset(wr, 0, sizeof wr);
752 for (j = 0; j < numpipes; j++) {
753 /* write the header */
754 *(outbuf[j]++) = type & 0xff;
755 SSL3_RECORD_set_type(&wr[j], type);
757 *(outbuf[j]++) = (s->version >> 8);
759 * Some servers hang if initial client hello is larger than 256 bytes
760 * and record version number > TLS 1.0
762 if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
763 && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
764 *(outbuf[j]++) = 0x1;
766 *(outbuf[j]++) = s->version & 0xff;
768 /* field where we are to write out packet length */
772 /* lets setup the record stuff. */
773 SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
774 SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
775 SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
776 totlen += pipelens[j];
779 * we now 'read' from wr->input, wr->length bytes into wr->data
782 /* first we compress */
783 if (s->compress != NULL) {
784 if (!ssl3_do_compress(s, &wr[j])) {
785 SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
789 memcpy(wr[j].data, wr[j].input, wr[j].length);
790 SSL3_RECORD_reset_input(&wr[j]);
794 * we should still have the output to wr->data and the input from
795 * wr->input. Length should be wr->length. wr->data still points in the
799 if (!SSL_USE_ETM(s) && mac_size != 0) {
800 if (s->method->ssl3_enc->mac(s, &wr[j],
801 &(outbuf[j][wr[j].length + eivlen]),
804 SSL3_RECORD_add_length(&wr[j], mac_size);
807 SSL3_RECORD_set_data(&wr[j], outbuf[j]);
808 SSL3_RECORD_reset_input(&wr[j]);
812 * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
814 SSL3_RECORD_add_length(&wr[j], eivlen);
818 if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
821 for (j = 0; j < numpipes; j++) {
822 if (SSL_USE_ETM(s) && mac_size != 0) {
823 if (s->method->ssl3_enc->mac(s, &wr[j],
824 outbuf[j] + wr[j].length, 1) < 0)
826 SSL3_RECORD_add_length(&wr[j], mac_size);
829 /* record length after mac and block padding */
830 s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
833 s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
834 s->msg_callback_arg);
837 * we should now have wr->data pointing to the encrypted data, which is
840 SSL3_RECORD_set_type(&wr[j], type); /* not needed but helps for
842 SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
844 if (create_empty_fragment) {
846 * we are in a recursive call; just return the length, don't write
850 /* We should never be pipelining an empty fragment!! */
851 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
854 return SSL3_RECORD_get_length(wr);
857 /* now let's set up wb */
858 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
859 prefix_len + SSL3_RECORD_get_length(&wr[j]));
863 * memorize arguments so that ssl3_write_pending can detect bad write
866 s->rlayer.wpend_tot = totlen;
867 s->rlayer.wpend_buf = buf;
868 s->rlayer.wpend_type = type;
869 s->rlayer.wpend_ret = totlen;
871 /* we now just need to write the buffer */
872 return ssl3_write_pending(s, type, buf, totlen);
877 /* if s->s3->wbuf.left != 0, we need to call this */
878 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
882 SSL3_BUFFER *wb = s->rlayer.wbuf;
883 unsigned int currbuf = 0;
886 if ((s->rlayer.wpend_tot > (int)len)
887 || ((s->rlayer.wpend_buf != buf) &&
888 !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
889 || (s->rlayer.wpend_type != type)) {
890 SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
895 /* Loop until we find a buffer we haven't written out yet */
896 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
897 && currbuf < s->rlayer.numwpipes - 1) {
902 if (s->wbio != NULL) {
903 s->rwstate = SSL_WRITING;
904 i = BIO_write(s->wbio, (char *)
905 &(SSL3_BUFFER_get_buf(&wb[currbuf])
906 [SSL3_BUFFER_get_offset(&wb[currbuf])]),
907 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
909 SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
912 if (i == SSL3_BUFFER_get_left(&wb[currbuf])) {
913 SSL3_BUFFER_set_left(&wb[currbuf], 0);
914 SSL3_BUFFER_add_offset(&wb[currbuf], i);
915 if (currbuf + 1 < s->rlayer.numwpipes)
917 s->rwstate = SSL_NOTHING;
918 return (s->rlayer.wpend_ret);
920 if (SSL_IS_DTLS(s)) {
922 * For DTLS, just drop it. That's kind of the whole point in
923 * using a datagram service
925 SSL3_BUFFER_set_left(&wb[currbuf], 0);
929 SSL3_BUFFER_add_offset(&wb[currbuf], i);
930 SSL3_BUFFER_add_left(&wb[currbuf], -i);
935 * Return up to 'len' payload bytes received in 'type' records.
936 * 'type' is one of the following:
938 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
939 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
940 * - 0 (during a shutdown, no data has to be returned)
942 * If we don't have stored data to work from, read a SSL/TLS record first
943 * (possibly multiple records if we still don't have anything to return).
945 * This function must handle any surprises the peer may have for us, such as
946 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
947 * messages are treated as if they were handshake messages *if* the |recd_type|
948 * argument is non NULL.
949 * Also if record payloads contain fragments too small to process, we store
950 * them until there is enough for the respective protocol (the record protocol
951 * may use arbitrary fragmentation and even interleaving):
952 * Change cipher spec protocol
953 * just 1 byte needed, no need for keeping anything stored
955 * 2 bytes needed (AlertLevel, AlertDescription)
957 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
958 * to detect unexpected Client Hello and Hello Request messages
959 * here, anything else is handled by higher layers
960 * Application data protocol
961 * none of our business
963 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
967 unsigned int n, curr_rec, num_recs, read_bytes;
970 void (*cb) (const SSL *ssl, int type2, int val) = NULL;
972 rbuf = &s->rlayer.rbuf;
974 if (!SSL3_BUFFER_is_initialised(rbuf)) {
975 /* Not initialized yet */
976 if (!ssl3_setup_read_buffer(s))
980 if ((type && (type != SSL3_RT_APPLICATION_DATA)
981 && (type != SSL3_RT_HANDSHAKE)) || (peek
983 SSL3_RT_APPLICATION_DATA))) {
984 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
988 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
989 /* (partially) satisfy request from storage */
991 unsigned char *src = s->rlayer.handshake_fragment;
992 unsigned char *dst = buf;
997 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1000 s->rlayer.handshake_fragment_len--;
1003 /* move any remaining fragment bytes: */
1004 for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1005 s->rlayer.handshake_fragment[k] = *src++;
1007 if (recvd_type != NULL)
1008 *recvd_type = SSL3_RT_HANDSHAKE;
1014 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1017 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) {
1018 /* type == SSL3_RT_APPLICATION_DATA */
1019 i = s->handshake_func(s);
1023 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1028 s->rwstate = SSL_NOTHING;
1031 * For each record 'i' up to |num_recs]
1032 * rr[i].type - is the type of record
1033 * rr[i].data, - data
1034 * rr[i].off, - offset into 'data' for next read
1035 * rr[i].length, - number of bytes.
1037 rr = s->rlayer.rrec;
1038 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1041 /* get new records if necessary */
1042 if (num_recs == 0) {
1043 ret = ssl3_get_record(s);
1046 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1047 if (num_recs == 0) {
1048 /* Shouldn't happen */
1049 al = SSL_AD_INTERNAL_ERROR;
1050 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1054 /* Skip over any records we have already read */
1056 curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
1058 if (curr_rec == num_recs) {
1059 RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1063 } while (num_recs == 0);
1066 /* we now have a packet which can be read and processed */
1068 if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1069 * reset by ssl3_get_finished */
1070 && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1071 al = SSL_AD_UNEXPECTED_MESSAGE;
1072 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1077 * If the other end has shut down, throw anything we read away (even in
1080 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1081 SSL3_RECORD_set_length(rr, 0);
1082 s->rwstate = SSL_NOTHING;
1086 if (type == SSL3_RECORD_get_type(rr)
1087 || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1088 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
1090 * SSL3_RT_APPLICATION_DATA or
1091 * SSL3_RT_HANDSHAKE or
1092 * SSL3_RT_CHANGE_CIPHER_SPEC
1095 * make sure that we are not getting application data when we are
1096 * doing a handshake for the first time
1098 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1099 (s->enc_read_ctx == NULL)) {
1100 al = SSL_AD_UNEXPECTED_MESSAGE;
1101 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1105 if (type == SSL3_RT_HANDSHAKE
1106 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1107 && s->rlayer.handshake_fragment_len > 0) {
1108 al = SSL_AD_UNEXPECTED_MESSAGE;
1109 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1113 if (recvd_type != NULL)
1114 *recvd_type = SSL3_RECORD_get_type(rr);
1121 if ((unsigned int)len - read_bytes > SSL3_RECORD_get_length(rr))
1122 n = SSL3_RECORD_get_length(rr);
1124 n = (unsigned int)len - read_bytes;
1126 memcpy(buf, &(rr->data[rr->off]), n);
1129 SSL3_RECORD_sub_length(rr, n);
1130 SSL3_RECORD_add_off(rr, n);
1131 if (SSL3_RECORD_get_length(rr) == 0) {
1132 s->rlayer.rstate = SSL_ST_READ_HEADER;
1133 SSL3_RECORD_set_off(rr, 0);
1134 SSL3_RECORD_set_read(rr);
1137 if (SSL3_RECORD_get_length(rr) == 0
1138 || (peek && n == SSL3_RECORD_get_length(rr))) {
1143 } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1144 && read_bytes < (unsigned int)len);
1145 if (read_bytes == 0) {
1146 /* We must have read empty records. Get more data */
1149 if (!peek && curr_rec == num_recs
1150 && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1151 && SSL3_BUFFER_get_left(rbuf) == 0)
1152 ssl3_release_read_buffer(s);
1157 * If we get here, then type != rr->type; if we have a handshake message,
1158 * then it was unexpected (Hello Request or Client Hello) or invalid (we
1159 * were actually expecting a CCS).
1162 if (rr->type == SSL3_RT_HANDSHAKE && type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1163 al = SSL_AD_UNEXPECTED_MESSAGE;
1164 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1169 * Lets just double check that we've not got an SSLv2 record
1171 if (rr->rec_version == SSL2_VERSION) {
1173 * Should never happen. ssl3_get_record() should only give us an SSLv2
1174 * record back if this is the first packet and we are looking for an
1175 * initial ClientHello. Therefore |type| should always be equal to
1176 * |rr->type|. If not then something has gone horribly wrong
1178 al = SSL_AD_INTERNAL_ERROR;
1179 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1183 if (s->method->version == TLS_ANY_VERSION
1184 && (s->server || rr->type != SSL3_RT_ALERT)) {
1186 * If we've got this far and still haven't decided on what version
1187 * we're using then this must be a client side alert we're dealing with
1188 * (we don't allow heartbeats yet). We shouldn't be receiving anything
1189 * other than a ClientHello if we are a server.
1191 s->version = rr->rec_version;
1192 al = SSL_AD_UNEXPECTED_MESSAGE;
1193 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_MESSAGE);
1198 * In case of record types for which we have 'fragment' storage, fill
1199 * that so that we can process the data at a fixed place.
1202 unsigned int dest_maxlen = 0;
1203 unsigned char *dest = NULL;
1204 unsigned int *dest_len = NULL;
1206 if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1207 dest_maxlen = sizeof s->rlayer.handshake_fragment;
1208 dest = s->rlayer.handshake_fragment;
1209 dest_len = &s->rlayer.handshake_fragment_len;
1210 } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1211 dest_maxlen = sizeof s->rlayer.alert_fragment;
1212 dest = s->rlayer.alert_fragment;
1213 dest_len = &s->rlayer.alert_fragment_len;
1216 if (dest_maxlen > 0) {
1217 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1218 if (SSL3_RECORD_get_length(rr) < n)
1219 n = SSL3_RECORD_get_length(rr); /* available bytes */
1221 /* now move 'n' bytes: */
1223 dest[(*dest_len)++] =
1224 SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
1225 SSL3_RECORD_add_off(rr, 1);
1226 SSL3_RECORD_add_length(rr, -1);
1229 if (*dest_len < dest_maxlen) {
1230 SSL3_RECORD_set_read(rr);
1231 goto start; /* fragment was too small */
1237 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1238 * s->rlayer.alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
1239 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1242 /* If we are a client, check for an incoming 'Hello Request': */
1244 (s->rlayer.handshake_fragment_len >= 4) &&
1245 (s->rlayer.handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1246 (s->session != NULL) && (s->session->cipher != NULL)) {
1247 s->rlayer.handshake_fragment_len = 0;
1249 if ((s->rlayer.handshake_fragment[1] != 0) ||
1250 (s->rlayer.handshake_fragment[2] != 0) ||
1251 (s->rlayer.handshake_fragment[3] != 0)) {
1252 al = SSL_AD_DECODE_ERROR;
1253 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1257 if (s->msg_callback)
1258 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1259 s->rlayer.handshake_fragment, 4, s,
1260 s->msg_callback_arg);
1262 if (SSL_is_init_finished(s) &&
1263 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1264 !s->s3->renegotiate) {
1265 ssl3_renegotiate(s);
1266 if (ssl3_renegotiate_check(s)) {
1267 i = s->handshake_func(s);
1271 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1275 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1276 if (SSL3_BUFFER_get_left(rbuf) == 0) {
1277 /* no read-ahead left? */
1280 * In the case where we try to read application data,
1281 * but we trigger an SSL handshake, we return -1 with
1282 * the retry option set. Otherwise renegotiation may
1283 * cause nasty problems in the blocking world
1285 s->rwstate = SSL_READING;
1286 bio = SSL_get_rbio(s);
1287 BIO_clear_retry_flags(bio);
1288 BIO_set_retry_read(bio);
1295 * we either finished a handshake or ignored the request, now try
1296 * again to obtain the (application) data we were asked for
1301 * If we are a server and get a client hello when renegotiation isn't
1302 * allowed send back a no renegotiation alert and carry on. WARNING:
1303 * experimental code, needs reviewing (steve)
1306 SSL_is_init_finished(s) &&
1307 !s->s3->send_connection_binding &&
1308 (s->version > SSL3_VERSION) &&
1309 (s->rlayer.handshake_fragment_len >= 4) &&
1310 (s->rlayer.handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1311 (s->session != NULL) && (s->session->cipher != NULL) &&
1312 !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1313 SSL3_RECORD_set_length(rr, 0);
1314 SSL3_RECORD_set_read(rr);
1315 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1318 if (s->rlayer.alert_fragment_len >= 2) {
1319 int alert_level = s->rlayer.alert_fragment[0];
1320 int alert_descr = s->rlayer.alert_fragment[1];
1322 s->rlayer.alert_fragment_len = 0;
1324 if (s->msg_callback)
1325 s->msg_callback(0, s->version, SSL3_RT_ALERT,
1326 s->rlayer.alert_fragment, 2, s,
1327 s->msg_callback_arg);
1329 if (s->info_callback != NULL)
1330 cb = s->info_callback;
1331 else if (s->ctx->info_callback != NULL)
1332 cb = s->ctx->info_callback;
1335 j = (alert_level << 8) | alert_descr;
1336 cb(s, SSL_CB_READ_ALERT, j);
1339 if (alert_level == SSL3_AL_WARNING) {
1340 s->s3->warn_alert = alert_descr;
1341 SSL3_RECORD_set_read(rr);
1342 if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1343 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1347 * This is a warning but we receive it if we requested
1348 * renegotiation and the peer denied it. Terminate with a fatal
1349 * alert because if application tried to renegotiate it
1350 * presumably had a good reason and expects it to succeed. In
1351 * future we might have a renegotiation where we don't care if
1352 * the peer refused it where we carry on.
1354 else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1355 al = SSL_AD_HANDSHAKE_FAILURE;
1356 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1359 #ifdef SSL_AD_MISSING_SRP_USERNAME
1360 else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1363 } else if (alert_level == SSL3_AL_FATAL) {
1366 s->rwstate = SSL_NOTHING;
1367 s->s3->fatal_alert = alert_descr;
1368 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1369 BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1370 ERR_add_error_data(2, "SSL alert number ", tmp);
1371 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1372 SSL3_RECORD_set_read(rr);
1373 SSL_CTX_remove_session(s->session_ctx, s->session);
1376 al = SSL_AD_ILLEGAL_PARAMETER;
1377 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1384 if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1386 s->rwstate = SSL_NOTHING;
1387 SSL3_RECORD_set_length(rr, 0);
1388 SSL3_RECORD_set_read(rr);
1392 if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1393 al = SSL_AD_UNEXPECTED_MESSAGE;
1394 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1399 * Unexpected handshake message (Client Hello, or protocol violation)
1401 if ((s->rlayer.handshake_fragment_len >= 4)
1402 && !ossl_statem_get_in_handshake(s)) {
1403 if (SSL_is_init_finished(s) &&
1404 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1405 ossl_statem_set_in_init(s, 1);
1409 i = s->handshake_func(s);
1413 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1417 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1418 if (SSL3_BUFFER_get_left(rbuf) == 0) {
1419 /* no read-ahead left? */
1422 * In the case where we try to read application data, but we
1423 * trigger an SSL handshake, we return -1 with the retry
1424 * option set. Otherwise renegotiation may cause nasty
1425 * problems in the blocking world
1427 s->rwstate = SSL_READING;
1428 bio = SSL_get_rbio(s);
1429 BIO_clear_retry_flags(bio);
1430 BIO_set_retry_read(bio);
1437 switch (SSL3_RECORD_get_type(rr)) {
1440 * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1441 * an unexpected message alert.
1443 if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1444 SSL3_RECORD_set_length(rr, 0);
1445 SSL3_RECORD_set_read(rr);
1448 al = SSL_AD_UNEXPECTED_MESSAGE;
1449 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1451 case SSL3_RT_CHANGE_CIPHER_SPEC:
1453 case SSL3_RT_HANDSHAKE:
1455 * we already handled all of these, with the possible exception of
1456 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1457 * that should not happen when type != rr->type
1459 al = SSL_AD_UNEXPECTED_MESSAGE;
1460 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1462 case SSL3_RT_APPLICATION_DATA:
1464 * At this point, we were expecting handshake data, but have
1465 * application data. If the library was running inside ssl3_read()
1466 * (i.e. in_read_app_data is set) and it makes sense to read
1467 * application data at this point (session renegotiation not yet
1468 * started), we will indulge it.
1470 if (ossl_statem_app_data_allowed(s)) {
1471 s->s3->in_read_app_data = 2;
1474 al = SSL_AD_UNEXPECTED_MESSAGE;
1475 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1482 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1486 void ssl3_record_sequence_update(unsigned char *seq)
1490 for (i = 7; i >= 0; i--) {
1498 * Returns true if the current rrec was sent in SSLv2 backwards compatible
1499 * format and false otherwise.
1501 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1503 return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1507 * Returns the length in bytes of the current rrec
1509 unsigned int RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1511 return SSL3_RECORD_get_length(&rl->rrec[0]);