xref: /openbsd-src/lib/libssl/d1_pkt.c (revision ffcef06798eb7b98532e76a80212f0772bebc4f6)
1 /* $OpenBSD: d1_pkt.c,v 1.109 2021/08/31 13:34:55 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_u16(&header, &epoch) ||
398 		    !CBS_get_bytes(&header, &seq_no, 6))
399 			goto again;
400 
401 		if (!CBS_get_u16(&header, &len))
402 			goto again;
403 
404 		if (!CBS_write_bytes(&seq_no, &rr->seq_num[2],
405 		    sizeof(rr->seq_num) - 2, NULL))
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 		if (rr->data[1] != 0 || rr->data[2] != 0 || rr->data[3] != 0) {
685 			al = SSL_AD_DECODE_ERROR;
686 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
687 			goto fatal_err;
688 		}
689 		rr->length = 0;
690 
691 		/* no need to check sequence number on HELLO REQUEST messages */
692 
693 		ssl_msg_callback(s, 0, SSL3_RT_HANDSHAKE, rr->data, 4);
694 
695 		if (SSL_is_init_finished(s) &&
696 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
697 		    !S3I(s)->renegotiate) {
698 			D1I(s)->handshake_read_seq++;
699 			s->internal->new_session = 1;
700 			ssl3_renegotiate(s);
701 			if (ssl3_renegotiate_check(s)) {
702 				i = s->internal->handshake_func(s);
703 				if (i < 0)
704 					return (i);
705 				if (i == 0) {
706 					SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
707 					return (-1);
708 				}
709 
710 				if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
711 					if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */
712 					{
713 						BIO *bio;
714 						/* In the case where we try to read application data,
715 						 * but we trigger an SSL handshake, we return -1 with
716 						 * the retry option set.  Otherwise renegotiation may
717 						 * cause nasty problems in the blocking world */
718 						s->internal->rwstate = SSL_READING;
719 						bio = SSL_get_rbio(s);
720 						BIO_clear_retry_flags(bio);
721 						BIO_set_retry_read(bio);
722 						return (-1);
723 					}
724 				}
725 			}
726 		}
727 		/* we either finished a handshake or ignored the request,
728 		 * now try again to obtain the (application) data we were asked for */
729 		rr->length = 0;
730 		goto start;
731 	}
732 
733 	if (rr->type == SSL3_RT_ALERT && rr->length >= DTLS1_AL_HEADER_LENGTH &&
734 	    rr->off == 0) {
735 		int alert_level = rr->data[0];
736 		int alert_descr = rr->data[1];
737 
738 		ssl_msg_callback(s, 0, SSL3_RT_ALERT, rr->data, 2);
739 
740 		ssl_info_callback(s, SSL_CB_READ_ALERT,
741 		    (alert_level << 8) | alert_descr);
742 
743 		if (alert_level == SSL3_AL_WARNING) {
744 			S3I(s)->warn_alert = alert_descr;
745 			if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
746 				s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
747 				return (0);
748 			}
749 		} else if (alert_level == SSL3_AL_FATAL) {
750 			s->internal->rwstate = SSL_NOTHING;
751 			S3I(s)->fatal_alert = alert_descr;
752 			SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
753 			ERR_asprintf_error_data("SSL alert number %d",
754 			    alert_descr);
755 			s->internal->shutdown|=SSL_RECEIVED_SHUTDOWN;
756 			SSL_CTX_remove_session(s->ctx, s->session);
757 			return (0);
758 		} else {
759 			al = SSL_AD_ILLEGAL_PARAMETER;
760 			SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
761 			goto fatal_err;
762 		}
763 
764 		rr->length = 0;
765 		goto start;
766 	}
767 
768 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
769 		s->internal->rwstate = SSL_NOTHING;
770 		rr->length = 0;
771 		return (0);
772 	}
773 
774 	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
775 		/* 'Change Cipher Spec' is just a single byte, so we know
776 		 * exactly what the record payload has to look like */
777 		/* XDTLS: check that epoch is consistent */
778 		if ((rr->length != DTLS1_CCS_HEADER_LENGTH) ||
779 		    (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
780 			al = SSL_AD_DECODE_ERROR;
781 			SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
782 			goto fatal_err;
783 		}
784 
785 		ssl_msg_callback(s, 0, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1);
786 
787 		/* We can't process a CCS now, because previous handshake
788 		 * messages are still missing, so just drop it.
789 		 */
790 		if (!D1I(s)->change_cipher_spec_ok) {
791 			rr->length = 0;
792 			goto start;
793 		}
794 
795 		D1I(s)->change_cipher_spec_ok = 0;
796 
797 		S3I(s)->change_cipher_spec = 1;
798 		if (!ssl3_do_change_cipher_spec(s))
799 			goto err;
800 
801 		rr->length = 0;
802 		goto start;
803 	}
804 
805 	/* Unexpected handshake message (Client Hello, or protocol violation) */
806 	if (rr->type == SSL3_RT_HANDSHAKE &&
807 	    rr->length >= DTLS1_HM_HEADER_LENGTH && rr->off == 0 &&
808 	    !s->internal->in_handshake) {
809 		struct hm_header_st msg_hdr;
810 
811 		/* this may just be a stale retransmit */
812 		if (!dtls1_get_message_header(rr->data, &msg_hdr))
813 			return -1;
814 		if (rr->epoch != tls12_record_layer_read_epoch(s->internal->rl)) {
815 			rr->length = 0;
816 			goto start;
817 		}
818 
819 		/* If we are server, we may have a repeated FINISHED of the
820 		 * client here, then retransmit our CCS and FINISHED.
821 		 */
822 		if (msg_hdr.type == SSL3_MT_FINISHED) {
823 			if (dtls1_check_timeout_num(s) < 0)
824 				return -1;
825 
826 			dtls1_retransmit_buffered_messages(s);
827 			rr->length = 0;
828 			goto start;
829 		}
830 
831 		if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) &&
832 		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
833 			S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
834 			s->internal->renegotiate = 1;
835 			s->internal->new_session = 1;
836 		}
837 		i = s->internal->handshake_func(s);
838 		if (i < 0)
839 			return (i);
840 		if (i == 0) {
841 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
842 			return (-1);
843 		}
844 
845 		if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
846 			if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */
847 			{
848 				BIO *bio;
849 				/* In the case where we try to read application data,
850 				 * but we trigger an SSL handshake, we return -1 with
851 				 * the retry option set.  Otherwise renegotiation may
852 				 * cause nasty problems in the blocking world */
853 				s->internal->rwstate = SSL_READING;
854 				bio = SSL_get_rbio(s);
855 				BIO_clear_retry_flags(bio);
856 				BIO_set_retry_read(bio);
857 				return (-1);
858 			}
859 		}
860 		rr->length = 0;
861 		goto start;
862 	}
863 
864 	switch (rr->type) {
865 	default:
866 		al = SSL_AD_UNEXPECTED_MESSAGE;
867 		SSLerror(s, SSL_R_UNEXPECTED_RECORD);
868 		goto fatal_err;
869 	case SSL3_RT_CHANGE_CIPHER_SPEC:
870 	case SSL3_RT_ALERT:
871 	case SSL3_RT_HANDSHAKE:
872 		/* we already handled all of these, with the possible exception
873 		 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that
874 		 * should not happen when type != rr->type */
875 		al = SSL_AD_UNEXPECTED_MESSAGE;
876 		SSLerror(s, ERR_R_INTERNAL_ERROR);
877 		goto fatal_err;
878 	case SSL3_RT_APPLICATION_DATA:
879 		/* At this point, we were expecting handshake data,
880 		 * but have application data.  If the library was
881 		 * running inside ssl3_read() (i.e. in_read_app_data
882 		 * is set) and it makes sense to read application data
883 		 * at this point (session renegotiation not yet started),
884 		 * we will indulge it.
885 		 */
886 		if (S3I(s)->in_read_app_data &&
887 		    (S3I(s)->total_renegotiations != 0) &&
888 		    (((S3I(s)->hs.state & SSL_ST_CONNECT) &&
889 		    (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
890 		    (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
891 		    (S3I(s)->hs.state & SSL_ST_ACCEPT) &&
892 		    (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
893 		    (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
894 			S3I(s)->in_read_app_data = 2;
895 			return (-1);
896 		} else {
897 			al = SSL_AD_UNEXPECTED_MESSAGE;
898 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
899 			goto fatal_err;
900 		}
901 	}
902 	/* not reached */
903 
904  fatal_err:
905 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
906  err:
907 	return (-1);
908 }
909 
910 int
911 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
912 {
913 	int i;
914 
915 	if (SSL_in_init(s) && !s->internal->in_handshake)
916 	{
917 		i = s->internal->handshake_func(s);
918 		if (i < 0)
919 			return (i);
920 		if (i == 0) {
921 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
922 			return -1;
923 		}
924 	}
925 
926 	if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
927 		SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
928 		return -1;
929 	}
930 
931 	i = dtls1_write_bytes(s, type, buf_, len);
932 	return i;
933 }
934 
935 /* Call this to write data in records of type 'type'
936  * It will return <= 0 if not all data has been sent or non-blocking IO.
937  */
938 int
939 dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
940 {
941 	int i;
942 
943 	OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
944 	s->internal->rwstate = SSL_NOTHING;
945 	i = do_dtls1_write(s, type, buf, len);
946 	return i;
947 }
948 
949 int
950 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
951 {
952 	SSL3_BUFFER_INTERNAL *wb = &(S3I(s)->wbuf);
953 	size_t out_len;
954 	CBB cbb;
955 	int ret;
956 
957 	memset(&cbb, 0, sizeof(cbb));
958 
959 	/*
960 	 * First check if there is a SSL3_BUFFER_INTERNAL still being written
961 	 * out.  This will happen with non blocking IO.
962 	 */
963 	if (wb->left != 0) {
964 		OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
965 		return (ssl3_write_pending(s, type, buf, len));
966 	}
967 
968 	/* If we have an alert to send, let's send it */
969 	if (S3I(s)->alert_dispatch) {
970 		if ((ret = ssl3_dispatch_alert(s)) <= 0)
971 			return (ret);
972 		/* If it went, fall through and send more stuff. */
973 	}
974 
975 	if (len == 0)
976 		return 0;
977 
978 	wb->offset = 0;
979 
980 	if (!CBB_init_fixed(&cbb, wb->buf, wb->len))
981 		goto err;
982 
983 	tls12_record_layer_set_version(s->internal->rl, s->version);
984 
985 	if (!tls12_record_layer_seal_record(s->internal->rl, type, buf, len, &cbb))
986 		goto err;
987 
988 	if (!CBB_finish(&cbb, NULL, &out_len))
989 		goto err;
990 
991 	wb->left = out_len;
992 
993 	/*
994 	 * Memorize arguments so that ssl3_write_pending can detect
995 	 * bad write retries later.
996 	 */
997 	S3I(s)->wpend_tot = len;
998 	S3I(s)->wpend_buf = buf;
999 	S3I(s)->wpend_type = type;
1000 	S3I(s)->wpend_ret = len;
1001 
1002 	/* We now just need to write the buffer. */
1003 	return ssl3_write_pending(s, type, buf, len);
1004 
1005  err:
1006 	CBB_cleanup(&cbb);
1007 
1008 	return -1;
1009 }
1010 
1011 static int
1012 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
1013     const unsigned char *seq)
1014 {
1015 	unsigned int shift;
1016 	int cmp;
1017 
1018 	cmp = satsub64be(seq, bitmap->max_seq_num);
1019 	if (cmp > 0)
1020 		return 1; /* this record in new */
1021 	shift = -cmp;
1022 	if (shift >= sizeof(bitmap->map)*8)
1023 		return 0; /* stale, outside the window */
1024 	else if (bitmap->map & (1UL << shift))
1025 		return 0; /* record previously received */
1026 
1027 	return 1;
1028 }
1029 
1030 static void
1031 dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap,
1032     const unsigned char *seq)
1033 {
1034 	unsigned int shift;
1035 	int cmp;
1036 
1037 	cmp = satsub64be(seq, bitmap->max_seq_num);
1038 	if (cmp > 0) {
1039 		shift = cmp;
1040 		if (shift < sizeof(bitmap->map)*8)
1041 			bitmap->map <<= shift, bitmap->map |= 1UL;
1042 		else
1043 			bitmap->map = 1UL;
1044 		memcpy(bitmap->max_seq_num, seq, 8);
1045 	} else {
1046 		shift = -cmp;
1047 		if (shift < sizeof(bitmap->map) * 8)
1048 			bitmap->map |= 1UL << shift;
1049 	}
1050 }
1051 
1052 static DTLS1_BITMAP *
1053 dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr, unsigned int *is_next_epoch)
1054 {
1055 	uint16_t read_epoch, read_epoch_next;
1056 
1057 	*is_next_epoch = 0;
1058 
1059 	read_epoch = tls12_record_layer_read_epoch(s->internal->rl);
1060 	read_epoch_next = read_epoch + 1;
1061 
1062 	/* In current epoch, accept HM, CCS, DATA, & ALERT */
1063 	if (rr->epoch == read_epoch)
1064 		return &D1I(s)->bitmap;
1065 
1066 	/* Only HM and ALERT messages can be from the next epoch */
1067 	if (rr->epoch == read_epoch_next &&
1068 	    (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1069 		*is_next_epoch = 1;
1070 		return &D1I(s)->next_bitmap;
1071 	}
1072 
1073 	return NULL;
1074 }
1075 
1076 void
1077 dtls1_reset_read_seq_numbers(SSL *s)
1078 {
1079 	memcpy(&(D1I(s)->bitmap), &(D1I(s)->next_bitmap), sizeof(DTLS1_BITMAP));
1080 	memset(&(D1I(s)->next_bitmap), 0, sizeof(DTLS1_BITMAP));
1081 }
1082