1 /* $OpenBSD: ssl_pkt.c,v 1.50 2021/08/30 19:25:43 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
ssl_force_want_read(SSL * s)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
ssl3_read_n(SSL * s,int n,int max,int extend)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
ssl3_packet_read(SSL * s,int plen)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
ssl3_packet_extend(SSL * s,int plen)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
ssl3_get_record(SSL * s)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
ssl3_write_bytes(SSL * s,int type,const void * buf_,int len)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
do_ssl3_write(SSL * s,int type,const unsigned char * buf,unsigned int len)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
ssl3_write_pending(SSL * s,int type,const unsigned char * buf,unsigned int len)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
ssl3_read_bytes(SSL * s,int type,unsigned char * buf,int len,int peek)715 ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
716 {
717 	int al, i, 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 		ssl_msg_callback(s, 0, SSL3_RT_HANDSHAKE,
917 		    S3I(s)->handshake_fragment, 4);
918 
919 		if (SSL_is_init_finished(s) &&
920 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
921 		    !S3I(s)->renegotiate) {
922 			ssl3_renegotiate(s);
923 			if (ssl3_renegotiate_check(s)) {
924 				i = s->internal->handshake_func(s);
925 				if (i < 0)
926 					return (i);
927 				if (i == 0) {
928 					SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
929 					return (-1);
930 				}
931 
932 				if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
933 					if (S3I(s)->rbuf.left == 0) {
934 						/* no read-ahead left? */
935 			/* In the case where we try to read application data,
936 			 * but we trigger an SSL handshake, we return -1 with
937 			 * the retry option set.  Otherwise renegotiation may
938 			 * cause nasty problems in the blocking world */
939 						ssl_force_want_read(s);
940 						return (-1);
941 					}
942 				}
943 			}
944 		}
945 		/* we either finished a handshake or ignored the request,
946 		 * now try again to obtain the (application) data we were asked for */
947 		goto start;
948 	}
949 	/* Disallow client initiated renegotiation if configured. */
950 	if (s->server && SSL_is_init_finished(s) &&
951 	    S3I(s)->handshake_fragment_len >= 4 &&
952 	    S3I(s)->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO &&
953 	    (s->internal->options & SSL_OP_NO_CLIENT_RENEGOTIATION)) {
954 		al = SSL_AD_NO_RENEGOTIATION;
955 		goto fatal_err;
956 	}
957 	/* If we are a server and get a client hello when renegotiation isn't
958 	 * allowed send back a no renegotiation alert and carry on.
959 	 * WARNING: experimental code, needs reviewing (steve)
960 	 */
961 	if (s->server &&
962 	    SSL_is_init_finished(s) &&
963 	    !S3I(s)->send_connection_binding &&
964 	    (S3I(s)->handshake_fragment_len >= 4) &&
965 	    (S3I(s)->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
966 	    (s->session != NULL) && (s->session->cipher != NULL)) {
967 		/*S3I(s)->handshake_fragment_len = 0;*/
968 		rr->length = 0;
969 		ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
970 		goto start;
971 	}
972 	if (S3I(s)->alert_fragment_len >= 2) {
973 		int alert_level = S3I(s)->alert_fragment[0];
974 		int alert_descr = S3I(s)->alert_fragment[1];
975 
976 		S3I(s)->alert_fragment_len = 0;
977 
978 		ssl_msg_callback(s, 0, SSL3_RT_ALERT,
979 		    S3I(s)->alert_fragment, 2);
980 
981 		ssl_info_callback(s, SSL_CB_READ_ALERT,
982 		    (alert_level << 8) | alert_descr);
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 fatal_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 fatal_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 fatal_err;
1037 		}
1038 
1039 		/* Check we have a cipher to change to */
1040 		if (S3I(s)->hs.cipher == NULL) {
1041 			al = SSL_AD_UNEXPECTED_MESSAGE;
1042 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1043 			goto fatal_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 fatal_err;
1051 		}
1052 		s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1053 
1054 		rr->length = 0;
1055 
1056 		ssl_msg_callback(s, 0, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1);
1057 
1058 		S3I(s)->change_cipher_spec = 1;
1059 		if (!ssl3_do_change_cipher_spec(s))
1060 			goto err;
1061 		else
1062 			goto start;
1063 	}
1064 
1065 	/* Unexpected handshake message (Client Hello, or protocol violation) */
1066 	if ((S3I(s)->handshake_fragment_len >= 4) && !s->internal->in_handshake) {
1067 		if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) &&
1068 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1069 			S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1070 			s->internal->renegotiate = 1;
1071 			s->internal->new_session = 1;
1072 		}
1073 		i = s->internal->handshake_func(s);
1074 		if (i < 0)
1075 			return (i);
1076 		if (i == 0) {
1077 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1078 			return (-1);
1079 		}
1080 
1081 		if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
1082 			if (S3I(s)->rbuf.left == 0) { /* no read-ahead left? */
1083 				/* In the case where we try to read application data,
1084 				 * but we trigger an SSL handshake, we return -1 with
1085 				 * the retry option set.  Otherwise renegotiation may
1086 				 * cause nasty problems in the blocking world */
1087 				ssl_force_want_read(s);
1088 				return (-1);
1089 			}
1090 		}
1091 		goto start;
1092 	}
1093 
1094 	switch (rr->type) {
1095 	default:
1096 		/*
1097 		 * TLS up to v1.1 just ignores unknown message types:
1098 		 * TLS v1.2 give an unexpected message alert.
1099 		 */
1100 		if (s->version >= TLS1_VERSION &&
1101 		    s->version <= TLS1_1_VERSION) {
1102 			rr->length = 0;
1103 			goto start;
1104 		}
1105 		al = SSL_AD_UNEXPECTED_MESSAGE;
1106 		SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1107 		goto fatal_err;
1108 	case SSL3_RT_CHANGE_CIPHER_SPEC:
1109 	case SSL3_RT_ALERT:
1110 	case SSL3_RT_HANDSHAKE:
1111 		/* we already handled all of these, with the possible exception
1112 		 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that
1113 		 * should not happen when type != rr->type */
1114 		al = SSL_AD_UNEXPECTED_MESSAGE;
1115 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1116 		goto fatal_err;
1117 	case SSL3_RT_APPLICATION_DATA:
1118 		/* At this point, we were expecting handshake data,
1119 		 * but have application data.  If the library was
1120 		 * running inside ssl3_read() (i.e. in_read_app_data
1121 		 * is set) and it makes sense to read application data
1122 		 * at this point (session renegotiation not yet started),
1123 		 * we will indulge it.
1124 		 */
1125 		if (S3I(s)->in_read_app_data &&
1126 		    (S3I(s)->total_renegotiations != 0) &&
1127 		    (((S3I(s)->hs.state & SSL_ST_CONNECT) &&
1128 		    (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1129 		    (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) ||
1130 		    ((S3I(s)->hs.state & SSL_ST_ACCEPT) &&
1131 		    (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
1132 		    (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1133 			S3I(s)->in_read_app_data = 2;
1134 			return (-1);
1135 		} else {
1136 			al = SSL_AD_UNEXPECTED_MESSAGE;
1137 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1138 			goto fatal_err;
1139 		}
1140 	}
1141 	/* not reached */
1142 
1143  fatal_err:
1144 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1145  err:
1146 	return (-1);
1147 }
1148 
1149 int
ssl3_do_change_cipher_spec(SSL * s)1150 ssl3_do_change_cipher_spec(SSL *s)
1151 {
1152 	if (S3I(s)->hs.tls12.key_block == NULL) {
1153 		if (s->session == NULL || s->session->master_key_length == 0) {
1154 			/* might happen if dtls1_read_bytes() calls this */
1155 			SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1156 			return (0);
1157 		}
1158 
1159 		s->session->cipher = S3I(s)->hs.cipher;
1160 		if (!tls1_setup_key_block(s))
1161 			return (0);
1162 	}
1163 
1164 	if (!tls1_change_read_cipher_state(s))
1165 		return (0);
1166 
1167 	/*
1168 	 * We have to record the message digest at this point so we can get it
1169 	 * before we read the finished message.
1170 	 */
1171 	if (!tls12_derive_peer_finished(s))
1172 		return (0);
1173 
1174 	return (1);
1175 }
1176 
1177 static int
ssl3_write_alert(SSL * s)1178 ssl3_write_alert(SSL *s)
1179 {
1180 	if (SSL_is_dtls(s))
1181 		return do_dtls1_write(s, SSL3_RT_ALERT, S3I(s)->send_alert,
1182 		    sizeof(S3I(s)->send_alert));
1183 
1184 	return do_ssl3_write(s, SSL3_RT_ALERT, S3I(s)->send_alert,
1185 	    sizeof(S3I(s)->send_alert));
1186 }
1187 
1188 int
ssl3_send_alert(SSL * s,int level,int desc)1189 ssl3_send_alert(SSL *s, int level, int desc)
1190 {
1191 	/* If alert is fatal, remove session from cache. */
1192 	if (level == SSL3_AL_FATAL)
1193 		SSL_CTX_remove_session(s->ctx, s->session);
1194 
1195 	S3I(s)->alert_dispatch = 1;
1196 	S3I(s)->send_alert[0] = level;
1197 	S3I(s)->send_alert[1] = desc;
1198 
1199 	/*
1200 	 * If data is still being written out, the alert will be dispatched at
1201 	 * some point in the future.
1202 	 */
1203 	if (S3I(s)->wbuf.left != 0)
1204 		return -1;
1205 
1206 	return ssl3_dispatch_alert(s);
1207 }
1208 
1209 int
ssl3_dispatch_alert(SSL * s)1210 ssl3_dispatch_alert(SSL *s)
1211 {
1212 	int ret;
1213 
1214 	S3I(s)->alert_dispatch = 0;
1215 	if ((ret = ssl3_write_alert(s)) <= 0) {
1216 		S3I(s)->alert_dispatch = 1;
1217 		return ret;
1218 	}
1219 
1220 	/*
1221 	 * Alert sent to BIO.  If it is important, flush it now.
1222 	 * If the message does not get sent due to non-blocking IO,
1223 	 * we will not worry too much.
1224 	 */
1225 	if (S3I(s)->send_alert[0] == SSL3_AL_FATAL)
1226 		(void)BIO_flush(s->wbio);
1227 
1228 	ssl_msg_callback(s, 1, SSL3_RT_ALERT, S3I(s)->send_alert, 2);
1229 
1230 	ssl_info_callback(s, SSL_CB_WRITE_ALERT,
1231 	    (S3I(s)->send_alert[0] << 8) | S3I(s)->send_alert[1]);
1232 
1233 	return ret;
1234 }
1235