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