Home | History | Annotate | Download | only in ssl
      1 /* ssl/s3_pkt.c */
      2 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      3  * All rights reserved.
      4  *
      5  * This package is an SSL implementation written
      6  * by Eric Young (eay (at) cryptsoft.com).
      7  * The implementation was written so as to conform with Netscapes SSL.
      8  *
      9  * This library is free for commercial and non-commercial use as long as
     10  * the following conditions are aheared to.  The following conditions
     11  * apply to all code found in this distribution, be it the RC4, RSA,
     12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
     13  * included with this distribution is covered by the same copyright terms
     14  * except that the holder is Tim Hudson (tjh (at) cryptsoft.com).
     15  *
     16  * Copyright remains Eric Young's, and as such any Copyright notices in
     17  * the code are not to be removed.
     18  * If this package is used in a product, Eric Young should be given attribution
     19  * as the author of the parts of the library used.
     20  * This can be in the form of a textual message at program startup or
     21  * in documentation (online or textual) provided with the package.
     22  *
     23  * Redistribution and use in source and binary forms, with or without
     24  * modification, are permitted provided that the following conditions
     25  * are met:
     26  * 1. Redistributions of source code must retain the copyright
     27  *    notice, this list of conditions and the following disclaimer.
     28  * 2. Redistributions in binary form must reproduce the above copyright
     29  *    notice, this list of conditions and the following disclaimer in the
     30  *    documentation and/or other materials provided with the distribution.
     31  * 3. All advertising materials mentioning features or use of this software
     32  *    must display the following acknowledgement:
     33  *    "This product includes cryptographic software written by
     34  *     Eric Young (eay (at) cryptsoft.com)"
     35  *    The word 'cryptographic' can be left out if the rouines from the library
     36  *    being used are not cryptographic related :-).
     37  * 4. If you include any Windows specific code (or a derivative thereof) from
     38  *    the apps directory (application code) you must include an acknowledgement:
     39  *    "This product includes software written by Tim Hudson (tjh (at) cryptsoft.com)"
     40  *
     41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
     42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     51  * SUCH DAMAGE.
     52  *
     53  * The licence and distribution terms for any publically available version or
     54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
     55  * copied and put under another distribution licence
     56  * [including the GNU Public Licence.]
     57  */
     58 /* ====================================================================
     59  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
     60  *
     61  * Redistribution and use in source and binary forms, with or without
     62  * modification, are permitted provided that the following conditions
     63  * are met:
     64  *
     65  * 1. Redistributions of source code must retain the above copyright
     66  *    notice, this list of conditions and the following disclaimer.
     67  *
     68  * 2. Redistributions in binary form must reproduce the above copyright
     69  *    notice, this list of conditions and the following disclaimer in
     70  *    the documentation and/or other materials provided with the
     71  *    distribution.
     72  *
     73  * 3. All advertising materials mentioning features or use of this
     74  *    software must display the following acknowledgment:
     75  *    "This product includes software developed by the OpenSSL Project
     76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
     77  *
     78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
     79  *    endorse or promote products derived from this software without
     80  *    prior written permission. For written permission, please contact
     81  *    openssl-core (at) openssl.org.
     82  *
     83  * 5. Products derived from this software may not be called "OpenSSL"
     84  *    nor may "OpenSSL" appear in their names without prior written
     85  *    permission of the OpenSSL Project.
     86  *
     87  * 6. Redistributions of any form whatsoever must retain the following
     88  *    acknowledgment:
     89  *    "This product includes software developed by the OpenSSL Project
     90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
     91  *
     92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
     93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
     96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    103  * OF THE POSSIBILITY OF SUCH DAMAGE.
    104  * ====================================================================
    105  *
    106  * This product includes cryptographic software written by Eric Young
    107  * (eay (at) cryptsoft.com).  This product includes software written by Tim
    108  * Hudson (tjh (at) cryptsoft.com).
    109  *
    110  */
    111 
    112 #include <stdio.h>
    113 #include <errno.h>
    114 #define USE_SOCKETS
    115 #include "ssl_locl.h"
    116 #include <openssl/evp.h>
    117 #include <openssl/buffer.h>
    118 
    119 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
    120 			 unsigned int len, int create_empty_fragment);
    121 static int ssl3_get_record(SSL *s);
    122 
    123 int ssl3_read_n(SSL *s, int n, int max, int extend)
    124 	{
    125 	/* If extend == 0, obtain new n-byte packet; if extend == 1, increase
    126 	 * packet by another n bytes.
    127 	 * The packet will be in the sub-array of s->s3->rbuf.buf specified
    128 	 * by s->packet and s->packet_length.
    129 	 * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
    130 	 * [plus s->packet_length bytes if extend == 1].)
    131 	 */
    132 	int i,len,left;
    133 	long align=0;
    134 	unsigned char *pkt;
    135 	SSL3_BUFFER *rb;
    136 
    137 	if (n <= 0) return n;
    138 
    139 	rb    = &(s->s3->rbuf);
    140 	if (rb->buf == NULL)
    141 		if (!ssl3_setup_read_buffer(s))
    142 			return -1;
    143 
    144 	left  = rb->left;
    145 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
    146 	align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
    147 	align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
    148 #endif
    149 
    150 	if (!extend)
    151 		{
    152 		/* start with empty packet ... */
    153 		if (left == 0)
    154 			rb->offset = align;
    155 		else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
    156 			{
    157 			/* check if next packet length is large
    158 			 * enough to justify payload alignment... */
    159 			pkt = rb->buf + rb->offset;
    160 			if (pkt[0] == SSL3_RT_APPLICATION_DATA
    161 			    && (pkt[3]<<8|pkt[4]) >= 128)
    162 				{
    163 				/* Note that even if packet is corrupted
    164 				 * and its length field is insane, we can
    165 				 * only be led to wrong decision about
    166 				 * whether memmove will occur or not.
    167 				 * Header values has no effect on memmove
    168 				 * arguments and therefore no buffer
    169 				 * overrun can be triggered. */
    170 				memmove (rb->buf+align,pkt,left);
    171 				rb->offset = align;
    172 				}
    173 			}
    174 		s->packet = rb->buf + rb->offset;
    175 		s->packet_length = 0;
    176 		/* ... now we can act as if 'extend' was set */
    177 		}
    178 
    179 	/* For DTLS/UDP reads should not span multiple packets
    180 	 * because the read operation returns the whole packet
    181 	 * at once (as long as it fits into the buffer). */
    182 	if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
    183 		{
    184 		if (left > 0 && n > left)
    185 			n = left;
    186 		}
    187 
    188 	/* if there is enough in the buffer from a previous read, take some */
    189 	if (left >= n)
    190 		{
    191 		s->packet_length+=n;
    192 		rb->left=left-n;
    193 		rb->offset+=n;
    194 		return(n);
    195 		}
    196 
    197 	/* else we need to read more data */
    198 
    199 	len = s->packet_length;
    200 	pkt = rb->buf+align;
    201 	/* Move any available bytes to front of buffer:
    202 	 * 'len' bytes already pointed to by 'packet',
    203 	 * 'left' extra ones at the end */
    204 	if (s->packet != pkt) /* len > 0 */
    205 		{
    206 		memmove(pkt, s->packet, len+left);
    207 		s->packet = pkt;
    208 		rb->offset = len + align;
    209 		}
    210 
    211 	if (n > (int)(rb->len - rb->offset)) /* does not happen */
    212 		{
    213 		SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR);
    214 		return -1;
    215 		}
    216 
    217 	if (!s->read_ahead)
    218 		/* ignore max parameter */
    219 		max = n;
    220 	else
    221 		{
    222 		if (max < n)
    223 			max = n;
    224 		if (max > (int)(rb->len - rb->offset))
    225 			max = rb->len - rb->offset;
    226 		}
    227 
    228 	while (left < n)
    229 		{
    230 		/* Now we have len+left bytes at the front of s->s3->rbuf.buf
    231 		 * and need to read in more until we have len+n (up to
    232 		 * len+max if possible) */
    233 
    234 		clear_sys_error();
    235 		if (s->rbio != NULL)
    236 			{
    237 			s->rwstate=SSL_READING;
    238 			i=BIO_read(s->rbio,pkt+len+left, max-left);
    239 			}
    240 		else
    241 			{
    242 			SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
    243 			i = -1;
    244 			}
    245 
    246 		if (i <= 0)
    247 			{
    248 			rb->left = left;
    249 			if (s->mode & SSL_MODE_RELEASE_BUFFERS)
    250 				if (len+left == 0)
    251 					ssl3_release_read_buffer(s);
    252 			return(i);
    253 			}
    254 		left+=i;
    255 		/* reads should *never* span multiple packets for DTLS because
    256 		 * the underlying transport protocol is message oriented as opposed
    257 		 * to byte oriented as in the TLS case. */
    258 		if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
    259 			{
    260 			if (n > left)
    261 				n = left; /* makes the while condition false */
    262 			}
    263 		}
    264 
    265 	/* done reading, now the book-keeping */
    266 	rb->offset += n;
    267 	rb->left = left - n;
    268 	s->packet_length += n;
    269 	s->rwstate=SSL_NOTHING;
    270 	return(n);
    271 	}
    272 
    273 /* Call this to get a new input record.
    274  * It will return <= 0 if more data is needed, normally due to an error
    275  * or non-blocking IO.
    276  * When it finishes, one packet has been decoded and can be found in
    277  * ssl->s3->rrec.type    - is the type of record
    278  * ssl->s3->rrec.data, 	 - data
    279  * ssl->s3->rrec.length, - number of bytes
    280  */
    281 /* used only by ssl3_read_bytes */
    282 static int ssl3_get_record(SSL *s)
    283 	{
    284 	int ssl_major,ssl_minor,al;
    285 	int enc_err,n,i,ret= -1;
    286 	SSL3_RECORD *rr;
    287 	SSL_SESSION *sess;
    288 	unsigned char *p;
    289 	unsigned char md[EVP_MAX_MD_SIZE];
    290 	short version;
    291 	int mac_size;
    292 	int clear=0;
    293 	size_t extra;
    294 	int decryption_failed_or_bad_record_mac = 0;
    295 	unsigned char *mac = NULL;
    296 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
    297 	long align=SSL3_ALIGN_PAYLOAD;
    298 #else
    299 	long align=0;
    300 #endif
    301 
    302 	rr= &(s->s3->rrec);
    303 	sess=s->session;
    304 
    305 	if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
    306 		extra=SSL3_RT_MAX_EXTRA;
    307 	else
    308 		extra=0;
    309 	if (!(SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS) &&
    310 		extra && !s->s3->init_extra)
    311 		{
    312 		/* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER
    313 		 * set after ssl3_setup_buffers() was done */
    314 		SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
    315 		return -1;
    316 		}
    317 
    318 again:
    319 	/* check if we have the header */
    320 	if (	(s->rstate != SSL_ST_READ_BODY) ||
    321 		(s->packet_length < SSL3_RT_HEADER_LENGTH))
    322 		{
    323 		n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
    324 		if (n <= 0) return(n); /* error or non-blocking */
    325 		s->rstate=SSL_ST_READ_BODY;
    326 
    327 		p=s->packet;
    328 
    329 		/* Pull apart the header into the SSL3_RECORD */
    330 		rr->type= *(p++);
    331 		ssl_major= *(p++);
    332 		ssl_minor= *(p++);
    333 		version=(ssl_major<<8)|ssl_minor;
    334 		n2s(p,rr->length);
    335 #if 0
    336 fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
    337 #endif
    338 
    339 		/* Lets check version */
    340 		if (!s->first_packet)
    341 			{
    342 			if (version != s->version)
    343 				{
    344 				SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
    345                                 if ((s->version & 0xFF00) == (version & 0xFF00))
    346                                 	/* Send back error using their minor version number :-) */
    347 					s->version = (unsigned short)version;
    348 				al=SSL_AD_PROTOCOL_VERSION;
    349 				goto f_err;
    350 				}
    351 			}
    352 
    353 		if ((version>>8) != SSL3_VERSION_MAJOR)
    354 			{
    355 			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
    356 			goto err;
    357 			}
    358 
    359 		/* If we receive a valid record larger than the current buffer size,
    360 		 * allocate some memory for it.
    361 		 */
    362 		if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH - align)
    363 			{
    364 			if ((p=OPENSSL_realloc(s->s3->rbuf.buf, rr->length + SSL3_RT_HEADER_LENGTH + align))==NULL)
    365 				{
    366 				SSLerr(SSL_F_SSL3_GET_RECORD,ERR_R_MALLOC_FAILURE);
    367 				goto err;
    368 				}
    369 			s->s3->rbuf.buf=p;
    370 			s->s3->rbuf.len=rr->length + SSL3_RT_HEADER_LENGTH + align;
    371 			s->packet= &(s->s3->rbuf.buf[0]);
    372 			}
    373 
    374 		if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)
    375 			{
    376 			al=SSL_AD_RECORD_OVERFLOW;
    377 			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
    378 			goto f_err;
    379 			}
    380 
    381 		/* now s->rstate == SSL_ST_READ_BODY */
    382 		}
    383 
    384 	/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
    385 
    386 	if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)
    387 		{
    388 		/* now s->packet_length == SSL3_RT_HEADER_LENGTH */
    389 		i=rr->length;
    390 		n=ssl3_read_n(s,i,i,1);
    391 		if (n <= 0) return(n); /* error or non-blocking io */
    392 		/* now n == rr->length,
    393 		 * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
    394 		}
    395 
    396 	s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
    397 
    398 	/* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
    399 	 * and we have that many bytes in s->packet
    400 	 */
    401 	rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
    402 
    403 	/* ok, we can now read from 's->packet' data into 'rr'
    404 	 * rr->input points at rr->length bytes, which
    405 	 * need to be copied into rr->data by either
    406 	 * the decryption or by the decompression
    407 	 * When the data is 'copied' into the rr->data buffer,
    408 	 * rr->input will be pointed at the new buffer */
    409 
    410 	/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
    411 	 * rr->length bytes of encrypted compressed stuff. */
    412 
    413 	/* check is not needed I believe */
    414 	if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
    415 		{
    416 		al=SSL_AD_RECORD_OVERFLOW;
    417 		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
    418 		goto f_err;
    419 		}
    420 
    421 	/* decrypt in place in 'rr->input' */
    422 	rr->data=rr->input;
    423 
    424 	enc_err = s->method->ssl3_enc->enc(s,0);
    425 	if (enc_err <= 0)
    426 		{
    427 		if (enc_err == 0)
    428 			/* SSLerr() and ssl3_send_alert() have been called */
    429 			goto err;
    430 
    431 		/* Otherwise enc_err == -1, which indicates bad padding
    432 		 * (rec->length has not been changed in this case).
    433 		 * To minimize information leaked via timing, we will perform
    434 		 * the MAC computation anyway. */
    435 		decryption_failed_or_bad_record_mac = 1;
    436 		}
    437 
    438 #ifdef TLS_DEBUG
    439 printf("dec %d\n",rr->length);
    440 { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
    441 printf("\n");
    442 #endif
    443 
    444 	/* r->length is now the compressed data plus mac */
    445 	if (	(sess == NULL) ||
    446 		(s->enc_read_ctx == NULL) ||
    447 		(EVP_MD_CTX_md(s->read_hash) == NULL))
    448 		clear=1;
    449 
    450 	if (!clear)
    451 		{
    452 		/* !clear => s->read_hash != NULL => mac_size != -1 */
    453 		mac_size=EVP_MD_CTX_size(s->read_hash);
    454 		OPENSSL_assert(mac_size >= 0);
    455 
    456 		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
    457 			{
    458 #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */
    459 			al=SSL_AD_RECORD_OVERFLOW;
    460 			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);
    461 			goto f_err;
    462 #else
    463 			decryption_failed_or_bad_record_mac = 1;
    464 #endif
    465 			}
    466 		/* check the MAC for rr->input (it's in mac_size bytes at the tail) */
    467 		if (rr->length >= (unsigned int)mac_size)
    468 			{
    469 			rr->length -= mac_size;
    470 			mac = &rr->data[rr->length];
    471 			}
    472 		else
    473 			{
    474 			/* record (minus padding) is too short to contain a MAC */
    475 #if 0 /* OK only for stream ciphers */
    476 			al=SSL_AD_DECODE_ERROR;
    477 			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);
    478 			goto f_err;
    479 #else
    480 			decryption_failed_or_bad_record_mac = 1;
    481 			rr->length = 0;
    482 #endif
    483 			}
    484 		i=s->method->ssl3_enc->mac(s,md,0);
    485 		if (i < 0 || mac == NULL || memcmp(md, mac, (size_t)mac_size) != 0)
    486 			{
    487 			decryption_failed_or_bad_record_mac = 1;
    488 			}
    489 		}
    490 
    491 	if (decryption_failed_or_bad_record_mac)
    492 		{
    493 		/* A separate 'decryption_failed' alert was introduced with TLS 1.0,
    494 		 * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
    495 		 * failure is directly visible from the ciphertext anyway,
    496 		 * we should not reveal which kind of error occured -- this
    497 		 * might become visible to an attacker (e.g. via a logfile) */
    498 		al=SSL_AD_BAD_RECORD_MAC;
    499 		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
    500 		goto f_err;
    501 		}
    502 
    503 	/* r->length is now just compressed */
    504 	if (s->expand != NULL)
    505 		{
    506 		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)
    507 			{
    508 			al=SSL_AD_RECORD_OVERFLOW;
    509 			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
    510 			goto f_err;
    511 			}
    512 		if (!ssl3_do_uncompress(s))
    513 			{
    514 			al=SSL_AD_DECOMPRESSION_FAILURE;
    515 			SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);
    516 			goto f_err;
    517 			}
    518 		}
    519 
    520 	if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)
    521 		{
    522 		al=SSL_AD_RECORD_OVERFLOW;
    523 		SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
    524 		goto f_err;
    525 		}
    526 
    527 	rr->off=0;
    528 	/* So at this point the following is true
    529 	 * ssl->s3->rrec.type 	is the type of record
    530 	 * ssl->s3->rrec.length	== number of bytes in record
    531 	 * ssl->s3->rrec.off	== offset to first valid byte
    532 	 * ssl->s3->rrec.data	== where to take bytes from, increment
    533 	 *			   after use :-).
    534 	 */
    535 
    536 	/* we have pulled in a full packet so zero things */
    537 	s->packet_length=0;
    538 
    539 	/* just read a 0 length packet */
    540 	if (rr->length == 0) goto again;
    541 
    542 #if 0
    543 fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length);
    544 #endif
    545 
    546 	return(1);
    547 
    548 f_err:
    549 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
    550 err:
    551 	return(ret);
    552 	}
    553 
    554 int ssl3_do_uncompress(SSL *ssl)
    555 	{
    556 #ifndef OPENSSL_NO_COMP
    557 	int i;
    558 	SSL3_RECORD *rr;
    559 
    560 	rr= &(ssl->s3->rrec);
    561 	i=COMP_expand_block(ssl->expand,rr->comp,
    562 		SSL3_RT_MAX_PLAIN_LENGTH,rr->data,(int)rr->length);
    563 	if (i < 0)
    564 		return(0);
    565 	else
    566 		rr->length=i;
    567 	rr->data=rr->comp;
    568 #endif
    569 	return(1);
    570 	}
    571 
    572 int ssl3_do_compress(SSL *ssl)
    573 	{
    574 #ifndef OPENSSL_NO_COMP
    575 	int i;
    576 	SSL3_RECORD *wr;
    577 
    578 	wr= &(ssl->s3->wrec);
    579 	i=COMP_compress_block(ssl->compress,wr->data,
    580 		SSL3_RT_MAX_COMPRESSED_LENGTH,
    581 		wr->input,(int)wr->length);
    582 	if (i < 0)
    583 		return(0);
    584 	else
    585 		wr->length=i;
    586 
    587 	wr->input=wr->data;
    588 #endif
    589 	return(1);
    590 	}
    591 
    592 /* Call this to write data in records of type 'type'
    593  * It will return <= 0 if not all data has been sent or non-blocking IO.
    594  */
    595 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
    596 	{
    597 	const unsigned char *buf=buf_;
    598 	unsigned int tot,n,nw;
    599 	int i;
    600 	unsigned int max_plain_length;
    601 
    602 	s->rwstate=SSL_NOTHING;
    603 	tot=s->s3->wnum;
    604 	s->s3->wnum=0;
    605 
    606 	if (SSL_in_init(s) && !s->in_handshake)
    607 		{
    608 		i=s->handshake_func(s);
    609 		if (i < 0) return(i);
    610 		if (i == 0)
    611 			{
    612 			SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
    613 			return -1;
    614 			}
    615 		}
    616 
    617 	n=(len-tot);
    618 	for (;;)
    619 		{
    620 		if (type == SSL3_RT_APPLICATION_DATA && (SSL_get_mode(s) & SSL_MODE_SMALL_BUFFERS))
    621 			max_plain_length = SSL3_RT_DEFAULT_PLAIN_LENGTH;
    622 		else
    623 			max_plain_length = s->max_send_fragment;
    624 
    625 		if (n > max_plain_length)
    626 			nw = max_plain_length;
    627 		else
    628 			nw=n;
    629 
    630 		i=do_ssl3_write(s, type, &(buf[tot]), nw, 0);
    631 		if (i <= 0)
    632 			{
    633 			s->s3->wnum=tot;
    634 			return i;
    635 			}
    636 
    637 		if ((i == (int)n) ||
    638 			(type == SSL3_RT_APPLICATION_DATA &&
    639 			 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
    640 			{
    641 			/* next chunk of data should get another prepended empty fragment
    642 			 * in ciphersuites with known-IV weakness: */
    643 			s->s3->empty_fragment_done = 0;
    644 
    645 			return tot+i;
    646 			}
    647 
    648 		n-=i;
    649 		tot+=i;
    650 		}
    651 	}
    652 
    653 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
    654 			 unsigned int len, int create_empty_fragment)
    655 	{
    656 	unsigned char *p,*plen;
    657 	int i,mac_size,clear=0;
    658 	int prefix_len=0;
    659 	long align=0;
    660 	SSL3_RECORD *wr;
    661 	SSL3_BUFFER *wb=&(s->s3->wbuf);
    662 	SSL_SESSION *sess;
    663 
    664  	if (wb->buf == NULL)
    665 		if (!ssl3_setup_write_buffer(s))
    666 			return -1;
    667 
    668 	/* first check if there is a SSL3_BUFFER still being written
    669 	 * out.  This will happen with non blocking IO */
    670 	if (wb->left != 0)
    671 		return(ssl3_write_pending(s,type,buf,len));
    672 
    673 	/* If we have an alert to send, lets send it */
    674 	if (s->s3->alert_dispatch)
    675 		{
    676 		i=s->method->ssl_dispatch_alert(s);
    677 		if (i <= 0)
    678 			return(i);
    679 		/* if it went, fall through and send more stuff */
    680 		}
    681 
    682 	if (len == 0 && !create_empty_fragment)
    683 		return 0;
    684 
    685 	wr= &(s->s3->wrec);
    686 	sess=s->session;
    687 
    688 	if (	(sess == NULL) ||
    689 		(s->enc_write_ctx == NULL) ||
    690 		(EVP_MD_CTX_md(s->write_hash) == NULL))
    691 		clear=1;
    692 
    693 	if (clear)
    694 		mac_size=0;
    695 	else
    696 		{
    697 		mac_size=EVP_MD_CTX_size(s->write_hash);
    698 		if (mac_size < 0)
    699 			goto err;
    700 		}
    701 
    702 	/* 'create_empty_fragment' is true only when this function calls itself */
    703 	if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done)
    704 		{
    705 		/* countermeasure against known-IV weakness in CBC ciphersuites
    706 		 * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
    707 
    708 		if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
    709 			{
    710 			/* recursive function call with 'create_empty_fragment' set;
    711 			 * this prepares and buffers the data for an empty fragment
    712 			 * (these 'prefix_len' bytes are sent out later
    713 			 * together with the actual payload) */
    714 			prefix_len = do_ssl3_write(s, type, buf, 0, 1);
    715 			if (prefix_len <= 0)
    716 				goto err;
    717 
    718 			if (prefix_len >
    719 		(SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
    720 				{
    721 				/* insufficient space */
    722 				SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
    723 				goto err;
    724 				}
    725 			}
    726 
    727 		s->s3->empty_fragment_done = 1;
    728 		}
    729 
    730 	/* resize if necessary to hold the data. */
    731 	if (len + SSL3_RT_DEFAULT_WRITE_OVERHEAD > wb->len)
    732 		{
    733 		if ((p=OPENSSL_realloc(wb->buf, len + SSL3_RT_DEFAULT_WRITE_OVERHEAD))==NULL)
    734 			{
    735 			SSLerr(SSL_F_DO_SSL3_WRITE,ERR_R_MALLOC_FAILURE);
    736 			goto err;
    737 			}
    738 		wb->buf = p;
    739 		wb->len = len + SSL3_RT_DEFAULT_WRITE_OVERHEAD;
    740 		}
    741 
    742 	if (create_empty_fragment)
    743 		{
    744 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
    745 		/* extra fragment would be couple of cipher blocks,
    746 		 * which would be multiple of SSL3_ALIGN_PAYLOAD, so
    747 		 * if we want to align the real payload, then we can
    748 		 * just pretent we simply have two headers. */
    749 		align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH;
    750 		align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
    751 #endif
    752 		p = wb->buf + align;
    753 		wb->offset  = align;
    754 		}
    755 	else if (prefix_len)
    756 		{
    757 		p = wb->buf + wb->offset + prefix_len;
    758 		}
    759 	else
    760 		{
    761 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
    762 		align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
    763 		align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
    764 #endif
    765 		p = wb->buf + align;
    766 		wb->offset  = align;
    767 		}
    768 
    769 	/* write the header */
    770 
    771 	*(p++)=type&0xff;
    772 	wr->type=type;
    773 
    774 	*(p++)=(s->version>>8);
    775 	*(p++)=s->version&0xff;
    776 
    777 	/* field where we are to write out packet length */
    778 	plen=p;
    779 	p+=2;
    780 
    781 	/* lets setup the record stuff. */
    782 	wr->data=p;
    783 	wr->length=(int)len;
    784 	wr->input=(unsigned char *)buf;
    785 
    786 	/* we now 'read' from wr->input, wr->length bytes into
    787 	 * wr->data */
    788 
    789 	/* first we compress */
    790 	if (s->compress != NULL)
    791 		{
    792 		if (!ssl3_do_compress(s))
    793 			{
    794 			SSLerr(SSL_F_DO_SSL3_WRITE,SSL_R_COMPRESSION_FAILURE);
    795 			goto err;
    796 			}
    797 		}
    798 	else
    799 		{
    800 		memcpy(wr->data,wr->input,wr->length);
    801 		wr->input=wr->data;
    802 		}
    803 
    804 	/* we should still have the output to wr->data and the input
    805 	 * from wr->input.  Length should be wr->length.
    806 	 * wr->data still points in the wb->buf */
    807 
    808 	if (mac_size != 0)
    809 		{
    810 		if (s->method->ssl3_enc->mac(s,&(p[wr->length]),1) < 0)
    811 			goto err;
    812 		wr->length+=mac_size;
    813 		wr->input=p;
    814 		wr->data=p;
    815 		}
    816 
    817 	/* ssl3_enc can only have an error on read */
    818 	s->method->ssl3_enc->enc(s,1);
    819 
    820 	/* record length after mac and block padding */
    821 	s2n(wr->length,plen);
    822 
    823 	/* we should now have
    824 	 * wr->data pointing to the encrypted data, which is
    825 	 * wr->length long */
    826 	wr->type=type; /* not needed but helps for debugging */
    827 	wr->length+=SSL3_RT_HEADER_LENGTH;
    828 
    829 	if (create_empty_fragment)
    830 		{
    831 		/* we are in a recursive call;
    832 		 * just return the length, don't write out anything here
    833 		 */
    834 		return wr->length;
    835 		}
    836 
    837 	/* now let's set up wb */
    838 	wb->left = prefix_len + wr->length;
    839 
    840 	/* memorize arguments so that ssl3_write_pending can detect bad write retries later */
    841 	s->s3->wpend_tot=len;
    842 	s->s3->wpend_buf=buf;
    843 	s->s3->wpend_type=type;
    844 	s->s3->wpend_ret=len;
    845 
    846 	/* we now just need to write the buffer */
    847 	return ssl3_write_pending(s,type,buf,len);
    848 err:
    849 	return -1;
    850 	}
    851 
    852 /* if s->s3->wbuf.left != 0, we need to call this */
    853 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
    854 	unsigned int len)
    855 	{
    856 	int i;
    857 	SSL3_BUFFER *wb=&(s->s3->wbuf);
    858 
    859 /* XXXX */
    860 	if ((s->s3->wpend_tot > (int)len)
    861 		|| ((s->s3->wpend_buf != buf) &&
    862 			!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
    863 		|| (s->s3->wpend_type != type))
    864 		{
    865 		SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY);
    866 		return(-1);
    867 		}
    868 
    869 	for (;;)
    870 		{
    871 		clear_sys_error();
    872 		if (s->wbio != NULL)
    873 			{
    874 			s->rwstate=SSL_WRITING;
    875 			i=BIO_write(s->wbio,
    876 				(char *)&(wb->buf[wb->offset]),
    877 				(unsigned int)wb->left);
    878 			}
    879 		else
    880 			{
    881 			SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BIO_NOT_SET);
    882 			i= -1;
    883 			}
    884 		if (i == wb->left)
    885 			{
    886 			wb->left=0;
    887 			wb->offset+=i;
    888 			if (s->mode & SSL_MODE_RELEASE_BUFFERS)
    889 				ssl3_release_write_buffer(s);
    890 			s->rwstate=SSL_NOTHING;
    891 			return(s->s3->wpend_ret);
    892 			}
    893 		else if (i <= 0) {
    894 			if (s->version == DTLS1_VERSION ||
    895 			    s->version == DTLS1_BAD_VER) {
    896 				/* For DTLS, just drop it. That's kind of the whole
    897 				   point in using a datagram service */
    898 				wb->left = 0;
    899 			}
    900 			return(i);
    901 		}
    902 		wb->offset+=i;
    903 		wb->left-=i;
    904 		}
    905 	}
    906 
    907 /* Return up to 'len' payload bytes received in 'type' records.
    908  * 'type' is one of the following:
    909  *
    910  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
    911  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
    912  *   -  0 (during a shutdown, no data has to be returned)
    913  *
    914  * If we don't have stored data to work from, read a SSL/TLS record first
    915  * (possibly multiple records if we still don't have anything to return).
    916  *
    917  * This function must handle any surprises the peer may have for us, such as
    918  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
    919  * a surprise, but handled as if it were), or renegotiation requests.
    920  * Also if record payloads contain fragments too small to process, we store
    921  * them until there is enough for the respective protocol (the record protocol
    922  * may use arbitrary fragmentation and even interleaving):
    923  *     Change cipher spec protocol
    924  *             just 1 byte needed, no need for keeping anything stored
    925  *     Alert protocol
    926  *             2 bytes needed (AlertLevel, AlertDescription)
    927  *     Handshake protocol
    928  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
    929  *             to detect unexpected Client Hello and Hello Request messages
    930  *             here, anything else is handled by higher layers
    931  *     Application data protocol
    932  *             none of our business
    933  */
    934 int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
    935 	{
    936 	int al,i,j,ret;
    937 	unsigned int n;
    938 	SSL3_RECORD *rr;
    939 	void (*cb)(const SSL *ssl,int type2,int val)=NULL;
    940 
    941 	if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
    942 		if (!ssl3_setup_read_buffer(s))
    943 			return(-1);
    944 
    945 	if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) ||
    946 	    (peek && (type != SSL3_RT_APPLICATION_DATA)))
    947 		{
    948 		SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
    949 		return -1;
    950 		}
    951 
    952 	if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
    953 		/* (partially) satisfy request from storage */
    954 		{
    955 		unsigned char *src = s->s3->handshake_fragment;
    956 		unsigned char *dst = buf;
    957 		unsigned int k;
    958 
    959 		/* peek == 0 */
    960 		n = 0;
    961 		while ((len > 0) && (s->s3->handshake_fragment_len > 0))
    962 			{
    963 			*dst++ = *src++;
    964 			len--; s->s3->handshake_fragment_len--;
    965 			n++;
    966 			}
    967 		/* move any remaining fragment bytes: */
    968 		for (k = 0; k < s->s3->handshake_fragment_len; k++)
    969 			s->s3->handshake_fragment[k] = *src++;
    970 		return n;
    971 	}
    972 
    973 	/* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
    974 
    975 	if (!s->in_handshake && SSL_in_init(s))
    976 		{
    977 		/* type == SSL3_RT_APPLICATION_DATA */
    978 		i=s->handshake_func(s);
    979 		if (i < 0) return(i);
    980 		if (i == 0)
    981 			{
    982 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
    983 			return(-1);
    984 			}
    985 		}
    986 start:
    987 	s->rwstate=SSL_NOTHING;
    988 
    989 	/* s->s3->rrec.type	    - is the type of record
    990 	 * s->s3->rrec.data,    - data
    991 	 * s->s3->rrec.off,     - offset into 'data' for next read
    992 	 * s->s3->rrec.length,  - number of bytes. */
    993 	rr = &(s->s3->rrec);
    994 
    995 	/* get new packet if necessary */
    996 	if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
    997 		{
    998 		ret=ssl3_get_record(s);
    999 		if (ret <= 0) return(ret);
   1000 		}
   1001 
   1002 	/* we now have a packet which can be read and processed */
   1003 
   1004 	if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
   1005 	                               * reset by ssl3_get_finished */
   1006 		&& (rr->type != SSL3_RT_HANDSHAKE))
   1007 		{
   1008 		al=SSL_AD_UNEXPECTED_MESSAGE;
   1009 		SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
   1010 		goto f_err;
   1011 		}
   1012 
   1013 	/* If the other end has shut down, throw anything we read away
   1014 	 * (even in 'peek' mode) */
   1015 	if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
   1016 		{
   1017 		rr->length=0;
   1018 		s->rwstate=SSL_NOTHING;
   1019 		return(0);
   1020 		}
   1021 
   1022 
   1023 	if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
   1024 		{
   1025 		/* make sure that we are not getting application data when we
   1026 		 * are doing a handshake for the first time */
   1027 		if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
   1028 			(s->enc_read_ctx == NULL))
   1029 			{
   1030 			al=SSL_AD_UNEXPECTED_MESSAGE;
   1031 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
   1032 			goto f_err;
   1033 			}
   1034 
   1035 		if (len <= 0) return(len);
   1036 
   1037 		if ((unsigned int)len > rr->length)
   1038 			n = rr->length;
   1039 		else
   1040 			n = (unsigned int)len;
   1041 
   1042 		memcpy(buf,&(rr->data[rr->off]),n);
   1043 		if (!peek)
   1044 			{
   1045 			rr->length-=n;
   1046 			rr->off+=n;
   1047 			if (rr->length == 0)
   1048 				{
   1049 				s->rstate=SSL_ST_READ_HEADER;
   1050 				rr->off=0;
   1051 				if (s->mode & SSL_MODE_RELEASE_BUFFERS)
   1052 					ssl3_release_read_buffer(s);
   1053 				}
   1054 			}
   1055 		return(n);
   1056 		}
   1057 
   1058 
   1059 	/* If we get here, then type != rr->type; if we have a handshake
   1060 	 * message, then it was unexpected (Hello Request or Client Hello). */
   1061 
   1062 	/* In case of record types for which we have 'fragment' storage,
   1063 	 * fill that so that we can process the data at a fixed place.
   1064 	 */
   1065 		{
   1066 		unsigned int dest_maxlen = 0;
   1067 		unsigned char *dest = NULL;
   1068 		unsigned int *dest_len = NULL;
   1069 
   1070 		if (rr->type == SSL3_RT_HANDSHAKE)
   1071 			{
   1072 			dest_maxlen = sizeof s->s3->handshake_fragment;
   1073 			dest = s->s3->handshake_fragment;
   1074 			dest_len = &s->s3->handshake_fragment_len;
   1075 			}
   1076 		else if (rr->type == SSL3_RT_ALERT)
   1077 			{
   1078 			dest_maxlen = sizeof s->s3->alert_fragment;
   1079 			dest = s->s3->alert_fragment;
   1080 			dest_len = &s->s3->alert_fragment_len;
   1081 			}
   1082 
   1083 		if (dest_maxlen > 0)
   1084 			{
   1085 			n = dest_maxlen - *dest_len; /* available space in 'dest' */
   1086 			if (rr->length < n)
   1087 				n = rr->length; /* available bytes */
   1088 
   1089 			/* now move 'n' bytes: */
   1090 			while (n-- > 0)
   1091 				{
   1092 				dest[(*dest_len)++] = rr->data[rr->off++];
   1093 				rr->length--;
   1094 				}
   1095 
   1096 			if (*dest_len < dest_maxlen)
   1097 				goto start; /* fragment was too small */
   1098 			}
   1099 		}
   1100 
   1101 	/* s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
   1102 	 * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
   1103 	 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
   1104 
   1105 	/* If we are a client, check for an incoming 'Hello Request': */
   1106 	if ((!s->server) &&
   1107 		(s->s3->handshake_fragment_len >= 4) &&
   1108 		(s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
   1109 		(s->session != NULL) && (s->session->cipher != NULL))
   1110 		{
   1111 		s->s3->handshake_fragment_len = 0;
   1112 
   1113 		if ((s->s3->handshake_fragment[1] != 0) ||
   1114 			(s->s3->handshake_fragment[2] != 0) ||
   1115 			(s->s3->handshake_fragment[3] != 0))
   1116 			{
   1117 			al=SSL_AD_DECODE_ERROR;
   1118 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
   1119 			goto f_err;
   1120 			}
   1121 
   1122 		if (s->msg_callback)
   1123 			s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
   1124 
   1125 		if (SSL_is_init_finished(s) &&
   1126 			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
   1127 			!s->s3->renegotiate)
   1128 			{
   1129 			ssl3_renegotiate(s);
   1130 			if (ssl3_renegotiate_check(s))
   1131 				{
   1132 				i=s->handshake_func(s);
   1133 				if (i < 0) return(i);
   1134 				if (i == 0)
   1135 					{
   1136 					SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
   1137 					return(-1);
   1138 					}
   1139 
   1140 				if (!(s->mode & SSL_MODE_AUTO_RETRY))
   1141 					{
   1142 					if (s->s3->rbuf.left == 0) /* no read-ahead left? */
   1143 						{
   1144 						BIO *bio;
   1145 						/* In the case where we try to read application data,
   1146 						 * but we trigger an SSL handshake, we return -1 with
   1147 						 * the retry option set.  Otherwise renegotiation may
   1148 						 * cause nasty problems in the blocking world */
   1149 						s->rwstate=SSL_READING;
   1150 						bio=SSL_get_rbio(s);
   1151 						BIO_clear_retry_flags(bio);
   1152 						BIO_set_retry_read(bio);
   1153 						return(-1);
   1154 						}
   1155 					}
   1156 				}
   1157 			}
   1158 		/* we either finished a handshake or ignored the request,
   1159 		 * now try again to obtain the (application) data we were asked for */
   1160 		goto start;
   1161 		}
   1162 	/* If we are a server and get a client hello when renegotiation isn't
   1163 	 * allowed send back a no renegotiation alert and carry on.
   1164 	 * WARNING: experimental code, needs reviewing (steve)
   1165 	 */
   1166 	if (s->server &&
   1167 		SSL_is_init_finished(s) &&
   1168     		!s->s3->send_connection_binding &&
   1169 		(s->version > SSL3_VERSION) &&
   1170 		(s->s3->handshake_fragment_len >= 4) &&
   1171 		(s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
   1172 		(s->session != NULL) && (s->session->cipher != NULL) &&
   1173 		!(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
   1174 
   1175 		{
   1176 		/*s->s3->handshake_fragment_len = 0;*/
   1177 		rr->length = 0;
   1178 		ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
   1179 		goto start;
   1180 		}
   1181 	if (s->s3->alert_fragment_len >= 2)
   1182 		{
   1183 		int alert_level = s->s3->alert_fragment[0];
   1184 		int alert_descr = s->s3->alert_fragment[1];
   1185 
   1186 		s->s3->alert_fragment_len = 0;
   1187 
   1188 		if (s->msg_callback)
   1189 			s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);
   1190 
   1191 		if (s->info_callback != NULL)
   1192 			cb=s->info_callback;
   1193 		else if (s->ctx->info_callback != NULL)
   1194 			cb=s->ctx->info_callback;
   1195 
   1196 		if (cb != NULL)
   1197 			{
   1198 			j = (alert_level << 8) | alert_descr;
   1199 			cb(s, SSL_CB_READ_ALERT, j);
   1200 			}
   1201 
   1202 		if (alert_level == 1) /* warning */
   1203 			{
   1204 			s->s3->warn_alert = alert_descr;
   1205 			if (alert_descr == SSL_AD_CLOSE_NOTIFY)
   1206 				{
   1207 				s->shutdown |= SSL_RECEIVED_SHUTDOWN;
   1208 				return(0);
   1209 				}
   1210 			/* This is a warning but we receive it if we requested
   1211 			 * renegotiation and the peer denied it. Terminate with
   1212 			 * a fatal alert because if application tried to
   1213 			 * renegotiatie it presumably had a good reason and
   1214 			 * expects it to succeed.
   1215 			 *
   1216 			 * In future we might have a renegotiation where we
   1217 			 * don't care if the peer refused it where we carry on.
   1218 			 */
   1219 			else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
   1220 				{
   1221 				al = SSL_AD_HANDSHAKE_FAILURE;
   1222 				SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION);
   1223 				goto f_err;
   1224 				}
   1225 			}
   1226 		else if (alert_level == 2) /* fatal */
   1227 			{
   1228 			char tmp[16];
   1229 
   1230 			s->rwstate=SSL_NOTHING;
   1231 			s->s3->fatal_alert = alert_descr;
   1232 			SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
   1233 			BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
   1234 			ERR_add_error_data(2,"SSL alert number ",tmp);
   1235 			s->shutdown|=SSL_RECEIVED_SHUTDOWN;
   1236 			SSL_CTX_remove_session(s->ctx,s->session);
   1237 			return(0);
   1238 			}
   1239 		else
   1240 			{
   1241 			al=SSL_AD_ILLEGAL_PARAMETER;
   1242 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
   1243 			goto f_err;
   1244 			}
   1245 
   1246 		goto start;
   1247 		}
   1248 
   1249 	if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
   1250 		{
   1251 		s->rwstate=SSL_NOTHING;
   1252 		rr->length=0;
   1253 		return(0);
   1254 		}
   1255 
   1256 	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
   1257 		{
   1258 		/* 'Change Cipher Spec' is just a single byte, so we know
   1259 		 * exactly what the record payload has to look like */
   1260 		if (	(rr->length != 1) || (rr->off != 0) ||
   1261 			(rr->data[0] != SSL3_MT_CCS))
   1262 			{
   1263 			al=SSL_AD_ILLEGAL_PARAMETER;
   1264 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
   1265 			goto f_err;
   1266 			}
   1267 
   1268 		/* Check we have a cipher to change to */
   1269 		if (s->s3->tmp.new_cipher == NULL)
   1270 			{
   1271 			al=SSL_AD_UNEXPECTED_MESSAGE;
   1272 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);
   1273 			goto f_err;
   1274 			}
   1275 
   1276 		rr->length=0;
   1277 
   1278 		if (s->msg_callback)
   1279 			s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
   1280 
   1281 		s->s3->change_cipher_spec=1;
   1282 		if (!ssl3_do_change_cipher_spec(s))
   1283 			goto err;
   1284 		else
   1285 			goto start;
   1286 		}
   1287 
   1288 	/* Unexpected handshake message (Client Hello, or protocol violation) */
   1289 	if ((s->s3->handshake_fragment_len >= 4) &&	!s->in_handshake)
   1290 		{
   1291 		if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
   1292 			!(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
   1293 			{
   1294 #if 0 /* worked only because C operator preferences are not as expected (and
   1295        * because this is not really needed for clients except for detecting
   1296        * protocol violations): */
   1297 			s->state=SSL_ST_BEFORE|(s->server)
   1298 				?SSL_ST_ACCEPT
   1299 				:SSL_ST_CONNECT;
   1300 #else
   1301 			s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
   1302 #endif
   1303 			s->new_session=1;
   1304 			}
   1305 		i=s->handshake_func(s);
   1306 		if (i < 0) return(i);
   1307 		if (i == 0)
   1308 			{
   1309 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
   1310 			return(-1);
   1311 			}
   1312 
   1313 		if (!(s->mode & SSL_MODE_AUTO_RETRY))
   1314 			{
   1315 			if (s->s3->rbuf.left == 0) /* no read-ahead left? */
   1316 				{
   1317 				BIO *bio;
   1318 				/* In the case where we try to read application data,
   1319 				 * but we trigger an SSL handshake, we return -1 with
   1320 				 * the retry option set.  Otherwise renegotiation may
   1321 				 * cause nasty problems in the blocking world */
   1322 				s->rwstate=SSL_READING;
   1323 				bio=SSL_get_rbio(s);
   1324 				BIO_clear_retry_flags(bio);
   1325 				BIO_set_retry_read(bio);
   1326 				return(-1);
   1327 				}
   1328 			}
   1329 		goto start;
   1330 		}
   1331 
   1332 	switch (rr->type)
   1333 		{
   1334 	default:
   1335 #ifndef OPENSSL_NO_TLS
   1336 		/* TLS just ignores unknown message types */
   1337 		if (s->version == TLS1_VERSION)
   1338 			{
   1339 			rr->length = 0;
   1340 			goto start;
   1341 			}
   1342 #endif
   1343 		al=SSL_AD_UNEXPECTED_MESSAGE;
   1344 		SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
   1345 		goto f_err;
   1346 	case SSL3_RT_CHANGE_CIPHER_SPEC:
   1347 	case SSL3_RT_ALERT:
   1348 	case SSL3_RT_HANDSHAKE:
   1349 		/* we already handled all of these, with the possible exception
   1350 		 * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
   1351 		 * should not happen when type != rr->type */
   1352 		al=SSL_AD_UNEXPECTED_MESSAGE;
   1353 		SSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR);
   1354 		goto f_err;
   1355 	case SSL3_RT_APPLICATION_DATA:
   1356 		/* At this point, we were expecting handshake data,
   1357 		 * but have application data.  If the library was
   1358 		 * running inside ssl3_read() (i.e. in_read_app_data
   1359 		 * is set) and it makes sense to read application data
   1360 		 * at this point (session renegotiation not yet started),
   1361 		 * we will indulge it.
   1362 		 */
   1363 		if (s->s3->in_read_app_data &&
   1364 			(s->s3->total_renegotiations != 0) &&
   1365 			((
   1366 				(s->state & SSL_ST_CONNECT) &&
   1367 				(s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
   1368 				(s->state <= SSL3_ST_CR_SRVR_HELLO_A)
   1369 				) || (
   1370 					(s->state & SSL_ST_ACCEPT) &&
   1371 					(s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
   1372 					(s->state >= SSL3_ST_SR_CLNT_HELLO_A)
   1373 					)
   1374 				))
   1375 			{
   1376 			s->s3->in_read_app_data=2;
   1377 			return(-1);
   1378 			}
   1379 		else
   1380 			{
   1381 			al=SSL_AD_UNEXPECTED_MESSAGE;
   1382 			SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
   1383 			goto f_err;
   1384 			}
   1385 		}
   1386 	/* not reached */
   1387 
   1388 f_err:
   1389 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1390 err:
   1391 	return(-1);
   1392 	}
   1393 
   1394 int ssl3_do_change_cipher_spec(SSL *s)
   1395 	{
   1396 	int i;
   1397 	const char *sender;
   1398 	int slen;
   1399 
   1400 	if (s->state & SSL_ST_ACCEPT)
   1401 		i=SSL3_CHANGE_CIPHER_SERVER_READ;
   1402 	else
   1403 		i=SSL3_CHANGE_CIPHER_CLIENT_READ;
   1404 
   1405 	if (s->s3->tmp.key_block == NULL)
   1406 		{
   1407 		if (s->session == NULL)
   1408 			{
   1409 			/* might happen if dtls1_read_bytes() calls this */
   1410 			SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,SSL_R_CCS_RECEIVED_EARLY);
   1411 			return (0);
   1412 			}
   1413 
   1414 		s->session->cipher=s->s3->tmp.new_cipher;
   1415 		if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
   1416 		}
   1417 
   1418 	if (!s->method->ssl3_enc->change_cipher_state(s,i))
   1419 		return(0);
   1420 
   1421 	/* we have to record the message digest at
   1422 	 * this point so we can get it before we read
   1423 	 * the finished message */
   1424 	if (s->state & SSL_ST_CONNECT)
   1425 		{
   1426 		sender=s->method->ssl3_enc->server_finished_label;
   1427 		slen=s->method->ssl3_enc->server_finished_label_len;
   1428 		}
   1429 	else
   1430 		{
   1431 		sender=s->method->ssl3_enc->client_finished_label;
   1432 		slen=s->method->ssl3_enc->client_finished_label_len;
   1433 		}
   1434 
   1435 	s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
   1436 		sender,slen,s->s3->tmp.peer_finish_md);
   1437 
   1438 	return(1);
   1439 	}
   1440 
   1441 int ssl3_send_alert(SSL *s, int level, int desc)
   1442 	{
   1443 	/* Map tls/ssl alert value to correct one */
   1444 	desc=s->method->ssl3_enc->alert_value(desc);
   1445 	if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
   1446 		desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
   1447 	if (desc < 0) return -1;
   1448 	/* If a fatal one, remove from cache */
   1449 	if ((level == 2) && (s->session != NULL))
   1450 		SSL_CTX_remove_session(s->ctx,s->session);
   1451 
   1452 	s->s3->alert_dispatch=1;
   1453 	s->s3->send_alert[0]=level;
   1454 	s->s3->send_alert[1]=desc;
   1455 	if (s->s3->wbuf.left == 0) /* data still being written out? */
   1456 		return s->method->ssl_dispatch_alert(s);
   1457 	/* else data is still being written out, we will get written
   1458 	 * some time in the future */
   1459 	return -1;
   1460 	}
   1461 
   1462 int ssl3_dispatch_alert(SSL *s)
   1463 	{
   1464 	int i,j;
   1465 	void (*cb)(const SSL *ssl,int type,int val)=NULL;
   1466 
   1467 	s->s3->alert_dispatch=0;
   1468 	i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
   1469 	if (i <= 0)
   1470 		{
   1471 		s->s3->alert_dispatch=1;
   1472 		}
   1473 	else
   1474 		{
   1475 		/* Alert sent to BIO.  If it is important, flush it now.
   1476 		 * If the message does not get sent due to non-blocking IO,
   1477 		 * we will not worry too much. */
   1478 		if (s->s3->send_alert[0] == SSL3_AL_FATAL)
   1479 			(void)BIO_flush(s->wbio);
   1480 
   1481 		if (s->msg_callback)
   1482 			s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
   1483 
   1484 		if (s->info_callback != NULL)
   1485 			cb=s->info_callback;
   1486 		else if (s->ctx->info_callback != NULL)
   1487 			cb=s->ctx->info_callback;
   1488 
   1489 		if (cb != NULL)
   1490 			{
   1491 			j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
   1492 			cb(s,SSL_CB_WRITE_ALERT,j);
   1493 			}
   1494 		}
   1495 	return(i);
   1496 	}
   1497