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