xref: /openbsd-src/lib/libssl/d1_pkt.c (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
1 /* $OpenBSD: d1_pkt.c,v 1.103 2021/07/21 08:42:14 jsing Exp $ */
2 /*
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
5  */
6 /* ====================================================================
7  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@openssl.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  *
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  *
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  *
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  *
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  *
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115 
116 #include <machine/endian.h>
117 
118 #include <errno.h>
119 #include <stdio.h>
120 
121 #include <openssl/buffer.h>
122 #include <openssl/evp.h>
123 
124 #include "bytestring.h"
125 #include "dtls_locl.h"
126 #include "pqueue.h"
127 #include "ssl_locl.h"
128 
129 static int	do_dtls1_write(SSL *s, int type, const unsigned char *buf,
130 		    unsigned int len);
131 
132 
133 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
134 static int
135 satsub64be(const unsigned char *v1, const unsigned char *v2)
136 {
137 	int ret, sat, brw, i;
138 
139 	if (sizeof(long) == 8)
140 		do {
141 			long l;
142 
143 			if (BYTE_ORDER == LITTLE_ENDIAN)
144 				break;
145 			/* not reached on little-endians */
146 			/* following test is redundant, because input is
147 			 * always aligned, but I take no chances... */
148 			if (((size_t)v1 | (size_t)v2) & 0x7)
149 				break;
150 
151 			l  = *((long *)v1);
152 			l -= *((long *)v2);
153 			if (l > 128)
154 				return 128;
155 			else if (l<-128)
156 				return -128;
157 			else
158 				return (int)l;
159 		} while (0);
160 
161 	ret = (int)v1[7] - (int)v2[7];
162 	sat = 0;
163 	brw = ret >> 8;	/* brw is either 0 or -1 */
164 	if (ret & 0x80) {
165 		for (i = 6; i >= 0; i--) {
166 			brw += (int)v1[i]-(int)v2[i];
167 			sat |= ~brw;
168 			brw >>= 8;
169 		}
170 	} else {
171 		for (i = 6; i >= 0; i--) {
172 			brw += (int)v1[i]-(int)v2[i];
173 			sat |= brw;
174 			brw >>= 8;
175 		}
176 	}
177 	brw <<= 8;	/* brw is either 0 or -256 */
178 
179 	if (sat & 0xff)
180 		return brw | 0x80;
181 	else
182 		return brw + (ret & 0xFF);
183 }
184 
185 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
186     int len, int peek);
187 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
188     const unsigned char *seq);
189 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap,
190     const unsigned char *seq);
191 static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr,
192     unsigned int *is_next_epoch);
193 static int dtls1_buffer_record(SSL *s, record_pqueue *q,
194     unsigned char *priority);
195 static int dtls1_process_record(SSL *s);
196 
197 /* copy buffered record into SSL structure */
198 static int
199 dtls1_copy_record(SSL *s, DTLS1_RECORD_DATA_INTERNAL *rdata)
200 {
201 	ssl3_release_buffer(&S3I(s)->rbuf);
202 
203 	s->internal->packet = rdata->packet;
204 	s->internal->packet_length = rdata->packet_length;
205 	memcpy(&(S3I(s)->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
206 	memcpy(&(S3I(s)->rrec), &(rdata->rrec), sizeof(SSL3_RECORD_INTERNAL));
207 
208 	return (1);
209 }
210 
211 static int
212 dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
213 {
214 	DTLS1_RECORD_DATA_INTERNAL *rdata;
215 	pitem *item;
216 
217 	/* Limit the size of the queue to prevent DOS attacks */
218 	if (pqueue_size(queue->q) >= 100)
219 		return 0;
220 
221 	rdata = malloc(sizeof(DTLS1_RECORD_DATA_INTERNAL));
222 	item = pitem_new(priority, rdata);
223 	if (rdata == NULL || item == NULL)
224 		goto init_err;
225 
226 	rdata->packet = s->internal->packet;
227 	rdata->packet_length = s->internal->packet_length;
228 	memcpy(&(rdata->rbuf), &(S3I(s)->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
229 	memcpy(&(rdata->rrec), &(S3I(s)->rrec), sizeof(SSL3_RECORD_INTERNAL));
230 
231 	item->data = rdata;
232 
233 	s->internal->packet = NULL;
234 	s->internal->packet_length = 0;
235 	memset(&(S3I(s)->rbuf), 0, sizeof(SSL3_BUFFER_INTERNAL));
236 	memset(&(S3I(s)->rrec), 0, sizeof(SSL3_RECORD_INTERNAL));
237 
238 	if (!ssl3_setup_buffers(s))
239 		goto err;
240 
241 	/* insert should not fail, since duplicates are dropped */
242 	if (pqueue_insert(queue->q, item) == NULL)
243 		goto err;
244 
245 	return (1);
246 
247  err:
248 	ssl3_release_buffer(&rdata->rbuf);
249 
250  init_err:
251 	SSLerror(s, ERR_R_INTERNAL_ERROR);
252 	free(rdata);
253 	pitem_free(item);
254 	return (-1);
255 }
256 
257 
258 static int
259 dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
260 {
261 	pitem *item;
262 
263 	item = pqueue_pop(queue->q);
264 	if (item) {
265 		dtls1_copy_record(s, item->data);
266 
267 		free(item->data);
268 		pitem_free(item);
269 
270 		return (1);
271 	}
272 
273 	return (0);
274 }
275 
276 static int
277 dtls1_process_buffered_record(SSL *s)
278 {
279 	/* Check if epoch is current. */
280 	if (D1I(s)->unprocessed_rcds.epoch != D1I(s)->r_epoch)
281 		return (0);
282 
283 	/* Update epoch once all unprocessed records have been processed. */
284 	if (pqueue_peek(D1I(s)->unprocessed_rcds.q) == NULL) {
285 		D1I(s)->unprocessed_rcds.epoch = D1I(s)->r_epoch + 1;
286 		return (0);
287 	}
288 
289 	/* Process one of the records. */
290 	if (!dtls1_retrieve_buffered_record(s, &D1I(s)->unprocessed_rcds))
291 		return (-1);
292 	if (!dtls1_process_record(s))
293 		return (-1);
294 
295 	return (1);
296 }
297 
298 static int
299 dtls1_process_record(SSL *s)
300 {
301 	SSL3_RECORD_INTERNAL *rr = &(S3I(s)->rrec);
302 	uint8_t alert_desc;
303 	uint8_t *out;
304 	size_t out_len;
305 
306 	tls12_record_layer_set_version(s->internal->rl, s->version);
307 
308 	if (!tls12_record_layer_open_record(s->internal->rl, s->internal->packet,
309 	    s->internal->packet_length, &out, &out_len)) {
310 		tls12_record_layer_alert(s->internal->rl, &alert_desc);
311 
312 		if (alert_desc == 0)
313 			goto err;
314 
315 		/*
316 		 * DTLS should silently discard invalid records, including those
317 		 * with a bad MAC, as per RFC 6347 section 4.1.2.1.
318 		 */
319 		if (alert_desc == SSL_AD_BAD_RECORD_MAC) {
320 			out_len = 0;
321 			goto done;
322 		}
323 
324 		if (alert_desc == SSL_AD_RECORD_OVERFLOW)
325 			SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
326 
327 		goto fatal_err;
328 	}
329 
330  done:
331 	rr->data = out;
332 	rr->length = out_len;
333 	rr->off = 0;
334 
335 	s->internal->packet_length = 0;
336 
337 	return (1);
338 
339  fatal_err:
340 	ssl3_send_alert(s, SSL3_AL_FATAL, alert_desc);
341  err:
342 	return (0);
343 }
344 
345 /* Call this to get a new input record.
346  * It will return <= 0 if more data is needed, normally due to an error
347  * or non-blocking IO.
348  * When it finishes, one packet has been decoded and can be found in
349  * ssl->s3->internal->rrec.type    - is the type of record
350  * ssl->s3->internal->rrec.data, 	 - data
351  * ssl->s3->internal->rrec.length, - number of bytes
352  */
353 /* used only by dtls1_read_bytes */
354 int
355 dtls1_get_record(SSL *s)
356 {
357 	SSL3_RECORD_INTERNAL *rr = &(S3I(s)->rrec);
358 	unsigned char *p = NULL;
359 	DTLS1_BITMAP *bitmap;
360 	unsigned int is_next_epoch;
361 	int ret, n;
362 
363 	/* See if there are pending records that can now be processed. */
364 	if ((ret = dtls1_process_buffered_record(s)) != 0)
365 		return (ret);
366 
367 	/* get something from the wire */
368 	if (0) {
369  again:
370 		/* dump this record on all retries */
371 		rr->length = 0;
372 		s->internal->packet_length = 0;
373 	}
374 
375 	/* check if we have the header */
376 	if ((s->internal->rstate != SSL_ST_READ_BODY) ||
377 	    (s->internal->packet_length < DTLS1_RT_HEADER_LENGTH)) {
378 		CBS header, seq_no;
379 		uint16_t epoch, len, ssl_version;
380 		uint8_t type;
381 
382 		n = ssl3_packet_read(s, DTLS1_RT_HEADER_LENGTH);
383 		if (n <= 0)
384 			return (n);
385 
386 		/* If this packet contained a partial record, dump it. */
387 		if (n != DTLS1_RT_HEADER_LENGTH)
388 			goto again;
389 
390 		s->internal->rstate = SSL_ST_READ_BODY;
391 
392 		CBS_init(&header, s->internal->packet, s->internal->packet_length);
393 
394 		/* Pull apart the header into the DTLS1_RECORD */
395 		if (!CBS_get_u8(&header, &type))
396 			goto again;
397 		if (!CBS_get_u16(&header, &ssl_version))
398 			goto again;
399 
400 		/* sequence number is 64 bits, with top 2 bytes = epoch */
401 		if (!CBS_get_u16(&header, &epoch) ||
402 		    !CBS_get_bytes(&header, &seq_no, 6))
403 			goto again;
404 
405 		if (!CBS_get_u16(&header, &len))
406 			goto again;
407 
408 		if (!CBS_write_bytes(&seq_no, &rr->seq_num[2],
409 		    sizeof(rr->seq_num) - 2, NULL))
410 			goto again;
411 
412 		rr->type = type;
413 		rr->epoch = epoch;
414 		rr->length = len;
415 
416 		/* unexpected version, silently discard */
417 		if (!s->internal->first_packet && ssl_version != s->version)
418 			goto again;
419 
420 		/* wrong version, silently discard record */
421 		if ((ssl_version & 0xff00) != (s->version & 0xff00))
422 			goto again;
423 
424 		/* record too long, silently discard it */
425 		if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
426 			goto again;
427 
428 		/* now s->internal->rstate == SSL_ST_READ_BODY */
429 		p = (unsigned char *)CBS_data(&header);
430 	}
431 
432 	/* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */
433 
434 	n = ssl3_packet_extend(s, DTLS1_RT_HEADER_LENGTH + rr->length);
435 	if (n <= 0)
436 		return (n);
437 
438 	/* If this packet contained a partial record, dump it. */
439 	if (n != DTLS1_RT_HEADER_LENGTH + rr->length)
440 		goto again;
441 
442 	s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
443 
444 	/* match epochs.  NULL means the packet is dropped on the floor */
445 	bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
446 	if (bitmap == NULL)
447 		goto again;
448 
449 	/*
450 	 * Check whether this is a repeat, or aged record.
451 	 * Don't check if we're listening and this message is
452 	 * a ClientHello. They can look as if they're replayed,
453 	 * since they arrive from different connections and
454 	 * would be dropped unnecessarily.
455 	 */
456 	if (!(D1I(s)->listen && rr->type == SSL3_RT_HANDSHAKE &&
457 	    p != NULL && *p == SSL3_MT_CLIENT_HELLO) &&
458 	    !dtls1_record_replay_check(s, bitmap, rr->seq_num))
459 		goto again;
460 
461 	/* just read a 0 length packet */
462 	if (rr->length == 0)
463 		goto again;
464 
465 	/* If this record is from the next epoch (either HM or ALERT),
466 	 * and a handshake is currently in progress, buffer it since it
467 	 * cannot be processed at this time. However, do not buffer
468 	 * anything while listening.
469 	 */
470 	if (is_next_epoch) {
471 		if ((SSL_in_init(s) || s->internal->in_handshake) && !D1I(s)->listen) {
472 			if (dtls1_buffer_record(s, &(D1I(s)->unprocessed_rcds),
473 			    rr->seq_num) < 0)
474 				return (-1);
475 			/* Mark receipt of record. */
476 			dtls1_record_bitmap_update(s, bitmap, rr->seq_num);
477 		}
478 		goto again;
479 	}
480 
481 	if (!dtls1_process_record(s))
482 		goto again;
483 
484 	/* Mark receipt of record. */
485 	dtls1_record_bitmap_update(s, bitmap, rr->seq_num);
486 
487 	return (1);
488 }
489 
490 /* Return up to 'len' payload bytes received in 'type' records.
491  * 'type' is one of the following:
492  *
493  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
494  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
495  *   -  0 (during a shutdown, no data has to be returned)
496  *
497  * If we don't have stored data to work from, read a SSL/TLS record first
498  * (possibly multiple records if we still don't have anything to return).
499  *
500  * This function must handle any surprises the peer may have for us, such as
501  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
502  * a surprise, but handled as if it were), or renegotiation requests.
503  * Also if record payloads contain fragments too small to process, we store
504  * them until there is enough for the respective protocol (the record protocol
505  * may use arbitrary fragmentation and even interleaving):
506  *     Change cipher spec protocol
507  *             just 1 byte needed, no need for keeping anything stored
508  *     Alert protocol
509  *             2 bytes needed (AlertLevel, AlertDescription)
510  *     Handshake protocol
511  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
512  *             to detect unexpected Client Hello and Hello Request messages
513  *             here, anything else is handled by higher layers
514  *     Application data protocol
515  *             none of our business
516  */
517 int
518 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
519 {
520 	int al, i, j, ret;
521 	unsigned int n;
522 	SSL3_RECORD_INTERNAL *rr;
523 	void (*cb)(const SSL *ssl, int type2, int val) = NULL;
524 
525 	if (S3I(s)->rbuf.buf == NULL) /* Not initialized yet */
526 		if (!ssl3_setup_buffers(s))
527 			return (-1);
528 
529 	if ((type &&
530 	     type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
531 	    (peek && (type != SSL3_RT_APPLICATION_DATA))) {
532 		SSLerror(s, ERR_R_INTERNAL_ERROR);
533 		return -1;
534 	}
535 
536 	/* check whether there's a handshake message (client hello?) waiting */
537 	if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
538 		return ret;
539 
540 	/* Now D1I(s)->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
541 
542 	if (!s->internal->in_handshake && SSL_in_init(s))
543 	{
544 		/* type == SSL3_RT_APPLICATION_DATA */
545 		i = s->internal->handshake_func(s);
546 		if (i < 0)
547 			return (i);
548 		if (i == 0) {
549 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
550 			return (-1);
551 		}
552 	}
553 
554  start:
555 	s->internal->rwstate = SSL_NOTHING;
556 
557 	/* S3I(s)->rrec.type	    - is the type of record
558 	 * S3I(s)->rrec.data,    - data
559 	 * S3I(s)->rrec.off,     - offset into 'data' for next read
560 	 * S3I(s)->rrec.length,  - number of bytes. */
561 	rr = &(S3I(s)->rrec);
562 
563 	/* We are not handshaking and have no data yet,
564 	 * so process data buffered during the last handshake
565 	 * in advance, if any.
566 	 */
567 	if (S3I(s)->hs.state == SSL_ST_OK && rr->length == 0)
568 		dtls1_retrieve_buffered_record(s, &(D1I(s)->buffered_app_data));
569 
570 	/* Check for timeout */
571 	if (dtls1_handle_timeout(s) > 0)
572 		goto start;
573 
574 	/* get new packet if necessary */
575 	if ((rr->length == 0) || (s->internal->rstate == SSL_ST_READ_BODY)) {
576 		ret = dtls1_get_record(s);
577 		if (ret <= 0) {
578 			ret = dtls1_read_failed(s, ret);
579 			/* anything other than a timeout is an error */
580 			if (ret <= 0)
581 				return (ret);
582 			else
583 				goto start;
584 		}
585 	}
586 
587 	if (D1I(s)->listen && rr->type != SSL3_RT_HANDSHAKE) {
588 		rr->length = 0;
589 		goto start;
590 	}
591 
592 	/* we now have a packet which can be read and processed */
593 
594 	if (S3I(s)->change_cipher_spec /* set when we receive ChangeCipherSpec,
595 	                               * reset by ssl3_get_finished */
596 	    && (rr->type != SSL3_RT_HANDSHAKE)) {
597 		/* We now have application data between CCS and Finished.
598 		 * Most likely the packets were reordered on their way, so
599 		 * buffer the application data for later processing rather
600 		 * than dropping the connection.
601 		 */
602 		if (dtls1_buffer_record(s, &(D1I(s)->buffered_app_data),
603 		    rr->seq_num) < 0) {
604 			SSLerror(s, ERR_R_INTERNAL_ERROR);
605 			return (-1);
606 		}
607 		rr->length = 0;
608 		goto start;
609 	}
610 
611 	/* If the other end has shut down, throw anything we read away
612 	 * (even in 'peek' mode) */
613 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
614 		rr->length = 0;
615 		s->internal->rwstate = SSL_NOTHING;
616 		return (0);
617 	}
618 
619 	/* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
620 	if (type == rr->type) {
621 		/* make sure that we are not getting application data when we
622 		 * are doing a handshake for the first time */
623 		if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
624 		    !tls12_record_layer_read_protected(s->internal->rl)) {
625 			al = SSL_AD_UNEXPECTED_MESSAGE;
626 			SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
627 			goto fatal_err;
628 		}
629 
630 		if (len <= 0)
631 			return (len);
632 
633 		if ((unsigned int)len > rr->length)
634 			n = rr->length;
635 		else
636 			n = (unsigned int)len;
637 
638 		memcpy(buf, &(rr->data[rr->off]), n);
639 		if (!peek) {
640 			rr->length -= n;
641 			rr->off += n;
642 			if (rr->length == 0) {
643 				s->internal->rstate = SSL_ST_READ_HEADER;
644 				rr->off = 0;
645 			}
646 		}
647 
648 		return (n);
649 	}
650 
651 
652 	/* If we get here, then type != rr->type; if we have a handshake
653 	 * message, then it was unexpected (Hello Request or Client Hello). */
654 
655 	/* In case of record types for which we have 'fragment' storage,
656 	 * fill that so that we can process the data at a fixed place.
657 	 */
658 	{
659 		unsigned int k, dest_maxlen = 0;
660 		unsigned char *dest = NULL;
661 		unsigned int *dest_len = NULL;
662 
663 		if (rr->type == SSL3_RT_HANDSHAKE) {
664 			dest_maxlen = sizeof D1I(s)->handshake_fragment;
665 			dest = D1I(s)->handshake_fragment;
666 			dest_len = &D1I(s)->handshake_fragment_len;
667 		} else if (rr->type == SSL3_RT_ALERT) {
668 			dest_maxlen = sizeof(D1I(s)->alert_fragment);
669 			dest = D1I(s)->alert_fragment;
670 			dest_len = &D1I(s)->alert_fragment_len;
671 		}
672 		/* else it's a CCS message, or application data or wrong */
673 		else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
674 			/* Application data while renegotiating
675 			 * is allowed. Try again reading.
676 			 */
677 			if (rr->type == SSL3_RT_APPLICATION_DATA) {
678 				BIO *bio;
679 				S3I(s)->in_read_app_data = 2;
680 				bio = SSL_get_rbio(s);
681 				s->internal->rwstate = SSL_READING;
682 				BIO_clear_retry_flags(bio);
683 				BIO_set_retry_read(bio);
684 				return (-1);
685 			}
686 
687 			/* Not certain if this is the right error handling */
688 			al = SSL_AD_UNEXPECTED_MESSAGE;
689 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
690 			goto fatal_err;
691 		}
692 
693 		if (dest_maxlen > 0) {
694             /* XDTLS:  In a pathalogical case, the Client Hello
695              *  may be fragmented--don't always expect dest_maxlen bytes */
696 			if (rr->length < dest_maxlen) {
697 				s->internal->rstate = SSL_ST_READ_HEADER;
698 				rr->length = 0;
699 				goto start;
700 			}
701 
702 			/* now move 'n' bytes: */
703 			for ( k = 0; k < dest_maxlen; k++) {
704 				dest[k] = rr->data[rr->off++];
705 				rr->length--;
706 			}
707 			*dest_len = dest_maxlen;
708 		}
709 	}
710 
711 	/* D1I(s)->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
712 	 * D1I(s)->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
713 	 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
714 
715 	/* If we are a client, check for an incoming 'Hello Request': */
716 	if ((!s->server) &&
717 	    (D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
718 	    (D1I(s)->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
719 	    (s->session != NULL) && (s->session->cipher != NULL)) {
720 		D1I(s)->handshake_fragment_len = 0;
721 
722 		if ((D1I(s)->handshake_fragment[1] != 0) ||
723 		    (D1I(s)->handshake_fragment[2] != 0) ||
724 		    (D1I(s)->handshake_fragment[3] != 0)) {
725 			al = SSL_AD_DECODE_ERROR;
726 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
727 			goto fatal_err;
728 		}
729 
730 		/* no need to check sequence number on HELLO REQUEST messages */
731 
732 		if (s->internal->msg_callback)
733 			s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
734 		D1I(s)->handshake_fragment, 4, s, s->internal->msg_callback_arg);
735 
736 		if (SSL_is_init_finished(s) &&
737 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
738 		    !S3I(s)->renegotiate) {
739 			D1I(s)->handshake_read_seq++;
740 			s->internal->new_session = 1;
741 			ssl3_renegotiate(s);
742 			if (ssl3_renegotiate_check(s)) {
743 				i = s->internal->handshake_func(s);
744 				if (i < 0)
745 					return (i);
746 				if (i == 0) {
747 					SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
748 					return (-1);
749 				}
750 
751 				if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
752 					if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */
753 					{
754 						BIO *bio;
755 						/* In the case where we try to read application data,
756 						 * but we trigger an SSL handshake, we return -1 with
757 						 * the retry option set.  Otherwise renegotiation may
758 						 * cause nasty problems in the blocking world */
759 						s->internal->rwstate = SSL_READING;
760 						bio = SSL_get_rbio(s);
761 						BIO_clear_retry_flags(bio);
762 						BIO_set_retry_read(bio);
763 						return (-1);
764 					}
765 				}
766 			}
767 		}
768 		/* we either finished a handshake or ignored the request,
769 		 * now try again to obtain the (application) data we were asked for */
770 		goto start;
771 	}
772 
773 	if (D1I(s)->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
774 		int alert_level = D1I(s)->alert_fragment[0];
775 		int alert_descr = D1I(s)->alert_fragment[1];
776 
777 		D1I(s)->alert_fragment_len = 0;
778 
779 		if (s->internal->msg_callback)
780 			s->internal->msg_callback(0, s->version, SSL3_RT_ALERT,
781 		D1I(s)->alert_fragment, 2, s, s->internal->msg_callback_arg);
782 
783 		if (s->internal->info_callback != NULL)
784 			cb = s->internal->info_callback;
785 		else if (s->ctx->internal->info_callback != NULL)
786 			cb = s->ctx->internal->info_callback;
787 
788 		if (cb != NULL) {
789 			j = (alert_level << 8) | alert_descr;
790 			cb(s, SSL_CB_READ_ALERT, j);
791 		}
792 
793 		if (alert_level == 1) /* warning */
794 		{
795 			S3I(s)->warn_alert = alert_descr;
796 			if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
797 				s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
798 				return (0);
799 			}
800 		} else if (alert_level == 2) /* fatal */
801 		{
802 			s->internal->rwstate = SSL_NOTHING;
803 			S3I(s)->fatal_alert = alert_descr;
804 			SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
805 			ERR_asprintf_error_data("SSL alert number %d",
806 			    alert_descr);
807 			s->internal->shutdown|=SSL_RECEIVED_SHUTDOWN;
808 			SSL_CTX_remove_session(s->ctx, s->session);
809 			return (0);
810 		} else {
811 			al = SSL_AD_ILLEGAL_PARAMETER;
812 			SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
813 			goto fatal_err;
814 		}
815 
816 		goto start;
817 	}
818 
819 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
820 	{
821 		s->internal->rwstate = SSL_NOTHING;
822 		rr->length = 0;
823 		return (0);
824 	}
825 
826 	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
827 		/* 'Change Cipher Spec' is just a single byte, so we know
828 		 * exactly what the record payload has to look like */
829 		/* XDTLS: check that epoch is consistent */
830 		if ((rr->length != DTLS1_CCS_HEADER_LENGTH) ||
831 		    (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
832 			al = SSL_AD_DECODE_ERROR;
833 			SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
834 			goto fatal_err;
835 		}
836 
837 		rr->length = 0;
838 
839 		if (s->internal->msg_callback)
840 			s->internal->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
841 		rr->data, 1, s, s->internal->msg_callback_arg);
842 
843 		/* We can't process a CCS now, because previous handshake
844 		 * messages are still missing, so just drop it.
845 		 */
846 		if (!D1I(s)->change_cipher_spec_ok) {
847 			goto start;
848 		}
849 
850 		D1I(s)->change_cipher_spec_ok = 0;
851 
852 		S3I(s)->change_cipher_spec = 1;
853 		if (!ssl3_do_change_cipher_spec(s))
854 			goto err;
855 
856 		goto start;
857 	}
858 
859 	/* Unexpected handshake message (Client Hello, or protocol violation) */
860 	if ((D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
861 	    !s->internal->in_handshake) {
862 		struct hm_header_st msg_hdr;
863 
864 		/* this may just be a stale retransmit */
865 		if (!dtls1_get_message_header(rr->data, &msg_hdr))
866 			return -1;
867 		if (rr->epoch != D1I(s)->r_epoch) {
868 			rr->length = 0;
869 			goto start;
870 		}
871 
872 		/* If we are server, we may have a repeated FINISHED of the
873 		 * client here, then retransmit our CCS and FINISHED.
874 		 */
875 		if (msg_hdr.type == SSL3_MT_FINISHED) {
876 			if (dtls1_check_timeout_num(s) < 0)
877 				return -1;
878 
879 			dtls1_retransmit_buffered_messages(s);
880 			rr->length = 0;
881 			goto start;
882 		}
883 
884 		if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) &&
885 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
886 			S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
887 			s->internal->renegotiate = 1;
888 			s->internal->new_session = 1;
889 		}
890 		i = s->internal->handshake_func(s);
891 		if (i < 0)
892 			return (i);
893 		if (i == 0) {
894 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
895 			return (-1);
896 		}
897 
898 		if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
899 			if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */
900 			{
901 				BIO *bio;
902 				/* In the case where we try to read application data,
903 				 * but we trigger an SSL handshake, we return -1 with
904 				 * the retry option set.  Otherwise renegotiation may
905 				 * cause nasty problems in the blocking world */
906 				s->internal->rwstate = SSL_READING;
907 				bio = SSL_get_rbio(s);
908 				BIO_clear_retry_flags(bio);
909 				BIO_set_retry_read(bio);
910 				return (-1);
911 			}
912 		}
913 		goto start;
914 	}
915 
916 	switch (rr->type) {
917 	default:
918 		/* TLS just ignores unknown message types */
919 		if (s->version == TLS1_VERSION) {
920 			rr->length = 0;
921 			goto start;
922 		}
923 		al = SSL_AD_UNEXPECTED_MESSAGE;
924 		SSLerror(s, SSL_R_UNEXPECTED_RECORD);
925 		goto fatal_err;
926 	case SSL3_RT_CHANGE_CIPHER_SPEC:
927 	case SSL3_RT_ALERT:
928 	case SSL3_RT_HANDSHAKE:
929 		/* we already handled all of these, with the possible exception
930 		 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that
931 		 * should not happen when type != rr->type */
932 		al = SSL_AD_UNEXPECTED_MESSAGE;
933 		SSLerror(s, ERR_R_INTERNAL_ERROR);
934 		goto fatal_err;
935 	case SSL3_RT_APPLICATION_DATA:
936 		/* At this point, we were expecting handshake data,
937 		 * but have application data.  If the library was
938 		 * running inside ssl3_read() (i.e. in_read_app_data
939 		 * is set) and it makes sense to read application data
940 		 * at this point (session renegotiation not yet started),
941 		 * we will indulge it.
942 		 */
943 		if (S3I(s)->in_read_app_data &&
944 		    (S3I(s)->total_renegotiations != 0) &&
945 		    (((S3I(s)->hs.state & SSL_ST_CONNECT) &&
946 		    (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
947 		    (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
948 		    (S3I(s)->hs.state & SSL_ST_ACCEPT) &&
949 		    (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
950 		    (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
951 			S3I(s)->in_read_app_data = 2;
952 			return (-1);
953 		} else {
954 			al = SSL_AD_UNEXPECTED_MESSAGE;
955 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
956 			goto fatal_err;
957 		}
958 	}
959 	/* not reached */
960 
961  fatal_err:
962 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
963  err:
964 	return (-1);
965 }
966 
967 int
968 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
969 {
970 	int i;
971 
972 	if (SSL_in_init(s) && !s->internal->in_handshake)
973 	{
974 		i = s->internal->handshake_func(s);
975 		if (i < 0)
976 			return (i);
977 		if (i == 0) {
978 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
979 			return -1;
980 		}
981 	}
982 
983 	if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
984 		SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
985 		return -1;
986 	}
987 
988 	i = dtls1_write_bytes(s, type, buf_, len);
989 	return i;
990 }
991 
992 
993 	/* this only happens when a client hello is received and a handshake
994 	 * is started. */
995 static int
996 have_handshake_fragment(SSL *s, int type, unsigned char *buf,
997     int len, int peek)
998 {
999 
1000 	if ((type == SSL3_RT_HANDSHAKE) && (D1I(s)->handshake_fragment_len > 0))
1001 		/* (partially) satisfy request from storage */
1002 	{
1003 		unsigned char *src = D1I(s)->handshake_fragment;
1004 		unsigned char *dst = buf;
1005 		unsigned int k, n;
1006 
1007 		/* peek == 0 */
1008 		n = 0;
1009 		while ((len > 0) && (D1I(s)->handshake_fragment_len > 0)) {
1010 			*dst++ = *src++;
1011 			len--;
1012 			D1I(s)->handshake_fragment_len--;
1013 			n++;
1014 		}
1015 		/* move any remaining fragment bytes: */
1016 		for (k = 0; k < D1I(s)->handshake_fragment_len; k++)
1017 			D1I(s)->handshake_fragment[k] = *src++;
1018 		return n;
1019 	}
1020 
1021 	return 0;
1022 }
1023 
1024 
1025 /* Call this to write data in records of type 'type'
1026  * It will return <= 0 if not all data has been sent or non-blocking IO.
1027  */
1028 int
1029 dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
1030 {
1031 	int i;
1032 
1033 	OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
1034 	s->internal->rwstate = SSL_NOTHING;
1035 	i = do_dtls1_write(s, type, buf, len);
1036 	return i;
1037 }
1038 
1039 int
1040 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
1041 {
1042 	SSL3_BUFFER_INTERNAL *wb = &(S3I(s)->wbuf);
1043 	size_t out_len;
1044 	CBB cbb;
1045 	int ret;
1046 
1047 	memset(&cbb, 0, sizeof(cbb));
1048 
1049 	/*
1050 	 * First check if there is a SSL3_BUFFER_INTERNAL still being written
1051 	 * out.  This will happen with non blocking IO.
1052 	 */
1053 	if (wb->left != 0) {
1054 		OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
1055 		return (ssl3_write_pending(s, type, buf, len));
1056 	}
1057 
1058 	/* If we have an alert to send, let's send it */
1059 	if (S3I(s)->alert_dispatch) {
1060 		if ((ret = s->method->ssl_dispatch_alert(s)) <= 0)
1061 			return (ret);
1062 		/* If it went, fall through and send more stuff. */
1063 	}
1064 
1065 	if (len == 0)
1066 		return 0;
1067 
1068 	wb->offset = 0;
1069 
1070 	if (!CBB_init_fixed(&cbb, wb->buf, wb->len))
1071 		goto err;
1072 
1073 	tls12_record_layer_set_version(s->internal->rl, s->version);
1074 
1075 	if (!tls12_record_layer_seal_record(s->internal->rl, type, buf, len, &cbb))
1076 		goto err;
1077 
1078 	if (!CBB_finish(&cbb, NULL, &out_len))
1079 		goto err;
1080 
1081 	wb->left = out_len;
1082 
1083 	/*
1084 	 * Memorize arguments so that ssl3_write_pending can detect
1085 	 * bad write retries later.
1086 	 */
1087 	S3I(s)->wpend_tot = len;
1088 	S3I(s)->wpend_buf = buf;
1089 	S3I(s)->wpend_type = type;
1090 	S3I(s)->wpend_ret = len;
1091 
1092 	/* We now just need to write the buffer. */
1093 	return ssl3_write_pending(s, type, buf, len);
1094 
1095  err:
1096 	CBB_cleanup(&cbb);
1097 
1098 	return -1;
1099 }
1100 
1101 static int
1102 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
1103     const unsigned char *seq)
1104 {
1105 	unsigned int shift;
1106 	int cmp;
1107 
1108 	cmp = satsub64be(seq, bitmap->max_seq_num);
1109 	if (cmp > 0)
1110 		return 1; /* this record in new */
1111 	shift = -cmp;
1112 	if (shift >= sizeof(bitmap->map)*8)
1113 		return 0; /* stale, outside the window */
1114 	else if (bitmap->map & (1UL << shift))
1115 		return 0; /* record previously received */
1116 
1117 	return 1;
1118 }
1119 
1120 static void
1121 dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap,
1122     const unsigned char *seq)
1123 {
1124 	unsigned int shift;
1125 	int cmp;
1126 
1127 	cmp = satsub64be(seq, bitmap->max_seq_num);
1128 	if (cmp > 0) {
1129 		shift = cmp;
1130 		if (shift < sizeof(bitmap->map)*8)
1131 			bitmap->map <<= shift, bitmap->map |= 1UL;
1132 		else
1133 			bitmap->map = 1UL;
1134 		memcpy(bitmap->max_seq_num, seq, 8);
1135 	} else {
1136 		shift = -cmp;
1137 		if (shift < sizeof(bitmap->map) * 8)
1138 			bitmap->map |= 1UL << shift;
1139 	}
1140 }
1141 
1142 int
1143 dtls1_dispatch_alert(SSL *s)
1144 {
1145 	int i, j;
1146 	void (*cb)(const SSL *ssl, int type, int val) = NULL;
1147 
1148 	S3I(s)->alert_dispatch = 0;
1149 
1150 	i = do_dtls1_write(s, SSL3_RT_ALERT, &S3I(s)->send_alert[0], 2);
1151 	if (i <= 0) {
1152 		S3I(s)->alert_dispatch = 1;
1153 	} else {
1154 		if (S3I(s)->send_alert[0] == SSL3_AL_FATAL)
1155 			(void)BIO_flush(s->wbio);
1156 
1157 		if (s->internal->msg_callback)
1158 			s->internal->msg_callback(1, s->version, SSL3_RT_ALERT,
1159 			    S3I(s)->send_alert, 2, s, s->internal->msg_callback_arg);
1160 
1161 		if (s->internal->info_callback != NULL)
1162 			cb = s->internal->info_callback;
1163 		else if (s->ctx->internal->info_callback != NULL)
1164 			cb = s->ctx->internal->info_callback;
1165 
1166 		if (cb != NULL) {
1167 			j = (S3I(s)->send_alert[0]<<8)|S3I(s)->send_alert[1];
1168 			cb(s, SSL_CB_WRITE_ALERT, j);
1169 		}
1170 	}
1171 	return (i);
1172 }
1173 
1174 static DTLS1_BITMAP *
1175 dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr, unsigned int *is_next_epoch)
1176 {
1177 	uint16_t next_epoch = D1I(s)->r_epoch + 1;
1178 
1179 	*is_next_epoch = 0;
1180 
1181 	/* In current epoch, accept HM, CCS, DATA, & ALERT */
1182 	if (rr->epoch == D1I(s)->r_epoch)
1183 		return &D1I(s)->bitmap;
1184 
1185 	/* Only HM and ALERT messages can be from the next epoch */
1186 	else if (rr->epoch == next_epoch &&
1187 		(rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1188 		*is_next_epoch = 1;
1189 		return &D1I(s)->next_bitmap;
1190 	}
1191 
1192 	return NULL;
1193 }
1194 
1195 void
1196 dtls1_reset_read_seq_numbers(SSL *s)
1197 {
1198 	D1I(s)->r_epoch++;
1199 	memcpy(&(D1I(s)->bitmap), &(D1I(s)->next_bitmap), sizeof(DTLS1_BITMAP));
1200 	memset(&(D1I(s)->next_bitmap), 0, sizeof(DTLS1_BITMAP));
1201 }
1202