xref: /dragonfly/crypto/libressl/ssl/ssl_pkt.c (revision a85cb24f)
1 /* $OpenBSD: ssl_pkt.c,v 1.24 2020/03/16 15:25:14 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@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@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@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@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@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@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 
112 #include <errno.h>
113 #include <stdio.h>
114 
115 #include "ssl_locl.h"
116 
117 #include <openssl/buffer.h>
118 #include <openssl/evp.h>
119 
120 #include "bytestring.h"
121 
122 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
123     unsigned int len);
124 static int ssl3_get_record(SSL *s);
125 
126 /*
127  * Force a WANT_READ return for certain error conditions where
128  * we don't want to spin internally.
129  */
130 static void
131 ssl_force_want_read(SSL *s)
132 {
133 	BIO * bio;
134 
135 	bio = SSL_get_rbio(s);
136 	BIO_clear_retry_flags(bio);
137 	BIO_set_retry_read(bio);
138 	s->internal->rwstate = SSL_READING;
139 }
140 
141 /*
142  * If extend == 0, obtain new n-byte packet; if extend == 1, increase
143  * packet by another n bytes.
144  * The packet will be in the sub-array of S3I(s)->rbuf.buf specified
145  * by s->internal->packet and s->internal->packet_length.
146  * (If s->internal->read_ahead is set, 'max' bytes may be stored in rbuf
147  * [plus s->internal->packet_length bytes if extend == 1].)
148  */
149 static int
150 ssl3_read_n(SSL *s, int n, int max, int extend)
151 {
152 	int i, len, left;
153 	size_t align;
154 	unsigned char *pkt;
155 	SSL3_BUFFER_INTERNAL *rb;
156 
157 	if (n <= 0)
158 		return n;
159 
160 	rb = &(S3I(s)->rbuf);
161 	if (rb->buf == NULL)
162 		if (!ssl3_setup_read_buffer(s))
163 			return -1;
164 
165 	left = rb->left;
166 	align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
167 	align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
168 
169 	if (!extend) {
170 		/* start with empty packet ... */
171 		if (left == 0)
172 			rb->offset = align;
173 		else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
174 			/* check if next packet length is large
175 			 * enough to justify payload alignment... */
176 			pkt = rb->buf + rb->offset;
177 			if (pkt[0] == SSL3_RT_APPLICATION_DATA &&
178 			    (pkt[3]<<8|pkt[4]) >= 128) {
179 				/* Note that even if packet is corrupted
180 				 * and its length field is insane, we can
181 				 * only be led to wrong decision about
182 				 * whether memmove will occur or not.
183 				 * Header values has no effect on memmove
184 				 * arguments and therefore no buffer
185 				 * overrun can be triggered. */
186 				memmove(rb->buf + align, pkt, left);
187 				rb->offset = align;
188 			}
189 		}
190 		s->internal->packet = rb->buf + rb->offset;
191 		s->internal->packet_length = 0;
192 		/* ... now we can act as if 'extend' was set */
193 	}
194 
195 	/* For DTLS/UDP reads should not span multiple packets
196 	 * because the read operation returns the whole packet
197 	 * at once (as long as it fits into the buffer). */
198 	if (SSL_IS_DTLS(s)) {
199 		if (left > 0 && n > left)
200 			n = left;
201 	}
202 
203 	/* if there is enough in the buffer from a previous read, take some */
204 	if (left >= n) {
205 		s->internal->packet_length += n;
206 		rb->left = left - n;
207 		rb->offset += n;
208 		return (n);
209 	}
210 
211 	/* else we need to read more data */
212 
213 	len = s->internal->packet_length;
214 	pkt = rb->buf + align;
215 	/* Move any available bytes to front of buffer:
216 	 * 'len' bytes already pointed to by 'packet',
217 	 * 'left' extra ones at the end */
218 	if (s->internal->packet != pkt)  {
219 		/* len > 0 */
220 		memmove(pkt, s->internal->packet, len + left);
221 		s->internal->packet = pkt;
222 		rb->offset = len + align;
223 	}
224 
225 	if (n > (int)(rb->len - rb->offset)) {
226 		/* does not happen */
227 		SSLerror(s, ERR_R_INTERNAL_ERROR);
228 		return -1;
229 	}
230 
231 	if (!s->internal->read_ahead) {
232 		/* ignore max parameter */
233 		max = n;
234 	} else {
235 		if (max < n)
236 			max = n;
237 		if (max > (int)(rb->len - rb->offset))
238 			max = rb->len - rb->offset;
239 	}
240 
241 	while (left < n) {
242 		/* Now we have len+left bytes at the front of S3I(s)->rbuf.buf
243 		 * and need to read in more until we have len+n (up to
244 		 * len+max if possible) */
245 
246 		errno = 0;
247 		if (s->rbio != NULL) {
248 			s->internal->rwstate = SSL_READING;
249 			i = BIO_read(s->rbio, pkt + len + left, max - left);
250 		} else {
251 			SSLerror(s, SSL_R_READ_BIO_NOT_SET);
252 			i = -1;
253 		}
254 
255 		if (i <= 0) {
256 			rb->left = left;
257 			if (s->internal->mode & SSL_MODE_RELEASE_BUFFERS &&
258 			    !SSL_IS_DTLS(s)) {
259 				if (len + left == 0)
260 					ssl3_release_read_buffer(s);
261 			}
262 			return (i);
263 		}
264 		left += i;
265 
266 		/*
267 		 * reads should *never* span multiple packets for DTLS because
268 		 * the underlying transport protocol is message oriented as
269 		 * opposed to byte oriented as in the TLS case.
270 		 */
271 		if (SSL_IS_DTLS(s)) {
272 			if (n > left)
273 				n = left; /* makes the while condition false */
274 		}
275 	}
276 
277 	/* done reading, now the book-keeping */
278 	rb->offset += n;
279 	rb->left = left - n;
280 	s->internal->packet_length += n;
281 	s->internal->rwstate = SSL_NOTHING;
282 
283 	return (n);
284 }
285 
286 int
287 ssl3_packet_read(SSL *s, int plen)
288 {
289 	int n;
290 
291 	n = ssl3_read_n(s, plen, S3I(s)->rbuf.len, 0);
292 	if (n <= 0)
293 		return n;
294 	if (s->internal->packet_length < plen)
295 		return s->internal->packet_length;
296 
297 	return plen;
298 }
299 
300 int
301 ssl3_packet_extend(SSL *s, int plen)
302 {
303 	int rlen, n;
304 
305 	if (s->internal->packet_length >= plen)
306 		return plen;
307 	rlen = plen - s->internal->packet_length;
308 
309 	n = ssl3_read_n(s, rlen, rlen, 1);
310 	if (n <= 0)
311 		return n;
312 	if (s->internal->packet_length < plen)
313 		return s->internal->packet_length;
314 
315 	return plen;
316 }
317 
318 /* Call this to get a new input record.
319  * It will return <= 0 if more data is needed, normally due to an error
320  * or non-blocking IO.
321  * When it finishes, one packet has been decoded and can be found in
322  * ssl->s3->internal->rrec.type    - is the type of record
323  * ssl->s3->internal->rrec.data, 	 - data
324  * ssl->s3->internal->rrec.length, - number of bytes
325  */
326 /* used only by ssl3_read_bytes */
327 static int
328 ssl3_get_record(SSL *s)
329 {
330 	int al;
331 	int enc_err, n, i, ret = -1;
332 	SSL3_RECORD_INTERNAL *rr;
333 	SSL_SESSION *sess;
334 	unsigned char md[EVP_MAX_MD_SIZE];
335 	unsigned int mac_size, orig_len;
336 
337 	rr = &(S3I(s)->rrec);
338 	sess = s->session;
339 
340  again:
341 	/* check if we have the header */
342 	if ((s->internal->rstate != SSL_ST_READ_BODY) ||
343 	    (s->internal->packet_length < SSL3_RT_HEADER_LENGTH)) {
344 		CBS header;
345 		uint16_t len, ssl_version;
346 		uint8_t type;
347 
348 		n = ssl3_packet_read(s, SSL3_RT_HEADER_LENGTH);
349 		if (n <= 0)
350 			return (n);
351 
352 		s->internal->mac_packet = 1;
353 		s->internal->rstate = SSL_ST_READ_BODY;
354 
355 		if (s->server && s->internal->first_packet) {
356 			if ((ret = ssl_server_legacy_first_packet(s)) != 1)
357 				return (ret);
358 			ret = -1;
359 		}
360 
361 		CBS_init(&header, s->internal->packet, SSL3_RT_HEADER_LENGTH);
362 
363 		/* Pull apart the header into the SSL3_RECORD_INTERNAL */
364 		if (!CBS_get_u8(&header, &type) ||
365 		    !CBS_get_u16(&header, &ssl_version) ||
366 		    !CBS_get_u16(&header, &len)) {
367 			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
368 			goto err;
369 		}
370 
371 		rr->type = type;
372 		rr->length = len;
373 
374 		/* Lets check version */
375 		if (!s->internal->first_packet && ssl_version != s->version) {
376 			SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
377 			if ((s->version & 0xFF00) == (ssl_version & 0xFF00) &&
378 			    !s->internal->enc_write_ctx && !s->internal->write_hash)
379 				/* Send back error using their minor version number :-) */
380 				s->version = ssl_version;
381 			al = SSL_AD_PROTOCOL_VERSION;
382 			goto f_err;
383 		}
384 
385 		if ((ssl_version >> 8) != SSL3_VERSION_MAJOR) {
386 			SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
387 			goto err;
388 		}
389 
390 		if (rr->length > S3I(s)->rbuf.len - SSL3_RT_HEADER_LENGTH) {
391 			al = SSL_AD_RECORD_OVERFLOW;
392 			SSLerror(s, SSL_R_PACKET_LENGTH_TOO_LONG);
393 			goto f_err;
394 		}
395 
396 		/* now s->internal->rstate == SSL_ST_READ_BODY */
397 	}
398 
399 	/* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */
400 
401 	n = ssl3_packet_extend(s, SSL3_RT_HEADER_LENGTH + rr->length);
402 	if (n <= 0)
403 		return (n);
404 	if (n != SSL3_RT_HEADER_LENGTH + rr->length)
405 		return (n);
406 
407 	s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
408 
409 	/* At this point, s->internal->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
410 	 * and we have that many bytes in s->internal->packet
411 	 */
412 	rr->input = &(s->internal->packet[SSL3_RT_HEADER_LENGTH]);
413 
414 	/* ok, we can now read from 's->internal->packet' data into 'rr'
415 	 * rr->input points at rr->length bytes, which
416 	 * need to be copied into rr->data by either
417 	 * the decryption or by the decompression
418 	 * When the data is 'copied' into the rr->data buffer,
419 	 * rr->input will be pointed at the new buffer */
420 
421 	/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
422 	 * rr->length bytes of encrypted compressed stuff. */
423 
424 	/* check is not needed I believe */
425 	if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
426 		al = SSL_AD_RECORD_OVERFLOW;
427 		SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
428 		goto f_err;
429 	}
430 
431 	/* decrypt in place in 'rr->input' */
432 	rr->data = rr->input;
433 
434 	/* enc_err is:
435 	 *    0: (in non-constant time) if the record is publically invalid.
436 	 *    1: if the padding is valid
437 	 *    -1: if the padding is invalid */
438 	if ((enc_err = tls1_enc(s, 0)) == 0) {
439 		al = SSL_AD_BAD_RECORD_MAC;
440 		SSLerror(s, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
441 		goto f_err;
442 	}
443 
444 	/* r->length is now the compressed data plus mac */
445 	if ((sess != NULL) && (s->enc_read_ctx != NULL) &&
446 	    (EVP_MD_CTX_md(s->read_hash) != NULL)) {
447 		/* s->read_hash != NULL => mac_size != -1 */
448 		unsigned char *mac = NULL;
449 		unsigned char mac_tmp[EVP_MAX_MD_SIZE];
450 
451 		mac_size = EVP_MD_CTX_size(s->read_hash);
452 		OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
453 
454 		orig_len = rr->length + rr->padding_length;
455 
456 		/* orig_len is the length of the record before any padding was
457 		 * removed. This is public information, as is the MAC in use,
458 		 * therefore we can safely process the record in a different
459 		 * amount of time if it's too short to possibly contain a MAC.
460 		 */
461 		if (orig_len < mac_size ||
462 			/* CBC records must have a padding length byte too. */
463 		    (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
464 		    orig_len < mac_size + 1)) {
465 			al = SSL_AD_DECODE_ERROR;
466 			SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
467 			goto f_err;
468 		}
469 
470 		if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
471 			/* We update the length so that the TLS header bytes
472 			 * can be constructed correctly but we need to extract
473 			 * the MAC in constant time from within the record,
474 			 * without leaking the contents of the padding bytes.
475 			 * */
476 			mac = mac_tmp;
477 			ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
478 			rr->length -= mac_size;
479 		} else {
480 			/* In this case there's no padding, so |orig_len|
481 			 * equals |rec->length| and we checked that there's
482 			 * enough bytes for |mac_size| above. */
483 			rr->length -= mac_size;
484 			mac = &rr->data[rr->length];
485 		}
486 
487 		i = tls1_mac(s,md,0 /* not send */);
488 		if (i < 0 || mac == NULL ||
489 		    timingsafe_memcmp(md, mac, (size_t)mac_size) != 0)
490 			enc_err = -1;
491 		if (rr->length >
492 		    SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
493 			enc_err = -1;
494 	}
495 
496 	if (enc_err < 0) {
497 		/*
498 		 * A separate 'decryption_failed' alert was introduced with
499 		 * TLS 1.0, SSL 3.0 only has 'bad_record_mac'. But unless a
500 		 * decryption failure is directly visible from the ciphertext
501 		 * anyway, we should not reveal which kind of error
502 		 * occurred -- this might become visible to an attacker
503 		 * (e.g. via a logfile)
504 		 */
505 		al = SSL_AD_BAD_RECORD_MAC;
506 		SSLerror(s, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
507 		goto f_err;
508 	}
509 
510 	if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
511 		al = SSL_AD_RECORD_OVERFLOW;
512 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
513 		goto f_err;
514 	}
515 
516 	rr->off = 0;
517 	/*
518 	 * So at this point the following is true
519 	 *
520 	 * ssl->s3->internal->rrec.type 	is the type of record
521 	 * ssl->s3->internal->rrec.length	== number of bytes in record
522 	 * ssl->s3->internal->rrec.off	== offset to first valid byte
523 	 * ssl->s3->internal->rrec.data	== where to take bytes from, increment
524 	 *			   after use :-).
525 	 */
526 
527 	/* we have pulled in a full packet so zero things */
528 	s->internal->packet_length = 0;
529 
530 	if (rr->length == 0) {
531 		/*
532 		 * CBC countermeasures for known IV weaknesses
533 		 * can legitimately insert a single empty record,
534 		 * so we allow ourselves to read once past a single
535 		 * empty record without forcing want_read.
536 		 */
537 		if (s->internal->empty_record_count++ > SSL_MAX_EMPTY_RECORDS) {
538 			SSLerror(s, SSL_R_PEER_BEHAVING_BADLY);
539 			return -1;
540 		}
541 		if (s->internal->empty_record_count > 1) {
542 			ssl_force_want_read(s);
543 			return -1;
544 		}
545 		goto again;
546 	} else {
547 		s->internal->empty_record_count = 0;
548 	}
549 
550 	return (1);
551 
552 f_err:
553 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
554 err:
555 	return (ret);
556 }
557 
558 /* Call this to write data in records of type 'type'
559  * It will return <= 0 if not all data has been sent or non-blocking IO.
560  */
561 int
562 ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
563 {
564 	const unsigned char *buf = buf_;
565 	unsigned int tot, n, nw;
566 	int i;
567 
568 	if (len < 0) {
569 		SSLerror(s, ERR_R_INTERNAL_ERROR);
570 		return -1;
571 	}
572 
573 	s->internal->rwstate = SSL_NOTHING;
574 	tot = S3I(s)->wnum;
575 	S3I(s)->wnum = 0;
576 
577 	if (SSL_in_init(s) && !s->internal->in_handshake) {
578 		i = s->internal->handshake_func(s);
579 		if (i < 0)
580 			return (i);
581 		if (i == 0) {
582 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
583 			return -1;
584 		}
585 	}
586 
587 	if (len < tot)
588 		len = tot;
589 	n = (len - tot);
590 	for (;;) {
591 		if (n > s->max_send_fragment)
592 			nw = s->max_send_fragment;
593 		else
594 			nw = n;
595 
596 		i = do_ssl3_write(s, type, &(buf[tot]), nw);
597 		if (i <= 0) {
598 			S3I(s)->wnum = tot;
599 			return i;
600 		}
601 
602 		if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA &&
603 		    (s->internal->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
604 			/*
605 			 * Next chunk of data should get another prepended
606 			 * empty fragment in ciphersuites with known-IV
607 			 * weakness.
608 			 */
609 			S3I(s)->empty_fragment_done = 0;
610 
611 			return tot + i;
612 		}
613 
614 		n -= i;
615 		tot += i;
616 	}
617 }
618 
619 static int
620 ssl3_create_record(SSL *s, unsigned char *p, int type, const unsigned char *buf,
621     unsigned int len)
622 {
623 	SSL3_RECORD_INTERNAL *wr = &(S3I(s)->wrec);
624 	SSL_SESSION *sess = s->session;
625 	int eivlen, mac_size;
626 	uint16_t version;
627 	CBB cbb;
628 
629 	memset(&cbb, 0, sizeof(cbb));
630 
631 	if ((sess == NULL) || (s->internal->enc_write_ctx == NULL) ||
632 	    (EVP_MD_CTX_md(s->internal->write_hash) == NULL)) {
633 		mac_size = 0;
634 	} else {
635 		mac_size = EVP_MD_CTX_size(s->internal->write_hash);
636 		if (mac_size < 0)
637 			goto err;
638 	}
639 
640 	/*
641 	 * Some servers hang if initial client hello is larger than 256
642 	 * bytes and record version number > TLS 1.0.
643 	 */
644 	version = s->version;
645 	if (S3I(s)->hs.state == SSL3_ST_CW_CLNT_HELLO_B && !s->internal->renegotiate &&
646 	    TLS1_get_version(s) > TLS1_VERSION)
647 		version = TLS1_VERSION;
648 
649 	if (!CBB_init_fixed(&cbb, p, SSL3_RT_HEADER_LENGTH))
650 		goto err;
651 
652 	/* Write the header. */
653 	if (!CBB_add_u8(&cbb, type))
654 		goto err;
655 	if (!CBB_add_u16(&cbb, version))
656 		goto err;
657 
658 	p += SSL3_RT_HEADER_LENGTH;
659 
660 	/* Explicit IV length. */
661 	eivlen = 0;
662 	if (s->internal->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
663 		int mode = EVP_CIPHER_CTX_mode(s->internal->enc_write_ctx);
664 		if (mode == EVP_CIPH_CBC_MODE) {
665 			eivlen = EVP_CIPHER_CTX_iv_length(s->internal->enc_write_ctx);
666 			if (eivlen <= 1)
667 				eivlen = 0;
668 		}
669 	} else if (s->internal->aead_write_ctx != NULL &&
670 	    s->internal->aead_write_ctx->variable_nonce_in_record) {
671 		eivlen = s->internal->aead_write_ctx->variable_nonce_len;
672 	}
673 
674 	/* lets setup the record stuff. */
675 	wr->type = type;
676 	wr->data = p + eivlen;
677 	wr->length = (int)len;
678 	wr->input = (unsigned char *)buf;
679 
680 	/* we now 'read' from wr->input, wr->length bytes into wr->data */
681 
682 	memcpy(wr->data, wr->input, wr->length);
683 	wr->input = wr->data;
684 
685 	/* we should still have the output to wr->data and the input
686 	 * from wr->input.  Length should be wr->length.
687 	 * wr->data still points in the wb->buf */
688 
689 	if (mac_size != 0) {
690 		if (tls1_mac(s, &(p[wr->length + eivlen]), 1) < 0)
691 			goto err;
692 		wr->length += mac_size;
693 	}
694 
695 	wr->input = p;
696 	wr->data = p;
697 
698 	if (eivlen) {
699 		/* if (RAND_pseudo_bytes(p, eivlen) <= 0)
700 			goto err;
701 		*/
702 		wr->length += eivlen;
703 	}
704 
705 	/* tls1_enc can only have an error on read */
706 	tls1_enc(s, 1);
707 
708 	/* record length after mac and block padding */
709 	if (!CBB_add_u16(&cbb, wr->length))
710 		goto err;
711 	if (!CBB_finish(&cbb, NULL, NULL))
712 		goto err;
713 
714 	/* we should now have
715 	 * wr->data pointing to the encrypted data, which is
716 	 * wr->length long */
717 	wr->type = type; /* not needed but helps for debugging */
718 	wr->length += SSL3_RT_HEADER_LENGTH;
719 
720 	return 1;
721 
722  err:
723 	CBB_cleanup(&cbb);
724 
725 	return 0;
726 }
727 
728 static int
729 do_ssl3_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
730 {
731 	SSL3_RECORD_INTERNAL *wr = &(S3I(s)->wrec);
732 	SSL3_BUFFER_INTERNAL *wb = &(S3I(s)->wbuf);
733 	SSL_SESSION *sess = s->session;
734 	unsigned char *p;
735 	int i, clear = 0;
736 	int prefix_len = 0;
737 	size_t align;
738 
739 	if (wb->buf == NULL)
740 		if (!ssl3_setup_write_buffer(s))
741 			return -1;
742 
743 	/* first check if there is a SSL3_BUFFER_INTERNAL still being written
744 	 * out.  This will happen with non blocking IO */
745 	if (wb->left != 0)
746 		return (ssl3_write_pending(s, type, buf, len));
747 
748 	/* If we have an alert to send, lets send it */
749 	if (S3I(s)->alert_dispatch) {
750 		i = s->method->ssl_dispatch_alert(s);
751 		if (i <= 0)
752 			return (i);
753 		/* if it went, fall through and send more stuff */
754 		/* we may have released our buffer, so get it again */
755 		if (wb->buf == NULL)
756 			if (!ssl3_setup_write_buffer(s))
757 				return -1;
758 	}
759 
760 	if (len == 0)
761 		return 0;
762 
763 	align = (size_t)wb->buf + SSL3_RT_HEADER_LENGTH;
764 	align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
765 
766 	p = wb->buf + align;
767 	wb->offset = align;
768 
769 	if ((sess == NULL) || (s->internal->enc_write_ctx == NULL) ||
770 	    (EVP_MD_CTX_md(s->internal->write_hash) == NULL)) {
771 		clear = s->internal->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
772 	}
773 
774 	if (!clear && !S3I(s)->empty_fragment_done) {
775 		/*
776 		 * Countermeasure against known-IV weakness in CBC ciphersuites
777 		 * (see http://www.openssl.org/~bodo/tls-cbc.txt)
778 		 */
779 		if (S3I(s)->need_empty_fragments &&
780 		    type == SSL3_RT_APPLICATION_DATA) {
781 			/* extra fragment would be couple of cipher blocks,
782 			 * which would be multiple of SSL3_ALIGN_PAYLOAD, so
783 			 * if we want to align the real payload, then we can
784 			 * just pretent we simply have two headers. */
785 			align = (size_t)wb->buf + 2 * SSL3_RT_HEADER_LENGTH;
786 			align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
787 
788 			p = wb->buf + align;
789 			wb->offset = align;
790 
791 			if (!ssl3_create_record(s, p, type, buf, 0))
792 				goto err;
793 
794 			prefix_len = wr->length;
795 			if (prefix_len > (SSL3_RT_HEADER_LENGTH +
796 			    SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
797 				/* insufficient space */
798 				SSLerror(s, ERR_R_INTERNAL_ERROR);
799 				goto err;
800 			}
801 
802 			p = wb->buf + wb->offset + prefix_len;
803 		}
804 
805 		S3I(s)->empty_fragment_done = 1;
806 	}
807 
808 	if (!ssl3_create_record(s, p, type, buf, len))
809 		goto err;
810 
811 	/* now let's set up wb */
812 	wb->left = prefix_len + wr->length;
813 
814 	/* memorize arguments so that ssl3_write_pending can detect
815 	 * bad write retries later */
816 	S3I(s)->wpend_tot = len;
817 	S3I(s)->wpend_buf = buf;
818 	S3I(s)->wpend_type = type;
819 	S3I(s)->wpend_ret = len;
820 
821 	/* we now just need to write the buffer */
822 	return ssl3_write_pending(s, type, buf, len);
823 err:
824 	return -1;
825 }
826 
827 /* if S3I(s)->wbuf.left != 0, we need to call this */
828 int
829 ssl3_write_pending(SSL *s, int type, const unsigned char *buf, unsigned int len)
830 {
831 	int i;
832 	SSL3_BUFFER_INTERNAL *wb = &(S3I(s)->wbuf);
833 
834 	/* XXXX */
835 	if ((S3I(s)->wpend_tot > (int)len) || ((S3I(s)->wpend_buf != buf) &&
836 	    !(s->internal->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
837 	    (S3I(s)->wpend_type != type)) {
838 		SSLerror(s, SSL_R_BAD_WRITE_RETRY);
839 		return (-1);
840 	}
841 
842 	for (;;) {
843 		errno = 0;
844 		if (s->wbio != NULL) {
845 			s->internal->rwstate = SSL_WRITING;
846 			i = BIO_write(s->wbio,
847 			(char *)&(wb->buf[wb->offset]),
848 			(unsigned int)wb->left);
849 		} else {
850 			SSLerror(s, SSL_R_BIO_NOT_SET);
851 			i = -1;
852 		}
853 		if (i == wb->left) {
854 			wb->left = 0;
855 			wb->offset += i;
856 			if (s->internal->mode & SSL_MODE_RELEASE_BUFFERS &&
857 			    !SSL_IS_DTLS(s))
858 				ssl3_release_write_buffer(s);
859 			s->internal->rwstate = SSL_NOTHING;
860 			return (S3I(s)->wpend_ret);
861 		} else if (i <= 0) {
862 			/*
863 			 * For DTLS, just drop it. That's kind of the
864 			 * whole point in using a datagram service.
865 			 */
866 			if (SSL_IS_DTLS(s))
867 				wb->left = 0;
868 			return (i);
869 		}
870 		wb->offset += i;
871 		wb->left -= i;
872 	}
873 }
874 
875 /* Return up to 'len' payload bytes received in 'type' records.
876  * 'type' is one of the following:
877  *
878  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
879  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
880  *   -  0 (during a shutdown, no data has to be returned)
881  *
882  * If we don't have stored data to work from, read a SSL/TLS record first
883  * (possibly multiple records if we still don't have anything to return).
884  *
885  * This function must handle any surprises the peer may have for us, such as
886  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
887  * a surprise, but handled as if it were), or renegotiation requests.
888  * Also if record payloads contain fragments too small to process, we store
889  * them until there is enough for the respective protocol (the record protocol
890  * may use arbitrary fragmentation and even interleaving):
891  *     Change cipher spec protocol
892  *             just 1 byte needed, no need for keeping anything stored
893  *     Alert protocol
894  *             2 bytes needed (AlertLevel, AlertDescription)
895  *     Handshake protocol
896  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
897  *             to detect unexpected Client Hello and Hello Request messages
898  *             here, anything else is handled by higher layers
899  *     Application data protocol
900  *             none of our business
901  */
902 int
903 ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
904 {
905 	void (*cb)(const SSL *ssl, int type2, int val) = NULL;
906 	int al, i, j, ret, rrcount = 0;
907 	unsigned int n;
908 	SSL3_RECORD_INTERNAL *rr;
909 
910 	if (S3I(s)->rbuf.buf == NULL) /* Not initialized yet */
911 		if (!ssl3_setup_read_buffer(s))
912 			return (-1);
913 
914 	if (len < 0) {
915 		SSLerror(s, ERR_R_INTERNAL_ERROR);
916 		return -1;
917 	}
918 
919 	if ((type && type != SSL3_RT_APPLICATION_DATA &&
920 	    type != SSL3_RT_HANDSHAKE) ||
921 	    (peek && (type != SSL3_RT_APPLICATION_DATA))) {
922 		SSLerror(s, ERR_R_INTERNAL_ERROR);
923 		return -1;
924 	}
925 
926 	if ((type == SSL3_RT_HANDSHAKE) &&
927 	    (S3I(s)->handshake_fragment_len > 0)) {
928 		/* (partially) satisfy request from storage */
929 		unsigned char *src = S3I(s)->handshake_fragment;
930 		unsigned char *dst = buf;
931 		unsigned int k;
932 
933 		/* peek == 0 */
934 		n = 0;
935 		while ((len > 0) && (S3I(s)->handshake_fragment_len > 0)) {
936 			*dst++ = *src++;
937 			len--;
938 			S3I(s)->handshake_fragment_len--;
939 			n++;
940 		}
941 		/* move any remaining fragment bytes: */
942 		for (k = 0; k < S3I(s)->handshake_fragment_len; k++)
943 			S3I(s)->handshake_fragment[k] = *src++;
944 		return n;
945 	}
946 
947 	/*
948 	 * Now S3I(s)->handshake_fragment_len == 0 if
949 	 * type == SSL3_RT_HANDSHAKE.
950 	 */
951 	if (!s->internal->in_handshake && SSL_in_init(s)) {
952 		/* type == SSL3_RT_APPLICATION_DATA */
953 		i = s->internal->handshake_func(s);
954 		if (i < 0)
955 			return (i);
956 		if (i == 0) {
957 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
958 			return (-1);
959 		}
960 	}
961 
962 start:
963 	/*
964 	 * Do not process more than three consecutive records, otherwise the
965 	 * peer can cause us to loop indefinitely. Instead, return with an
966 	 * SSL_ERROR_WANT_READ so the caller can choose when to handle further
967 	 * processing. In the future, the total number of non-handshake and
968 	 * non-application data records per connection should probably also be
969 	 * limited...
970 	 */
971 	if (rrcount++ >= 3) {
972 		ssl_force_want_read(s);
973 		return -1;
974 	}
975 
976 	s->internal->rwstate = SSL_NOTHING;
977 
978 	/*
979 	 * S3I(s)->rrec.type	    - is the type of record
980 	 * S3I(s)->rrec.data,    - data
981 	 * S3I(s)->rrec.off,     - offset into 'data' for next read
982 	 * S3I(s)->rrec.length,  - number of bytes.
983 	 */
984 	rr = &(S3I(s)->rrec);
985 
986 	/* get new packet if necessary */
987 	if ((rr->length == 0) || (s->internal->rstate == SSL_ST_READ_BODY)) {
988 		ret = ssl3_get_record(s);
989 		if (ret <= 0)
990 			return (ret);
991 	}
992 
993 	/* we now have a packet which can be read and processed */
994 
995 	if (S3I(s)->change_cipher_spec /* set when we receive ChangeCipherSpec,
996 	                               * reset by ssl3_get_finished */
997 	    && (rr->type != SSL3_RT_HANDSHAKE)) {
998 		al = SSL_AD_UNEXPECTED_MESSAGE;
999 		SSLerror(s, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1000 		goto f_err;
1001 	}
1002 
1003 	/* If the other end has shut down, throw anything we read away
1004 	 * (even in 'peek' mode) */
1005 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
1006 		rr->length = 0;
1007 		s->internal->rwstate = SSL_NOTHING;
1008 		return (0);
1009 	}
1010 
1011 
1012 	/* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
1013 	if (type == rr->type) {
1014 		/* make sure that we are not getting application data when we
1015 		 * are doing a handshake for the first time */
1016 		if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1017 			(s->enc_read_ctx == NULL)) {
1018 			al = SSL_AD_UNEXPECTED_MESSAGE;
1019 			SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
1020 			goto f_err;
1021 		}
1022 
1023 		if (len <= 0)
1024 			return (len);
1025 
1026 		if ((unsigned int)len > rr->length)
1027 			n = rr->length;
1028 		else
1029 			n = (unsigned int)len;
1030 
1031 		memcpy(buf, &(rr->data[rr->off]), n);
1032 		if (!peek) {
1033 			memset(&(rr->data[rr->off]), 0, n);
1034 			rr->length -= n;
1035 			rr->off += n;
1036 			if (rr->length == 0) {
1037 				s->internal->rstate = SSL_ST_READ_HEADER;
1038 				rr->off = 0;
1039 				if (s->internal->mode & SSL_MODE_RELEASE_BUFFERS &&
1040 				    S3I(s)->rbuf.left == 0)
1041 					ssl3_release_read_buffer(s);
1042 			}
1043 		}
1044 		return (n);
1045 	}
1046 
1047 
1048 	/* If we get here, then type != rr->type; if we have a handshake
1049 	 * message, then it was unexpected (Hello Request or Client Hello). */
1050 
1051 	{
1052 		/*
1053 		 * In case of record types for which we have 'fragment'
1054 		 * storage, * fill that so that we can process the data
1055 		 * at a fixed place.
1056 		 */
1057 		unsigned int dest_maxlen = 0;
1058 		unsigned char *dest = NULL;
1059 		unsigned int *dest_len = NULL;
1060 
1061 		if (rr->type == SSL3_RT_HANDSHAKE) {
1062 			dest_maxlen = sizeof S3I(s)->handshake_fragment;
1063 			dest = S3I(s)->handshake_fragment;
1064 			dest_len = &S3I(s)->handshake_fragment_len;
1065 		} else if (rr->type == SSL3_RT_ALERT) {
1066 			dest_maxlen = sizeof S3I(s)->alert_fragment;
1067 			dest = S3I(s)->alert_fragment;
1068 			dest_len = &S3I(s)->alert_fragment_len;
1069 		}
1070 		if (dest_maxlen > 0) {
1071 			/* available space in 'dest' */
1072 			n = dest_maxlen - *dest_len;
1073 			if (rr->length < n)
1074 				n = rr->length; /* available bytes */
1075 
1076 			/* now move 'n' bytes: */
1077 			while (n-- > 0) {
1078 				dest[(*dest_len)++] = rr->data[rr->off++];
1079 				rr->length--;
1080 			}
1081 
1082 			if (*dest_len < dest_maxlen)
1083 				goto start; /* fragment was too small */
1084 		}
1085 	}
1086 
1087 	/* S3I(s)->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1088 	 * S3I(s)->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1089 	 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
1090 
1091 	/* If we are a client, check for an incoming 'Hello Request': */
1092 	if ((!s->server) && (S3I(s)->handshake_fragment_len >= 4) &&
1093 	    (S3I(s)->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1094 	    (s->session != NULL) && (s->session->cipher != NULL)) {
1095 		S3I(s)->handshake_fragment_len = 0;
1096 
1097 		if ((S3I(s)->handshake_fragment[1] != 0) ||
1098 		    (S3I(s)->handshake_fragment[2] != 0) ||
1099 		    (S3I(s)->handshake_fragment[3] != 0)) {
1100 			al = SSL_AD_DECODE_ERROR;
1101 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
1102 			goto f_err;
1103 		}
1104 
1105 		if (s->internal->msg_callback)
1106 			s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1107 			    S3I(s)->handshake_fragment, 4, s,
1108 			    s->internal->msg_callback_arg);
1109 
1110 		if (SSL_is_init_finished(s) &&
1111 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1112 		    !S3I(s)->renegotiate) {
1113 			ssl3_renegotiate(s);
1114 			if (ssl3_renegotiate_check(s)) {
1115 				i = s->internal->handshake_func(s);
1116 				if (i < 0)
1117 					return (i);
1118 				if (i == 0) {
1119 					SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1120 					return (-1);
1121 				}
1122 
1123 				if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
1124 					if (S3I(s)->rbuf.left == 0) {
1125 						/* no read-ahead left? */
1126 			/* In the case where we try to read application data,
1127 			 * but we trigger an SSL handshake, we return -1 with
1128 			 * the retry option set.  Otherwise renegotiation may
1129 			 * cause nasty problems in the blocking world */
1130 						ssl_force_want_read(s);
1131 						return (-1);
1132 					}
1133 				}
1134 			}
1135 		}
1136 		/* we either finished a handshake or ignored the request,
1137 		 * now try again to obtain the (application) data we were asked for */
1138 		goto start;
1139 	}
1140 	/* Disallow client initiated renegotiation if configured. */
1141 	if (s->server && SSL_is_init_finished(s) &&
1142 	    S3I(s)->handshake_fragment_len >= 4 &&
1143 	    S3I(s)->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO &&
1144 	    (s->internal->options & SSL_OP_NO_CLIENT_RENEGOTIATION)) {
1145 		al = SSL_AD_NO_RENEGOTIATION;
1146 		goto f_err;
1147 	}
1148 	/* If we are a server and get a client hello when renegotiation isn't
1149 	 * allowed send back a no renegotiation alert and carry on.
1150 	 * WARNING: experimental code, needs reviewing (steve)
1151 	 */
1152 	if (s->server &&
1153 	    SSL_is_init_finished(s) &&
1154 	    !S3I(s)->send_connection_binding &&
1155 	    (S3I(s)->handshake_fragment_len >= 4) &&
1156 	    (S3I(s)->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1157 	    (s->session != NULL) && (s->session->cipher != NULL)) {
1158 		/*S3I(s)->handshake_fragment_len = 0;*/
1159 		rr->length = 0;
1160 		ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1161 		goto start;
1162 	}
1163 	if (S3I(s)->alert_fragment_len >= 2) {
1164 		int alert_level = S3I(s)->alert_fragment[0];
1165 		int alert_descr = S3I(s)->alert_fragment[1];
1166 
1167 		S3I(s)->alert_fragment_len = 0;
1168 
1169 		if (s->internal->msg_callback)
1170 			s->internal->msg_callback(0, s->version, SSL3_RT_ALERT,
1171 			    S3I(s)->alert_fragment, 2, s, s->internal->msg_callback_arg);
1172 
1173 		if (s->internal->info_callback != NULL)
1174 			cb = s->internal->info_callback;
1175 		else if (s->ctx->internal->info_callback != NULL)
1176 			cb = s->ctx->internal->info_callback;
1177 
1178 		if (cb != NULL) {
1179 			j = (alert_level << 8) | alert_descr;
1180 			cb(s, SSL_CB_READ_ALERT, j);
1181 		}
1182 
1183 		if (alert_level == SSL3_AL_WARNING) {
1184 			S3I(s)->warn_alert = alert_descr;
1185 			if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1186 				s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
1187 				return (0);
1188 			}
1189 			/* This is a warning but we receive it if we requested
1190 			 * renegotiation and the peer denied it. Terminate with
1191 			 * a fatal alert because if application tried to
1192 			 * renegotiatie it presumably had a good reason and
1193 			 * expects it to succeed.
1194 			 *
1195 			 * In future we might have a renegotiation where we
1196 			 * don't care if the peer refused it where we carry on.
1197 			 */
1198 			else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1199 				al = SSL_AD_HANDSHAKE_FAILURE;
1200 				SSLerror(s, SSL_R_NO_RENEGOTIATION);
1201 				goto f_err;
1202 			}
1203 		} else if (alert_level == SSL3_AL_FATAL) {
1204 			s->internal->rwstate = SSL_NOTHING;
1205 			S3I(s)->fatal_alert = alert_descr;
1206 			SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
1207 			ERR_asprintf_error_data("SSL alert number %d",
1208 			    alert_descr);
1209 			s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
1210 			SSL_CTX_remove_session(s->ctx, s->session);
1211 			return (0);
1212 		} else {
1213 			al = SSL_AD_ILLEGAL_PARAMETER;
1214 			SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
1215 			goto f_err;
1216 		}
1217 
1218 		goto start;
1219 	}
1220 
1221 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
1222 		/* but we have not received a shutdown */
1223 		s->internal->rwstate = SSL_NOTHING;
1224 		rr->length = 0;
1225 		return (0);
1226 	}
1227 
1228 	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1229 		/* 'Change Cipher Spec' is just a single byte, so we know
1230 		 * exactly what the record payload has to look like */
1231 		if ((rr->length != 1) || (rr->off != 0) ||
1232 			(rr->data[0] != SSL3_MT_CCS)) {
1233 			al = SSL_AD_ILLEGAL_PARAMETER;
1234 			SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
1235 			goto f_err;
1236 		}
1237 
1238 		/* Check we have a cipher to change to */
1239 		if (S3I(s)->hs.new_cipher == NULL) {
1240 			al = SSL_AD_UNEXPECTED_MESSAGE;
1241 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1242 			goto f_err;
1243 		}
1244 
1245 		/* Check that we should be receiving a Change Cipher Spec. */
1246 		if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
1247 			al = SSL_AD_UNEXPECTED_MESSAGE;
1248 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1249 			goto f_err;
1250 		}
1251 		s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1252 
1253 		rr->length = 0;
1254 
1255 		if (s->internal->msg_callback) {
1256 			s->internal->msg_callback(0, s->version,
1257 			    SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
1258 			    s->internal->msg_callback_arg);
1259 		}
1260 
1261 		S3I(s)->change_cipher_spec = 1;
1262 		if (!ssl3_do_change_cipher_spec(s))
1263 			goto err;
1264 		else
1265 			goto start;
1266 	}
1267 
1268 	/* Unexpected handshake message (Client Hello, or protocol violation) */
1269 	if ((S3I(s)->handshake_fragment_len >= 4) && !s->internal->in_handshake) {
1270 		if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) &&
1271 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1272 			S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1273 			s->internal->renegotiate = 1;
1274 			s->internal->new_session = 1;
1275 		}
1276 		i = s->internal->handshake_func(s);
1277 		if (i < 0)
1278 			return (i);
1279 		if (i == 0) {
1280 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1281 			return (-1);
1282 		}
1283 
1284 		if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
1285 			if (S3I(s)->rbuf.left == 0) { /* no read-ahead left? */
1286 				/* In the case where we try to read application data,
1287 				 * but we trigger an SSL handshake, we return -1 with
1288 				 * the retry option set.  Otherwise renegotiation may
1289 				 * cause nasty problems in the blocking world */
1290 				ssl_force_want_read(s);
1291 				return (-1);
1292 			}
1293 		}
1294 		goto start;
1295 	}
1296 
1297 	switch (rr->type) {
1298 	default:
1299 		/*
1300 		 * TLS up to v1.1 just ignores unknown message types:
1301 		 * TLS v1.2 give an unexpected message alert.
1302 		 */
1303 		if (s->version >= TLS1_VERSION &&
1304 		    s->version <= TLS1_1_VERSION) {
1305 			rr->length = 0;
1306 			goto start;
1307 		}
1308 		al = SSL_AD_UNEXPECTED_MESSAGE;
1309 		SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1310 		goto f_err;
1311 	case SSL3_RT_CHANGE_CIPHER_SPEC:
1312 	case SSL3_RT_ALERT:
1313 	case SSL3_RT_HANDSHAKE:
1314 		/* we already handled all of these, with the possible exception
1315 		 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that
1316 		 * should not happen when type != rr->type */
1317 		al = SSL_AD_UNEXPECTED_MESSAGE;
1318 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1319 		goto f_err;
1320 	case SSL3_RT_APPLICATION_DATA:
1321 		/* At this point, we were expecting handshake data,
1322 		 * but have application data.  If the library was
1323 		 * running inside ssl3_read() (i.e. in_read_app_data
1324 		 * is set) and it makes sense to read application data
1325 		 * at this point (session renegotiation not yet started),
1326 		 * we will indulge it.
1327 		 */
1328 		if (S3I(s)->in_read_app_data &&
1329 		    (S3I(s)->total_renegotiations != 0) &&
1330 		    (((S3I(s)->hs.state & SSL_ST_CONNECT) &&
1331 		    (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1332 		    (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) ||
1333 		    ((S3I(s)->hs.state & SSL_ST_ACCEPT) &&
1334 		    (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
1335 		    (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1336 			S3I(s)->in_read_app_data = 2;
1337 			return (-1);
1338 		} else {
1339 			al = SSL_AD_UNEXPECTED_MESSAGE;
1340 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1341 			goto f_err;
1342 		}
1343 	}
1344 	/* not reached */
1345 
1346 f_err:
1347 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1348 err:
1349 	return (-1);
1350 }
1351 
1352 int
1353 ssl3_do_change_cipher_spec(SSL *s)
1354 {
1355 	int i;
1356 	const char *sender;
1357 	int slen;
1358 
1359 	if (S3I(s)->hs.state & SSL_ST_ACCEPT)
1360 		i = SSL3_CHANGE_CIPHER_SERVER_READ;
1361 	else
1362 		i = SSL3_CHANGE_CIPHER_CLIENT_READ;
1363 
1364 	if (S3I(s)->hs.key_block == NULL) {
1365 		if (s->session == NULL || s->session->master_key_length == 0) {
1366 			/* might happen if dtls1_read_bytes() calls this */
1367 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1368 			return (0);
1369 		}
1370 
1371 		s->session->cipher = S3I(s)->hs.new_cipher;
1372 		if (!tls1_setup_key_block(s))
1373 			return (0);
1374 	}
1375 
1376 	if (!tls1_change_cipher_state(s, i))
1377 		return (0);
1378 
1379 	/* we have to record the message digest at
1380 	 * this point so we can get it before we read
1381 	 * the finished message */
1382 	if (S3I(s)->hs.state & SSL_ST_CONNECT) {
1383 		sender = TLS_MD_SERVER_FINISH_CONST;
1384 		slen = TLS_MD_SERVER_FINISH_CONST_SIZE;
1385 	} else {
1386 		sender = TLS_MD_CLIENT_FINISH_CONST;
1387 		slen = TLS_MD_CLIENT_FINISH_CONST_SIZE;
1388 	}
1389 
1390 	i = tls1_final_finish_mac(s, sender, slen,
1391 	    S3I(s)->tmp.peer_finish_md);
1392 	if (i == 0) {
1393 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1394 		return 0;
1395 	}
1396 	S3I(s)->tmp.peer_finish_md_len = i;
1397 
1398 	return (1);
1399 }
1400 
1401 int
1402 ssl3_send_alert(SSL *s, int level, int desc)
1403 {
1404 	/* Map tls/ssl alert value to correct one */
1405 	desc = tls1_alert_code(desc);
1406 	if (desc < 0)
1407 		return -1;
1408 	/* If a fatal one, remove from cache */
1409 	if ((level == 2) && (s->session != NULL))
1410 		SSL_CTX_remove_session(s->ctx, s->session);
1411 
1412 	S3I(s)->alert_dispatch = 1;
1413 	S3I(s)->send_alert[0] = level;
1414 	S3I(s)->send_alert[1] = desc;
1415 	if (S3I(s)->wbuf.left == 0) /* data still being written out? */
1416 		return s->method->ssl_dispatch_alert(s);
1417 
1418 	/* else data is still being written out, we will get written
1419 	 * some time in the future */
1420 	return -1;
1421 }
1422 
1423 int
1424 ssl3_dispatch_alert(SSL *s)
1425 {
1426 	int i, j;
1427 	void (*cb)(const SSL *ssl, int type, int val) = NULL;
1428 
1429 	S3I(s)->alert_dispatch = 0;
1430 	i = do_ssl3_write(s, SSL3_RT_ALERT, &S3I(s)->send_alert[0], 2);
1431 	if (i <= 0) {
1432 		S3I(s)->alert_dispatch = 1;
1433 	} else {
1434 		/* Alert sent to BIO.  If it is important, flush it now.
1435 		 * If the message does not get sent due to non-blocking IO,
1436 		 * we will not worry too much. */
1437 		if (S3I(s)->send_alert[0] == SSL3_AL_FATAL)
1438 			(void)BIO_flush(s->wbio);
1439 
1440 		if (s->internal->msg_callback)
1441 			s->internal->msg_callback(1, s->version, SSL3_RT_ALERT,
1442 			    S3I(s)->send_alert, 2, s, s->internal->msg_callback_arg);
1443 
1444 		if (s->internal->info_callback != NULL)
1445 			cb = s->internal->info_callback;
1446 		else if (s->ctx->internal->info_callback != NULL)
1447 			cb = s->ctx->internal->info_callback;
1448 
1449 		if (cb != NULL) {
1450 			j = (S3I(s)->send_alert[0]<<8)|S3I(s)->send_alert[1];
1451 			cb(s, SSL_CB_WRITE_ALERT, j);
1452 		}
1453 	}
1454 	return (i);
1455 }
1456