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