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