xref: /openbsd-src/lib/libssl/ssl_pkt.c (revision 3374c67d44f9b75b98444cbf63020f777792342e)
1 /* $OpenBSD: ssl_pkt.c,v 1.65 2022/11/26 16:08:56 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 <limits.h>
114 #include <stdio.h>
115 
116 #include <openssl/buffer.h>
117 #include <openssl/evp.h>
118 
119 #include "bytestring.h"
120 #include "dtls_local.h"
121 #include "ssl_local.h"
122 #include "tls_content.h"
123 
124 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
125     unsigned int len);
126 static int ssl3_get_record(SSL *s);
127 
128 /*
129  * Force a WANT_READ return for certain error conditions where
130  * we don't want to spin internally.
131  */
132 void
133 ssl_force_want_read(SSL *s)
134 {
135 	BIO *bio;
136 
137 	bio = SSL_get_rbio(s);
138 	BIO_clear_retry_flags(bio);
139 	BIO_set_retry_read(bio);
140 
141 	s->rwstate = SSL_READING;
142 }
143 
144 /*
145  * If extend == 0, obtain new n-byte packet; if extend == 1, increase
146  * packet by another n bytes.
147  * The packet will be in the sub-array of s->s3->rbuf.buf specified
148  * by s->packet and s->packet_length.
149  * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
150  * [plus s->packet_length bytes if extend == 1].)
151  */
152 static int
153 ssl3_read_n(SSL *s, int n, int max, int extend)
154 {
155 	SSL3_BUFFER_INTERNAL *rb = &(s->s3->rbuf);
156 	int i, len, left;
157 	size_t align;
158 	unsigned char *pkt;
159 
160 	if (n <= 0)
161 		return n;
162 
163 	if (rb->buf == NULL) {
164 		if (!ssl3_setup_read_buffer(s))
165 			return -1;
166 	}
167 	if (rb->buf == NULL)
168 		return -1;
169 
170 	left = rb->left;
171 	align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
172 	align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
173 
174 	if (!extend) {
175 		/* start with empty packet ... */
176 		if (left == 0)
177 			rb->offset = align;
178 		else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
179 			/* check if next packet length is large
180 			 * enough to justify payload alignment... */
181 			pkt = rb->buf + rb->offset;
182 			if (pkt[0] == SSL3_RT_APPLICATION_DATA &&
183 			    (pkt[3]<<8|pkt[4]) >= 128) {
184 				/* Note that even if packet is corrupted
185 				 * and its length field is insane, we can
186 				 * only be led to wrong decision about
187 				 * whether memmove will occur or not.
188 				 * Header values has no effect on memmove
189 				 * arguments and therefore no buffer
190 				 * overrun can be triggered. */
191 				memmove(rb->buf + align, pkt, left);
192 				rb->offset = align;
193 			}
194 		}
195 		s->packet = rb->buf + rb->offset;
196 		s->packet_length = 0;
197 		/* ... now we can act as if 'extend' was set */
198 	}
199 
200 	/* For DTLS/UDP reads should not span multiple packets
201 	 * because the read operation returns the whole packet
202 	 * at once (as long as it fits into the buffer). */
203 	if (SSL_is_dtls(s)) {
204 		if (left > 0 && n > left)
205 			n = left;
206 	}
207 
208 	/* if there is enough in the buffer from a previous read, take some */
209 	if (left >= n) {
210 		s->packet_length += n;
211 		rb->left = left - n;
212 		rb->offset += n;
213 		return (n);
214 	}
215 
216 	/* else we need to read more data */
217 
218 	len = s->packet_length;
219 	pkt = rb->buf + align;
220 	/* Move any available bytes to front of buffer:
221 	 * 'len' bytes already pointed to by 'packet',
222 	 * 'left' extra ones at the end */
223 	if (s->packet != pkt)  {
224 		/* len > 0 */
225 		memmove(pkt, s->packet, len + left);
226 		s->packet = pkt;
227 		rb->offset = len + align;
228 	}
229 
230 	if (n > (int)(rb->len - rb->offset)) {
231 		/* does not happen */
232 		SSLerror(s, ERR_R_INTERNAL_ERROR);
233 		return -1;
234 	}
235 
236 	if (s->read_ahead || SSL_is_dtls(s)) {
237 		if (max < n)
238 			max = n;
239 		if (max > (int)(rb->len - rb->offset))
240 			max = rb->len - rb->offset;
241 	} else {
242 		/* ignore max parameter */
243 		max = n;
244 	}
245 
246 	while (left < n) {
247 		/* Now we have len+left bytes at the front of s->s3->rbuf.buf
248 		 * and need to read in more until we have len+n (up to
249 		 * len+max if possible) */
250 
251 		errno = 0;
252 		if (s->rbio != NULL) {
253 			s->rwstate = SSL_READING;
254 			i = BIO_read(s->rbio, pkt + len + left, max - left);
255 		} else {
256 			SSLerror(s, SSL_R_READ_BIO_NOT_SET);
257 			i = -1;
258 		}
259 
260 		if (i <= 0) {
261 			rb->left = left;
262 			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
263 			    !SSL_is_dtls(s)) {
264 				if (len + left == 0)
265 					ssl3_release_read_buffer(s);
266 			}
267 			return (i);
268 		}
269 		left += i;
270 
271 		/*
272 		 * reads should *never* span multiple packets for DTLS because
273 		 * the underlying transport protocol is message oriented as
274 		 * opposed to byte oriented as in the TLS case.
275 		 */
276 		if (SSL_is_dtls(s)) {
277 			if (n > left)
278 				n = left; /* makes the while condition false */
279 		}
280 	}
281 
282 	/* done reading, now the book-keeping */
283 	rb->offset += n;
284 	rb->left = left - n;
285 	s->packet_length += n;
286 	s->rwstate = SSL_NOTHING;
287 
288 	return (n);
289 }
290 
291 int
292 ssl3_packet_read(SSL *s, int plen)
293 {
294 	int n;
295 
296 	n = ssl3_read_n(s, plen, s->s3->rbuf.len, 0);
297 	if (n <= 0)
298 		return n;
299 	if (s->packet_length < plen)
300 		return s->packet_length;
301 
302 	return plen;
303 }
304 
305 int
306 ssl3_packet_extend(SSL *s, int plen)
307 {
308 	int rlen, n;
309 
310 	if (s->packet_length >= plen)
311 		return plen;
312 	rlen = plen - s->packet_length;
313 
314 	n = ssl3_read_n(s, rlen, rlen, 1);
315 	if (n <= 0)
316 		return n;
317 	if (s->packet_length < plen)
318 		return s->packet_length;
319 
320 	return plen;
321 }
322 
323 /* Call this to get a new input record.
324  * It will return <= 0 if more data is needed, normally due to an error
325  * or non-blocking IO.
326  * When it finishes, one packet has been decoded and can be found in
327  * ssl->s3->rrec.type    - is the type of record
328  * ssl->s3->rrec.data, 	 - data
329  * ssl->s3->rrec.length, - number of bytes
330  */
331 /* used only by ssl3_read_bytes */
332 static int
333 ssl3_get_record(SSL *s)
334 {
335 	SSL3_BUFFER_INTERNAL *rb = &(s->s3->rbuf);
336 	SSL3_RECORD_INTERNAL *rr = &(s->s3->rrec);
337 	uint8_t alert_desc;
338 	int al, n;
339 	int ret = -1;
340 
341  again:
342 	/* check if we have the header */
343 	if ((s->rstate != SSL_ST_READ_BODY) ||
344 	    (s->packet_length < SSL3_RT_HEADER_LENGTH)) {
345 		CBS header;
346 		uint16_t len, ssl_version;
347 		uint8_t type;
348 
349 		n = ssl3_packet_read(s, SSL3_RT_HEADER_LENGTH);
350 		if (n <= 0)
351 			return (n);
352 
353 		s->mac_packet = 1;
354 		s->rstate = SSL_ST_READ_BODY;
355 
356 		if (s->server && s->first_packet) {
357 			if ((ret = ssl_server_legacy_first_packet(s)) != 1)
358 				return (ret);
359 			ret = -1;
360 		}
361 
362 		CBS_init(&header, s->packet, SSL3_RT_HEADER_LENGTH);
363 
364 		/* Pull apart the header into the SSL3_RECORD_INTERNAL */
365 		if (!CBS_get_u8(&header, &type) ||
366 		    !CBS_get_u16(&header, &ssl_version) ||
367 		    !CBS_get_u16(&header, &len)) {
368 			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
369 			goto err;
370 		}
371 
372 		rr->type = type;
373 		rr->length = len;
374 
375 		/* Lets check version */
376 		if (!s->first_packet && ssl_version != s->version) {
377 			if ((s->version & 0xFF00) == (ssl_version & 0xFF00) &&
378 			    !tls12_record_layer_write_protected(s->rl)) {
379 				/* Send back error using their minor version number :-) */
380 				s->version = ssl_version;
381 			}
382 			SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
383 			al = SSL_AD_PROTOCOL_VERSION;
384 			goto fatal_err;
385 		}
386 
387 		if ((ssl_version >> 8) != SSL3_VERSION_MAJOR) {
388 			SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
389 			goto err;
390 		}
391 
392 		if (rr->length > rb->len - SSL3_RT_HEADER_LENGTH) {
393 			al = SSL_AD_RECORD_OVERFLOW;
394 			SSLerror(s, SSL_R_PACKET_LENGTH_TOO_LONG);
395 			goto fatal_err;
396 		}
397 	}
398 
399 	n = ssl3_packet_extend(s, SSL3_RT_HEADER_LENGTH + rr->length);
400 	if (n <= 0)
401 		return (n);
402 	if (n != SSL3_RT_HEADER_LENGTH + rr->length)
403 		return (n);
404 
405 	s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
406 
407 	/*
408 	 * A full record has now been read from the wire, which now needs
409 	 * to be processed.
410 	 */
411 	tls12_record_layer_set_version(s->rl, s->version);
412 
413 	if (!tls12_record_layer_open_record(s->rl, s->packet, s->packet_length,
414 	    s->s3->rcontent)) {
415 		tls12_record_layer_alert(s->rl, &alert_desc);
416 
417 		if (alert_desc == 0)
418 			goto err;
419 
420 		if (alert_desc == SSL_AD_RECORD_OVERFLOW)
421 			SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
422 		else if (alert_desc == SSL_AD_BAD_RECORD_MAC)
423 			SSLerror(s, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
424 
425 		al = alert_desc;
426 		goto fatal_err;
427 	}
428 
429 	/* we have pulled in a full packet so zero things */
430 	s->packet_length = 0;
431 
432 	if (tls_content_remaining(s->s3->rcontent) == 0) {
433 		/*
434 		 * Zero-length fragments are only permitted for application
435 		 * data, as per RFC 5246 section 6.2.1.
436 		 */
437 		if (rr->type != SSL3_RT_APPLICATION_DATA) {
438 			SSLerror(s, SSL_R_BAD_LENGTH);
439 			al = SSL_AD_UNEXPECTED_MESSAGE;
440 			goto fatal_err;
441 		}
442 
443 		tls_content_clear(s->s3->rcontent);
444 
445 		/*
446 		 * CBC countermeasures for known IV weaknesses can legitimately
447 		 * insert a single empty record, so we allow ourselves to read
448 		 * once past a single empty record without forcing want_read.
449 		 */
450 		if (s->empty_record_count++ > SSL_MAX_EMPTY_RECORDS) {
451 			SSLerror(s, SSL_R_PEER_BEHAVING_BADLY);
452 			return -1;
453 		}
454 		if (s->empty_record_count > 1) {
455 			ssl_force_want_read(s);
456 			return -1;
457 		}
458 		goto again;
459 	}
460 
461 	s->empty_record_count = 0;
462 
463 	return (1);
464 
465  fatal_err:
466 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
467  err:
468 	return (ret);
469 }
470 
471 /* Call this to write data in records of type 'type'
472  * It will return <= 0 if not all data has been sent or non-blocking IO.
473  */
474 int
475 ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
476 {
477 	const unsigned char *buf = buf_;
478 	unsigned int tot, n, nw;
479 	int i;
480 
481 	if (len < 0) {
482 		SSLerror(s, ERR_R_INTERNAL_ERROR);
483 		return -1;
484 	}
485 
486 	s->rwstate = SSL_NOTHING;
487 	tot = s->s3->wnum;
488 	s->s3->wnum = 0;
489 
490 	if (SSL_in_init(s) && !s->in_handshake) {
491 		i = s->handshake_func(s);
492 		if (i < 0)
493 			return (i);
494 		if (i == 0) {
495 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
496 			return -1;
497 		}
498 	}
499 
500 	if (len < tot)
501 		len = tot;
502 	n = (len - tot);
503 	for (;;) {
504 		if (n > s->max_send_fragment)
505 			nw = s->max_send_fragment;
506 		else
507 			nw = n;
508 
509 		i = do_ssl3_write(s, type, &(buf[tot]), nw);
510 		if (i <= 0) {
511 			s->s3->wnum = tot;
512 			return i;
513 		}
514 
515 		if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA &&
516 		    (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
517 			/*
518 			 * Next chunk of data should get another prepended
519 			 * empty fragment in ciphersuites with known-IV
520 			 * weakness.
521 			 */
522 			s->s3->empty_fragment_done = 0;
523 
524 			return tot + i;
525 		}
526 
527 		n -= i;
528 		tot += i;
529 	}
530 }
531 
532 static int
533 do_ssl3_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
534 {
535 	SSL3_BUFFER_INTERNAL *wb = &(s->s3->wbuf);
536 	SSL_SESSION *sess = s->session;
537 	int need_empty_fragment = 0;
538 	size_t align, out_len;
539 	uint16_t version;
540 	CBB cbb;
541 	int ret;
542 
543 	memset(&cbb, 0, sizeof(cbb));
544 
545 	if (wb->buf == NULL)
546 		if (!ssl3_setup_write_buffer(s))
547 			return -1;
548 
549 	/*
550 	 * First check if there is a SSL3_BUFFER_INTERNAL still being written
551 	 * out.  This will happen with non blocking IO.
552 	 */
553 	if (wb->left != 0)
554 		return (ssl3_write_pending(s, type, buf, len));
555 
556 	/* If we have an alert to send, let's send it. */
557 	if (s->s3->alert_dispatch) {
558 		if ((ret = ssl3_dispatch_alert(s)) <= 0)
559 			return (ret);
560 		/* If it went, fall through and send more stuff. */
561 
562 		/* We may have released our buffer, if so get it again. */
563 		if (wb->buf == NULL)
564 			if (!ssl3_setup_write_buffer(s))
565 				return -1;
566 	}
567 
568 	if (len == 0)
569 		return 0;
570 
571 	/*
572 	 * Some servers hang if initial client hello is larger than 256
573 	 * bytes and record version number > TLS 1.0.
574 	 */
575 	version = s->version;
576 	if (s->s3->hs.state == SSL3_ST_CW_CLNT_HELLO_B &&
577 	    !s->renegotiate &&
578 	    s->s3->hs.our_max_tls_version > TLS1_VERSION)
579 		version = TLS1_VERSION;
580 
581 	/*
582 	 * Countermeasure against known-IV weakness in CBC ciphersuites
583 	 * (see http://www.openssl.org/~bodo/tls-cbc.txt). Note that this
584 	 * is unnecessary for AEAD.
585 	 */
586 	if (sess != NULL && tls12_record_layer_write_protected(s->rl)) {
587 		if (s->s3->need_empty_fragments &&
588 		    !s->s3->empty_fragment_done &&
589 		    type == SSL3_RT_APPLICATION_DATA)
590 			need_empty_fragment = 1;
591 	}
592 
593 	/*
594 	 * An extra fragment would be a couple of cipher blocks, which would
595 	 * be a multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
596 	 * payload, then we can just simply pretend we have two headers.
597 	 */
598 	align = (size_t)wb->buf + SSL3_RT_HEADER_LENGTH;
599 	if (need_empty_fragment)
600 		align += SSL3_RT_HEADER_LENGTH;
601 	align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
602 	wb->offset = align;
603 
604 	if (!CBB_init_fixed(&cbb, wb->buf + align, wb->len - align))
605 		goto err;
606 
607 	tls12_record_layer_set_version(s->rl, version);
608 
609 	if (need_empty_fragment) {
610 		if (!tls12_record_layer_seal_record(s->rl, type,
611 		    buf, 0, &cbb))
612 			goto err;
613 		s->s3->empty_fragment_done = 1;
614 	}
615 
616 	if (!tls12_record_layer_seal_record(s->rl, type, buf, len, &cbb))
617 		goto err;
618 
619 	if (!CBB_finish(&cbb, NULL, &out_len))
620 		goto err;
621 
622 	wb->left = out_len;
623 
624 	/*
625 	 * Memorize arguments so that ssl3_write_pending can detect
626 	 * bad write retries later.
627 	 */
628 	s->s3->wpend_tot = len;
629 	s->s3->wpend_buf = buf;
630 	s->s3->wpend_type = type;
631 	s->s3->wpend_ret = len;
632 
633 	/* We now just need to write the buffer. */
634 	return ssl3_write_pending(s, type, buf, len);
635 
636  err:
637 	CBB_cleanup(&cbb);
638 
639 	return -1;
640 }
641 
642 /* if s->s3->wbuf.left != 0, we need to call this */
643 int
644 ssl3_write_pending(SSL *s, int type, const unsigned char *buf, unsigned int len)
645 {
646 	int i;
647 	SSL3_BUFFER_INTERNAL *wb = &(s->s3->wbuf);
648 
649 	/* XXXX */
650 	if ((s->s3->wpend_tot > (int)len) || ((s->s3->wpend_buf != buf) &&
651 	    !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
652 	    (s->s3->wpend_type != type)) {
653 		SSLerror(s, SSL_R_BAD_WRITE_RETRY);
654 		return (-1);
655 	}
656 
657 	for (;;) {
658 		errno = 0;
659 		if (s->wbio != NULL) {
660 			s->rwstate = SSL_WRITING;
661 			i = BIO_write(s->wbio, (char *)&(wb->buf[wb->offset]),
662 			    (unsigned int)wb->left);
663 		} else {
664 			SSLerror(s, SSL_R_BIO_NOT_SET);
665 			i = -1;
666 		}
667 		if (i == wb->left) {
668 			wb->left = 0;
669 			wb->offset += i;
670 			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
671 			    !SSL_is_dtls(s))
672 				ssl3_release_write_buffer(s);
673 			s->rwstate = SSL_NOTHING;
674 			return (s->s3->wpend_ret);
675 		} else if (i <= 0) {
676 			/*
677 			 * For DTLS, just drop it. That's kind of the
678 			 * whole point in using a datagram service.
679 			 */
680 			if (SSL_is_dtls(s))
681 				wb->left = 0;
682 			return (i);
683 		}
684 		wb->offset += i;
685 		wb->left -= i;
686 	}
687 }
688 
689 static ssize_t
690 ssl3_read_cb(void *buf, size_t n, void *cb_arg)
691 {
692 	SSL *s = cb_arg;
693 
694 	return tls_content_read(s->s3->rcontent, buf, n);
695 }
696 
697 #define SSL3_ALERT_LENGTH	2
698 
699 int
700 ssl3_read_alert(SSL *s)
701 {
702 	uint8_t alert_level, alert_descr;
703 	ssize_t ret;
704 	CBS cbs;
705 
706 	/*
707 	 * TLSv1.2 permits an alert to be fragmented across multiple records or
708 	 * for multiple alerts to be be coalesced into a single alert record.
709 	 * In the case of DTLS, there is no way to reassemble an alert
710 	 * fragmented across multiple records, hence a full alert must be
711 	 * available in the record.
712 	 */
713 	if (s->s3->alert_fragment == NULL) {
714 		if ((s->s3->alert_fragment = tls_buffer_new(0)) == NULL)
715 			return -1;
716 		tls_buffer_set_capacity_limit(s->s3->alert_fragment,
717 		    SSL3_ALERT_LENGTH);
718 	}
719 	ret = tls_buffer_extend(s->s3->alert_fragment, SSL3_ALERT_LENGTH,
720 	    ssl3_read_cb, s);
721 	if (ret <= 0 && ret != TLS_IO_WANT_POLLIN)
722 		return -1;
723 	if (ret != SSL3_ALERT_LENGTH) {
724 		if (SSL_is_dtls(s)) {
725 			SSLerror(s, SSL_R_BAD_LENGTH);
726 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
727 			return -1;
728 		}
729 		return 1;
730 	}
731 
732 	if (!tls_buffer_data(s->s3->alert_fragment, &cbs))
733 		return -1;
734 
735 	ssl_msg_callback_cbs(s, 0, SSL3_RT_ALERT, &cbs);
736 
737 	if (!CBS_get_u8(&cbs, &alert_level))
738 		return -1;
739 	if (!CBS_get_u8(&cbs, &alert_descr))
740 		return -1;
741 
742 	tls_buffer_free(s->s3->alert_fragment);
743 	s->s3->alert_fragment = NULL;
744 
745 	ssl_info_callback(s, SSL_CB_READ_ALERT,
746 	    (alert_level << 8) | alert_descr);
747 
748 	if (alert_level == SSL3_AL_WARNING) {
749 		s->s3->warn_alert = alert_descr;
750 		if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
751 			s->shutdown |= SSL_RECEIVED_SHUTDOWN;
752 			return 0;
753 		}
754 		/* We requested renegotiation and the peer rejected it. */
755 		if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
756 			SSLerror(s, SSL_R_NO_RENEGOTIATION);
757 			ssl3_send_alert(s, SSL3_AL_FATAL,
758 			    SSL_AD_HANDSHAKE_FAILURE);
759 			return -1;
760 		}
761 	} else if (alert_level == SSL3_AL_FATAL) {
762 		s->rwstate = SSL_NOTHING;
763 		s->s3->fatal_alert = alert_descr;
764 		SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
765 		ERR_asprintf_error_data("SSL alert number %d", alert_descr);
766 		s->shutdown |= SSL_RECEIVED_SHUTDOWN;
767 		SSL_CTX_remove_session(s->ctx, s->session);
768 		return 0;
769 	} else {
770 		SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
771 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
772 		return -1;
773 	}
774 
775 	return 1;
776 }
777 
778 int
779 ssl3_read_change_cipher_spec(SSL *s)
780 {
781 	const uint8_t ccs[1] = { SSL3_MT_CCS };
782 
783 	/*
784 	 * 'Change Cipher Spec' is just a single byte, so we know exactly what
785 	 * the record payload has to look like.
786 	 */
787 	if (tls_content_remaining(s->s3->rcontent) != sizeof(ccs)) {
788 		SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
789 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
790 		return -1;
791 	}
792 	if (!tls_content_equal(s->s3->rcontent, ccs, sizeof(ccs))) {
793 		SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
794 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
795 		return -1;
796 	}
797 
798 	/* XDTLS: check that epoch is consistent */
799 
800 	ssl_msg_callback_cbs(s, 0, SSL3_RT_CHANGE_CIPHER_SPEC,
801 	    tls_content_cbs(s->s3->rcontent));
802 
803 	/* Check that we have a cipher to change to. */
804 	if (s->s3->hs.cipher == NULL) {
805 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
806 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
807 		return -1;
808 	}
809 
810 	/* Check that we should be receiving a Change Cipher Spec. */
811 	if (SSL_is_dtls(s)) {
812 		if (!s->d1->change_cipher_spec_ok) {
813 			/*
814 			 * We can't process a CCS now, because previous
815 			 * handshake messages are still missing, so just
816 			 * drop it.
817 			 */
818 			tls_content_clear(s->s3->rcontent);
819 			return 1;
820 		}
821 		s->d1->change_cipher_spec_ok = 0;
822 	} else {
823 		if ((s->s3->flags & SSL3_FLAGS_CCS_OK) == 0) {
824 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
825 			ssl3_send_alert(s, SSL3_AL_FATAL,
826 			    SSL_AD_UNEXPECTED_MESSAGE);
827 			return -1;
828 		}
829 		s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
830 	}
831 
832 	tls_content_clear(s->s3->rcontent);
833 
834 	s->s3->change_cipher_spec = 1;
835 	if (!ssl3_do_change_cipher_spec(s))
836 		return -1;
837 
838 	return 1;
839 }
840 
841 static int
842 ssl3_read_handshake_unexpected(SSL *s)
843 {
844 	uint32_t hs_msg_length;
845 	uint8_t hs_msg_type;
846 	ssize_t ssret;
847 	CBS cbs;
848 	int ret;
849 
850 	/*
851 	 * We need four bytes of handshake data so we have a handshake message
852 	 * header - this may be in the same record or fragmented across multiple
853 	 * records.
854 	 */
855 	if (s->s3->handshake_fragment == NULL) {
856 		if ((s->s3->handshake_fragment = tls_buffer_new(0)) == NULL)
857 			return -1;
858 		tls_buffer_set_capacity_limit(s->s3->handshake_fragment,
859 		    SSL3_HM_HEADER_LENGTH);
860 	}
861 	ssret = tls_buffer_extend(s->s3->handshake_fragment, SSL3_HM_HEADER_LENGTH,
862 	    ssl3_read_cb, s);
863 	if (ssret <= 0 && ssret != TLS_IO_WANT_POLLIN)
864 		return -1;
865 	if (ssret != SSL3_HM_HEADER_LENGTH)
866 		return 1;
867 
868 	if (s->in_handshake) {
869 		SSLerror(s, ERR_R_INTERNAL_ERROR);
870 		return -1;
871 	}
872 
873 	/*
874 	 * This code currently deals with HelloRequest and ClientHello messages -
875 	 * anything else is pushed to the handshake_func. Almost all of this
876 	 * belongs in the client/server handshake code.
877 	 */
878 
879 	/* Parse handshake message header. */
880 	if (!tls_buffer_data(s->s3->handshake_fragment, &cbs))
881 		return -1;
882 	if (!CBS_get_u8(&cbs, &hs_msg_type))
883 		return -1;
884 	if (!CBS_get_u24(&cbs, &hs_msg_length))
885 		return -1;
886 
887 	if (hs_msg_type == SSL3_MT_HELLO_REQUEST) {
888 		/*
889 		 * Incoming HelloRequest messages should only be received by a
890 		 * client. A server may send these at any time - a client should
891 		 * ignore the message if received in the middle of a handshake.
892 		 * See RFC 5246 sections 7.4 and 7.4.1.1.
893 		 */
894 		if (s->server) {
895 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
896 			ssl3_send_alert(s, SSL3_AL_FATAL,
897 			     SSL_AD_UNEXPECTED_MESSAGE);
898 			return -1;
899 		}
900 
901 		if (hs_msg_length != 0) {
902 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
903 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
904 			return -1;
905 		}
906 
907 		if (!tls_buffer_data(s->s3->handshake_fragment, &cbs))
908 			return -1;
909 		ssl_msg_callback_cbs(s, 0, SSL3_RT_HANDSHAKE, &cbs);
910 
911 		tls_buffer_free(s->s3->handshake_fragment);
912 		s->s3->handshake_fragment = NULL;
913 
914 		/*
915 		 * It should be impossible to hit this, but keep the safety
916 		 * harness for now...
917 		 */
918 		if (s->session == NULL || s->session->cipher == NULL)
919 			return 1;
920 
921 		/*
922 		 * Ignore this message if we're currently handshaking,
923 		 * renegotiation is already pending or renegotiation is disabled
924 		 * via flags.
925 		 */
926 		if (!SSL_is_init_finished(s) || s->s3->renegotiate ||
927 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0)
928 			return 1;
929 
930 		if (!ssl3_renegotiate(s))
931 			return 1;
932 		if (!ssl3_renegotiate_check(s))
933 			return 1;
934 
935 	} else if (hs_msg_type == SSL3_MT_CLIENT_HELLO) {
936 		/*
937 		 * Incoming ClientHello messages should only be received by a
938 		 * server. A client may send these in response to server
939 		 * initiated renegotiation (HelloRequest) or in order to
940 		 * initiate renegotiation by the client. See RFC 5246 section
941 		 * 7.4.1.2.
942 		 */
943 		if (!s->server) {
944 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
945 			ssl3_send_alert(s, SSL3_AL_FATAL,
946 			     SSL_AD_UNEXPECTED_MESSAGE);
947 			return -1;
948 		}
949 
950 		/*
951 		 * A client should not be sending a ClientHello unless we're not
952 		 * currently handshaking.
953 		 */
954 		if (!SSL_is_init_finished(s)) {
955 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
956 			ssl3_send_alert(s, SSL3_AL_FATAL,
957 			    SSL_AD_UNEXPECTED_MESSAGE);
958 			return -1;
959 		}
960 
961 		if ((s->options & SSL_OP_NO_CLIENT_RENEGOTIATION) != 0) {
962 			ssl3_send_alert(s, SSL3_AL_FATAL,
963 			    SSL_AD_NO_RENEGOTIATION);
964 			return -1;
965 		}
966 
967 		if (s->session == NULL || s->session->cipher == NULL) {
968 			SSLerror(s, ERR_R_INTERNAL_ERROR);
969 			return -1;
970 		}
971 
972 		/* Client requested renegotiation but it is not permitted. */
973 		if (!s->s3->send_connection_binding ||
974 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0) {
975 			ssl3_send_alert(s, SSL3_AL_WARNING,
976 			    SSL_AD_NO_RENEGOTIATION);
977 			return 1;
978 		}
979 
980 		s->s3->hs.state = SSL_ST_ACCEPT;
981 		s->renegotiate = 1;
982 		s->new_session = 1;
983 
984 	} else {
985 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
986 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
987 		return -1;
988 	}
989 
990 	if ((ret = s->handshake_func(s)) < 0)
991 		return ret;
992 	if (ret == 0) {
993 		SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
994 		return -1;
995 	}
996 
997 	if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
998 		if (s->s3->rbuf.left == 0) {
999 			ssl_force_want_read(s);
1000 			return -1;
1001 		}
1002 	}
1003 
1004 	/*
1005 	 * We either finished a handshake or ignored the request, now try again
1006 	 * to obtain the (application) data we were asked for.
1007 	 */
1008 	return 1;
1009 }
1010 
1011 /* Return up to 'len' payload bytes received in 'type' records.
1012  * 'type' is one of the following:
1013  *
1014  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1015  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1016  *   -  0 (during a shutdown, no data has to be returned)
1017  *
1018  * If we don't have stored data to work from, read a SSL/TLS record first
1019  * (possibly multiple records if we still don't have anything to return).
1020  *
1021  * This function must handle any surprises the peer may have for us, such as
1022  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
1023  * a surprise, but handled as if it were), or renegotiation requests.
1024  * Also if record payloads contain fragments too small to process, we store
1025  * them until there is enough for the respective protocol (the record protocol
1026  * may use arbitrary fragmentation and even interleaving):
1027  *     Change cipher spec protocol
1028  *             just 1 byte needed, no need for keeping anything stored
1029  *     Alert protocol
1030  *             2 bytes needed (AlertLevel, AlertDescription)
1031  *     Handshake protocol
1032  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1033  *             to detect unexpected Client Hello and Hello Request messages
1034  *             here, anything else is handled by higher layers
1035  *     Application data protocol
1036  *             none of our business
1037  */
1038 int
1039 ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
1040 {
1041 	int rrcount = 0;
1042 	ssize_t ssret;
1043 	int ret;
1044 
1045 	if (s->s3->rbuf.buf == NULL) {
1046 		if (!ssl3_setup_read_buffer(s))
1047 			return -1;
1048 	}
1049 
1050 	if (s->s3->rcontent == NULL) {
1051 		if ((s->s3->rcontent = tls_content_new()) == NULL)
1052 			return -1;
1053 	}
1054 
1055 	if (len < 0) {
1056 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1057 		return -1;
1058 	}
1059 
1060 	if (type != 0 && type != SSL3_RT_APPLICATION_DATA &&
1061 	    type != SSL3_RT_HANDSHAKE) {
1062 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1063 		return -1;
1064 	}
1065 	if (peek && type != SSL3_RT_APPLICATION_DATA) {
1066 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1067 		return -1;
1068 	}
1069 
1070 	if (type == SSL3_RT_HANDSHAKE &&
1071 	    s->s3->handshake_fragment != NULL &&
1072 	    tls_buffer_remaining(s->s3->handshake_fragment) > 0) {
1073 		ssize_t ssn;
1074 
1075 		if ((ssn = tls_buffer_read(s->s3->handshake_fragment, buf,
1076 		    len)) <= 0)
1077 			return -1;
1078 
1079 		if (tls_buffer_remaining(s->s3->handshake_fragment) == 0) {
1080 			tls_buffer_free(s->s3->handshake_fragment);
1081 			s->s3->handshake_fragment = NULL;
1082 		}
1083 
1084 		return (int)ssn;
1085 	}
1086 
1087 	if (SSL_in_init(s) && !s->in_handshake) {
1088 		if ((ret = s->handshake_func(s)) < 0)
1089 			return ret;
1090 		if (ret == 0) {
1091 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1092 			return -1;
1093 		}
1094 	}
1095 
1096  start:
1097 	/*
1098 	 * Do not process more than three consecutive records, otherwise the
1099 	 * peer can cause us to loop indefinitely. Instead, return with an
1100 	 * SSL_ERROR_WANT_READ so the caller can choose when to handle further
1101 	 * processing. In the future, the total number of non-handshake and
1102 	 * non-application data records per connection should probably also be
1103 	 * limited...
1104 	 */
1105 	if (rrcount++ >= 3) {
1106 		ssl_force_want_read(s);
1107 		return -1;
1108 	}
1109 
1110 	s->rwstate = SSL_NOTHING;
1111 
1112 	if (tls_content_remaining(s->s3->rcontent) == 0) {
1113 		if ((ret = ssl3_get_record(s)) <= 0)
1114 			return ret;
1115 	}
1116 
1117 	/* We now have a packet which can be read and processed. */
1118 
1119 	if (s->s3->change_cipher_spec &&
1120 	    tls_content_type(s->s3->rcontent) != SSL3_RT_HANDSHAKE) {
1121 		SSLerror(s, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1122 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1123 		return -1;
1124 	}
1125 
1126 	/*
1127 	 * If the other end has shut down, throw anything we read away (even in
1128 	 * 'peek' mode).
1129 	 */
1130 	if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1131 		s->rwstate = SSL_NOTHING;
1132 		tls_content_clear(s->s3->rcontent);
1133 		s->s3->rrec.length = 0;
1134 		return 0;
1135 	}
1136 
1137 	/* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
1138 	if (tls_content_type(s->s3->rcontent) == type) {
1139 		/*
1140 		 * Make sure that we are not getting application data when we
1141 		 * are doing a handshake for the first time.
1142 		 */
1143 		if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
1144 		    !tls12_record_layer_read_protected(s->rl)) {
1145 			SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
1146 			ssl3_send_alert(s, SSL3_AL_FATAL,
1147 			    SSL_AD_UNEXPECTED_MESSAGE);
1148 			return -1;
1149 		}
1150 
1151 		if (len <= 0)
1152 			return len;
1153 
1154 		if (peek) {
1155 			ssret = tls_content_peek(s->s3->rcontent, buf, len);
1156 		} else {
1157 			ssret = tls_content_read(s->s3->rcontent, buf, len);
1158 		}
1159 		if (ssret < INT_MIN || ssret > INT_MAX)
1160 			return -1;
1161 		if (ssret < 0)
1162 			return (int)ssret;
1163 
1164 		if (tls_content_remaining(s->s3->rcontent) == 0) {
1165 			s->rstate = SSL_ST_READ_HEADER;
1166 
1167 			if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
1168 			    s->s3->rbuf.left == 0)
1169 				ssl3_release_read_buffer(s);
1170 		}
1171 
1172 		return ssret;
1173 	}
1174 
1175 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_ALERT) {
1176 		if ((ret = ssl3_read_alert(s)) <= 0)
1177 			return ret;
1178 		goto start;
1179 	}
1180 
1181 	if (s->shutdown & SSL_SENT_SHUTDOWN) {
1182 		s->rwstate = SSL_NOTHING;
1183 		tls_content_clear(s->s3->rcontent);
1184 		s->s3->rrec.length = 0;
1185 		return 0;
1186 	}
1187 
1188 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_APPLICATION_DATA) {
1189 		/*
1190 		 * At this point, we were expecting handshake data, but have
1191 		 * application data. If the library was running inside
1192 		 * ssl3_read() (i.e. in_read_app_data is set) and it makes
1193 		 * sense to read application data at this point (session
1194 		 * renegotiation not yet started), we will indulge it.
1195 		 */
1196 		if (s->s3->in_read_app_data != 0 &&
1197 		    s->s3->total_renegotiations != 0 &&
1198 		    (((s->s3->hs.state & SSL_ST_CONNECT) &&
1199 		    (s->s3->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1200 		    (s->s3->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
1201 		    (s->s3->hs.state & SSL_ST_ACCEPT) &&
1202 		    (s->s3->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
1203 		    (s->s3->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1204 			s->s3->in_read_app_data = 2;
1205 			return -1;
1206 		} else {
1207 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1208 			ssl3_send_alert(s, SSL3_AL_FATAL,
1209 			    SSL_AD_UNEXPECTED_MESSAGE);
1210 			return -1;
1211 		}
1212 	}
1213 
1214 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1215 		if ((ret = ssl3_read_change_cipher_spec(s)) <= 0)
1216 			return ret;
1217 		goto start;
1218 	}
1219 
1220 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_HANDSHAKE) {
1221 		if ((ret = ssl3_read_handshake_unexpected(s)) <= 0)
1222 			return ret;
1223 		goto start;
1224 	}
1225 
1226 	/*
1227 	 * Unknown record type - TLSv1.2 sends an unexpected message alert while
1228 	 * earlier versions silently ignore the record.
1229 	 */
1230 	if (ssl_effective_tls_version(s) <= TLS1_1_VERSION) {
1231 		tls_content_clear(s->s3->rcontent);
1232 		goto start;
1233 	}
1234 	SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1235 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1236 	return -1;
1237 }
1238 
1239 int
1240 ssl3_do_change_cipher_spec(SSL *s)
1241 {
1242 	if (s->s3->hs.tls12.key_block == NULL) {
1243 		if (s->session == NULL || s->session->master_key_length == 0) {
1244 			/* might happen if dtls1_read_bytes() calls this */
1245 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1246 			return (0);
1247 		}
1248 
1249 		s->session->cipher = s->s3->hs.cipher;
1250 		if (!tls1_setup_key_block(s))
1251 			return (0);
1252 	}
1253 
1254 	if (!tls1_change_read_cipher_state(s))
1255 		return (0);
1256 
1257 	/*
1258 	 * We have to record the message digest at this point so we can get it
1259 	 * before we read the finished message.
1260 	 */
1261 	if (!tls12_derive_peer_finished(s))
1262 		return (0);
1263 
1264 	return (1);
1265 }
1266 
1267 static int
1268 ssl3_write_alert(SSL *s)
1269 {
1270 	if (SSL_is_dtls(s))
1271 		return do_dtls1_write(s, SSL3_RT_ALERT, s->s3->send_alert,
1272 		    sizeof(s->s3->send_alert));
1273 
1274 	return do_ssl3_write(s, SSL3_RT_ALERT, s->s3->send_alert,
1275 	    sizeof(s->s3->send_alert));
1276 }
1277 
1278 int
1279 ssl3_send_alert(SSL *s, int level, int desc)
1280 {
1281 	/* If alert is fatal, remove session from cache. */
1282 	if (level == SSL3_AL_FATAL)
1283 		SSL_CTX_remove_session(s->ctx, s->session);
1284 
1285 	s->s3->alert_dispatch = 1;
1286 	s->s3->send_alert[0] = level;
1287 	s->s3->send_alert[1] = desc;
1288 
1289 	/*
1290 	 * If data is still being written out, the alert will be dispatched at
1291 	 * some point in the future.
1292 	 */
1293 	if (s->s3->wbuf.left != 0)
1294 		return -1;
1295 
1296 	return ssl3_dispatch_alert(s);
1297 }
1298 
1299 int
1300 ssl3_dispatch_alert(SSL *s)
1301 {
1302 	int ret;
1303 
1304 	s->s3->alert_dispatch = 0;
1305 	if ((ret = ssl3_write_alert(s)) <= 0) {
1306 		s->s3->alert_dispatch = 1;
1307 		return ret;
1308 	}
1309 
1310 	/*
1311 	 * Alert sent to BIO.  If it is important, flush it now.
1312 	 * If the message does not get sent due to non-blocking IO,
1313 	 * we will not worry too much.
1314 	 */
1315 	if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1316 		(void)BIO_flush(s->wbio);
1317 
1318 	ssl_msg_callback(s, 1, SSL3_RT_ALERT, s->s3->send_alert, 2);
1319 
1320 	ssl_info_callback(s, SSL_CB_WRITE_ALERT,
1321 	    (s->s3->send_alert[0] << 8) | s->s3->send_alert[1]);
1322 
1323 	return ret;
1324 }
1325