s3_pkt.c revision 265124
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>
11355714Skris#include <errno.h>
11455714Skris#define USE_SOCKETS
115109998Smarkm#include "ssl_locl.h"
11655714Skris#include <openssl/evp.h>
11755714Skris#include <openssl/buffer.h>
118238405Sjkim#include <openssl/rand.h>
11955714Skris
12055714Skrisstatic int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
121100928Snectar			 unsigned int len, int create_empty_fragment);
12255714Skrisstatic int ssl3_get_record(SSL *s);
12359191Skris
124160814Ssimonint ssl3_read_n(SSL *s, int n, int max, int extend)
12555714Skris	{
12659191Skris	/* If extend == 0, obtain new n-byte packet; if extend == 1, increase
12759191Skris	 * packet by another n bytes.
12859191Skris	 * The packet will be in the sub-array of s->s3->rbuf.buf specified
12959191Skris	 * by s->packet and s->packet_length.
13059191Skris	 * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
13159191Skris	 * [plus s->packet_length bytes if extend == 1].)
13259191Skris	 */
133238405Sjkim	int i,len,left;
134238405Sjkim	long align=0;
135238405Sjkim	unsigned char *pkt;
136238405Sjkim	SSL3_BUFFER *rb;
13755714Skris
138238405Sjkim	if (n <= 0) return n;
139238405Sjkim
140238405Sjkim	rb    = &(s->s3->rbuf);
141238405Sjkim	if (rb->buf == NULL)
142238405Sjkim		if (!ssl3_setup_read_buffer(s))
143238405Sjkim			return -1;
144238405Sjkim
145238405Sjkim	left  = rb->left;
146238405Sjkim#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
147238405Sjkim	align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
148238405Sjkim	align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
149238405Sjkim#endif
150238405Sjkim
15159191Skris	if (!extend)
15259191Skris		{
15359191Skris		/* start with empty packet ... */
154238405Sjkim		if (left == 0)
155238405Sjkim			rb->offset = align;
156238405Sjkim		else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
157238405Sjkim			{
158238405Sjkim			/* check if next packet length is large
159238405Sjkim			 * enough to justify payload alignment... */
160238405Sjkim			pkt = rb->buf + rb->offset;
161238405Sjkim			if (pkt[0] == SSL3_RT_APPLICATION_DATA
162238405Sjkim			    && (pkt[3]<<8|pkt[4]) >= 128)
163238405Sjkim				{
164238405Sjkim				/* Note that even if packet is corrupted
165238405Sjkim				 * and its length field is insane, we can
166238405Sjkim				 * only be led to wrong decision about
167238405Sjkim				 * whether memmove will occur or not.
168238405Sjkim				 * Header values has no effect on memmove
169238405Sjkim				 * arguments and therefore no buffer
170238405Sjkim				 * overrun can be triggered. */
171238405Sjkim				memmove (rb->buf+align,pkt,left);
172238405Sjkim				rb->offset = align;
173238405Sjkim				}
174238405Sjkim			}
175238405Sjkim		s->packet = rb->buf + rb->offset;
17659191Skris		s->packet_length = 0;
17759191Skris		/* ... now we can act as if 'extend' was set */
17859191Skris		}
17959191Skris
180205128Ssimon	/* For DTLS/UDP reads should not span multiple packets
181205128Ssimon	 * because the read operation returns the whole packet
182205128Ssimon	 * at once (as long as it fits into the buffer). */
183238405Sjkim	if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
184160814Ssimon		{
185238405Sjkim		if (left > 0 && n > left)
186238405Sjkim			n = left;
187160814Ssimon		}
188160814Ssimon
18959191Skris	/* if there is enough in the buffer from a previous read, take some */
190238405Sjkim	if (left >= n)
19155714Skris		{
19259191Skris		s->packet_length+=n;
193238405Sjkim		rb->left=left-n;
194238405Sjkim		rb->offset+=n;
19555714Skris		return(n);
19655714Skris		}
19755714Skris
19855714Skris	/* else we need to read more data */
19955714Skris
200238405Sjkim	len = s->packet_length;
201238405Sjkim	pkt = rb->buf+align;
202238405Sjkim	/* Move any available bytes to front of buffer:
203238405Sjkim	 * 'len' bytes already pointed to by 'packet',
204238405Sjkim	 * 'left' extra ones at the end */
205238405Sjkim	if (s->packet != pkt) /* len > 0 */
20655714Skris		{
207238405Sjkim		memmove(pkt, s->packet, len+left);
208238405Sjkim		s->packet = pkt;
209238405Sjkim		rb->offset = len + align;
210238405Sjkim		}
211238405Sjkim
212238405Sjkim	if (n > (int)(rb->len - rb->offset)) /* does not happen */
213238405Sjkim		{
214109998Smarkm		SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR);
21559191Skris		return -1;
21659191Skris		}
21755714Skris
218238405Sjkim	if (!s->read_ahead)
219238405Sjkim		/* ignore max parameter */
220238405Sjkim		max = n;
221238405Sjkim	else
22259191Skris		{
223238405Sjkim		if (max < n)
224238405Sjkim			max = n;
225238405Sjkim		if (max > (int)(rb->len - rb->offset))
226238405Sjkim			max = rb->len - rb->offset;
22755714Skris		}
22855714Skris
229238405Sjkim	while (left < n)
23055714Skris		{
231238405Sjkim		/* Now we have len+left bytes at the front of s->s3->rbuf.buf
232238405Sjkim		 * and need to read in more until we have len+n (up to
233238405Sjkim		 * len+max if possible) */
23459191Skris
23555714Skris		clear_sys_error();
23655714Skris		if (s->rbio != NULL)
23755714Skris			{
23855714Skris			s->rwstate=SSL_READING;
239238405Sjkim			i=BIO_read(s->rbio,pkt+len+left, max-left);
24055714Skris			}
24155714Skris		else
24255714Skris			{
24355714Skris			SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
24459191Skris			i = -1;
24555714Skris			}
24655714Skris
24755714Skris		if (i <= 0)
24855714Skris			{
249238405Sjkim			rb->left = left;
250238405Sjkim			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
251238405Sjkim			    SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
252238405Sjkim				if (len+left == 0)
253238405Sjkim					ssl3_release_read_buffer(s);
25455714Skris			return(i);
25555714Skris			}
256238405Sjkim		left+=i;
257205128Ssimon		/* reads should *never* span multiple packets for DTLS because
258205128Ssimon		 * the underlying transport protocol is message oriented as opposed
259205128Ssimon		 * to byte oriented as in the TLS case. */
260238405Sjkim		if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
261205128Ssimon			{
262238405Sjkim			if (n > left)
263238405Sjkim				n = left; /* makes the while condition false */
264205128Ssimon			}
26555714Skris		}
26655714Skris
26759191Skris	/* done reading, now the book-keeping */
268238405Sjkim	rb->offset += n;
269238405Sjkim	rb->left = left - n;
27059191Skris	s->packet_length += n;
27159191Skris	s->rwstate=SSL_NOTHING;
27255714Skris	return(n);
27355714Skris	}
27455714Skris
27555714Skris/* Call this to get a new input record.
27655714Skris * It will return <= 0 if more data is needed, normally due to an error
27755714Skris * or non-blocking IO.
27855714Skris * When it finishes, one packet has been decoded and can be found in
27959191Skris * ssl->s3->rrec.type    - is the type of record
28059191Skris * ssl->s3->rrec.data, 	 - data
28155714Skris * ssl->s3->rrec.length, - number of bytes
28255714Skris */
28359191Skris/* used only by ssl3_read_bytes */
28455714Skrisstatic int ssl3_get_record(SSL *s)
28555714Skris	{
28655714Skris	int ssl_major,ssl_minor,al;
28789837Skris	int enc_err,n,i,ret= -1;
28855714Skris	SSL3_RECORD *rr;
28955714Skris	SSL_SESSION *sess;
29055714Skris	unsigned char *p;
29155714Skris	unsigned char md[EVP_MAX_MD_SIZE];
29255714Skris	short version;
293246772Sjkim	unsigned mac_size, orig_len;
294100928Snectar	size_t extra;
29555714Skris
29655714Skris	rr= &(s->s3->rrec);
29755714Skris	sess=s->session;
29855714Skris
29955714Skris	if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
30055714Skris		extra=SSL3_RT_MAX_EXTRA;
30155714Skris	else
30255714Skris		extra=0;
303238405Sjkim	if (extra && !s->s3->init_extra)
304100928Snectar		{
305238405Sjkim		/* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER
306100928Snectar		 * set after ssl3_setup_buffers() was done */
307109998Smarkm		SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
308100928Snectar		return -1;
309100928Snectar		}
31055714Skris
31155714Skrisagain:
31255714Skris	/* check if we have the header */
31355714Skris	if (	(s->rstate != SSL_ST_READ_BODY) ||
31455714Skris		(s->packet_length < SSL3_RT_HEADER_LENGTH))
31555714Skris		{
316109998Smarkm		n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
31755714Skris		if (n <= 0) return(n); /* error or non-blocking */
31855714Skris		s->rstate=SSL_ST_READ_BODY;
31955714Skris
32055714Skris		p=s->packet;
32155714Skris
32255714Skris		/* Pull apart the header into the SSL3_RECORD */
32355714Skris		rr->type= *(p++);
32455714Skris		ssl_major= *(p++);
32555714Skris		ssl_minor= *(p++);
32655714Skris		version=(ssl_major<<8)|ssl_minor;
32755714Skris		n2s(p,rr->length);
328238405Sjkim#if 0
329238405Sjkimfprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
330238405Sjkim#endif
33155714Skris
33255714Skris		/* Lets check version */
333167612Ssimon		if (!s->first_packet)
33455714Skris			{
33555714Skris			if (version != s->version)
33655714Skris				{
33755714Skris				SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
338206046Ssimon                                if ((s->version & 0xFF00) == (version & 0xFF00))
339206046Ssimon                                	/* Send back error using their minor version number :-) */
340206046Ssimon					s->version = (unsigned short)version;
34155714Skris				al=SSL_AD_PROTOCOL_VERSION;
34255714Skris				goto f_err;
34355714Skris				}
34455714Skris			}
34555714Skris
34655714Skris		if ((version>>8) != SSL3_VERSION_MAJOR)
34755714Skris			{
34855714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
34955714Skris			goto err;
35055714Skris			}
35155714Skris
352238405Sjkim		if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)
35355714Skris			{
35455714Skris			al=SSL_AD_RECORD_OVERFLOW;
35555714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
35655714Skris			goto f_err;
35755714Skris			}
35855714Skris
35959191Skris		/* now s->rstate == SSL_ST_READ_BODY */
36055714Skris		}
36155714Skris
36259191Skris	/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
36359191Skris
364100928Snectar	if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)
36555714Skris		{
36659191Skris		/* now s->packet_length == SSL3_RT_HEADER_LENGTH */
36759191Skris		i=rr->length;
36859191Skris		n=ssl3_read_n(s,i,i,1);
36959191Skris		if (n <= 0) return(n); /* error or non-blocking io */
37059191Skris		/* now n == rr->length,
37159191Skris		 * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
37255714Skris		}
37355714Skris
37459191Skris	s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
37555714Skris
37659191Skris	/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
37759191Skris	 * and we have that many bytes in s->packet
37859191Skris	 */
37955714Skris	rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
38055714Skris
38155714Skris	/* ok, we can now read from 's->packet' data into 'rr'
38255714Skris	 * rr->input points at rr->length bytes, which
38355714Skris	 * need to be copied into rr->data by either
38455714Skris	 * the decryption or by the decompression
38555714Skris	 * When the data is 'copied' into the rr->data buffer,
38655714Skris	 * rr->input will be pointed at the new buffer */
38755714Skris
38855714Skris	/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
38955714Skris	 * rr->length bytes of encrypted compressed stuff. */
39055714Skris
39159191Skris	/* check is not needed I believe */
392100928Snectar	if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
39355714Skris		{
39455714Skris		al=SSL_AD_RECORD_OVERFLOW;
39555714Skris		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
39655714Skris		goto f_err;
39755714Skris		}
39855714Skris
39955714Skris	/* decrypt in place in 'rr->input' */
40055714Skris	rr->data=rr->input;
40155714Skris
40289837Skris	enc_err = s->method->ssl3_enc->enc(s,0);
403246772Sjkim	/* enc_err is:
404246772Sjkim	 *    0: (in non-constant time) if the record is publically invalid.
405246772Sjkim	 *    1: if the padding is valid
406246772Sjkim	 *    -1: if the padding is invalid */
407246772Sjkim	if (enc_err == 0)
40855714Skris		{
409246772Sjkim		al=SSL_AD_DECRYPTION_FAILED;
410246772Sjkim		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
411246772Sjkim		goto f_err;
41255714Skris		}
41389837Skris
41455714Skris#ifdef TLS_DEBUG
41555714Skrisprintf("dec %d\n",rr->length);
41655714Skris{ unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
41755714Skrisprintf("\n");
41855714Skris#endif
41989837Skris
42055714Skris	/* r->length is now the compressed data plus mac */
421246772Sjkim	if ((sess != NULL) &&
422246772Sjkim	    (s->enc_read_ctx != NULL) &&
423246772Sjkim	    (EVP_MD_CTX_md(s->read_hash) != NULL))
42455714Skris		{
425246772Sjkim		/* s->read_hash != NULL => mac_size != -1 */
426246772Sjkim		unsigned char *mac = NULL;
427246772Sjkim		unsigned char mac_tmp[EVP_MAX_MD_SIZE];
428238405Sjkim		mac_size=EVP_MD_CTX_size(s->read_hash);
429246772Sjkim		OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
43055714Skris
431246772Sjkim		/* kludge: *_cbc_remove_padding passes padding length in rr->type */
432246772Sjkim		orig_len = rr->length+((unsigned int)rr->type>>8);
433246772Sjkim
434246772Sjkim		/* orig_len is the length of the record before any padding was
435246772Sjkim		 * removed. This is public information, as is the MAC in use,
436246772Sjkim		 * therefore we can safely process the record in a different
437246772Sjkim		 * amount of time if it's too short to possibly contain a MAC.
438246772Sjkim		 */
439246772Sjkim		if (orig_len < mac_size ||
440246772Sjkim		    /* CBC records must have a padding length byte too. */
441246772Sjkim		    (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
442246772Sjkim		     orig_len < mac_size+1))
44355714Skris			{
444246772Sjkim			al=SSL_AD_DECODE_ERROR;
445246772Sjkim			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);
44655714Skris			goto f_err;
44755714Skris			}
448246772Sjkim
449246772Sjkim		if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
45055714Skris			{
451246772Sjkim			/* We update the length so that the TLS header bytes
452246772Sjkim			 * can be constructed correctly but we need to extract
453246772Sjkim			 * the MAC in constant time from within the record,
454246772Sjkim			 * without leaking the contents of the padding bytes.
455246772Sjkim			 * */
456246772Sjkim			mac = mac_tmp;
457246772Sjkim			ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
458111147Snectar			rr->length -= mac_size;
459111147Snectar			}
460111147Snectar		else
461111147Snectar			{
462246772Sjkim			/* In this case there's no padding, so |orig_len|
463246772Sjkim			 * equals |rec->length| and we checked that there's
464246772Sjkim			 * enough bytes for |mac_size| above. */
465246772Sjkim			rr->length -= mac_size;
466246772Sjkim			mac = &rr->data[rr->length];
46755714Skris			}
468246772Sjkim
469246772Sjkim		i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
470246772Sjkim		if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
471246772Sjkim			enc_err = -1;
472246772Sjkim		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
473246772Sjkim			enc_err = -1;
47455714Skris		}
47555714Skris
476246772Sjkim	if (enc_err < 0)
477111147Snectar		{
478111147Snectar		/* A separate 'decryption_failed' alert was introduced with TLS 1.0,
479111147Snectar		 * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
480111147Snectar		 * failure is directly visible from the ciphertext anyway,
481111147Snectar		 * we should not reveal which kind of error occured -- this
482111147Snectar		 * might become visible to an attacker (e.g. via a logfile) */
483111147Snectar		al=SSL_AD_BAD_RECORD_MAC;
484111147Snectar		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
485111147Snectar		goto f_err;
486111147Snectar		}
487111147Snectar
48855714Skris	/* r->length is now just compressed */
48955714Skris	if (s->expand != NULL)
49055714Skris		{
491100928Snectar		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)
49255714Skris			{
49355714Skris			al=SSL_AD_RECORD_OVERFLOW;
49455714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
49555714Skris			goto f_err;
49655714Skris			}
497160814Ssimon		if (!ssl3_do_uncompress(s))
49855714Skris			{
49955714Skris			al=SSL_AD_DECOMPRESSION_FAILURE;
50055714Skris			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);
50155714Skris			goto f_err;
50255714Skris			}
50355714Skris		}
50455714Skris
505100928Snectar	if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)
50655714Skris		{
50755714Skris		al=SSL_AD_RECORD_OVERFLOW;
50855714Skris		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
50955714Skris		goto f_err;
51055714Skris		}
51155714Skris
51255714Skris	rr->off=0;
51355714Skris	/* So at this point the following is true
51455714Skris	 * ssl->s3->rrec.type 	is the type of record
51555714Skris	 * ssl->s3->rrec.length	== number of bytes in record
51655714Skris	 * ssl->s3->rrec.off	== offset to first valid byte
51755714Skris	 * ssl->s3->rrec.data	== where to take bytes from, increment
51855714Skris	 *			   after use :-).
51955714Skris	 */
52055714Skris
52155714Skris	/* we have pulled in a full packet so zero things */
52255714Skris	s->packet_length=0;
52355714Skris
52455714Skris	/* just read a 0 length packet */
52555714Skris	if (rr->length == 0) goto again;
52655714Skris
527238405Sjkim#if 0
528238405Sjkimfprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length);
529238405Sjkim#endif
530238405Sjkim
53155714Skris	return(1);
53289837Skris
53355714Skrisf_err:
53455714Skris	ssl3_send_alert(s,SSL3_AL_FATAL,al);
53555714Skriserr:
53655714Skris	return(ret);
53755714Skris	}
53855714Skris
539160814Ssimonint ssl3_do_uncompress(SSL *ssl)
54055714Skris	{
541160814Ssimon#ifndef OPENSSL_NO_COMP
54255714Skris	int i;
54355714Skris	SSL3_RECORD *rr;
54455714Skris
54555714Skris	rr= &(ssl->s3->rrec);
54655714Skris	i=COMP_expand_block(ssl->expand,rr->comp,
54755714Skris		SSL3_RT_MAX_PLAIN_LENGTH,rr->data,(int)rr->length);
54855714Skris	if (i < 0)
54955714Skris		return(0);
55055714Skris	else
55155714Skris		rr->length=i;
55255714Skris	rr->data=rr->comp;
553160814Ssimon#endif
55455714Skris	return(1);
55555714Skris	}
55655714Skris
557160814Ssimonint ssl3_do_compress(SSL *ssl)
55855714Skris	{
559160814Ssimon#ifndef OPENSSL_NO_COMP
56055714Skris	int i;
56155714Skris	SSL3_RECORD *wr;
56255714Skris
56355714Skris	wr= &(ssl->s3->wrec);
56455714Skris	i=COMP_compress_block(ssl->compress,wr->data,
56555714Skris		SSL3_RT_MAX_COMPRESSED_LENGTH,
56655714Skris		wr->input,(int)wr->length);
56755714Skris	if (i < 0)
56855714Skris		return(0);
56955714Skris	else
57055714Skris		wr->length=i;
57155714Skris
57255714Skris	wr->input=wr->data;
573160814Ssimon#endif
57455714Skris	return(1);
57555714Skris	}
57655714Skris
57759191Skris/* Call this to write data in records of type 'type'
57855714Skris * It will return <= 0 if not all data has been sent or non-blocking IO.
57955714Skris */
58059191Skrisint ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
58155714Skris	{
58259191Skris	const unsigned char *buf=buf_;
58355714Skris	unsigned int tot,n,nw;
58455714Skris	int i;
58555714Skris
58655714Skris	s->rwstate=SSL_NOTHING;
58755714Skris	tot=s->s3->wnum;
58855714Skris	s->s3->wnum=0;
58955714Skris
59055714Skris	if (SSL_in_init(s) && !s->in_handshake)
59155714Skris		{
59255714Skris		i=s->handshake_func(s);
59355714Skris		if (i < 0) return(i);
59455714Skris		if (i == 0)
59555714Skris			{
59655714Skris			SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
597100928Snectar			return -1;
59855714Skris			}
59955714Skris		}
60055714Skris
60155714Skris	n=(len-tot);
60255714Skris	for (;;)
60355714Skris		{
604238405Sjkim		if (n > s->max_send_fragment)
605238405Sjkim			nw=s->max_send_fragment;
60655714Skris		else
60755714Skris			nw=n;
60859191Skris
609100928Snectar		i=do_ssl3_write(s, type, &(buf[tot]), nw, 0);
61055714Skris		if (i <= 0)
61155714Skris			{
61255714Skris			s->s3->wnum=tot;
613100928Snectar			return i;
61455714Skris			}
61555714Skris
61655714Skris		if ((i == (int)n) ||
61755714Skris			(type == SSL3_RT_APPLICATION_DATA &&
61855714Skris			 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
61955714Skris			{
620100928Snectar			/* next chunk of data should get another prepended empty fragment
621100928Snectar			 * in ciphersuites with known-IV weakness: */
622100928Snectar			s->s3->empty_fragment_done = 0;
623100928Snectar
624100928Snectar			return tot+i;
62555714Skris			}
62655714Skris
62755714Skris		n-=i;
62855714Skris		tot+=i;
62955714Skris		}
63055714Skris	}
63155714Skris
63255714Skrisstatic int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
633100928Snectar			 unsigned int len, int create_empty_fragment)
63455714Skris	{
63555714Skris	unsigned char *p,*plen;
63655714Skris	int i,mac_size,clear=0;
637238405Sjkim	int prefix_len=0;
638238405Sjkim	int eivlen;
639238405Sjkim	long align=0;
64055714Skris	SSL3_RECORD *wr;
641238405Sjkim	SSL3_BUFFER *wb=&(s->s3->wbuf);
64255714Skris	SSL_SESSION *sess;
64355714Skris
644238405Sjkim 	if (wb->buf == NULL)
645238405Sjkim		if (!ssl3_setup_write_buffer(s))
646238405Sjkim			return -1;
647238405Sjkim
648100928Snectar	/* first check if there is a SSL3_BUFFER still being written
64955714Skris	 * out.  This will happen with non blocking IO */
650238405Sjkim	if (wb->left != 0)
65155714Skris		return(ssl3_write_pending(s,type,buf,len));
65255714Skris
65355714Skris	/* If we have an alert to send, lets send it */
65455714Skris	if (s->s3->alert_dispatch)
65555714Skris		{
656160814Ssimon		i=s->method->ssl_dispatch_alert(s);
65755714Skris		if (i <= 0)
65855714Skris			return(i);
65955714Skris		/* if it went, fall through and send more stuff */
66055714Skris		}
66155714Skris
662100928Snectar	if (len == 0 && !create_empty_fragment)
663100928Snectar		return 0;
66459191Skris
66555714Skris	wr= &(s->s3->wrec);
66655714Skris	sess=s->session;
66755714Skris
66855714Skris	if (	(sess == NULL) ||
66955714Skris		(s->enc_write_ctx == NULL) ||
670238405Sjkim		(EVP_MD_CTX_md(s->write_hash) == NULL))
671238405Sjkim		{
672238405Sjkim#if 1
673238405Sjkim		clear=s->enc_write_ctx?0:1;	/* must be AEAD cipher */
674238405Sjkim#else
67555714Skris		clear=1;
676238405Sjkim#endif
67755714Skris		mac_size=0;
678238405Sjkim		}
67955714Skris	else
680238405Sjkim		{
681238405Sjkim		mac_size=EVP_MD_CTX_size(s->write_hash);
682238405Sjkim		if (mac_size < 0)
683238405Sjkim			goto err;
684238405Sjkim		}
68555714Skris
686100928Snectar	/* 'create_empty_fragment' is true only when this function calls itself */
687100928Snectar	if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done)
688100928Snectar		{
689100928Snectar		/* countermeasure against known-IV weakness in CBC ciphersuites
690100928Snectar		 * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
69155714Skris
692100928Snectar		if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
693100928Snectar			{
694100928Snectar			/* recursive function call with 'create_empty_fragment' set;
695100928Snectar			 * this prepares and buffers the data for an empty fragment
696100928Snectar			 * (these 'prefix_len' bytes are sent out later
697100928Snectar			 * together with the actual payload) */
698100928Snectar			prefix_len = do_ssl3_write(s, type, buf, 0, 1);
699100928Snectar			if (prefix_len <= 0)
700100928Snectar				goto err;
701100928Snectar
702238405Sjkim			if (prefix_len >
703238405Sjkim		(SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
704100928Snectar				{
705100928Snectar				/* insufficient space */
706109998Smarkm				SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
707100928Snectar				goto err;
708100928Snectar				}
709100928Snectar			}
710100928Snectar
711100928Snectar		s->s3->empty_fragment_done = 1;
712100928Snectar		}
713100928Snectar
714238405Sjkim	if (create_empty_fragment)
715238405Sjkim		{
716238405Sjkim#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
717238405Sjkim		/* extra fragment would be couple of cipher blocks,
718238405Sjkim		 * which would be multiple of SSL3_ALIGN_PAYLOAD, so
719238405Sjkim		 * if we want to align the real payload, then we can
720238405Sjkim		 * just pretent we simply have two headers. */
721238405Sjkim		align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH;
722238405Sjkim		align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
723238405Sjkim#endif
724238405Sjkim		p = wb->buf + align;
725238405Sjkim		wb->offset  = align;
726238405Sjkim		}
727238405Sjkim	else if (prefix_len)
728238405Sjkim		{
729238405Sjkim		p = wb->buf + wb->offset + prefix_len;
730238405Sjkim		}
731238405Sjkim	else
732238405Sjkim		{
733238405Sjkim#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
734238405Sjkim		align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
735238405Sjkim		align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
736238405Sjkim#endif
737238405Sjkim		p = wb->buf + align;
738238405Sjkim		wb->offset  = align;
739238405Sjkim		}
740100928Snectar
74155714Skris	/* write the header */
742100928Snectar
74355714Skris	*(p++)=type&0xff;
74455714Skris	wr->type=type;
74555714Skris
74655714Skris	*(p++)=(s->version>>8);
747238405Sjkim	/* Some servers hang if iniatial client hello is larger than 256
748238405Sjkim	 * bytes and record version number > TLS 1.0
749238405Sjkim	 */
750238405Sjkim	if (s->state == SSL3_ST_CW_CLNT_HELLO_B
751246772Sjkim				&& !s->renegotiate
752238405Sjkim				&& TLS1_get_version(s) > TLS1_VERSION)
753238405Sjkim		*(p++) = 0x1;
754238405Sjkim	else
755238405Sjkim		*(p++)=s->version&0xff;
75659191Skris
757100928Snectar	/* field where we are to write out packet length */
75855714Skris	plen=p;
75955714Skris	p+=2;
760238405Sjkim	/* Explicit IV length, block ciphers and TLS version 1.1 or later */
761238405Sjkim	if (s->enc_write_ctx && s->version >= TLS1_1_VERSION)
762238405Sjkim		{
763238405Sjkim		int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
764238405Sjkim		if (mode == EVP_CIPH_CBC_MODE)
765238405Sjkim			{
766238405Sjkim			eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
767238405Sjkim			if (eivlen <= 1)
768238405Sjkim				eivlen = 0;
769238405Sjkim			}
770238405Sjkim		/* Need explicit part of IV for GCM mode */
771238405Sjkim		else if (mode == EVP_CIPH_GCM_MODE)
772238405Sjkim			eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
773238405Sjkim		else
774238405Sjkim			eivlen = 0;
775238405Sjkim		}
776238405Sjkim	else
777238405Sjkim		eivlen = 0;
77859191Skris
77955714Skris	/* lets setup the record stuff. */
780238405Sjkim	wr->data=p + eivlen;
78155714Skris	wr->length=(int)len;
78255714Skris	wr->input=(unsigned char *)buf;
78355714Skris
78455714Skris	/* we now 'read' from wr->input, wr->length bytes into
78555714Skris	 * wr->data */
78655714Skris
78755714Skris	/* first we compress */
78855714Skris	if (s->compress != NULL)
78955714Skris		{
790160814Ssimon		if (!ssl3_do_compress(s))
79155714Skris			{
79255714Skris			SSLerr(SSL_F_DO_SSL3_WRITE,SSL_R_COMPRESSION_FAILURE);
79355714Skris			goto err;
79455714Skris			}
79555714Skris		}
79655714Skris	else
79755714Skris		{
79855714Skris		memcpy(wr->data,wr->input,wr->length);
79955714Skris		wr->input=wr->data;
80055714Skris		}
80155714Skris
80255714Skris	/* we should still have the output to wr->data and the input
80355714Skris	 * from wr->input.  Length should be wr->length.
80455714Skris	 * wr->data still points in the wb->buf */
80555714Skris
80655714Skris	if (mac_size != 0)
80755714Skris		{
808238405Sjkim		if (s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
809238405Sjkim			goto err;
81055714Skris		wr->length+=mac_size;
81155714Skris		}
81255714Skris
813238405Sjkim	wr->input=p;
814238405Sjkim	wr->data=p;
815238405Sjkim
816238405Sjkim	if (eivlen)
817238405Sjkim		{
818238405Sjkim	/*	if (RAND_pseudo_bytes(p, eivlen) <= 0)
819238405Sjkim			goto err; */
820238405Sjkim		wr->length += eivlen;
821238405Sjkim		}
822238405Sjkim
82355714Skris	/* ssl3_enc can only have an error on read */
82455714Skris	s->method->ssl3_enc->enc(s,1);
82555714Skris
82655714Skris	/* record length after mac and block padding */
82755714Skris	s2n(wr->length,plen);
82855714Skris
82955714Skris	/* we should now have
83055714Skris	 * wr->data pointing to the encrypted data, which is
83155714Skris	 * wr->length long */
83255714Skris	wr->type=type; /* not needed but helps for debugging */
83355714Skris	wr->length+=SSL3_RT_HEADER_LENGTH;
83455714Skris
835100928Snectar	if (create_empty_fragment)
836100928Snectar		{
837100928Snectar		/* we are in a recursive call;
838100928Snectar		 * just return the length, don't write out anything here
839100928Snectar		 */
840100928Snectar		return wr->length;
841100928Snectar		}
84255714Skris
843100928Snectar	/* now let's set up wb */
844100928Snectar	wb->left = prefix_len + wr->length;
845100928Snectar
846100928Snectar	/* memorize arguments so that ssl3_write_pending can detect bad write retries later */
84755714Skris	s->s3->wpend_tot=len;
84855714Skris	s->s3->wpend_buf=buf;
84955714Skris	s->s3->wpend_type=type;
85055714Skris	s->s3->wpend_ret=len;
85155714Skris
85255714Skris	/* we now just need to write the buffer */
853100928Snectar	return ssl3_write_pending(s,type,buf,len);
85455714Skriserr:
855100928Snectar	return -1;
85655714Skris	}
85755714Skris
85855714Skris/* if s->s3->wbuf.left != 0, we need to call this */
859160814Ssimonint ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
860160814Ssimon	unsigned int len)
86155714Skris	{
86255714Skris	int i;
863238405Sjkim	SSL3_BUFFER *wb=&(s->s3->wbuf);
86455714Skris
86555714Skris/* XXXX */
86655714Skris	if ((s->s3->wpend_tot > (int)len)
86755714Skris		|| ((s->s3->wpend_buf != buf) &&
86855714Skris			!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
86955714Skris		|| (s->s3->wpend_type != type))
87055714Skris		{
87155714Skris		SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY);
87255714Skris		return(-1);
87355714Skris		}
87455714Skris
87555714Skris	for (;;)
87655714Skris		{
87755714Skris		clear_sys_error();
87855714Skris		if (s->wbio != NULL)
87955714Skris			{
88055714Skris			s->rwstate=SSL_WRITING;
88155714Skris			i=BIO_write(s->wbio,
882238405Sjkim				(char *)&(wb->buf[wb->offset]),
883238405Sjkim				(unsigned int)wb->left);
88455714Skris			}
88555714Skris		else
88655714Skris			{
88755714Skris			SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BIO_NOT_SET);
88855714Skris			i= -1;
88955714Skris			}
890238405Sjkim		if (i == wb->left)
89155714Skris			{
892238405Sjkim			wb->left=0;
893238405Sjkim			wb->offset+=i;
894238405Sjkim			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
895238405Sjkim			    SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
896238405Sjkim				ssl3_release_write_buffer(s);
89755714Skris			s->rwstate=SSL_NOTHING;
89855714Skris			return(s->s3->wpend_ret);
89955714Skris			}
900194206Ssimon		else if (i <= 0) {
901194206Ssimon			if (s->version == DTLS1_VERSION ||
902194206Ssimon			    s->version == DTLS1_BAD_VER) {
903194206Ssimon				/* For DTLS, just drop it. That's kind of the whole
904194206Ssimon				   point in using a datagram service */
905238405Sjkim				wb->left = 0;
906194206Ssimon			}
90755714Skris			return(i);
908194206Ssimon		}
909238405Sjkim		wb->offset+=i;
910238405Sjkim		wb->left-=i;
91155714Skris		}
91255714Skris	}
91355714Skris
91459191Skris/* Return up to 'len' payload bytes received in 'type' records.
91559191Skris * 'type' is one of the following:
91659191Skris *
91759191Skris *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
91859191Skris *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
91959191Skris *   -  0 (during a shutdown, no data has to be returned)
92059191Skris *
92159191Skris * If we don't have stored data to work from, read a SSL/TLS record first
92259191Skris * (possibly multiple records if we still don't have anything to return).
92359191Skris *
92459191Skris * This function must handle any surprises the peer may have for us, such as
92559191Skris * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
92659191Skris * a surprise, but handled as if it were), or renegotiation requests.
92759191Skris * Also if record payloads contain fragments too small to process, we store
92859191Skris * them until there is enough for the respective protocol (the record protocol
92959191Skris * may use arbitrary fragmentation and even interleaving):
93059191Skris *     Change cipher spec protocol
93159191Skris *             just 1 byte needed, no need for keeping anything stored
93259191Skris *     Alert protocol
93359191Skris *             2 bytes needed (AlertLevel, AlertDescription)
93459191Skris *     Handshake protocol
93559191Skris *             4 bytes needed (HandshakeType, uint24 length) -- we just have
93659191Skris *             to detect unexpected Client Hello and Hello Request messages
93759191Skris *             here, anything else is handled by higher layers
93859191Skris *     Application data protocol
93959191Skris *             none of our business
94059191Skris */
94172613Skrisint ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
94255714Skris	{
94359191Skris	int al,i,j,ret;
94459191Skris	unsigned int n;
94555714Skris	SSL3_RECORD *rr;
946109998Smarkm	void (*cb)(const SSL *ssl,int type2,int val)=NULL;
94755714Skris
94859191Skris	if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
949238405Sjkim		if (!ssl3_setup_read_buffer(s))
95055714Skris			return(-1);
95155714Skris
95272613Skris	if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) ||
95372613Skris	    (peek && (type != SSL3_RT_APPLICATION_DATA)))
95459191Skris		{
955109998Smarkm		SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
95659191Skris		return -1;
95759191Skris		}
95859191Skris
95959191Skris	if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
96059191Skris		/* (partially) satisfy request from storage */
96159191Skris		{
96259191Skris		unsigned char *src = s->s3->handshake_fragment;
96359191Skris		unsigned char *dst = buf;
96459191Skris		unsigned int k;
96559191Skris
96672613Skris		/* peek == 0 */
96759191Skris		n = 0;
96859191Skris		while ((len > 0) && (s->s3->handshake_fragment_len > 0))
96959191Skris			{
97059191Skris			*dst++ = *src++;
97159191Skris			len--; s->s3->handshake_fragment_len--;
97259191Skris			n++;
97359191Skris			}
97459191Skris		/* move any remaining fragment bytes: */
97559191Skris		for (k = 0; k < s->s3->handshake_fragment_len; k++)
97659191Skris			s->s3->handshake_fragment[k] = *src++;
97759191Skris		return n;
97859191Skris	}
97959191Skris
98059191Skris	/* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
98159191Skris
98255714Skris	if (!s->in_handshake && SSL_in_init(s))
98355714Skris		{
98459191Skris		/* type == SSL3_RT_APPLICATION_DATA */
98555714Skris		i=s->handshake_func(s);
98655714Skris		if (i < 0) return(i);
98755714Skris		if (i == 0)
98855714Skris			{
98955714Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
99055714Skris			return(-1);
99155714Skris			}
99255714Skris		}
99355714Skrisstart:
99455714Skris	s->rwstate=SSL_NOTHING;
99555714Skris
99659191Skris	/* s->s3->rrec.type	    - is the type of record
99759191Skris	 * s->s3->rrec.data,    - data
99859191Skris	 * s->s3->rrec.off,     - offset into 'data' for next read
99959191Skris	 * s->s3->rrec.length,  - number of bytes. */
100059191Skris	rr = &(s->s3->rrec);
100155714Skris
100272613Skris	/* get new packet if necessary */
100355714Skris	if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
100455714Skris		{
100555714Skris		ret=ssl3_get_record(s);
100655714Skris		if (ret <= 0) return(ret);
100755714Skris		}
100855714Skris
100955714Skris	/* we now have a packet which can be read and processed */
101055714Skris
101159191Skris	if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
101259191Skris	                               * reset by ssl3_get_finished */
101359191Skris		&& (rr->type != SSL3_RT_HANDSHAKE))
101455714Skris		{
101555714Skris		al=SSL_AD_UNEXPECTED_MESSAGE;
101655714Skris		SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1017142425Snectar		goto f_err;
101855714Skris		}
101955714Skris
102072613Skris	/* If the other end has shut down, throw anything we read away
102172613Skris	 * (even in 'peek' mode) */
102255714Skris	if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
102355714Skris		{
102455714Skris		rr->length=0;
102555714Skris		s->rwstate=SSL_NOTHING;
102655714Skris		return(0);
102755714Skris		}
102855714Skris
102959191Skris
103059191Skris	if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
103159191Skris		{
103259191Skris		/* make sure that we are not getting application data when we
103359191Skris		 * are doing a handshake for the first time */
103459191Skris		if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
103559191Skris			(s->enc_read_ctx == NULL))
103659191Skris			{
103759191Skris			al=SSL_AD_UNEXPECTED_MESSAGE;
103859191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
103959191Skris			goto f_err;
104059191Skris			}
104159191Skris
104259191Skris		if (len <= 0) return(len);
104359191Skris
104459191Skris		if ((unsigned int)len > rr->length)
104559191Skris			n = rr->length;
104659191Skris		else
104759191Skris			n = (unsigned int)len;
104859191Skris
104959191Skris		memcpy(buf,&(rr->data[rr->off]),n);
105072613Skris		if (!peek)
105159191Skris			{
105272613Skris			rr->length-=n;
105372613Skris			rr->off+=n;
105472613Skris			if (rr->length == 0)
105572613Skris				{
105672613Skris				s->rstate=SSL_ST_READ_HEADER;
105772613Skris				rr->off=0;
1058265124Sdelphij				if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)
1059238405Sjkim					ssl3_release_read_buffer(s);
106072613Skris				}
106159191Skris			}
106259191Skris		return(n);
106359191Skris		}
106459191Skris
106559191Skris
106659191Skris	/* If we get here, then type != rr->type; if we have a handshake
106759191Skris	 * message, then it was unexpected (Hello Request or Client Hello). */
106859191Skris
106959191Skris	/* In case of record types for which we have 'fragment' storage,
107059191Skris	 * fill that so that we can process the data at a fixed place.
107159191Skris	 */
107259191Skris		{
107359191Skris		unsigned int dest_maxlen = 0;
107459191Skris		unsigned char *dest = NULL;
107559191Skris		unsigned int *dest_len = NULL;
107659191Skris
107759191Skris		if (rr->type == SSL3_RT_HANDSHAKE)
107859191Skris			{
107959191Skris			dest_maxlen = sizeof s->s3->handshake_fragment;
108059191Skris			dest = s->s3->handshake_fragment;
108159191Skris			dest_len = &s->s3->handshake_fragment_len;
108259191Skris			}
108359191Skris		else if (rr->type == SSL3_RT_ALERT)
108459191Skris			{
108559191Skris			dest_maxlen = sizeof s->s3->alert_fragment;
108659191Skris			dest = s->s3->alert_fragment;
108759191Skris			dest_len = &s->s3->alert_fragment_len;
108859191Skris			}
1089238405Sjkim#ifndef OPENSSL_NO_HEARTBEATS
1090238405Sjkim		else if (rr->type == TLS1_RT_HEARTBEAT)
1091238405Sjkim			{
1092238405Sjkim			tls1_process_heartbeat(s);
109359191Skris
1094238405Sjkim			/* Exit and notify application to read again */
1095238405Sjkim			rr->length = 0;
1096238405Sjkim			s->rwstate=SSL_READING;
1097238405Sjkim			BIO_clear_retry_flags(SSL_get_rbio(s));
1098238405Sjkim			BIO_set_retry_read(SSL_get_rbio(s));
1099238405Sjkim			return(-1);
1100238405Sjkim			}
1101238405Sjkim#endif
1102238405Sjkim
110359191Skris		if (dest_maxlen > 0)
110459191Skris			{
110559191Skris			n = dest_maxlen - *dest_len; /* available space in 'dest' */
110659191Skris			if (rr->length < n)
110759191Skris				n = rr->length; /* available bytes */
110859191Skris
110959191Skris			/* now move 'n' bytes: */
111059191Skris			while (n-- > 0)
111159191Skris				{
111259191Skris				dest[(*dest_len)++] = rr->data[rr->off++];
111359191Skris				rr->length--;
111459191Skris				}
111559191Skris
111659191Skris			if (*dest_len < dest_maxlen)
111759191Skris				goto start; /* fragment was too small */
111859191Skris			}
111959191Skris		}
112059191Skris
112159191Skris	/* s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
112259191Skris	 * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
112359191Skris	 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
112459191Skris
112559191Skris	/* If we are a client, check for an incoming 'Hello Request': */
112659191Skris	if ((!s->server) &&
112759191Skris		(s->s3->handshake_fragment_len >= 4) &&
112859191Skris		(s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
112955714Skris		(s->session != NULL) && (s->session->cipher != NULL))
113055714Skris		{
113159191Skris		s->s3->handshake_fragment_len = 0;
113259191Skris
113359191Skris		if ((s->s3->handshake_fragment[1] != 0) ||
113459191Skris			(s->s3->handshake_fragment[2] != 0) ||
113559191Skris			(s->s3->handshake_fragment[3] != 0))
113655714Skris			{
113755714Skris			al=SSL_AD_DECODE_ERROR;
113859191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
1139142425Snectar			goto f_err;
114055714Skris			}
114155714Skris
1142109998Smarkm		if (s->msg_callback)
1143109998Smarkm			s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
1144109998Smarkm
1145205128Ssimon		if (SSL_is_init_finished(s) &&
1146205128Ssimon			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1147205128Ssimon			!s->s3->renegotiate)
114855714Skris			{
114955714Skris			ssl3_renegotiate(s);
115055714Skris			if (ssl3_renegotiate_check(s))
115155714Skris				{
115259191Skris				i=s->handshake_func(s);
115359191Skris				if (i < 0) return(i);
115459191Skris				if (i == 0)
115555714Skris					{
115655714Skris					SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
115755714Skris					return(-1);
115855714Skris					}
115959191Skris
116068651Skris				if (!(s->mode & SSL_MODE_AUTO_RETRY))
116159191Skris					{
116268651Skris					if (s->s3->rbuf.left == 0) /* no read-ahead left? */
116368651Skris						{
116468651Skris						BIO *bio;
116568651Skris						/* In the case where we try to read application data,
116668651Skris						 * but we trigger an SSL handshake, we return -1 with
116768651Skris						 * the retry option set.  Otherwise renegotiation may
116868651Skris						 * cause nasty problems in the blocking world */
116968651Skris						s->rwstate=SSL_READING;
117068651Skris						bio=SSL_get_rbio(s);
117168651Skris						BIO_clear_retry_flags(bio);
117268651Skris						BIO_set_retry_read(bio);
117368651Skris						return(-1);
117468651Skris						}
117559191Skris					}
117655714Skris				}
117755714Skris			}
117859191Skris		/* we either finished a handshake or ignored the request,
117959191Skris		 * now try again to obtain the (application) data we were asked for */
118059191Skris		goto start;
118155714Skris		}
1182205128Ssimon	/* If we are a server and get a client hello when renegotiation isn't
1183205128Ssimon	 * allowed send back a no renegotiation alert and carry on.
1184205128Ssimon	 * WARNING: experimental code, needs reviewing (steve)
1185205128Ssimon	 */
1186205128Ssimon	if (s->server &&
1187205128Ssimon		SSL_is_init_finished(s) &&
1188205128Ssimon    		!s->s3->send_connection_binding &&
1189205128Ssimon		(s->version > SSL3_VERSION) &&
1190205128Ssimon		(s->s3->handshake_fragment_len >= 4) &&
1191205128Ssimon		(s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1192205128Ssimon		(s->session != NULL) && (s->session->cipher != NULL) &&
1193205128Ssimon		!(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1194205128Ssimon
1195205128Ssimon		{
1196205128Ssimon		/*s->s3->handshake_fragment_len = 0;*/
1197205128Ssimon		rr->length = 0;
1198205128Ssimon		ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1199205128Ssimon		goto start;
1200205128Ssimon		}
120159191Skris	if (s->s3->alert_fragment_len >= 2)
120255714Skris		{
120359191Skris		int alert_level = s->s3->alert_fragment[0];
120459191Skris		int alert_descr = s->s3->alert_fragment[1];
120555714Skris
120659191Skris		s->s3->alert_fragment_len = 0;
120755714Skris
1208109998Smarkm		if (s->msg_callback)
1209109998Smarkm			s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);
1210109998Smarkm
121159191Skris		if (s->info_callback != NULL)
121259191Skris			cb=s->info_callback;
121359191Skris		else if (s->ctx->info_callback != NULL)
121459191Skris			cb=s->ctx->info_callback;
121555714Skris
121659191Skris		if (cb != NULL)
121759191Skris			{
121859191Skris			j = (alert_level << 8) | alert_descr;
121959191Skris			cb(s, SSL_CB_READ_ALERT, j);
122059191Skris			}
122155714Skris
122259191Skris		if (alert_level == 1) /* warning */
122359191Skris			{
122459191Skris			s->s3->warn_alert = alert_descr;
122559191Skris			if (alert_descr == SSL_AD_CLOSE_NOTIFY)
122655714Skris				{
122759191Skris				s->shutdown |= SSL_RECEIVED_SHUTDOWN;
122855714Skris				return(0);
122955714Skris				}
1230205128Ssimon			/* This is a warning but we receive it if we requested
1231205128Ssimon			 * renegotiation and the peer denied it. Terminate with
1232205128Ssimon			 * a fatal alert because if application tried to
1233205128Ssimon			 * renegotiatie it presumably had a good reason and
1234205128Ssimon			 * expects it to succeed.
1235205128Ssimon			 *
1236205128Ssimon			 * In future we might have a renegotiation where we
1237205128Ssimon			 * don't care if the peer refused it where we carry on.
1238205128Ssimon			 */
1239205128Ssimon			else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
1240205128Ssimon				{
1241205128Ssimon				al = SSL_AD_HANDSHAKE_FAILURE;
1242205128Ssimon				SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION);
1243205128Ssimon				goto f_err;
1244205128Ssimon				}
1245238405Sjkim#ifdef SSL_AD_MISSING_SRP_USERNAME
1246246772Sjkim			else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1247238405Sjkim				return(0);
1248238405Sjkim#endif
124955714Skris			}
125059191Skris		else if (alert_level == 2) /* fatal */
125159191Skris			{
125259191Skris			char tmp[16];
125355714Skris
125455714Skris			s->rwstate=SSL_NOTHING;
125559191Skris			s->s3->fatal_alert = alert_descr;
125659191Skris			SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
125768651Skris			BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
125859191Skris			ERR_add_error_data(2,"SSL alert number ",tmp);
125959191Skris			s->shutdown|=SSL_RECEIVED_SHUTDOWN;
126059191Skris			SSL_CTX_remove_session(s->ctx,s->session);
126155714Skris			return(0);
126255714Skris			}
126359191Skris		else
126459191Skris			{
126559191Skris			al=SSL_AD_ILLEGAL_PARAMETER;
126659191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
126759191Skris			goto f_err;
126859191Skris			}
126955714Skris
127059191Skris		goto start;
127159191Skris		}
127259191Skris
127359191Skris	if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
127459191Skris		{
127559191Skris		s->rwstate=SSL_NOTHING;
127659191Skris		rr->length=0;
127759191Skris		return(0);
127859191Skris		}
127959191Skris
128059191Skris	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
128159191Skris		{
128259191Skris		/* 'Change Cipher Spec' is just a single byte, so we know
128359191Skris		 * exactly what the record payload has to look like */
128459191Skris		if (	(rr->length != 1) || (rr->off != 0) ||
128559191Skris			(rr->data[0] != SSL3_MT_CCS))
128655714Skris			{
1287142425Snectar			al=SSL_AD_ILLEGAL_PARAMETER;
128859191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
1289142425Snectar			goto f_err;
129059191Skris			}
129155714Skris
1292127114Snectar		/* Check we have a cipher to change to */
1293127114Snectar		if (s->s3->tmp.new_cipher == NULL)
1294127114Snectar			{
1295142425Snectar			al=SSL_AD_UNEXPECTED_MESSAGE;
1296160814Ssimon			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);
1297142425Snectar			goto f_err;
1298127114Snectar			}
1299127114Snectar
130059191Skris		rr->length=0;
1301109998Smarkm
1302109998Smarkm		if (s->msg_callback)
1303109998Smarkm			s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
1304109998Smarkm
130559191Skris		s->s3->change_cipher_spec=1;
1306160814Ssimon		if (!ssl3_do_change_cipher_spec(s))
130759191Skris			goto err;
130859191Skris		else
130959191Skris			goto start;
131059191Skris		}
131159191Skris
131259191Skris	/* Unexpected handshake message (Client Hello, or protocol violation) */
131359191Skris	if ((s->s3->handshake_fragment_len >= 4) &&	!s->in_handshake)
131459191Skris		{
1315205128Ssimon		if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1316205128Ssimon			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
131759191Skris			{
131859191Skris#if 0 /* worked only because C operator preferences are not as expected (and
131959191Skris       * because this is not really needed for clients except for detecting
132059191Skris       * protocol violations): */
132159191Skris			s->state=SSL_ST_BEFORE|(s->server)
132259191Skris				?SSL_ST_ACCEPT
132359191Skris				:SSL_ST_CONNECT;
132459191Skris#else
132559191Skris			s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
132659191Skris#endif
1327238405Sjkim			s->renegotiate=1;
132859191Skris			s->new_session=1;
132955714Skris			}
133059191Skris		i=s->handshake_func(s);
133159191Skris		if (i < 0) return(i);
133259191Skris		if (i == 0)
133359191Skris			{
133459191Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
133559191Skris			return(-1);
133659191Skris			}
133755714Skris
133868651Skris		if (!(s->mode & SSL_MODE_AUTO_RETRY))
133955714Skris			{
134068651Skris			if (s->s3->rbuf.left == 0) /* no read-ahead left? */
134168651Skris				{
134268651Skris				BIO *bio;
134368651Skris				/* In the case where we try to read application data,
134468651Skris				 * but we trigger an SSL handshake, we return -1 with
134568651Skris				 * the retry option set.  Otherwise renegotiation may
134668651Skris				 * cause nasty problems in the blocking world */
134768651Skris				s->rwstate=SSL_READING;
134868651Skris				bio=SSL_get_rbio(s);
134968651Skris				BIO_clear_retry_flags(bio);
135068651Skris				BIO_set_retry_read(bio);
135168651Skris				return(-1);
135268651Skris				}
135355714Skris			}
135459191Skris		goto start;
135559191Skris		}
135655714Skris
135759191Skris	switch (rr->type)
135859191Skris		{
135959191Skris	default:
1360109998Smarkm#ifndef OPENSSL_NO_TLS
1361238405Sjkim		/* TLS up to v1.1 just ignores unknown message types:
1362238405Sjkim		 * TLS v1.2 give an unexpected message alert.
1363238405Sjkim		 */
1364238405Sjkim		if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)
136555714Skris			{
1366100928Snectar			rr->length = 0;
136759191Skris			goto start;
136859191Skris			}
136955714Skris#endif
137059191Skris		al=SSL_AD_UNEXPECTED_MESSAGE;
137159191Skris		SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
137259191Skris		goto f_err;
137359191Skris	case SSL3_RT_CHANGE_CIPHER_SPEC:
137459191Skris	case SSL3_RT_ALERT:
137559191Skris	case SSL3_RT_HANDSHAKE:
137659191Skris		/* we already handled all of these, with the possible exception
137759191Skris		 * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
137859191Skris		 * should not happen when type != rr->type */
137959191Skris		al=SSL_AD_UNEXPECTED_MESSAGE;
1380109998Smarkm		SSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR);
138159191Skris		goto f_err;
138259191Skris	case SSL3_RT_APPLICATION_DATA:
138359191Skris		/* At this point, we were expecting handshake data,
138459191Skris		 * but have application data.  If the library was
138559191Skris		 * running inside ssl3_read() (i.e. in_read_app_data
138659191Skris		 * is set) and it makes sense to read application data
138759191Skris		 * at this point (session renegotiation not yet started),
138859191Skris		 * we will indulge it.
138959191Skris		 */
139059191Skris		if (s->s3->in_read_app_data &&
139159191Skris			(s->s3->total_renegotiations != 0) &&
139259191Skris			((
139359191Skris				(s->state & SSL_ST_CONNECT) &&
139459191Skris				(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
139559191Skris				(s->state <= SSL3_ST_CR_SRVR_HELLO_A)
139659191Skris				) || (
139759191Skris					(s->state & SSL_ST_ACCEPT) &&
139859191Skris					(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
139959191Skris					(s->state >= SSL3_ST_SR_CLNT_HELLO_A)
140059191Skris					)
140159191Skris				))
140259191Skris			{
1403100928Snectar			s->s3->in_read_app_data=2;
140459191Skris			return(-1);
140559191Skris			}
140659191Skris		else
140759191Skris			{
140855714Skris			al=SSL_AD_UNEXPECTED_MESSAGE;
140955714Skris			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
141055714Skris			goto f_err;
141155714Skris			}
141255714Skris		}
141359191Skris	/* not reached */
141455714Skris
141555714Skrisf_err:
141655714Skris	ssl3_send_alert(s,SSL3_AL_FATAL,al);
141755714Skriserr:
141855714Skris	return(-1);
141955714Skris	}
142055714Skris
1421160814Ssimonint ssl3_do_change_cipher_spec(SSL *s)
142255714Skris	{
142355714Skris	int i;
142459191Skris	const char *sender;
142555714Skris	int slen;
142655714Skris
142755714Skris	if (s->state & SSL_ST_ACCEPT)
142855714Skris		i=SSL3_CHANGE_CIPHER_SERVER_READ;
142955714Skris	else
143055714Skris		i=SSL3_CHANGE_CIPHER_CLIENT_READ;
143155714Skris
143255714Skris	if (s->s3->tmp.key_block == NULL)
143355714Skris		{
1434194206Ssimon		if (s->session == NULL)
1435194206Ssimon			{
1436194206Ssimon			/* might happen if dtls1_read_bytes() calls this */
1437194206Ssimon			SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,SSL_R_CCS_RECEIVED_EARLY);
1438194206Ssimon			return (0);
1439194206Ssimon			}
1440194206Ssimon
144155714Skris		s->session->cipher=s->s3->tmp.new_cipher;
144255714Skris		if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
144355714Skris		}
144455714Skris
144555714Skris	if (!s->method->ssl3_enc->change_cipher_state(s,i))
144655714Skris		return(0);
144755714Skris
144855714Skris	/* we have to record the message digest at
144955714Skris	 * this point so we can get it before we read
145055714Skris	 * the finished message */
145155714Skris	if (s->state & SSL_ST_CONNECT)
145255714Skris		{
145359191Skris		sender=s->method->ssl3_enc->server_finished_label;
145459191Skris		slen=s->method->ssl3_enc->server_finished_label_len;
145555714Skris		}
145655714Skris	else
145755714Skris		{
145859191Skris		sender=s->method->ssl3_enc->client_finished_label;
145959191Skris		slen=s->method->ssl3_enc->client_finished_label_len;
146055714Skris		}
146155714Skris
146259191Skris	s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
146359191Skris		sender,slen,s->s3->tmp.peer_finish_md);
146455714Skris
146555714Skris	return(1);
146655714Skris	}
146755714Skris
1468205128Ssimonint ssl3_send_alert(SSL *s, int level, int desc)
146955714Skris	{
147055714Skris	/* Map tls/ssl alert value to correct one */
147155714Skris	desc=s->method->ssl3_enc->alert_value(desc);
147289837Skris	if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
147389837Skris		desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
1474205128Ssimon	if (desc < 0) return -1;
147555714Skris	/* If a fatal one, remove from cache */
147655714Skris	if ((level == 2) && (s->session != NULL))
147755714Skris		SSL_CTX_remove_session(s->ctx,s->session);
147855714Skris
147955714Skris	s->s3->alert_dispatch=1;
148055714Skris	s->s3->send_alert[0]=level;
148155714Skris	s->s3->send_alert[1]=desc;
148289837Skris	if (s->s3->wbuf.left == 0) /* data still being written out? */
1483205128Ssimon		return s->method->ssl_dispatch_alert(s);
148455714Skris	/* else data is still being written out, we will get written
148555714Skris	 * some time in the future */
1486205128Ssimon	return -1;
148755714Skris	}
148855714Skris
148955714Skrisint ssl3_dispatch_alert(SSL *s)
149055714Skris	{
149155714Skris	int i,j;
1492109998Smarkm	void (*cb)(const SSL *ssl,int type,int val)=NULL;
149355714Skris
149455714Skris	s->s3->alert_dispatch=0;
1495100928Snectar	i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
149655714Skris	if (i <= 0)
149755714Skris		{
149855714Skris		s->s3->alert_dispatch=1;
149955714Skris		}
150055714Skris	else
150155714Skris		{
150289837Skris		/* Alert sent to BIO.  If it is important, flush it now.
150389837Skris		 * If the message does not get sent due to non-blocking IO,
150489837Skris		 * we will not worry too much. */
150555714Skris		if (s->s3->send_alert[0] == SSL3_AL_FATAL)
150655714Skris			(void)BIO_flush(s->wbio);
150755714Skris
1508109998Smarkm		if (s->msg_callback)
1509109998Smarkm			s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
1510109998Smarkm
151155714Skris		if (s->info_callback != NULL)
151255714Skris			cb=s->info_callback;
151355714Skris		else if (s->ctx->info_callback != NULL)
151455714Skris			cb=s->ctx->info_callback;
151559191Skris
151655714Skris		if (cb != NULL)
151755714Skris			{
151855714Skris			j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
151955714Skris			cb(s,SSL_CB_WRITE_ALERT,j);
152055714Skris			}
152155714Skris		}
152255714Skris	return(i);
152355714Skris	}
1524