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