xref: /openbsd-src/lib/libssl/d1_pkt.c (revision 5a38ef86d0b61900239c7913d24a05e7b88a58f0)
1 /* $OpenBSD: d1_pkt.c,v 1.116 2021/11/09 18:40:21 bcook 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 <endian.h>
117 #include <errno.h>
118 #include <stdio.h>
119 
120 #include <openssl/buffer.h>
121 #include <openssl/evp.h>
122 
123 #include "bytestring.h"
124 #include "dtls_locl.h"
125 #include "pqueue.h"
126 #include "ssl_locl.h"
127 
128 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
129 static int
130 satsub64be(const unsigned char *v1, const unsigned char *v2)
131 {
132 	int ret, sat, brw, i;
133 
134 	if (sizeof(long) == 8)
135 		do {
136 			long l;
137 
138 			if (BYTE_ORDER == LITTLE_ENDIAN)
139 				break;
140 			/* not reached on little-endians */
141 			/* following test is redundant, because input is
142 			 * always aligned, but I take no chances... */
143 			if (((size_t)v1 | (size_t)v2) & 0x7)
144 				break;
145 
146 			l  = *((long *)v1);
147 			l -= *((long *)v2);
148 			if (l > 128)
149 				return 128;
150 			else if (l<-128)
151 				return -128;
152 			else
153 				return (int)l;
154 		} while (0);
155 
156 	ret = (int)v1[7] - (int)v2[7];
157 	sat = 0;
158 	brw = ret >> 8;	/* brw is either 0 or -1 */
159 	if (ret & 0x80) {
160 		for (i = 6; i >= 0; i--) {
161 			brw += (int)v1[i]-(int)v2[i];
162 			sat |= ~brw;
163 			brw >>= 8;
164 		}
165 	} else {
166 		for (i = 6; i >= 0; i--) {
167 			brw += (int)v1[i]-(int)v2[i];
168 			sat |= brw;
169 			brw >>= 8;
170 		}
171 	}
172 	brw <<= 8;	/* brw is either 0 or -256 */
173 
174 	if (sat & 0xff)
175 		return brw | 0x80;
176 	else
177 		return brw + (ret & 0xFF);
178 }
179 
180 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
181     const unsigned char *seq);
182 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap,
183     const unsigned char *seq);
184 static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr,
185     unsigned int *is_next_epoch);
186 static int dtls1_buffer_record(SSL *s, record_pqueue *q,
187     unsigned char *priority);
188 static int dtls1_process_record(SSL *s);
189 
190 /* copy buffered record into SSL structure */
191 static int
192 dtls1_copy_record(SSL *s, DTLS1_RECORD_DATA_INTERNAL *rdata)
193 {
194 	ssl3_release_buffer(&S3I(s)->rbuf);
195 
196 	s->internal->packet = rdata->packet;
197 	s->internal->packet_length = rdata->packet_length;
198 	memcpy(&(S3I(s)->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
199 	memcpy(&(S3I(s)->rrec), &(rdata->rrec), sizeof(SSL3_RECORD_INTERNAL));
200 
201 	return (1);
202 }
203 
204 static int
205 dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
206 {
207 	DTLS1_RECORD_DATA_INTERNAL *rdata;
208 	pitem *item;
209 
210 	/* Limit the size of the queue to prevent DOS attacks */
211 	if (pqueue_size(queue->q) >= 100)
212 		return 0;
213 
214 	rdata = malloc(sizeof(DTLS1_RECORD_DATA_INTERNAL));
215 	item = pitem_new(priority, rdata);
216 	if (rdata == NULL || item == NULL)
217 		goto init_err;
218 
219 	rdata->packet = s->internal->packet;
220 	rdata->packet_length = s->internal->packet_length;
221 	memcpy(&(rdata->rbuf), &(S3I(s)->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
222 	memcpy(&(rdata->rrec), &(S3I(s)->rrec), sizeof(SSL3_RECORD_INTERNAL));
223 
224 	item->data = rdata;
225 
226 	s->internal->packet = NULL;
227 	s->internal->packet_length = 0;
228 	memset(&(S3I(s)->rbuf), 0, sizeof(SSL3_BUFFER_INTERNAL));
229 	memset(&(S3I(s)->rrec), 0, sizeof(SSL3_RECORD_INTERNAL));
230 
231 	if (!ssl3_setup_buffers(s))
232 		goto err;
233 
234 	/* insert should not fail, since duplicates are dropped */
235 	if (pqueue_insert(queue->q, item) == NULL)
236 		goto err;
237 
238 	return (1);
239 
240  err:
241 	ssl3_release_buffer(&rdata->rbuf);
242 
243  init_err:
244 	SSLerror(s, ERR_R_INTERNAL_ERROR);
245 	free(rdata);
246 	pitem_free(item);
247 	return (-1);
248 }
249 
250 
251 static int
252 dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
253 {
254 	pitem *item;
255 
256 	item = pqueue_pop(queue->q);
257 	if (item) {
258 		dtls1_copy_record(s, item->data);
259 
260 		free(item->data);
261 		pitem_free(item);
262 
263 		return (1);
264 	}
265 
266 	return (0);
267 }
268 
269 static int
270 dtls1_process_buffered_record(SSL *s)
271 {
272 	/* Check if epoch is current. */
273 	if (s->d1->unprocessed_rcds.epoch !=
274 	    tls12_record_layer_read_epoch(s->internal->rl))
275 		return (0);
276 
277 	/* Update epoch once all unprocessed records have been processed. */
278 	if (pqueue_peek(s->d1->unprocessed_rcds.q) == NULL) {
279 		s->d1->unprocessed_rcds.epoch =
280 		    tls12_record_layer_read_epoch(s->internal->rl) + 1;
281 		return (0);
282 	}
283 
284 	/* Process one of the records. */
285 	if (!dtls1_retrieve_buffered_record(s, &s->d1->unprocessed_rcds))
286 		return (-1);
287 	if (!dtls1_process_record(s))
288 		return (-1);
289 
290 	return (1);
291 }
292 
293 static int
294 dtls1_process_record(SSL *s)
295 {
296 	SSL3_RECORD_INTERNAL *rr = &(S3I(s)->rrec);
297 	uint8_t alert_desc;
298 	uint8_t *out;
299 	size_t out_len;
300 
301 	tls12_record_layer_set_version(s->internal->rl, s->version);
302 
303 	if (!tls12_record_layer_open_record(s->internal->rl, s->internal->packet,
304 	    s->internal->packet_length, &out, &out_len)) {
305 		tls12_record_layer_alert(s->internal->rl, &alert_desc);
306 
307 		if (alert_desc == 0)
308 			goto err;
309 
310 		/*
311 		 * DTLS should silently discard invalid records, including those
312 		 * with a bad MAC, as per RFC 6347 section 4.1.2.1.
313 		 */
314 		if (alert_desc == SSL_AD_BAD_RECORD_MAC) {
315 			out_len = 0;
316 			goto done;
317 		}
318 
319 		if (alert_desc == SSL_AD_RECORD_OVERFLOW)
320 			SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
321 
322 		goto fatal_err;
323 	}
324 
325  done:
326 	rr->data = out;
327 	rr->length = out_len;
328 	rr->off = 0;
329 
330 	s->internal->packet_length = 0;
331 
332 	return (1);
333 
334  fatal_err:
335 	ssl3_send_alert(s, SSL3_AL_FATAL, alert_desc);
336  err:
337 	return (0);
338 }
339 
340 /* Call this to get a new input record.
341  * It will return <= 0 if more data is needed, normally due to an error
342  * or non-blocking IO.
343  * When it finishes, one packet has been decoded and can be found in
344  * ssl->s3->internal->rrec.type    - is the type of record
345  * ssl->s3->internal->rrec.data, 	 - data
346  * ssl->s3->internal->rrec.length, - number of bytes
347  */
348 /* used only by dtls1_read_bytes */
349 int
350 dtls1_get_record(SSL *s)
351 {
352 	SSL3_RECORD_INTERNAL *rr = &(S3I(s)->rrec);
353 	unsigned char *p = NULL;
354 	DTLS1_BITMAP *bitmap;
355 	unsigned int is_next_epoch;
356 	int ret, n;
357 
358 	/* See if there are pending records that can now be processed. */
359 	if ((ret = dtls1_process_buffered_record(s)) != 0)
360 		return (ret);
361 
362 	/* get something from the wire */
363 	if (0) {
364  again:
365 		/* dump this record on all retries */
366 		rr->length = 0;
367 		s->internal->packet_length = 0;
368 	}
369 
370 	/* check if we have the header */
371 	if ((s->internal->rstate != SSL_ST_READ_BODY) ||
372 	    (s->internal->packet_length < DTLS1_RT_HEADER_LENGTH)) {
373 		CBS header, seq_no;
374 		uint16_t epoch, len, ssl_version;
375 		uint8_t type;
376 
377 		n = ssl3_packet_read(s, DTLS1_RT_HEADER_LENGTH);
378 		if (n <= 0)
379 			return (n);
380 
381 		/* If this packet contained a partial record, dump it. */
382 		if (n != DTLS1_RT_HEADER_LENGTH)
383 			goto again;
384 
385 		s->internal->rstate = SSL_ST_READ_BODY;
386 
387 		CBS_init(&header, s->internal->packet, s->internal->packet_length);
388 
389 		/* Pull apart the header into the DTLS1_RECORD */
390 		if (!CBS_get_u8(&header, &type))
391 			goto again;
392 		if (!CBS_get_u16(&header, &ssl_version))
393 			goto again;
394 
395 		/* Sequence number is 64 bits, with top 2 bytes = epoch. */
396 		if (!CBS_get_bytes(&header, &seq_no, SSL3_SEQUENCE_SIZE))
397 			goto again;
398 		if (!CBS_get_u16(&seq_no, &epoch))
399 			goto again;
400 		if (!CBS_write_bytes(&seq_no, &rr->seq_num[2],
401 		    sizeof(rr->seq_num) - 2, NULL))
402 			goto again;
403 
404 		if (!CBS_get_u16(&header, &len))
405 			goto again;
406 
407 		rr->type = type;
408 		rr->epoch = epoch;
409 		rr->length = len;
410 
411 		/* unexpected version, silently discard */
412 		if (!s->internal->first_packet && ssl_version != s->version)
413 			goto again;
414 
415 		/* wrong version, silently discard record */
416 		if ((ssl_version & 0xff00) != (s->version & 0xff00))
417 			goto again;
418 
419 		/* record too long, silently discard it */
420 		if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
421 			goto again;
422 
423 		/* now s->internal->rstate == SSL_ST_READ_BODY */
424 		p = (unsigned char *)CBS_data(&header);
425 	}
426 
427 	/* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */
428 
429 	n = ssl3_packet_extend(s, DTLS1_RT_HEADER_LENGTH + rr->length);
430 	if (n <= 0)
431 		return (n);
432 
433 	/* If this packet contained a partial record, dump it. */
434 	if (n != DTLS1_RT_HEADER_LENGTH + rr->length)
435 		goto again;
436 
437 	s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
438 
439 	/* match epochs.  NULL means the packet is dropped on the floor */
440 	bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
441 	if (bitmap == NULL)
442 		goto again;
443 
444 	/*
445 	 * Check whether this is a repeat, or aged record.
446 	 * Don't check if we're listening and this message is
447 	 * a ClientHello. They can look as if they're replayed,
448 	 * since they arrive from different connections and
449 	 * would be dropped unnecessarily.
450 	 */
451 	if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
452 	    p != NULL && *p == SSL3_MT_CLIENT_HELLO) &&
453 	    !dtls1_record_replay_check(s, bitmap, rr->seq_num))
454 		goto again;
455 
456 	/* just read a 0 length packet */
457 	if (rr->length == 0)
458 		goto again;
459 
460 	/* If this record is from the next epoch (either HM or ALERT),
461 	 * and a handshake is currently in progress, buffer it since it
462 	 * cannot be processed at this time. However, do not buffer
463 	 * anything while listening.
464 	 */
465 	if (is_next_epoch) {
466 		if ((SSL_in_init(s) || s->internal->in_handshake) && !s->d1->listen) {
467 			if (dtls1_buffer_record(s, &(s->d1->unprocessed_rcds),
468 			    rr->seq_num) < 0)
469 				return (-1);
470 			/* Mark receipt of record. */
471 			dtls1_record_bitmap_update(s, bitmap, rr->seq_num);
472 		}
473 		goto again;
474 	}
475 
476 	if (!dtls1_process_record(s))
477 		goto again;
478 
479 	/* Mark receipt of record. */
480 	dtls1_record_bitmap_update(s, bitmap, rr->seq_num);
481 
482 	return (1);
483 }
484 
485 /* Return up to 'len' payload bytes received in 'type' records.
486  * 'type' is one of the following:
487  *
488  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
489  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
490  *   -  0 (during a shutdown, no data has to be returned)
491  *
492  * If we don't have stored data to work from, read a SSL/TLS record first
493  * (possibly multiple records if we still don't have anything to return).
494  *
495  * This function must handle any surprises the peer may have for us, such as
496  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
497  * a surprise, but handled as if it were), or renegotiation requests.
498  * Also if record payloads contain fragments too small to process, we store
499  * them until there is enough for the respective protocol (the record protocol
500  * may use arbitrary fragmentation and even interleaving):
501  *     Change cipher spec protocol
502  *             just 1 byte needed, no need for keeping anything stored
503  *     Alert protocol
504  *             2 bytes needed (AlertLevel, AlertDescription)
505  *     Handshake protocol
506  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
507  *             to detect unexpected Client Hello and Hello Request messages
508  *             here, anything else is handled by higher layers
509  *     Application data protocol
510  *             none of our business
511  */
512 int
513 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
514 {
515 	int al, i, ret;
516 	int rrcount = 0;
517 	unsigned int n;
518 	SSL3_RECORD_INTERNAL *rr;
519 
520 	if (S3I(s)->rbuf.buf == NULL) /* Not initialized yet */
521 		if (!ssl3_setup_buffers(s))
522 			return (-1);
523 
524 	if ((type &&
525 	     type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
526 	    (peek && (type != SSL3_RT_APPLICATION_DATA))) {
527 		SSLerror(s, ERR_R_INTERNAL_ERROR);
528 		return -1;
529 	}
530 
531 	if (!s->internal->in_handshake && SSL_in_init(s)) {
532 		i = s->internal->handshake_func(s);
533 		if (i < 0)
534 			return (i);
535 		if (i == 0) {
536 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
537 			return (-1);
538 		}
539 	}
540 
541  start:
542 	/*
543 	 * Do not process more than three consecutive records, otherwise the
544 	 * peer can cause us to loop indefinitely. Instead, return with an
545 	 * SSL_ERROR_WANT_READ so the caller can choose when to handle further
546 	 * processing. In the future, the total number of non-handshake and
547 	 * non-application data records per connection should probably also be
548 	 * limited...
549 	 */
550 	if (rrcount++ >= 3) {
551 		ssl_force_want_read(s);
552 		return -1;
553 	}
554 
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, &(s->d1->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 (s->d1->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, &(s->d1->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 
656 	{
657 		unsigned int record_min_len = 0;
658 
659 		if (rr->type == SSL3_RT_HANDSHAKE) {
660 			record_min_len = DTLS1_HM_HEADER_LENGTH;
661 		} else if (rr->type == SSL3_RT_ALERT) {
662 			record_min_len = DTLS1_AL_HEADER_LENGTH;
663 		} else if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
664 			record_min_len = DTLS1_CCS_HEADER_LENGTH;
665 		} else if (rr->type == SSL3_RT_APPLICATION_DATA) {
666 			/*
667 			 * Application data while renegotiating is allowed.
668 			 * Try reading again.
669 			 */
670 			S3I(s)->in_read_app_data = 2;
671 			ssl_force_want_read(s);
672 			return -1;
673 		} else {
674 			/* Not certain if this is the right error handling */
675 			al = SSL_AD_UNEXPECTED_MESSAGE;
676 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
677 			goto fatal_err;
678 		}
679 
680 		if (record_min_len > 0 && rr->length < record_min_len) {
681 			s->internal->rstate = SSL_ST_READ_HEADER;
682 			rr->length = 0;
683 			goto start;
684 		}
685 	}
686 
687 	/* If we are a client, check for an incoming 'Hello Request': */
688 	if (!s->server && rr->type == SSL3_RT_HANDSHAKE &&
689 	    rr->length >= DTLS1_HM_HEADER_LENGTH && rr->off == 0 &&
690 	    rr->data[0] == SSL3_MT_HELLO_REQUEST &&
691 	    s->session != NULL && s->session->cipher != NULL) {
692 		struct hm_header_st msg_hdr;
693 		CBS cbs;
694 
695 		CBS_init(&cbs, rr->data, rr->length);
696 		if (!dtls1_get_message_header(&cbs, &msg_hdr))
697 			return -1;
698 		if (msg_hdr.msg_len != 0) {
699 			al = SSL_AD_DECODE_ERROR;
700 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
701 			goto fatal_err;
702 		}
703 		rr->length = 0;
704 
705 		/* no need to check sequence number on HELLO REQUEST messages */
706 
707 		ssl_msg_callback(s, 0, SSL3_RT_HANDSHAKE, rr->data, 4);
708 
709 		if (SSL_is_init_finished(s) &&
710 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
711 		    !S3I(s)->renegotiate) {
712 			s->d1->handshake_read_seq++;
713 			s->internal->new_session = 1;
714 			ssl3_renegotiate(s);
715 			if (ssl3_renegotiate_check(s)) {
716 				i = s->internal->handshake_func(s);
717 				if (i < 0)
718 					return (i);
719 				if (i == 0) {
720 					SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
721 					return (-1);
722 				}
723 
724 				if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
725 					if (S3I(s)->rbuf.left == 0) {
726 						ssl_force_want_read(s);
727 						return (-1);
728 					}
729 				}
730 			}
731 		}
732 		/* we either finished a handshake or ignored the request,
733 		 * now try again to obtain the (application) data we were asked for */
734 		rr->length = 0;
735 		goto start;
736 	}
737 
738 	if (rr->type == SSL3_RT_ALERT && rr->length >= DTLS1_AL_HEADER_LENGTH &&
739 	    rr->off == 0) {
740 		int alert_level = rr->data[0];
741 		int alert_descr = rr->data[1];
742 
743 		ssl_msg_callback(s, 0, SSL3_RT_ALERT, rr->data, 2);
744 
745 		ssl_info_callback(s, SSL_CB_READ_ALERT,
746 		    (alert_level << 8) | alert_descr);
747 
748 		if (alert_level == SSL3_AL_WARNING) {
749 			S3I(s)->warn_alert = alert_descr;
750 			if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
751 				s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
752 				return (0);
753 			}
754 		} else if (alert_level == SSL3_AL_FATAL) {
755 			s->internal->rwstate = SSL_NOTHING;
756 			S3I(s)->fatal_alert = alert_descr;
757 			SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
758 			ERR_asprintf_error_data("SSL alert number %d",
759 			    alert_descr);
760 			s->internal->shutdown|=SSL_RECEIVED_SHUTDOWN;
761 			SSL_CTX_remove_session(s->ctx, s->session);
762 			return (0);
763 		} else {
764 			al = SSL_AD_ILLEGAL_PARAMETER;
765 			SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
766 			goto fatal_err;
767 		}
768 
769 		rr->length = 0;
770 		goto start;
771 	}
772 
773 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
774 		s->internal->rwstate = SSL_NOTHING;
775 		rr->length = 0;
776 		return (0);
777 	}
778 
779 	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
780 		/* 'Change Cipher Spec' is just a single byte, so we know
781 		 * exactly what the record payload has to look like */
782 		/* XDTLS: check that epoch is consistent */
783 		if ((rr->length != DTLS1_CCS_HEADER_LENGTH) ||
784 		    (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
785 			al = SSL_AD_DECODE_ERROR;
786 			SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
787 			goto fatal_err;
788 		}
789 
790 		ssl_msg_callback(s, 0, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1);
791 
792 		/* We can't process a CCS now, because previous handshake
793 		 * messages are still missing, so just drop it.
794 		 */
795 		if (!s->d1->change_cipher_spec_ok) {
796 			rr->length = 0;
797 			goto start;
798 		}
799 
800 		s->d1->change_cipher_spec_ok = 0;
801 
802 		S3I(s)->change_cipher_spec = 1;
803 		if (!ssl3_do_change_cipher_spec(s))
804 			goto err;
805 
806 		rr->length = 0;
807 		goto start;
808 	}
809 
810 	/* Unexpected handshake message (Client Hello, or protocol violation) */
811 	if (rr->type == SSL3_RT_HANDSHAKE &&
812 	    rr->length >= DTLS1_HM_HEADER_LENGTH && rr->off == 0 &&
813 	    !s->internal->in_handshake) {
814 		struct hm_header_st msg_hdr;
815 		CBS cbs;
816 
817 		/* this may just be a stale retransmit */
818 		CBS_init(&cbs, rr->data, rr->length);
819 		if (!dtls1_get_message_header(&cbs, &msg_hdr))
820 			return -1;
821 		if (rr->epoch != tls12_record_layer_read_epoch(s->internal->rl)) {
822 			rr->length = 0;
823 			goto start;
824 		}
825 
826 		/* If we are server, we may have a repeated FINISHED of the
827 		 * client here, then retransmit our CCS and FINISHED.
828 		 */
829 		if (msg_hdr.type == SSL3_MT_FINISHED) {
830 			if (dtls1_check_timeout_num(s) < 0)
831 				return -1;
832 
833 			dtls1_retransmit_buffered_messages(s);
834 			rr->length = 0;
835 			goto start;
836 		}
837 
838 		if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) &&
839 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
840 			S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
841 			s->internal->renegotiate = 1;
842 			s->internal->new_session = 1;
843 		}
844 		i = s->internal->handshake_func(s);
845 		if (i < 0)
846 			return (i);
847 		if (i == 0) {
848 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
849 			return (-1);
850 		}
851 
852 		if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
853 			if (S3I(s)->rbuf.left == 0) {
854 				ssl_force_want_read(s);
855 				return (-1);
856 			}
857 		}
858 		rr->length = 0;
859 		goto start;
860 	}
861 
862 	switch (rr->type) {
863 	default:
864 		al = SSL_AD_UNEXPECTED_MESSAGE;
865 		SSLerror(s, SSL_R_UNEXPECTED_RECORD);
866 		goto fatal_err;
867 	case SSL3_RT_CHANGE_CIPHER_SPEC:
868 	case SSL3_RT_ALERT:
869 	case SSL3_RT_HANDSHAKE:
870 		/* we already handled all of these, with the possible exception
871 		 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that
872 		 * should not happen when type != rr->type */
873 		al = SSL_AD_UNEXPECTED_MESSAGE;
874 		SSLerror(s, ERR_R_INTERNAL_ERROR);
875 		goto fatal_err;
876 	case SSL3_RT_APPLICATION_DATA:
877 		/* At this point, we were expecting handshake data,
878 		 * but have application data.  If the library was
879 		 * running inside ssl3_read() (i.e. in_read_app_data
880 		 * is set) and it makes sense to read application data
881 		 * at this point (session renegotiation not yet started),
882 		 * we will indulge it.
883 		 */
884 		if (S3I(s)->in_read_app_data &&
885 		    (S3I(s)->total_renegotiations != 0) &&
886 		    (((S3I(s)->hs.state & SSL_ST_CONNECT) &&
887 		    (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
888 		    (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
889 		    (S3I(s)->hs.state & SSL_ST_ACCEPT) &&
890 		    (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
891 		    (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
892 			S3I(s)->in_read_app_data = 2;
893 			return (-1);
894 		} else {
895 			al = SSL_AD_UNEXPECTED_MESSAGE;
896 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
897 			goto fatal_err;
898 		}
899 	}
900 	/* not reached */
901 
902  fatal_err:
903 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
904  err:
905 	return (-1);
906 }
907 
908 int
909 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
910 {
911 	int i;
912 
913 	if (SSL_in_init(s) && !s->internal->in_handshake)
914 	{
915 		i = s->internal->handshake_func(s);
916 		if (i < 0)
917 			return (i);
918 		if (i == 0) {
919 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
920 			return -1;
921 		}
922 	}
923 
924 	if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
925 		SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
926 		return -1;
927 	}
928 
929 	i = dtls1_write_bytes(s, type, buf_, len);
930 	return i;
931 }
932 
933 /* Call this to write data in records of type 'type'
934  * It will return <= 0 if not all data has been sent or non-blocking IO.
935  */
936 int
937 dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
938 {
939 	int i;
940 
941 	OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
942 	s->internal->rwstate = SSL_NOTHING;
943 	i = do_dtls1_write(s, type, buf, len);
944 	return i;
945 }
946 
947 int
948 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
949 {
950 	SSL3_BUFFER_INTERNAL *wb = &(S3I(s)->wbuf);
951 	size_t out_len;
952 	CBB cbb;
953 	int ret;
954 
955 	memset(&cbb, 0, sizeof(cbb));
956 
957 	/*
958 	 * First check if there is a SSL3_BUFFER_INTERNAL still being written
959 	 * out.  This will happen with non blocking IO.
960 	 */
961 	if (wb->left != 0) {
962 		OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
963 		return (ssl3_write_pending(s, type, buf, len));
964 	}
965 
966 	/* If we have an alert to send, let's send it */
967 	if (S3I(s)->alert_dispatch) {
968 		if ((ret = ssl3_dispatch_alert(s)) <= 0)
969 			return (ret);
970 		/* If it went, fall through and send more stuff. */
971 	}
972 
973 	if (len == 0)
974 		return 0;
975 
976 	wb->offset = 0;
977 
978 	if (!CBB_init_fixed(&cbb, wb->buf, wb->len))
979 		goto err;
980 
981 	tls12_record_layer_set_version(s->internal->rl, s->version);
982 
983 	if (!tls12_record_layer_seal_record(s->internal->rl, type, buf, len, &cbb))
984 		goto err;
985 
986 	if (!CBB_finish(&cbb, NULL, &out_len))
987 		goto err;
988 
989 	wb->left = out_len;
990 
991 	/*
992 	 * Memorize arguments so that ssl3_write_pending can detect
993 	 * bad write retries later.
994 	 */
995 	S3I(s)->wpend_tot = len;
996 	S3I(s)->wpend_buf = buf;
997 	S3I(s)->wpend_type = type;
998 	S3I(s)->wpend_ret = len;
999 
1000 	/* We now just need to write the buffer. */
1001 	return ssl3_write_pending(s, type, buf, len);
1002 
1003  err:
1004 	CBB_cleanup(&cbb);
1005 
1006 	return -1;
1007 }
1008 
1009 static int
1010 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
1011     const unsigned char *seq)
1012 {
1013 	unsigned int shift;
1014 	int cmp;
1015 
1016 	cmp = satsub64be(seq, bitmap->max_seq_num);
1017 	if (cmp > 0)
1018 		return 1; /* this record in new */
1019 	shift = -cmp;
1020 	if (shift >= sizeof(bitmap->map)*8)
1021 		return 0; /* stale, outside the window */
1022 	else if (bitmap->map & (1UL << shift))
1023 		return 0; /* record previously received */
1024 
1025 	return 1;
1026 }
1027 
1028 static void
1029 dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap,
1030     const unsigned char *seq)
1031 {
1032 	unsigned int shift;
1033 	int cmp;
1034 
1035 	cmp = satsub64be(seq, bitmap->max_seq_num);
1036 	if (cmp > 0) {
1037 		shift = cmp;
1038 		if (shift < sizeof(bitmap->map)*8)
1039 			bitmap->map <<= shift, bitmap->map |= 1UL;
1040 		else
1041 			bitmap->map = 1UL;
1042 		memcpy(bitmap->max_seq_num, seq, 8);
1043 	} else {
1044 		shift = -cmp;
1045 		if (shift < sizeof(bitmap->map) * 8)
1046 			bitmap->map |= 1UL << shift;
1047 	}
1048 }
1049 
1050 static DTLS1_BITMAP *
1051 dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr, unsigned int *is_next_epoch)
1052 {
1053 	uint16_t read_epoch, read_epoch_next;
1054 
1055 	*is_next_epoch = 0;
1056 
1057 	read_epoch = tls12_record_layer_read_epoch(s->internal->rl);
1058 	read_epoch_next = read_epoch + 1;
1059 
1060 	/* In current epoch, accept HM, CCS, DATA, & ALERT */
1061 	if (rr->epoch == read_epoch)
1062 		return &s->d1->bitmap;
1063 
1064 	/* Only HM and ALERT messages can be from the next epoch */
1065 	if (rr->epoch == read_epoch_next &&
1066 	    (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1067 		*is_next_epoch = 1;
1068 		return &s->d1->next_bitmap;
1069 	}
1070 
1071 	return NULL;
1072 }
1073 
1074 void
1075 dtls1_reset_read_seq_numbers(SSL *s)
1076 {
1077 	memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
1078 	memset(&(s->d1->next_bitmap), 0, sizeof(DTLS1_BITMAP));
1079 }
1080