155714Skris/* ssl/s3_pkt.c */
255714Skris/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
355714Skris * All rights reserved.
455714Skris *
555714Skris * This package is an SSL implementation written
655714Skris * by Eric Young (eay@cryptsoft.com).
755714Skris * The implementation was written so as to conform with Netscapes SSL.
855714Skris *
955714Skris * This library is free for commercial and non-commercial use as long as
1055714Skris * the following conditions are aheared to.  The following conditions
1155714Skris * apply to all code found in this distribution, be it the RC4, RSA,
1255714Skris * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1355714Skris * included with this distribution is covered by the same copyright terms
1455714Skris * except that the holder is Tim Hudson (tjh@cryptsoft.com).
1555714Skris *
1655714Skris * Copyright remains Eric Young's, and as such any Copyright notices in
1755714Skris * the code are not to be removed.
1855714Skris * If this package is used in a product, Eric Young should be given attribution
1955714Skris * as the author of the parts of the library used.
2055714Skris * This can be in the form of a textual message at program startup or
2155714Skris * in documentation (online or textual) provided with the package.
2255714Skris *
2355714Skris * Redistribution and use in source and binary forms, with or without
2455714Skris * modification, are permitted provided that the following conditions
2555714Skris * are met:
2655714Skris * 1. Redistributions of source code must retain the copyright
2755714Skris *    notice, this list of conditions and the following disclaimer.
2855714Skris * 2. Redistributions in binary form must reproduce the above copyright
2955714Skris *    notice, this list of conditions and the following disclaimer in the
3055714Skris *    documentation and/or other materials provided with the distribution.
3155714Skris * 3. All advertising materials mentioning features or use of this software
3255714Skris *    must display the following acknowledgement:
3355714Skris *    "This product includes cryptographic software written by
3455714Skris *     Eric Young (eay@cryptsoft.com)"
3555714Skris *    The word 'cryptographic' can be left out if the rouines from the library
3655714Skris *    being used are not cryptographic related :-).
3755714Skris * 4. If you include any Windows specific code (or a derivative thereof) from
3855714Skris *    the apps directory (application code) you must include an acknowledgement:
3955714Skris *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
4055714Skris *
4155714Skris * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4255714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4355714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4455714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4555714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4655714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4755714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4855714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4955714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
5055714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5155714Skris * SUCH DAMAGE.
5255714Skris *
5355714Skris * The licence and distribution terms for any publically available version or
5455714Skris * derivative of this code cannot be changed.  i.e. this code cannot simply be
5555714Skris * copied and put under another distribution licence
5655714Skris * [including the GNU Public Licence.]
5755714Skris */
5859191Skris/* ====================================================================
59100928Snectar * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
6059191Skris *
6159191Skris * Redistribution and use in source and binary forms, with or without
6259191Skris * modification, are permitted provided that the following conditions
6359191Skris * are met:
6459191Skris *
6559191Skris * 1. Redistributions of source code must retain the above copyright
6659191Skris *    notice, this list of conditions and the following disclaimer.
6759191Skris *
6859191Skris * 2. Redistributions in binary form must reproduce the above copyright
6959191Skris *    notice, this list of conditions and the following disclaimer in
7059191Skris *    the documentation and/or other materials provided with the
7159191Skris *    distribution.
7259191Skris *
7359191Skris * 3. All advertising materials mentioning features or use of this
7459191Skris *    software must display the following acknowledgment:
7559191Skris *    "This product includes software developed by the OpenSSL Project
7659191Skris *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
7759191Skris *
7859191Skris * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
7959191Skris *    endorse or promote products derived from this software without
8059191Skris *    prior written permission. For written permission, please contact
8159191Skris *    openssl-core@openssl.org.
8259191Skris *
8359191Skris * 5. Products derived from this software may not be called "OpenSSL"
8459191Skris *    nor may "OpenSSL" appear in their names without prior written
8559191Skris *    permission of the OpenSSL Project.
8659191Skris *
8759191Skris * 6. Redistributions of any form whatsoever must retain the following
8859191Skris *    acknowledgment:
8959191Skris *    "This product includes software developed by the OpenSSL Project
9059191Skris *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
9159191Skris *
9259191Skris * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
9359191Skris * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9459191Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
9559191Skris * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
9659191Skris * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9759191Skris * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
9859191Skris * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9959191Skris * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
10059191Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
10159191Skris * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
10259191Skris * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
10359191Skris * OF THE POSSIBILITY OF SUCH DAMAGE.
10459191Skris * ====================================================================
10559191Skris *
10659191Skris * This product includes cryptographic software written by Eric Young
10759191Skris * (eay@cryptsoft.com).  This product includes software written by Tim
10859191Skris * Hudson (tjh@cryptsoft.com).
10959191Skris *
11059191Skris */
11155714Skris
11255714Skris#include <stdio.h>
113279264Sdelphij#include <limits.h>
11455714Skris#include <errno.h>
11555714Skris#define USE_SOCKETS
116109998Smarkm#include "ssl_locl.h"
11755714Skris#include <openssl/evp.h>
11855714Skris#include <openssl/buffer.h>
119238405Sjkim#include <openssl/rand.h>
12055714Skris
12155714Skrisstatic int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
122100928Snectar			 unsigned int len, int create_empty_fragment);
12355714Skrisstatic int ssl3_get_record(SSL *s);
12459191Skris
125160814Ssimonint ssl3_read_n(SSL *s, int n, int max, int extend)
12655714Skris	{
12759191Skris	/* If extend == 0, obtain new n-byte packet; if extend == 1, increase
12859191Skris	 * packet by another n bytes.
12959191Skris	 * The packet will be in the sub-array of s->s3->rbuf.buf specified
13059191Skris	 * by s->packet and s->packet_length.
13159191Skris	 * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
13259191Skris	 * [plus s->packet_length bytes if extend == 1].)
13359191Skris	 */
134238405Sjkim	int i,len,left;
135238405Sjkim	long align=0;
136238405Sjkim	unsigned char *pkt;
137238405Sjkim	SSL3_BUFFER *rb;
13855714Skris
139238405Sjkim	if (n <= 0) return n;
140238405Sjkim
141238405Sjkim	rb    = &(s->s3->rbuf);
142238405Sjkim	if (rb->buf == NULL)
143238405Sjkim		if (!ssl3_setup_read_buffer(s))
144238405Sjkim			return -1;
145238405Sjkim
146238405Sjkim	left  = rb->left;
147238405Sjkim#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
148238405Sjkim	align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
149238405Sjkim	align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
150238405Sjkim#endif
151238405Sjkim
15259191Skris	if (!extend)
15359191Skris		{
15459191Skris		/* start with empty packet ... */
155238405Sjkim		if (left == 0)
156238405Sjkim			rb->offset = align;
157238405Sjkim		else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
158238405Sjkim			{
159238405Sjkim			/* check if next packet length is large
160238405Sjkim			 * enough to justify payload alignment... */
161238405Sjkim			pkt = rb->buf + rb->offset;
162238405Sjkim			if (pkt[0] == SSL3_RT_APPLICATION_DATA
163238405Sjkim			    && (pkt[3]<<8|pkt[4]) >= 128)
164238405Sjkim				{
165238405Sjkim				/* Note that even if packet is corrupted
166238405Sjkim				 * and its length field is insane, we can
167238405Sjkim				 * only be led to wrong decision about
168238405Sjkim				 * whether memmove will occur or not.
169238405Sjkim				 * Header values has no effect on memmove
170238405Sjkim				 * arguments and therefore no buffer
171238405Sjkim				 * overrun can be triggered. */
172238405Sjkim				memmove (rb->buf+align,pkt,left);
173238405Sjkim				rb->offset = align;
174238405Sjkim				}
175238405Sjkim			}
176238405Sjkim		s->packet = rb->buf + rb->offset;
17759191Skris		s->packet_length = 0;
17859191Skris		/* ... now we can act as if 'extend' was set */
17959191Skris		}
18059191Skris
181205128Ssimon	/* For DTLS/UDP reads should not span multiple packets
182205128Ssimon	 * because the read operation returns the whole packet
183205128Ssimon	 * at once (as long as it fits into the buffer). */
184238405Sjkim	if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
185160814Ssimon		{
186277195Sdelphij		if (left == 0 && extend)
187277195Sdelphij			return 0;
188238405Sjkim		if (left > 0 && n > left)
189238405Sjkim			n = left;
190160814Ssimon		}
191160814Ssimon
19259191Skris	/* if there is enough in the buffer from a previous read, take some */
193238405Sjkim	if (left >= n)
19455714Skris		{
19559191Skris		s->packet_length+=n;
196238405Sjkim		rb->left=left-n;
197238405Sjkim		rb->offset+=n;
19855714Skris		return(n);
19955714Skris		}
20055714Skris
20155714Skris	/* else we need to read more data */
20255714Skris
203238405Sjkim	len = s->packet_length;
204238405Sjkim	pkt = rb->buf+align;
205238405Sjkim	/* Move any available bytes to front of buffer:
206238405Sjkim	 * 'len' bytes already pointed to by 'packet',
207238405Sjkim	 * 'left' extra ones at the end */
208238405Sjkim	if (s->packet != pkt) /* len > 0 */
20955714Skris		{
210238405Sjkim		memmove(pkt, s->packet, len+left);
211238405Sjkim		s->packet = pkt;
212238405Sjkim		rb->offset = len + align;
213238405Sjkim		}
214238405Sjkim
215238405Sjkim	if (n > (int)(rb->len - rb->offset)) /* does not happen */
216238405Sjkim		{
217109998Smarkm		SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR);
21859191Skris		return -1;
21959191Skris		}
22055714Skris
221238405Sjkim	if (!s->read_ahead)
222238405Sjkim		/* ignore max parameter */
223238405Sjkim		max = n;
224238405Sjkim	else
22559191Skris		{
226238405Sjkim		if (max < n)
227238405Sjkim			max = n;
228238405Sjkim		if (max > (int)(rb->len - rb->offset))
229238405Sjkim			max = rb->len - rb->offset;
23055714Skris		}
23155714Skris
232238405Sjkim	while (left < n)
23355714Skris		{
234238405Sjkim		/* Now we have len+left bytes at the front of s->s3->rbuf.buf
235238405Sjkim		 * and need to read in more until we have len+n (up to
236238405Sjkim		 * len+max if possible) */
23759191Skris
23855714Skris		clear_sys_error();
23955714Skris		if (s->rbio != NULL)
24055714Skris			{
24155714Skris			s->rwstate=SSL_READING;
242238405Sjkim			i=BIO_read(s->rbio,pkt+len+left, max-left);
24355714Skris			}
24455714Skris		else
24555714Skris			{
24655714Skris			SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
24759191Skris			i = -1;
24855714Skris			}
24955714Skris
25055714Skris		if (i <= 0)
25155714Skris			{
252238405Sjkim			rb->left = left;
253238405Sjkim			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
254238405Sjkim			    SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
255238405Sjkim				if (len+left == 0)
256238405Sjkim					ssl3_release_read_buffer(s);
25755714Skris			return(i);
25855714Skris			}
259238405Sjkim		left+=i;
260205128Ssimon		/* reads should *never* span multiple packets for DTLS because
261205128Ssimon		 * the underlying transport protocol is message oriented as opposed
262205128Ssimon		 * to byte oriented as in the TLS case. */
263238405Sjkim		if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
264205128Ssimon			{
265238405Sjkim			if (n > left)
266238405Sjkim				n = left; /* makes the while condition false */
267205128Ssimon			}
26855714Skris		}
26955714Skris
27059191Skris	/* done reading, now the book-keeping */
271238405Sjkim	rb->offset += n;
272238405Sjkim	rb->left = left - n;
27359191Skris	s->packet_length += n;
27459191Skris	s->rwstate=SSL_NOTHING;
27555714Skris	return(n);
27655714Skris	}
27755714Skris
278279264Sdelphij/* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that will
279279264Sdelphij * be processed per call to ssl3_get_record. Without this limit an attacker
280279264Sdelphij * could send empty records at a faster rate than we can process and cause
281279264Sdelphij * ssl3_get_record to loop forever. */
282279264Sdelphij#define MAX_EMPTY_RECORDS 32
283279264Sdelphij
28455714Skris/* Call this to get a new input record.
28555714Skris * It will return <= 0 if more data is needed, normally due to an error
28655714Skris * or non-blocking IO.
28755714Skris * When it finishes, one packet has been decoded and can be found in
28859191Skris * ssl->s3->rrec.type    - is the type of record
28959191Skris * ssl->s3->rrec.data, 	 - data
29055714Skris * ssl->s3->rrec.length, - number of bytes
29155714Skris */
29259191Skris/* used only by ssl3_read_bytes */
29355714Skrisstatic int ssl3_get_record(SSL *s)
29455714Skris	{
29555714Skris	int ssl_major,ssl_minor,al;
29689837Skris	int enc_err,n,i,ret= -1;
29755714Skris	SSL3_RECORD *rr;
29855714Skris	SSL_SESSION *sess;
29955714Skris	unsigned char *p;
30055714Skris	unsigned char md[EVP_MAX_MD_SIZE];
30155714Skris	short version;
302246772Sjkim	unsigned mac_size, orig_len;
303100928Snectar	size_t extra;
304279264Sdelphij	unsigned empty_record_count = 0;
30555714Skris
30655714Skris	rr= &(s->s3->rrec);
30755714Skris	sess=s->session;
30855714Skris
30955714Skris	if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
31055714Skris		extra=SSL3_RT_MAX_EXTRA;
31155714Skris	else
31255714Skris		extra=0;
313238405Sjkim	if (extra && !s->s3->init_extra)
314100928Snectar		{
315238405Sjkim		/* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER
316100928Snectar		 * set after ssl3_setup_buffers() was done */
317109998Smarkm		SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
318100928Snectar		return -1;
319100928Snectar		}
32055714Skris
32155714Skrisagain:
32255714Skris	/* check if we have the header */
32355714Skris	if (	(s->rstate != SSL_ST_READ_BODY) ||
32455714Skris		(s->packet_length < SSL3_RT_HEADER_LENGTH))
32555714Skris		{
326109998Smarkm		n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
32755714Skris		if (n <= 0) return(n); /* error or non-blocking */
32855714Skris		s->rstate=SSL_ST_READ_BODY;
32955714Skris
33055714Skris		p=s->packet;
33155714Skris
33255714Skris		/* Pull apart the header into the SSL3_RECORD */
33355714Skris		rr->type= *(p++);
33455714Skris		ssl_major= *(p++);
33555714Skris		ssl_minor= *(p++);
33655714Skris		version=(ssl_major<<8)|ssl_minor;
33755714Skris		n2s(p,rr->length);
338238405Sjkim#if 0
339238405Sjkimfprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
340238405Sjkim#endif
34155714Skris
34255714Skris		/* Lets check version */
343167612Ssimon		if (!s->first_packet)
34455714Skris			{
34555714Skris			if (version != s->version)
34655714Skris				{
34755714Skris				SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
348279264Sdelphij                                if ((s->version & 0xFF00) == (version & 0xFF00) && !s->enc_write_ctx && !s->write_hash)
349206046Ssimon                                	/* Send back error using their minor version number :-) */
350206046Ssimon					s->version = (unsigned short)version;
35155714Skris				al=SSL_AD_PROTOCOL_VERSION;
35255714Skris				goto f_err;
35355714Skris				}
35455714Skris			}
35555714Skris
35655714Skris		if ((version>>8) != SSL3_VERSION_MAJOR)
35755714Skris			{
35855714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
35955714Skris			goto err;
36055714Skris			}
36155714Skris
362238405Sjkim		if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)
36355714Skris			{
36455714Skris			al=SSL_AD_RECORD_OVERFLOW;
36555714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
36655714Skris			goto f_err;
36755714Skris			}
36855714Skris
36959191Skris		/* now s->rstate == SSL_ST_READ_BODY */
37055714Skris		}
37155714Skris
37259191Skris	/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
37359191Skris
374100928Snectar	if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)
37555714Skris		{
37659191Skris		/* now s->packet_length == SSL3_RT_HEADER_LENGTH */
37759191Skris		i=rr->length;
37859191Skris		n=ssl3_read_n(s,i,i,1);
37959191Skris		if (n <= 0) return(n); /* error or non-blocking io */
38059191Skris		/* now n == rr->length,
38159191Skris		 * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
38255714Skris		}
38355714Skris
38459191Skris	s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
38555714Skris
38659191Skris	/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
38759191Skris	 * and we have that many bytes in s->packet
38859191Skris	 */
38955714Skris	rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
39055714Skris
39155714Skris	/* ok, we can now read from 's->packet' data into 'rr'
39255714Skris	 * rr->input points at rr->length bytes, which
39355714Skris	 * need to be copied into rr->data by either
39455714Skris	 * the decryption or by the decompression
39555714Skris	 * When the data is 'copied' into the rr->data buffer,
39655714Skris	 * rr->input will be pointed at the new buffer */
39755714Skris
39855714Skris	/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
39955714Skris	 * rr->length bytes of encrypted compressed stuff. */
40055714Skris
40159191Skris	/* check is not needed I believe */
402100928Snectar	if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
40355714Skris		{
40455714Skris		al=SSL_AD_RECORD_OVERFLOW;
40555714Skris		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
40655714Skris		goto f_err;
40755714Skris		}
40855714Skris
40955714Skris	/* decrypt in place in 'rr->input' */
41055714Skris	rr->data=rr->input;
41155714Skris
41289837Skris	enc_err = s->method->ssl3_enc->enc(s,0);
413246772Sjkim	/* enc_err is:
414246772Sjkim	 *    0: (in non-constant time) if the record is publically invalid.
415246772Sjkim	 *    1: if the padding is valid
416246772Sjkim	 *    -1: if the padding is invalid */
417246772Sjkim	if (enc_err == 0)
41855714Skris		{
419246772Sjkim		al=SSL_AD_DECRYPTION_FAILED;
420246772Sjkim		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
421246772Sjkim		goto f_err;
42255714Skris		}
42389837Skris
42455714Skris#ifdef TLS_DEBUG
42555714Skrisprintf("dec %d\n",rr->length);
42655714Skris{ unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
42755714Skrisprintf("\n");
42855714Skris#endif
42989837Skris
43055714Skris	/* r->length is now the compressed data plus mac */
431246772Sjkim	if ((sess != NULL) &&
432246772Sjkim	    (s->enc_read_ctx != NULL) &&
433246772Sjkim	    (EVP_MD_CTX_md(s->read_hash) != NULL))
43455714Skris		{
435246772Sjkim		/* s->read_hash != NULL => mac_size != -1 */
436246772Sjkim		unsigned char *mac = NULL;
437246772Sjkim		unsigned char mac_tmp[EVP_MAX_MD_SIZE];
438238405Sjkim		mac_size=EVP_MD_CTX_size(s->read_hash);
439246772Sjkim		OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
44055714Skris
441246772Sjkim		/* kludge: *_cbc_remove_padding passes padding length in rr->type */
442246772Sjkim		orig_len = rr->length+((unsigned int)rr->type>>8);
443246772Sjkim
444246772Sjkim		/* orig_len is the length of the record before any padding was
445246772Sjkim		 * removed. This is public information, as is the MAC in use,
446246772Sjkim		 * therefore we can safely process the record in a different
447246772Sjkim		 * amount of time if it's too short to possibly contain a MAC.
448246772Sjkim		 */
449246772Sjkim		if (orig_len < mac_size ||
450246772Sjkim		    /* CBC records must have a padding length byte too. */
451246772Sjkim		    (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
452246772Sjkim		     orig_len < mac_size+1))
45355714Skris			{
454246772Sjkim			al=SSL_AD_DECODE_ERROR;
455246772Sjkim			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);
45655714Skris			goto f_err;
45755714Skris			}
458246772Sjkim
459246772Sjkim		if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
46055714Skris			{
461246772Sjkim			/* We update the length so that the TLS header bytes
462246772Sjkim			 * can be constructed correctly but we need to extract
463246772Sjkim			 * the MAC in constant time from within the record,
464246772Sjkim			 * without leaking the contents of the padding bytes.
465246772Sjkim			 * */
466246772Sjkim			mac = mac_tmp;
467246772Sjkim			ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
468111147Snectar			rr->length -= mac_size;
469111147Snectar			}
470111147Snectar		else
471111147Snectar			{
472246772Sjkim			/* In this case there's no padding, so |orig_len|
473246772Sjkim			 * equals |rec->length| and we checked that there's
474246772Sjkim			 * enough bytes for |mac_size| above. */
475246772Sjkim			rr->length -= mac_size;
476246772Sjkim			mac = &rr->data[rr->length];
47755714Skris			}
478246772Sjkim
479246772Sjkim		i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
480246772Sjkim		if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
481246772Sjkim			enc_err = -1;
482246772Sjkim		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
483246772Sjkim			enc_err = -1;
48455714Skris		}
48555714Skris
486246772Sjkim	if (enc_err < 0)
487111147Snectar		{
488111147Snectar		/* A separate 'decryption_failed' alert was introduced with TLS 1.0,
489111147Snectar		 * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
490111147Snectar		 * failure is directly visible from the ciphertext anyway,
491111147Snectar		 * we should not reveal which kind of error occured -- this
492111147Snectar		 * might become visible to an attacker (e.g. via a logfile) */
493111147Snectar		al=SSL_AD_BAD_RECORD_MAC;
494111147Snectar		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
495111147Snectar		goto f_err;
496111147Snectar		}
497111147Snectar
49855714Skris	/* r->length is now just compressed */
49955714Skris	if (s->expand != NULL)
50055714Skris		{
501100928Snectar		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)
50255714Skris			{
50355714Skris			al=SSL_AD_RECORD_OVERFLOW;
50455714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
50555714Skris			goto f_err;
50655714Skris			}
507160814Ssimon		if (!ssl3_do_uncompress(s))
50855714Skris			{
50955714Skris			al=SSL_AD_DECOMPRESSION_FAILURE;
51055714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);
51155714Skris			goto f_err;
51255714Skris			}
51355714Skris		}
51455714Skris
515100928Snectar	if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)
51655714Skris		{
51755714Skris		al=SSL_AD_RECORD_OVERFLOW;
51855714Skris		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
51955714Skris		goto f_err;
52055714Skris		}
52155714Skris
52255714Skris	rr->off=0;
52355714Skris	/* So at this point the following is true
52455714Skris	 * ssl->s3->rrec.type 	is the type of record
52555714Skris	 * ssl->s3->rrec.length	== number of bytes in record
52655714Skris	 * ssl->s3->rrec.off	== offset to first valid byte
52755714Skris	 * ssl->s3->rrec.data	== where to take bytes from, increment
52855714Skris	 *			   after use :-).
52955714Skris	 */
53055714Skris
53155714Skris	/* we have pulled in a full packet so zero things */
53255714Skris	s->packet_length=0;
53355714Skris
53455714Skris	/* just read a 0 length packet */
535279264Sdelphij	if (rr->length == 0)
536279264Sdelphij		{
537279264Sdelphij		empty_record_count++;
538279264Sdelphij		if (empty_record_count > MAX_EMPTY_RECORDS)
539279264Sdelphij			{
540279264Sdelphij			al=SSL_AD_UNEXPECTED_MESSAGE;
541279264Sdelphij			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_RECORD_TOO_SMALL);
542279264Sdelphij			goto f_err;
543279264Sdelphij			}
544279264Sdelphij		goto again;
545279264Sdelphij		}
54655714Skris
547238405Sjkim#if 0
548238405Sjkimfprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length);
549238405Sjkim#endif
550238405Sjkim
55155714Skris	return(1);
55289837Skris
55355714Skrisf_err:
55455714Skris	ssl3_send_alert(s,SSL3_AL_FATAL,al);
55555714Skriserr:
55655714Skris	return(ret);
55755714Skris	}
55855714Skris
559160814Ssimonint ssl3_do_uncompress(SSL *ssl)
56055714Skris	{
561160814Ssimon#ifndef OPENSSL_NO_COMP
56255714Skris	int i;
56355714Skris	SSL3_RECORD *rr;
56455714Skris
56555714Skris	rr= &(ssl->s3->rrec);
56655714Skris	i=COMP_expand_block(ssl->expand,rr->comp,
56755714Skris		SSL3_RT_MAX_PLAIN_LENGTH,rr->data,(int)rr->length);
56855714Skris	if (i < 0)
56955714Skris		return(0);
57055714Skris	else
57155714Skris		rr->length=i;
57255714Skris	rr->data=rr->comp;
573160814Ssimon#endif
57455714Skris	return(1);
57555714Skris	}
57655714Skris
577160814Ssimonint ssl3_do_compress(SSL *ssl)
57855714Skris	{
579160814Ssimon#ifndef OPENSSL_NO_COMP
58055714Skris	int i;
58155714Skris	SSL3_RECORD *wr;
58255714Skris
58355714Skris	wr= &(ssl->s3->wrec);
58455714Skris	i=COMP_compress_block(ssl->compress,wr->data,
58555714Skris		SSL3_RT_MAX_COMPRESSED_LENGTH,
58655714Skris		wr->input,(int)wr->length);
58755714Skris	if (i < 0)
58855714Skris		return(0);
58955714Skris	else
59055714Skris		wr->length=i;
59155714Skris
59255714Skris	wr->input=wr->data;
593160814Ssimon#endif
59455714Skris	return(1);
59555714Skris	}
59655714Skris
59759191Skris/* Call this to write data in records of type 'type'
59855714Skris * It will return <= 0 if not all data has been sent or non-blocking IO.
59955714Skris */
60059191Skrisint ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
60155714Skris	{
60259191Skris	const unsigned char *buf=buf_;
603279264Sdelphij	unsigned int n,nw;
604279264Sdelphij	int i,tot;
60555714Skris
60655714Skris	s->rwstate=SSL_NOTHING;
607279264Sdelphij	OPENSSL_assert(s->s3->wnum <= INT_MAX);
60855714Skris	tot=s->s3->wnum;
60955714Skris	s->s3->wnum=0;
61055714Skris
61155714Skris	if (SSL_in_init(s) && !s->in_handshake)
61255714Skris		{
61355714Skris		i=s->handshake_func(s);
61455714Skris		if (i < 0) return(i);
61555714Skris		if (i == 0)
61655714Skris			{
61755714Skris			SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
618100928Snectar			return -1;
61955714Skris			}
62055714Skris		}
62155714Skris
622279264Sdelphij	/* ensure that if we end up with a smaller value of data to write
623279264Sdelphij	 * out than the the original len from a write which didn't complete
624279264Sdelphij	 * for non-blocking I/O and also somehow ended up avoiding
625279264Sdelphij	 * the check for this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as
626279264Sdelphij	 * it must never be possible to end up with (len-tot) as a large
627279264Sdelphij	 * number that will then promptly send beyond the end of the users
628279264Sdelphij	 * buffer ... so we trap and report the error in a way the user
629279264Sdelphij	 * will notice
630279264Sdelphij	 */
631279264Sdelphij	if (len < tot)
632279264Sdelphij		{
633279264Sdelphij		SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_BAD_LENGTH);
634279264Sdelphij		return(-1);
635279264Sdelphij		}
636279264Sdelphij
637279264Sdelphij
63855714Skris	n=(len-tot);
63955714Skris	for (;;)
64055714Skris		{
641238405Sjkim		if (n > s->max_send_fragment)
642238405Sjkim			nw=s->max_send_fragment;
64355714Skris		else
64455714Skris			nw=n;
64559191Skris
646100928Snectar		i=do_ssl3_write(s, type, &(buf[tot]), nw, 0);
64755714Skris		if (i <= 0)
64855714Skris			{
64955714Skris			s->s3->wnum=tot;
650100928Snectar			return i;
65155714Skris			}
65255714Skris
65355714Skris		if ((i == (int)n) ||
65455714Skris			(type == SSL3_RT_APPLICATION_DATA &&
65555714Skris			 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
65655714Skris			{
657100928Snectar			/* next chunk of data should get another prepended empty fragment
658100928Snectar			 * in ciphersuites with known-IV weakness: */
659100928Snectar			s->s3->empty_fragment_done = 0;
660100928Snectar
661100928Snectar			return tot+i;
66255714Skris			}
66355714Skris
66455714Skris		n-=i;
66555714Skris		tot+=i;
66655714Skris		}
66755714Skris	}
66855714Skris
66955714Skrisstatic int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
670100928Snectar			 unsigned int len, int create_empty_fragment)
67155714Skris	{
67255714Skris	unsigned char *p,*plen;
67355714Skris	int i,mac_size,clear=0;
674238405Sjkim	int prefix_len=0;
675238405Sjkim	int eivlen;
676238405Sjkim	long align=0;
67755714Skris	SSL3_RECORD *wr;
678238405Sjkim	SSL3_BUFFER *wb=&(s->s3->wbuf);
67955714Skris	SSL_SESSION *sess;
68055714Skris
681238405Sjkim
682100928Snectar	/* first check if there is a SSL3_BUFFER still being written
68355714Skris	 * out.  This will happen with non blocking IO */
684238405Sjkim	if (wb->left != 0)
68555714Skris		return(ssl3_write_pending(s,type,buf,len));
68655714Skris
68755714Skris	/* If we have an alert to send, lets send it */
68855714Skris	if (s->s3->alert_dispatch)
68955714Skris		{
690160814Ssimon		i=s->method->ssl_dispatch_alert(s);
69155714Skris		if (i <= 0)
69255714Skris			return(i);
69355714Skris		/* if it went, fall through and send more stuff */
69455714Skris		}
69555714Skris
696279264Sdelphij 	if (wb->buf == NULL)
697279264Sdelphij		if (!ssl3_setup_write_buffer(s))
698279264Sdelphij			return -1;
699279264Sdelphij
700100928Snectar	if (len == 0 && !create_empty_fragment)
701100928Snectar		return 0;
70259191Skris
70355714Skris	wr= &(s->s3->wrec);
70455714Skris	sess=s->session;
70555714Skris
70655714Skris	if (	(sess == NULL) ||
70755714Skris		(s->enc_write_ctx == NULL) ||
708238405Sjkim		(EVP_MD_CTX_md(s->write_hash) == NULL))
709238405Sjkim		{
710238405Sjkim#if 1
711238405Sjkim		clear=s->enc_write_ctx?0:1;	/* must be AEAD cipher */
712238405Sjkim#else
71355714Skris		clear=1;
714238405Sjkim#endif
71555714Skris		mac_size=0;
716238405Sjkim		}
71755714Skris	else
718238405Sjkim		{
719238405Sjkim		mac_size=EVP_MD_CTX_size(s->write_hash);
720238405Sjkim		if (mac_size < 0)
721238405Sjkim			goto err;
722238405Sjkim		}
72355714Skris
724100928Snectar	/* 'create_empty_fragment' is true only when this function calls itself */
725100928Snectar	if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done)
726100928Snectar		{
727100928Snectar		/* countermeasure against known-IV weakness in CBC ciphersuites
728100928Snectar		 * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
72955714Skris
730100928Snectar		if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
731100928Snectar			{
732100928Snectar			/* recursive function call with 'create_empty_fragment' set;
733100928Snectar			 * this prepares and buffers the data for an empty fragment
734100928Snectar			 * (these 'prefix_len' bytes are sent out later
735100928Snectar			 * together with the actual payload) */
736100928Snectar			prefix_len = do_ssl3_write(s, type, buf, 0, 1);
737100928Snectar			if (prefix_len <= 0)
738100928Snectar				goto err;
739100928Snectar
740238405Sjkim			if (prefix_len >
741238405Sjkim		(SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
742100928Snectar				{
743100928Snectar				/* insufficient space */
744109998Smarkm				SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
745100928Snectar				goto err;
746100928Snectar				}
747100928Snectar			}
748100928Snectar
749100928Snectar		s->s3->empty_fragment_done = 1;
750100928Snectar		}
751100928Snectar
752238405Sjkim	if (create_empty_fragment)
753238405Sjkim		{
754238405Sjkim#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
755238405Sjkim		/* extra fragment would be couple of cipher blocks,
756238405Sjkim		 * which would be multiple of SSL3_ALIGN_PAYLOAD, so
757238405Sjkim		 * if we want to align the real payload, then we can
758238405Sjkim		 * just pretent we simply have two headers. */
759238405Sjkim		align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH;
760238405Sjkim		align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
761238405Sjkim#endif
762238405Sjkim		p = wb->buf + align;
763238405Sjkim		wb->offset  = align;
764238405Sjkim		}
765238405Sjkim	else if (prefix_len)
766238405Sjkim		{
767238405Sjkim		p = wb->buf + wb->offset + prefix_len;
768238405Sjkim		}
769238405Sjkim	else
770238405Sjkim		{
771238405Sjkim#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
772238405Sjkim		align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
773238405Sjkim		align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
774238405Sjkim#endif
775238405Sjkim		p = wb->buf + align;
776238405Sjkim		wb->offset  = align;
777238405Sjkim		}
778100928Snectar
77955714Skris	/* write the header */
780100928Snectar
78155714Skris	*(p++)=type&0xff;
78255714Skris	wr->type=type;
78355714Skris
78455714Skris	*(p++)=(s->version>>8);
785238405Sjkim	/* Some servers hang if iniatial client hello is larger than 256
786238405Sjkim	 * bytes and record version number > TLS 1.0
787238405Sjkim	 */
788238405Sjkim	if (s->state == SSL3_ST_CW_CLNT_HELLO_B
789246772Sjkim				&& !s->renegotiate
790238405Sjkim				&& TLS1_get_version(s) > TLS1_VERSION)
791238405Sjkim		*(p++) = 0x1;
792238405Sjkim	else
793238405Sjkim		*(p++)=s->version&0xff;
79459191Skris
795100928Snectar	/* field where we are to write out packet length */
79655714Skris	plen=p;
79755714Skris	p+=2;
798238405Sjkim	/* Explicit IV length, block ciphers and TLS version 1.1 or later */
799238405Sjkim	if (s->enc_write_ctx && s->version >= TLS1_1_VERSION)
800238405Sjkim		{
801238405Sjkim		int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
802238405Sjkim		if (mode == EVP_CIPH_CBC_MODE)
803238405Sjkim			{
804238405Sjkim			eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
805238405Sjkim			if (eivlen <= 1)
806238405Sjkim				eivlen = 0;
807238405Sjkim			}
808238405Sjkim		/* Need explicit part of IV for GCM mode */
809238405Sjkim		else if (mode == EVP_CIPH_GCM_MODE)
810238405Sjkim			eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
811238405Sjkim		else
812238405Sjkim			eivlen = 0;
813238405Sjkim		}
814238405Sjkim	else
815238405Sjkim		eivlen = 0;
81659191Skris
81755714Skris	/* lets setup the record stuff. */
818238405Sjkim	wr->data=p + eivlen;
81955714Skris	wr->length=(int)len;
82055714Skris	wr->input=(unsigned char *)buf;
82155714Skris
82255714Skris	/* we now 'read' from wr->input, wr->length bytes into
82355714Skris	 * wr->data */
82455714Skris
82555714Skris	/* first we compress */
82655714Skris	if (s->compress != NULL)
82755714Skris		{
828160814Ssimon		if (!ssl3_do_compress(s))
82955714Skris			{
83055714Skris			SSLerr(SSL_F_DO_SSL3_WRITE,SSL_R_COMPRESSION_FAILURE);
83155714Skris			goto err;
83255714Skris			}
83355714Skris		}
83455714Skris	else
83555714Skris		{
83655714Skris		memcpy(wr->data,wr->input,wr->length);
83755714Skris		wr->input=wr->data;
83855714Skris		}
83955714Skris
84055714Skris	/* we should still have the output to wr->data and the input
84155714Skris	 * from wr->input.  Length should be wr->length.
84255714Skris	 * wr->data still points in the wb->buf */
84355714Skris
84455714Skris	if (mac_size != 0)
84555714Skris		{
846238405Sjkim		if (s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
847238405Sjkim			goto err;
84855714Skris		wr->length+=mac_size;
84955714Skris		}
85055714Skris
851238405Sjkim	wr->input=p;
852238405Sjkim	wr->data=p;
853238405Sjkim
854238405Sjkim	if (eivlen)
855238405Sjkim		{
856238405Sjkim	/*	if (RAND_pseudo_bytes(p, eivlen) <= 0)
857238405Sjkim			goto err; */
858238405Sjkim		wr->length += eivlen;
859238405Sjkim		}
860238405Sjkim
861279264Sdelphij	if(s->method->ssl3_enc->enc(s,1)<1) goto err;
86255714Skris
86355714Skris	/* record length after mac and block padding */
86455714Skris	s2n(wr->length,plen);
86555714Skris
86655714Skris	/* we should now have
86755714Skris	 * wr->data pointing to the encrypted data, which is
86855714Skris	 * wr->length long */
86955714Skris	wr->type=type; /* not needed but helps for debugging */
87055714Skris	wr->length+=SSL3_RT_HEADER_LENGTH;
87155714Skris
872100928Snectar	if (create_empty_fragment)
873100928Snectar		{
874100928Snectar		/* we are in a recursive call;
875100928Snectar		 * just return the length, don't write out anything here
876100928Snectar		 */
877100928Snectar		return wr->length;
878100928Snectar		}
87955714Skris
880100928Snectar	/* now let's set up wb */
881100928Snectar	wb->left = prefix_len + wr->length;
882100928Snectar
883100928Snectar	/* memorize arguments so that ssl3_write_pending can detect bad write retries later */
88455714Skris	s->s3->wpend_tot=len;
88555714Skris	s->s3->wpend_buf=buf;
88655714Skris	s->s3->wpend_type=type;
88755714Skris	s->s3->wpend_ret=len;
88855714Skris
88955714Skris	/* we now just need to write the buffer */
890100928Snectar	return ssl3_write_pending(s,type,buf,len);
89155714Skriserr:
892100928Snectar	return -1;
89355714Skris	}
89455714Skris
89555714Skris/* if s->s3->wbuf.left != 0, we need to call this */
896160814Ssimonint ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
897160814Ssimon	unsigned int len)
89855714Skris	{
89955714Skris	int i;
900238405Sjkim	SSL3_BUFFER *wb=&(s->s3->wbuf);
90155714Skris
90255714Skris/* XXXX */
90355714Skris	if ((s->s3->wpend_tot > (int)len)
90455714Skris		|| ((s->s3->wpend_buf != buf) &&
90555714Skris			!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
90655714Skris		|| (s->s3->wpend_type != type))
90755714Skris		{
90855714Skris		SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY);
90955714Skris		return(-1);
91055714Skris		}
91155714Skris
91255714Skris	for (;;)
91355714Skris		{
91455714Skris		clear_sys_error();
91555714Skris		if (s->wbio != NULL)
91655714Skris			{
91755714Skris			s->rwstate=SSL_WRITING;
91855714Skris			i=BIO_write(s->wbio,
919238405Sjkim				(char *)&(wb->buf[wb->offset]),
920238405Sjkim				(unsigned int)wb->left);
92155714Skris			}
92255714Skris		else
92355714Skris			{
92455714Skris			SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BIO_NOT_SET);
92555714Skris			i= -1;
92655714Skris			}
927238405Sjkim		if (i == wb->left)
92855714Skris			{
929238405Sjkim			wb->left=0;
930238405Sjkim			wb->offset+=i;
931238405Sjkim			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
932238405Sjkim			    SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
933238405Sjkim				ssl3_release_write_buffer(s);
93455714Skris			s->rwstate=SSL_NOTHING;
93555714Skris			return(s->s3->wpend_ret);
93655714Skris			}
937194206Ssimon		else if (i <= 0) {
938194206Ssimon			if (s->version == DTLS1_VERSION ||
939194206Ssimon			    s->version == DTLS1_BAD_VER) {
940194206Ssimon				/* For DTLS, just drop it. That's kind of the whole
941194206Ssimon				   point in using a datagram service */
942238405Sjkim				wb->left = 0;
943194206Ssimon			}
94455714Skris			return(i);
945194206Ssimon		}
946238405Sjkim		wb->offset+=i;
947238405Sjkim		wb->left-=i;
94855714Skris		}
94955714Skris	}
95055714Skris
95159191Skris/* Return up to 'len' payload bytes received in 'type' records.
95259191Skris * 'type' is one of the following:
95359191Skris *
95459191Skris *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
95559191Skris *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
95659191Skris *   -  0 (during a shutdown, no data has to be returned)
95759191Skris *
95859191Skris * If we don't have stored data to work from, read a SSL/TLS record first
95959191Skris * (possibly multiple records if we still don't have anything to return).
96059191Skris *
96159191Skris * This function must handle any surprises the peer may have for us, such as
96259191Skris * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
96359191Skris * a surprise, but handled as if it were), or renegotiation requests.
96459191Skris * Also if record payloads contain fragments too small to process, we store
96559191Skris * them until there is enough for the respective protocol (the record protocol
96659191Skris * may use arbitrary fragmentation and even interleaving):
96759191Skris *     Change cipher spec protocol
96859191Skris *             just 1 byte needed, no need for keeping anything stored
96959191Skris *     Alert protocol
97059191Skris *             2 bytes needed (AlertLevel, AlertDescription)
97159191Skris *     Handshake protocol
97259191Skris *             4 bytes needed (HandshakeType, uint24 length) -- we just have
97359191Skris *             to detect unexpected Client Hello and Hello Request messages
97459191Skris *             here, anything else is handled by higher layers
97559191Skris *     Application data protocol
97659191Skris *             none of our business
97759191Skris */
97872613Skrisint ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
97955714Skris	{
98059191Skris	int al,i,j,ret;
98159191Skris	unsigned int n;
98255714Skris	SSL3_RECORD *rr;
983109998Smarkm	void (*cb)(const SSL *ssl,int type2,int val)=NULL;
98455714Skris
98559191Skris	if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
986238405Sjkim		if (!ssl3_setup_read_buffer(s))
98755714Skris			return(-1);
98855714Skris
989279264Sdelphij	if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) ||
99072613Skris	    (peek && (type != SSL3_RT_APPLICATION_DATA)))
99159191Skris		{
992109998Smarkm		SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
99359191Skris		return -1;
99459191Skris		}
99559191Skris
99659191Skris	if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
99759191Skris		/* (partially) satisfy request from storage */
99859191Skris		{
99959191Skris		unsigned char *src = s->s3->handshake_fragment;
100059191Skris		unsigned char *dst = buf;
100159191Skris		unsigned int k;
100259191Skris
100372613Skris		/* peek == 0 */
100459191Skris		n = 0;
100559191Skris		while ((len > 0) && (s->s3->handshake_fragment_len > 0))
100659191Skris			{
100759191Skris			*dst++ = *src++;
100859191Skris			len--; s->s3->handshake_fragment_len--;
100959191Skris			n++;
101059191Skris			}
101159191Skris		/* move any remaining fragment bytes: */
101259191Skris		for (k = 0; k < s->s3->handshake_fragment_len; k++)
101359191Skris			s->s3->handshake_fragment[k] = *src++;
101459191Skris		return n;
101559191Skris	}
101659191Skris
101759191Skris	/* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
101859191Skris
101955714Skris	if (!s->in_handshake && SSL_in_init(s))
102055714Skris		{
102159191Skris		/* type == SSL3_RT_APPLICATION_DATA */
102255714Skris		i=s->handshake_func(s);
102355714Skris		if (i < 0) return(i);
102455714Skris		if (i == 0)
102555714Skris			{
102655714Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
102755714Skris			return(-1);
102855714Skris			}
102955714Skris		}
103055714Skrisstart:
103155714Skris	s->rwstate=SSL_NOTHING;
103255714Skris
103359191Skris	/* s->s3->rrec.type	    - is the type of record
103459191Skris	 * s->s3->rrec.data,    - data
103559191Skris	 * s->s3->rrec.off,     - offset into 'data' for next read
103659191Skris	 * s->s3->rrec.length,  - number of bytes. */
103759191Skris	rr = &(s->s3->rrec);
103855714Skris
103972613Skris	/* get new packet if necessary */
104055714Skris	if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
104155714Skris		{
104255714Skris		ret=ssl3_get_record(s);
104355714Skris		if (ret <= 0) return(ret);
104455714Skris		}
104555714Skris
104655714Skris	/* we now have a packet which can be read and processed */
104755714Skris
104859191Skris	if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
104959191Skris	                               * reset by ssl3_get_finished */
105059191Skris		&& (rr->type != SSL3_RT_HANDSHAKE))
105155714Skris		{
105255714Skris		al=SSL_AD_UNEXPECTED_MESSAGE;
105355714Skris		SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1054142425Snectar		goto f_err;
105555714Skris		}
105655714Skris
105772613Skris	/* If the other end has shut down, throw anything we read away
105872613Skris	 * (even in 'peek' mode) */
105955714Skris	if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
106055714Skris		{
106155714Skris		rr->length=0;
106255714Skris		s->rwstate=SSL_NOTHING;
106355714Skris		return(0);
106455714Skris		}
106555714Skris
106659191Skris
106759191Skris	if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
106859191Skris		{
106959191Skris		/* make sure that we are not getting application data when we
107059191Skris		 * are doing a handshake for the first time */
107159191Skris		if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
107259191Skris			(s->enc_read_ctx == NULL))
107359191Skris			{
107459191Skris			al=SSL_AD_UNEXPECTED_MESSAGE;
107559191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
107659191Skris			goto f_err;
107759191Skris			}
107859191Skris
107959191Skris		if (len <= 0) return(len);
108059191Skris
108159191Skris		if ((unsigned int)len > rr->length)
108259191Skris			n = rr->length;
108359191Skris		else
108459191Skris			n = (unsigned int)len;
108559191Skris
108659191Skris		memcpy(buf,&(rr->data[rr->off]),n);
108772613Skris		if (!peek)
108859191Skris			{
108972613Skris			rr->length-=n;
109072613Skris			rr->off+=n;
109172613Skris			if (rr->length == 0)
109272613Skris				{
109372613Skris				s->rstate=SSL_ST_READ_HEADER;
109472613Skris				rr->off=0;
1095265124Sdelphij				if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)
1096238405Sjkim					ssl3_release_read_buffer(s);
109772613Skris				}
109859191Skris			}
109959191Skris		return(n);
110059191Skris		}
110159191Skris
110259191Skris
110359191Skris	/* If we get here, then type != rr->type; if we have a handshake
110459191Skris	 * message, then it was unexpected (Hello Request or Client Hello). */
110559191Skris
110659191Skris	/* In case of record types for which we have 'fragment' storage,
110759191Skris	 * fill that so that we can process the data at a fixed place.
110859191Skris	 */
110959191Skris		{
111059191Skris		unsigned int dest_maxlen = 0;
111159191Skris		unsigned char *dest = NULL;
111259191Skris		unsigned int *dest_len = NULL;
111359191Skris
111459191Skris		if (rr->type == SSL3_RT_HANDSHAKE)
111559191Skris			{
111659191Skris			dest_maxlen = sizeof s->s3->handshake_fragment;
111759191Skris			dest = s->s3->handshake_fragment;
111859191Skris			dest_len = &s->s3->handshake_fragment_len;
111959191Skris			}
112059191Skris		else if (rr->type == SSL3_RT_ALERT)
112159191Skris			{
112259191Skris			dest_maxlen = sizeof s->s3->alert_fragment;
112359191Skris			dest = s->s3->alert_fragment;
112459191Skris			dest_len = &s->s3->alert_fragment_len;
112559191Skris			}
1126238405Sjkim#ifndef OPENSSL_NO_HEARTBEATS
1127238405Sjkim		else if (rr->type == TLS1_RT_HEARTBEAT)
1128238405Sjkim			{
1129238405Sjkim			tls1_process_heartbeat(s);
113059191Skris
1131238405Sjkim			/* Exit and notify application to read again */
1132238405Sjkim			rr->length = 0;
1133238405Sjkim			s->rwstate=SSL_READING;
1134238405Sjkim			BIO_clear_retry_flags(SSL_get_rbio(s));
1135238405Sjkim			BIO_set_retry_read(SSL_get_rbio(s));
1136238405Sjkim			return(-1);
1137238405Sjkim			}
1138238405Sjkim#endif
1139238405Sjkim
114059191Skris		if (dest_maxlen > 0)
114159191Skris			{
114259191Skris			n = dest_maxlen - *dest_len; /* available space in 'dest' */
114359191Skris			if (rr->length < n)
114459191Skris				n = rr->length; /* available bytes */
114559191Skris
114659191Skris			/* now move 'n' bytes: */
114759191Skris			while (n-- > 0)
114859191Skris				{
114959191Skris				dest[(*dest_len)++] = rr->data[rr->off++];
115059191Skris				rr->length--;
115159191Skris				}
115259191Skris
115359191Skris			if (*dest_len < dest_maxlen)
115459191Skris				goto start; /* fragment was too small */
115559191Skris			}
115659191Skris		}
115759191Skris
115859191Skris	/* s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
115959191Skris	 * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
116059191Skris	 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
116159191Skris
116259191Skris	/* If we are a client, check for an incoming 'Hello Request': */
116359191Skris	if ((!s->server) &&
116459191Skris		(s->s3->handshake_fragment_len >= 4) &&
116559191Skris		(s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
116655714Skris		(s->session != NULL) && (s->session->cipher != NULL))
116755714Skris		{
116859191Skris		s->s3->handshake_fragment_len = 0;
116959191Skris
117059191Skris		if ((s->s3->handshake_fragment[1] != 0) ||
117159191Skris			(s->s3->handshake_fragment[2] != 0) ||
117259191Skris			(s->s3->handshake_fragment[3] != 0))
117355714Skris			{
117455714Skris			al=SSL_AD_DECODE_ERROR;
117559191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
1176142425Snectar			goto f_err;
117755714Skris			}
117855714Skris
1179109998Smarkm		if (s->msg_callback)
1180109998Smarkm			s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
1181109998Smarkm
1182205128Ssimon		if (SSL_is_init_finished(s) &&
1183205128Ssimon			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1184205128Ssimon			!s->s3->renegotiate)
118555714Skris			{
118655714Skris			ssl3_renegotiate(s);
118755714Skris			if (ssl3_renegotiate_check(s))
118855714Skris				{
118959191Skris				i=s->handshake_func(s);
119059191Skris				if (i < 0) return(i);
119159191Skris				if (i == 0)
119255714Skris					{
119355714Skris					SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
119455714Skris					return(-1);
119555714Skris					}
119659191Skris
119768651Skris				if (!(s->mode & SSL_MODE_AUTO_RETRY))
119859191Skris					{
119968651Skris					if (s->s3->rbuf.left == 0) /* no read-ahead left? */
120068651Skris						{
120168651Skris						BIO *bio;
120268651Skris						/* In the case where we try to read application data,
120368651Skris						 * but we trigger an SSL handshake, we return -1 with
120468651Skris						 * the retry option set.  Otherwise renegotiation may
120568651Skris						 * cause nasty problems in the blocking world */
120668651Skris						s->rwstate=SSL_READING;
120768651Skris						bio=SSL_get_rbio(s);
120868651Skris						BIO_clear_retry_flags(bio);
120968651Skris						BIO_set_retry_read(bio);
121068651Skris						return(-1);
121168651Skris						}
121259191Skris					}
121355714Skris				}
121455714Skris			}
121559191Skris		/* we either finished a handshake or ignored the request,
121659191Skris		 * now try again to obtain the (application) data we were asked for */
121759191Skris		goto start;
121855714Skris		}
1219205128Ssimon	/* If we are a server and get a client hello when renegotiation isn't
1220205128Ssimon	 * allowed send back a no renegotiation alert and carry on.
1221205128Ssimon	 * WARNING: experimental code, needs reviewing (steve)
1222205128Ssimon	 */
1223205128Ssimon	if (s->server &&
1224205128Ssimon		SSL_is_init_finished(s) &&
1225205128Ssimon    		!s->s3->send_connection_binding &&
1226205128Ssimon		(s->version > SSL3_VERSION) &&
1227205128Ssimon		(s->s3->handshake_fragment_len >= 4) &&
1228205128Ssimon		(s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1229205128Ssimon		(s->session != NULL) && (s->session->cipher != NULL) &&
1230205128Ssimon		!(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1231205128Ssimon
1232205128Ssimon		{
1233205128Ssimon		/*s->s3->handshake_fragment_len = 0;*/
1234205128Ssimon		rr->length = 0;
1235205128Ssimon		ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1236205128Ssimon		goto start;
1237205128Ssimon		}
123859191Skris	if (s->s3->alert_fragment_len >= 2)
123955714Skris		{
124059191Skris		int alert_level = s->s3->alert_fragment[0];
124159191Skris		int alert_descr = s->s3->alert_fragment[1];
124255714Skris
124359191Skris		s->s3->alert_fragment_len = 0;
124455714Skris
1245109998Smarkm		if (s->msg_callback)
1246109998Smarkm			s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);
1247109998Smarkm
124859191Skris		if (s->info_callback != NULL)
124959191Skris			cb=s->info_callback;
125059191Skris		else if (s->ctx->info_callback != NULL)
125159191Skris			cb=s->ctx->info_callback;
125255714Skris
125359191Skris		if (cb != NULL)
125459191Skris			{
125559191Skris			j = (alert_level << 8) | alert_descr;
125659191Skris			cb(s, SSL_CB_READ_ALERT, j);
125759191Skris			}
125855714Skris
125959191Skris		if (alert_level == 1) /* warning */
126059191Skris			{
126159191Skris			s->s3->warn_alert = alert_descr;
126259191Skris			if (alert_descr == SSL_AD_CLOSE_NOTIFY)
126355714Skris				{
126459191Skris				s->shutdown |= SSL_RECEIVED_SHUTDOWN;
126555714Skris				return(0);
126655714Skris				}
1267205128Ssimon			/* This is a warning but we receive it if we requested
1268205128Ssimon			 * renegotiation and the peer denied it. Terminate with
1269205128Ssimon			 * a fatal alert because if application tried to
1270205128Ssimon			 * renegotiatie it presumably had a good reason and
1271205128Ssimon			 * expects it to succeed.
1272205128Ssimon			 *
1273205128Ssimon			 * In future we might have a renegotiation where we
1274205128Ssimon			 * don't care if the peer refused it where we carry on.
1275205128Ssimon			 */
1276205128Ssimon			else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
1277205128Ssimon				{
1278205128Ssimon				al = SSL_AD_HANDSHAKE_FAILURE;
1279205128Ssimon				SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION);
1280205128Ssimon				goto f_err;
1281205128Ssimon				}
1282238405Sjkim#ifdef SSL_AD_MISSING_SRP_USERNAME
1283246772Sjkim			else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1284238405Sjkim				return(0);
1285238405Sjkim#endif
128655714Skris			}
128759191Skris		else if (alert_level == 2) /* fatal */
128859191Skris			{
128959191Skris			char tmp[16];
129055714Skris
129155714Skris			s->rwstate=SSL_NOTHING;
129259191Skris			s->s3->fatal_alert = alert_descr;
129359191Skris			SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
129468651Skris			BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
129559191Skris			ERR_add_error_data(2,"SSL alert number ",tmp);
129659191Skris			s->shutdown|=SSL_RECEIVED_SHUTDOWN;
129759191Skris			SSL_CTX_remove_session(s->ctx,s->session);
129855714Skris			return(0);
129955714Skris			}
130059191Skris		else
130159191Skris			{
130259191Skris			al=SSL_AD_ILLEGAL_PARAMETER;
130359191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
130459191Skris			goto f_err;
130559191Skris			}
130655714Skris
130759191Skris		goto start;
130859191Skris		}
130959191Skris
131059191Skris	if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
131159191Skris		{
131259191Skris		s->rwstate=SSL_NOTHING;
131359191Skris		rr->length=0;
131459191Skris		return(0);
131559191Skris		}
131659191Skris
131759191Skris	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
131859191Skris		{
131959191Skris		/* 'Change Cipher Spec' is just a single byte, so we know
132059191Skris		 * exactly what the record payload has to look like */
132159191Skris		if (	(rr->length != 1) || (rr->off != 0) ||
132259191Skris			(rr->data[0] != SSL3_MT_CCS))
132355714Skris			{
1324142425Snectar			al=SSL_AD_ILLEGAL_PARAMETER;
132559191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
1326142425Snectar			goto f_err;
132759191Skris			}
132855714Skris
1329127114Snectar		/* Check we have a cipher to change to */
1330127114Snectar		if (s->s3->tmp.new_cipher == NULL)
1331127114Snectar			{
1332142425Snectar			al=SSL_AD_UNEXPECTED_MESSAGE;
1333160814Ssimon			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);
1334142425Snectar			goto f_err;
1335127114Snectar			}
1336127114Snectar
1337267104Sdelphij		if (!(s->s3->flags & SSL3_FLAGS_CCS_OK))
1338267104Sdelphij			{
1339267104Sdelphij			al=SSL_AD_UNEXPECTED_MESSAGE;
1340267104Sdelphij			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);
1341267104Sdelphij			goto f_err;
1342267104Sdelphij			}
1343267104Sdelphij
1344267104Sdelphij		s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1345267104Sdelphij
134659191Skris		rr->length=0;
1347109998Smarkm
1348109998Smarkm		if (s->msg_callback)
1349109998Smarkm			s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
1350109998Smarkm
135159191Skris		s->s3->change_cipher_spec=1;
1352160814Ssimon		if (!ssl3_do_change_cipher_spec(s))
135359191Skris			goto err;
135459191Skris		else
135559191Skris			goto start;
135659191Skris		}
135759191Skris
135859191Skris	/* Unexpected handshake message (Client Hello, or protocol violation) */
135959191Skris	if ((s->s3->handshake_fragment_len >= 4) &&	!s->in_handshake)
136059191Skris		{
1361205128Ssimon		if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1362205128Ssimon			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
136359191Skris			{
136459191Skris#if 0 /* worked only because C operator preferences are not as expected (and
136559191Skris       * because this is not really needed for clients except for detecting
136659191Skris       * protocol violations): */
136759191Skris			s->state=SSL_ST_BEFORE|(s->server)
136859191Skris				?SSL_ST_ACCEPT
136959191Skris				:SSL_ST_CONNECT;
137059191Skris#else
137159191Skris			s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
137259191Skris#endif
1373238405Sjkim			s->renegotiate=1;
137459191Skris			s->new_session=1;
137555714Skris			}
137659191Skris		i=s->handshake_func(s);
137759191Skris		if (i < 0) return(i);
137859191Skris		if (i == 0)
137959191Skris			{
138059191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
138159191Skris			return(-1);
138259191Skris			}
138355714Skris
138468651Skris		if (!(s->mode & SSL_MODE_AUTO_RETRY))
138555714Skris			{
138668651Skris			if (s->s3->rbuf.left == 0) /* no read-ahead left? */
138768651Skris				{
138868651Skris				BIO *bio;
138968651Skris				/* In the case where we try to read application data,
139068651Skris				 * but we trigger an SSL handshake, we return -1 with
139168651Skris				 * the retry option set.  Otherwise renegotiation may
139268651Skris				 * cause nasty problems in the blocking world */
139368651Skris				s->rwstate=SSL_READING;
139468651Skris				bio=SSL_get_rbio(s);
139568651Skris				BIO_clear_retry_flags(bio);
139668651Skris				BIO_set_retry_read(bio);
139768651Skris				return(-1);
139868651Skris				}
139955714Skris			}
140059191Skris		goto start;
140159191Skris		}
140255714Skris
140359191Skris	switch (rr->type)
140459191Skris		{
140559191Skris	default:
1406109998Smarkm#ifndef OPENSSL_NO_TLS
1407238405Sjkim		/* TLS up to v1.1 just ignores unknown message types:
1408238405Sjkim		 * TLS v1.2 give an unexpected message alert.
1409238405Sjkim		 */
1410238405Sjkim		if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)
141155714Skris			{
1412100928Snectar			rr->length = 0;
141359191Skris			goto start;
141459191Skris			}
141555714Skris#endif
141659191Skris		al=SSL_AD_UNEXPECTED_MESSAGE;
141759191Skris		SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
141859191Skris		goto f_err;
141959191Skris	case SSL3_RT_CHANGE_CIPHER_SPEC:
142059191Skris	case SSL3_RT_ALERT:
142159191Skris	case SSL3_RT_HANDSHAKE:
142259191Skris		/* we already handled all of these, with the possible exception
142359191Skris		 * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
142459191Skris		 * should not happen when type != rr->type */
142559191Skris		al=SSL_AD_UNEXPECTED_MESSAGE;
1426109998Smarkm		SSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR);
142759191Skris		goto f_err;
142859191Skris	case SSL3_RT_APPLICATION_DATA:
142959191Skris		/* At this point, we were expecting handshake data,
143059191Skris		 * but have application data.  If the library was
143159191Skris		 * running inside ssl3_read() (i.e. in_read_app_data
143259191Skris		 * is set) and it makes sense to read application data
143359191Skris		 * at this point (session renegotiation not yet started),
143459191Skris		 * we will indulge it.
143559191Skris		 */
143659191Skris		if (s->s3->in_read_app_data &&
143759191Skris			(s->s3->total_renegotiations != 0) &&
143859191Skris			((
143959191Skris				(s->state & SSL_ST_CONNECT) &&
144059191Skris				(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
144159191Skris				(s->state <= SSL3_ST_CR_SRVR_HELLO_A)
144259191Skris				) || (
144359191Skris					(s->state & SSL_ST_ACCEPT) &&
144459191Skris					(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
144559191Skris					(s->state >= SSL3_ST_SR_CLNT_HELLO_A)
144659191Skris					)
144759191Skris				))
144859191Skris			{
1449100928Snectar			s->s3->in_read_app_data=2;
145059191Skris			return(-1);
145159191Skris			}
145259191Skris		else
145359191Skris			{
145455714Skris			al=SSL_AD_UNEXPECTED_MESSAGE;
145555714Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
145655714Skris			goto f_err;
145755714Skris			}
145855714Skris		}
145959191Skris	/* not reached */
146055714Skris
146155714Skrisf_err:
146255714Skris	ssl3_send_alert(s,SSL3_AL_FATAL,al);
146355714Skriserr:
146455714Skris	return(-1);
146555714Skris	}
146655714Skris
1467160814Ssimonint ssl3_do_change_cipher_spec(SSL *s)
146855714Skris	{
146955714Skris	int i;
147059191Skris	const char *sender;
147155714Skris	int slen;
147255714Skris
147355714Skris	if (s->state & SSL_ST_ACCEPT)
147455714Skris		i=SSL3_CHANGE_CIPHER_SERVER_READ;
147555714Skris	else
147655714Skris		i=SSL3_CHANGE_CIPHER_CLIENT_READ;
147755714Skris
147855714Skris	if (s->s3->tmp.key_block == NULL)
147955714Skris		{
1480267104Sdelphij		if (s->session == NULL || s->session->master_key_length == 0)
1481194206Ssimon			{
1482194206Ssimon			/* might happen if dtls1_read_bytes() calls this */
1483194206Ssimon			SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,SSL_R_CCS_RECEIVED_EARLY);
1484194206Ssimon			return (0);
1485194206Ssimon			}
1486194206Ssimon
148755714Skris		s->session->cipher=s->s3->tmp.new_cipher;
148855714Skris		if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
148955714Skris		}
149055714Skris
149155714Skris	if (!s->method->ssl3_enc->change_cipher_state(s,i))
149255714Skris		return(0);
149355714Skris
149455714Skris	/* we have to record the message digest at
149555714Skris	 * this point so we can get it before we read
149655714Skris	 * the finished message */
149755714Skris	if (s->state & SSL_ST_CONNECT)
149855714Skris		{
149959191Skris		sender=s->method->ssl3_enc->server_finished_label;
150059191Skris		slen=s->method->ssl3_enc->server_finished_label_len;
150155714Skris		}
150255714Skris	else
150355714Skris		{
150459191Skris		sender=s->method->ssl3_enc->client_finished_label;
150559191Skris		slen=s->method->ssl3_enc->client_finished_label_len;
150655714Skris		}
150755714Skris
1508279264Sdelphij	i = s->method->ssl3_enc->final_finish_mac(s,
150959191Skris		sender,slen,s->s3->tmp.peer_finish_md);
1510279264Sdelphij	if (i == 0)
1511279264Sdelphij		{
1512279264Sdelphij		SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
1513279264Sdelphij		return 0;
1514279264Sdelphij		}
1515279264Sdelphij	s->s3->tmp.peer_finish_md_len = i;
151655714Skris
151755714Skris	return(1);
151855714Skris	}
151955714Skris
1520205128Ssimonint ssl3_send_alert(SSL *s, int level, int desc)
152155714Skris	{
152255714Skris	/* Map tls/ssl alert value to correct one */
152355714Skris	desc=s->method->ssl3_enc->alert_value(desc);
152489837Skris	if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
152589837Skris		desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
1526205128Ssimon	if (desc < 0) return -1;
152755714Skris	/* If a fatal one, remove from cache */
152855714Skris	if ((level == 2) && (s->session != NULL))
152955714Skris		SSL_CTX_remove_session(s->ctx,s->session);
153055714Skris
153155714Skris	s->s3->alert_dispatch=1;
153255714Skris	s->s3->send_alert[0]=level;
153355714Skris	s->s3->send_alert[1]=desc;
153489837Skris	if (s->s3->wbuf.left == 0) /* data still being written out? */
1535205128Ssimon		return s->method->ssl_dispatch_alert(s);
153655714Skris	/* else data is still being written out, we will get written
153755714Skris	 * some time in the future */
1538205128Ssimon	return -1;
153955714Skris	}
154055714Skris
154155714Skrisint ssl3_dispatch_alert(SSL *s)
154255714Skris	{
154355714Skris	int i,j;
1544109998Smarkm	void (*cb)(const SSL *ssl,int type,int val)=NULL;
154555714Skris
154655714Skris	s->s3->alert_dispatch=0;
1547100928Snectar	i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
154855714Skris	if (i <= 0)
154955714Skris		{
155055714Skris		s->s3->alert_dispatch=1;
155155714Skris		}
155255714Skris	else
155355714Skris		{
155489837Skris		/* Alert sent to BIO.  If it is important, flush it now.
155589837Skris		 * If the message does not get sent due to non-blocking IO,
155689837Skris		 * we will not worry too much. */
155755714Skris		if (s->s3->send_alert[0] == SSL3_AL_FATAL)
155855714Skris			(void)BIO_flush(s->wbio);
155955714Skris
1560109998Smarkm		if (s->msg_callback)
1561109998Smarkm			s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
1562109998Smarkm
156355714Skris		if (s->info_callback != NULL)
156455714Skris			cb=s->info_callback;
156555714Skris		else if (s->ctx->info_callback != NULL)
156655714Skris			cb=s->ctx->info_callback;
156759191Skris
156855714Skris		if (cb != NULL)
156955714Skris			{
157055714Skris			j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
157155714Skris			cb(s,SSL_CB_WRITE_ALERT,j);
157255714Skris			}
157355714Skris		}
157455714Skris	return(i);
157555714Skris	}
1576