xref: /openbsd-src/lib/libssl/ssl_pkt.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
1 /* $OpenBSD: ssl_pkt.c,v 1.58 2022/03/26 15:05:53 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 
694 	/*
695 	 * TLSv1.2 permits an alert to be fragmented across multiple records or
696 	 * for multiple alerts to be be coalesced into a single alert record.
697 	 * In the case of DTLS, there is no way to reassemble an alert
698 	 * fragmented across multiple records, hence a full alert must be
699 	 * available in the record.
700 	 */
701 	while (rr->length > 0 &&
702 	    s->s3->alert_fragment_len < sizeof(s->s3->alert_fragment)) {
703 		s->s3->alert_fragment[s->s3->alert_fragment_len++] =
704 		    rr->data[rr->off++];
705 		rr->length--;
706 	}
707 	if (s->s3->alert_fragment_len < sizeof(s->s3->alert_fragment)) {
708 		if (SSL_is_dtls(s)) {
709 			SSLerror(s, SSL_R_BAD_LENGTH);
710 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
711 			return -1;
712 		}
713 		return 1;
714 	}
715 
716 	ssl_msg_callback(s, 0, SSL3_RT_ALERT, s->s3->alert_fragment, 2);
717 
718 	alert_level = s->s3->alert_fragment[0];
719 	alert_descr = s->s3->alert_fragment[1];
720 	s->s3->alert_fragment_len = 0;
721 
722 	ssl_info_callback(s, SSL_CB_READ_ALERT,
723 	    (alert_level << 8) | alert_descr);
724 
725 	if (alert_level == SSL3_AL_WARNING) {
726 		s->s3->warn_alert = alert_descr;
727 		if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
728 			s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
729 			return 0;
730 		}
731 		/* We requested renegotiation and the peer rejected it. */
732 		if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
733 			SSLerror(s, SSL_R_NO_RENEGOTIATION);
734 			ssl3_send_alert(s, SSL3_AL_FATAL,
735 			    SSL_AD_HANDSHAKE_FAILURE);
736 			return -1;
737 		}
738 	} else if (alert_level == SSL3_AL_FATAL) {
739 		s->internal->rwstate = SSL_NOTHING;
740 		s->s3->fatal_alert = alert_descr;
741 		SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
742 		ERR_asprintf_error_data("SSL alert number %d", alert_descr);
743 		s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
744 		SSL_CTX_remove_session(s->ctx, s->session);
745 		return 0;
746 	} else {
747 		SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
748 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
749 		return -1;
750 	}
751 
752 	return 1;
753 }
754 
755 int
756 ssl3_read_change_cipher_spec(SSL *s)
757 {
758 	SSL3_RECORD_INTERNAL *rr = &s->s3->rrec;
759 
760 	/*
761 	 * 'Change Cipher Spec' is just a single byte, so we know exactly what
762 	 * the record payload has to look like.
763 	 */
764 	if (rr->length != 1 || rr->off != 0) {
765 		SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
766 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
767 		return -1;
768 	}
769 	if (rr->data[0] != SSL3_MT_CCS) {
770 		SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
771 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
772 		return -1;
773 	}
774 
775 	/* XDTLS: check that epoch is consistent */
776 
777 	ssl_msg_callback(s, 0, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1);
778 
779 	/* Check that we have a cipher to change to. */
780 	if (s->s3->hs.cipher == NULL) {
781 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
782 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
783 		return -1;
784 	}
785 
786 	/* Check that we should be receiving a Change Cipher Spec. */
787 	if (SSL_is_dtls(s)) {
788 		if (!s->d1->change_cipher_spec_ok) {
789 			/*
790 			 * We can't process a CCS now, because previous
791 			 * handshake messages are still missing, so just
792 			 * drop it.
793 			 */
794 			rr->length = 0;
795 			return 1;
796 		}
797 		s->d1->change_cipher_spec_ok = 0;
798 	} else {
799 		if ((s->s3->flags & SSL3_FLAGS_CCS_OK) == 0) {
800 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
801 			ssl3_send_alert(s, SSL3_AL_FATAL,
802 			    SSL_AD_UNEXPECTED_MESSAGE);
803 			return -1;
804 		}
805 		s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
806 	}
807 
808 	rr->length = 0;
809 
810 	s->s3->change_cipher_spec = 1;
811 	if (!ssl3_do_change_cipher_spec(s))
812 		return -1;
813 
814 	return 1;
815 }
816 
817 static int
818 ssl3_read_handshake_unexpected(SSL *s)
819 {
820 	SSL3_RECORD_INTERNAL *rr = &s->s3->rrec;
821 	uint32_t hs_msg_length;
822 	uint8_t hs_msg_type;
823 	CBS cbs;
824 	int ret;
825 
826 	/*
827 	 * We need four bytes of handshake data so we have a handshake message
828 	 * header - this may be in the same record or fragmented across multiple
829 	 * records.
830 	 */
831 	while (rr->length > 0 &&
832 	    s->s3->handshake_fragment_len < sizeof(s->s3->handshake_fragment)) {
833 		s->s3->handshake_fragment[s->s3->handshake_fragment_len++] =
834 		    rr->data[rr->off++];
835 		rr->length--;
836 	}
837 
838 	if (s->s3->handshake_fragment_len < sizeof(s->s3->handshake_fragment))
839 		return 1;
840 
841 	if (s->internal->in_handshake) {
842 		SSLerror(s, ERR_R_INTERNAL_ERROR);
843 		return -1;
844 	}
845 
846 	/*
847 	 * This code currently deals with HelloRequest and ClientHello messages -
848 	 * anything else is pushed to the handshake_func. Almost all of this
849 	 * belongs in the client/server handshake code.
850 	 */
851 
852 	/* Parse handshake message header. */
853 	CBS_init(&cbs, s->s3->handshake_fragment, s->s3->handshake_fragment_len);
854 	if (!CBS_get_u8(&cbs, &hs_msg_type))
855 		return -1;
856 	if (!CBS_get_u24(&cbs, &hs_msg_length))
857 		return -1;
858 
859 	if (hs_msg_type == SSL3_MT_HELLO_REQUEST) {
860 		/*
861 		 * Incoming HelloRequest messages should only be received by a
862 		 * client. A server may send these at any time - a client should
863 		 * ignore the message if received in the middle of a handshake.
864 		 * See RFC 5246 sections 7.4 and 7.4.1.1.
865 		 */
866 		if (s->server) {
867 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
868 			ssl3_send_alert(s, SSL3_AL_FATAL,
869 			     SSL_AD_UNEXPECTED_MESSAGE);
870 			return -1;
871 		}
872 
873 		if (hs_msg_length != 0) {
874 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
875 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
876 			return -1;
877 		}
878 
879 		ssl_msg_callback(s, 0, SSL3_RT_HANDSHAKE,
880 		    s->s3->handshake_fragment, s->s3->handshake_fragment_len);
881 
882 		s->s3->handshake_fragment_len = 0;
883 
884 		/*
885 		 * It should be impossible to hit this, but keep the safety
886 		 * harness for now...
887 		 */
888 		if (s->session == NULL || s->session->cipher == NULL)
889 			return 1;
890 
891 		/*
892 		 * Ignore this message if we're currently handshaking,
893 		 * renegotiation is already pending or renegotiation is disabled
894 		 * via flags.
895 		 */
896 		if (!SSL_is_init_finished(s) || s->s3->renegotiate ||
897 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0)
898 			return 1;
899 
900 		if (!ssl3_renegotiate(s))
901 			return 1;
902 		if (!ssl3_renegotiate_check(s))
903 			return 1;
904 
905 	} else if (hs_msg_type == SSL3_MT_CLIENT_HELLO) {
906 		/*
907 		 * Incoming ClientHello messages should only be received by a
908 		 * server. A client may send these in response to server
909 		 * initiated renegotiation (HelloRequest) or in order to
910 		 * initiate renegotiation by the client. See RFC 5246 section
911 		 * 7.4.1.2.
912 		 */
913 		if (!s->server) {
914 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
915 			ssl3_send_alert(s, SSL3_AL_FATAL,
916 			     SSL_AD_UNEXPECTED_MESSAGE);
917 			return -1;
918 		}
919 
920 		/*
921 		 * A client should not be sending a ClientHello unless we're not
922 		 * currently handshaking.
923 		 */
924 		if (!SSL_is_init_finished(s)) {
925 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
926 			ssl3_send_alert(s, SSL3_AL_FATAL,
927 			    SSL_AD_UNEXPECTED_MESSAGE);
928 			return -1;
929 		}
930 
931 		if ((s->internal->options & SSL_OP_NO_CLIENT_RENEGOTIATION) != 0) {
932 			ssl3_send_alert(s, SSL3_AL_FATAL,
933 			    SSL_AD_NO_RENEGOTIATION);
934 			return -1;
935 		}
936 
937 		if (s->session == NULL || s->session->cipher == NULL) {
938 			SSLerror(s, ERR_R_INTERNAL_ERROR);
939 			return -1;
940 		}
941 
942 		/* Client requested renegotiation but it is not permitted. */
943 		if (!s->s3->send_connection_binding ||
944 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0) {
945 			ssl3_send_alert(s, SSL3_AL_WARNING,
946 			    SSL_AD_NO_RENEGOTIATION);
947 			return 1;
948 		}
949 
950 		s->s3->hs.state = SSL_ST_ACCEPT;
951 		s->internal->renegotiate = 1;
952 		s->internal->new_session = 1;
953 
954 	} else {
955 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
956 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
957 		return -1;
958 	}
959 
960 	if ((ret = s->internal->handshake_func(s)) < 0)
961 		return ret;
962 	if (ret == 0) {
963 		SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
964 		return -1;
965 	}
966 
967 	if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
968 		if (s->s3->rbuf.left == 0) {
969 			ssl_force_want_read(s);
970 			return -1;
971 		}
972 	}
973 
974 	/*
975 	 * We either finished a handshake or ignored the request, now try again
976 	 * to obtain the (application) data we were asked for.
977 	 */
978 	return 1;
979 }
980 
981 /* Return up to 'len' payload bytes received in 'type' records.
982  * 'type' is one of the following:
983  *
984  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
985  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
986  *   -  0 (during a shutdown, no data has to be returned)
987  *
988  * If we don't have stored data to work from, read a SSL/TLS record first
989  * (possibly multiple records if we still don't have anything to return).
990  *
991  * This function must handle any surprises the peer may have for us, such as
992  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
993  * a surprise, but handled as if it were), or renegotiation requests.
994  * Also if record payloads contain fragments too small to process, we store
995  * them until there is enough for the respective protocol (the record protocol
996  * may use arbitrary fragmentation and even interleaving):
997  *     Change cipher spec protocol
998  *             just 1 byte needed, no need for keeping anything stored
999  *     Alert protocol
1000  *             2 bytes needed (AlertLevel, AlertDescription)
1001  *     Handshake protocol
1002  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1003  *             to detect unexpected Client Hello and Hello Request messages
1004  *             here, anything else is handled by higher layers
1005  *     Application data protocol
1006  *             none of our business
1007  */
1008 int
1009 ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
1010 {
1011 	SSL3_RECORD_INTERNAL *rr;
1012 	int rrcount = 0;
1013 	unsigned int n;
1014 	int ret;
1015 
1016 	if (s->s3->rbuf.buf == NULL) {
1017 		if (!ssl3_setup_read_buffer(s))
1018 			return -1;
1019 	}
1020 
1021 	if (len < 0) {
1022 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1023 		return -1;
1024 	}
1025 
1026 	if (type != 0 && type != SSL3_RT_APPLICATION_DATA &&
1027 	    type != SSL3_RT_HANDSHAKE) {
1028 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1029 		return -1;
1030 	}
1031 	if (peek && type != SSL3_RT_APPLICATION_DATA) {
1032 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1033 		return -1;
1034 	}
1035 
1036 	if (type == SSL3_RT_HANDSHAKE && s->s3->handshake_fragment_len > 0) {
1037 		/* Partially satisfy request from fragment storage. */
1038 		unsigned char *src = s->s3->handshake_fragment;
1039 		unsigned char *dst = buf;
1040 		unsigned int k;
1041 
1042 		/* peek == 0 */
1043 		n = 0;
1044 		while (len > 0 && s->s3->handshake_fragment_len > 0) {
1045 			*dst++ = *src++;
1046 			len--;
1047 			s->s3->handshake_fragment_len--;
1048 			n++;
1049 		}
1050 		/* move any remaining fragment bytes: */
1051 		for (k = 0; k < s->s3->handshake_fragment_len; k++)
1052 			s->s3->handshake_fragment[k] = *src++;
1053 		return n;
1054 	}
1055 
1056 	if (SSL_in_init(s) && !s->internal->in_handshake) {
1057 		if ((ret = s->internal->handshake_func(s)) < 0)
1058 			return ret;
1059 		if (ret == 0) {
1060 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1061 			return -1;
1062 		}
1063 	}
1064 
1065  start:
1066 	/*
1067 	 * Do not process more than three consecutive records, otherwise the
1068 	 * peer can cause us to loop indefinitely. Instead, return with an
1069 	 * SSL_ERROR_WANT_READ so the caller can choose when to handle further
1070 	 * processing. In the future, the total number of non-handshake and
1071 	 * non-application data records per connection should probably also be
1072 	 * limited...
1073 	 */
1074 	if (rrcount++ >= 3) {
1075 		ssl_force_want_read(s);
1076 		return -1;
1077 	}
1078 
1079 	s->internal->rwstate = SSL_NOTHING;
1080 
1081 	rr = &s->s3->rrec;
1082 
1083 	if (rr->length == 0 || s->internal->rstate == SSL_ST_READ_BODY) {
1084 		if ((ret = ssl3_get_record(s)) <= 0)
1085 			return ret;
1086 	}
1087 
1088 	/* We now have a packet which can be read and processed. */
1089 
1090 	if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE) {
1091 		SSLerror(s, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1092 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1093 		return -1;
1094 	}
1095 
1096 	/*
1097 	 * If the other end has shut down, throw anything we read away (even in
1098 	 * 'peek' mode).
1099 	 */
1100 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
1101 		s->internal->rwstate = SSL_NOTHING;
1102 		rr->length = 0;
1103 		return 0;
1104 	}
1105 
1106 	/* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
1107 	if (type == rr->type) {
1108 		/*
1109 		 * Make sure that we are not getting application data when we
1110 		 * are doing a handshake for the first time.
1111 		 */
1112 		if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
1113 		    !tls12_record_layer_read_protected(s->internal->rl)) {
1114 			SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
1115 			ssl3_send_alert(s, SSL3_AL_FATAL,
1116 			    SSL_AD_UNEXPECTED_MESSAGE);
1117 			return -1;
1118 		}
1119 
1120 		if (len <= 0)
1121 			return len;
1122 
1123 		if ((unsigned int)len > rr->length)
1124 			n = rr->length;
1125 		else
1126 			n = (unsigned int)len;
1127 
1128 		memcpy(buf, &rr->data[rr->off], n);
1129 		if (!peek) {
1130 			memset(&rr->data[rr->off], 0, n);
1131 			rr->length -= n;
1132 			rr->off += n;
1133 			if (rr->length == 0) {
1134 				s->internal->rstate = SSL_ST_READ_HEADER;
1135 				rr->off = 0;
1136 				if (s->internal->mode & SSL_MODE_RELEASE_BUFFERS &&
1137 				    s->s3->rbuf.left == 0)
1138 					ssl3_release_read_buffer(s);
1139 			}
1140 		}
1141 
1142 		return n;
1143 	}
1144 
1145 	/*
1146 	 * If we get here, then type != rr->type; if we have a handshake
1147 	 * message, then it was unexpected (Hello Request or Client Hello).
1148 	 */
1149 
1150 	if (rr->type == SSL3_RT_ALERT) {
1151 		if ((ret = ssl3_read_alert(s)) <= 0)
1152 			return ret;
1153 		goto start;
1154 	}
1155 
1156 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
1157 		s->internal->rwstate = SSL_NOTHING;
1158 		rr->length = 0;
1159 		return 0;
1160 	}
1161 
1162 	if (rr->type == SSL3_RT_APPLICATION_DATA) {
1163 		/*
1164 		 * At this point, we were expecting handshake data, but have
1165 		 * application data. If the library was running inside
1166 		 * ssl3_read() (i.e. in_read_app_data is set) and it makes
1167 		 * sense to read application data at this point (session
1168 		 * renegotiation not yet started), we will indulge it.
1169 		 */
1170 		if (s->s3->in_read_app_data != 0 &&
1171 		    s->s3->total_renegotiations != 0 &&
1172 		    (((s->s3->hs.state & SSL_ST_CONNECT) &&
1173 		    (s->s3->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1174 		    (s->s3->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
1175 		    (s->s3->hs.state & SSL_ST_ACCEPT) &&
1176 		    (s->s3->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
1177 		    (s->s3->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1178 			s->s3->in_read_app_data = 2;
1179 			return -1;
1180 		} else {
1181 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1182 			ssl3_send_alert(s, SSL3_AL_FATAL,
1183 			    SSL_AD_UNEXPECTED_MESSAGE);
1184 			return -1;
1185 		}
1186 	}
1187 
1188 	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1189 		if ((ret = ssl3_read_change_cipher_spec(s)) <= 0)
1190 			return ret;
1191 		goto start;
1192 	}
1193 
1194 	if (rr->type == SSL3_RT_HANDSHAKE) {
1195 		if ((ret = ssl3_read_handshake_unexpected(s)) <= 0)
1196 			return ret;
1197 		goto start;
1198 	}
1199 
1200 	/*
1201 	 * Unknown record type - TLSv1.2 sends an unexpected message alert while
1202 	 * earlier versions silently ignore the record.
1203 	 */
1204 	if (ssl_effective_tls_version(s) <= TLS1_1_VERSION) {
1205 		rr->length = 0;
1206 		goto start;
1207 	}
1208 	SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1209 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1210 	return -1;
1211 }
1212 
1213 int
1214 ssl3_do_change_cipher_spec(SSL *s)
1215 {
1216 	if (s->s3->hs.tls12.key_block == NULL) {
1217 		if (s->session == NULL || s->session->master_key_length == 0) {
1218 			/* might happen if dtls1_read_bytes() calls this */
1219 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1220 			return (0);
1221 		}
1222 
1223 		s->session->cipher = s->s3->hs.cipher;
1224 		if (!tls1_setup_key_block(s))
1225 			return (0);
1226 	}
1227 
1228 	if (!tls1_change_read_cipher_state(s))
1229 		return (0);
1230 
1231 	/*
1232 	 * We have to record the message digest at this point so we can get it
1233 	 * before we read the finished message.
1234 	 */
1235 	if (!tls12_derive_peer_finished(s))
1236 		return (0);
1237 
1238 	return (1);
1239 }
1240 
1241 static int
1242 ssl3_write_alert(SSL *s)
1243 {
1244 	if (SSL_is_dtls(s))
1245 		return do_dtls1_write(s, SSL3_RT_ALERT, s->s3->send_alert,
1246 		    sizeof(s->s3->send_alert));
1247 
1248 	return do_ssl3_write(s, SSL3_RT_ALERT, s->s3->send_alert,
1249 	    sizeof(s->s3->send_alert));
1250 }
1251 
1252 int
1253 ssl3_send_alert(SSL *s, int level, int desc)
1254 {
1255 	/* If alert is fatal, remove session from cache. */
1256 	if (level == SSL3_AL_FATAL)
1257 		SSL_CTX_remove_session(s->ctx, s->session);
1258 
1259 	s->s3->alert_dispatch = 1;
1260 	s->s3->send_alert[0] = level;
1261 	s->s3->send_alert[1] = desc;
1262 
1263 	/*
1264 	 * If data is still being written out, the alert will be dispatched at
1265 	 * some point in the future.
1266 	 */
1267 	if (s->s3->wbuf.left != 0)
1268 		return -1;
1269 
1270 	return ssl3_dispatch_alert(s);
1271 }
1272 
1273 int
1274 ssl3_dispatch_alert(SSL *s)
1275 {
1276 	int ret;
1277 
1278 	s->s3->alert_dispatch = 0;
1279 	if ((ret = ssl3_write_alert(s)) <= 0) {
1280 		s->s3->alert_dispatch = 1;
1281 		return ret;
1282 	}
1283 
1284 	/*
1285 	 * Alert sent to BIO.  If it is important, flush it now.
1286 	 * If the message does not get sent due to non-blocking IO,
1287 	 * we will not worry too much.
1288 	 */
1289 	if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1290 		(void)BIO_flush(s->wbio);
1291 
1292 	ssl_msg_callback(s, 1, SSL3_RT_ALERT, s->s3->send_alert, 2);
1293 
1294 	ssl_info_callback(s, SSL_CB_WRITE_ALERT,
1295 	    (s->s3->send_alert[0] << 8) | s->s3->send_alert[1]);
1296 
1297 	return ret;
1298 }
1299