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