xref: /dragonfly/crypto/libressl/ssl/d1_pkt.c (revision 6f5ec8b5)
1 /* $OpenBSD: d1_pkt.c,v 1.123 2022/03/26 15:05:53 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 <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(&s->s3->rbuf);
195 
196 	s->internal->packet = rdata->packet;
197 	s->internal->packet_length = rdata->packet_length;
198 	memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
199 	memcpy(&(s->s3->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), &(s->s3->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
222 	memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD_INTERNAL));
223 
224 	item->data = rdata;
225 
226 	s->internal->packet = NULL;
227 	s->internal->packet_length = 0;
228 	memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER_INTERNAL));
229 	memset(&(s->s3->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 = &(s->s3->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 = &(s->s3->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 static int
486 dtls1_read_handshake_unexpected(SSL *s)
487 {
488 	SSL3_RECORD_INTERNAL *rr = &s->s3->rrec;
489 	struct hm_header_st hs_msg_hdr;
490 	CBS cbs;
491 	int ret;
492 
493 	if (s->internal->in_handshake) {
494 		SSLerror(s, ERR_R_INTERNAL_ERROR);
495 		return -1;
496 	}
497 
498 	if (rr->off != 0) {
499 		SSLerror(s, ERR_R_INTERNAL_ERROR);
500 		return -1;
501 	}
502 
503 	/* Parse handshake message header. */
504 	CBS_init(&cbs, rr->data, rr->length);
505 	if (!dtls1_get_message_header(&cbs, &hs_msg_hdr))
506 		return -1; /* XXX - probably should drop/continue. */
507 
508 	/* This may just be a stale retransmit. */
509 	if (rr->epoch != tls12_record_layer_read_epoch(s->internal->rl)) {
510 		rr->length = 0;
511 		return 1;
512 	}
513 
514 	if (hs_msg_hdr.type == SSL3_MT_HELLO_REQUEST) {
515 		/*
516 		 * Incoming HelloRequest messages should only be received by a
517 		 * client. A server may send these at any time - a client should
518 		 * ignore the message if received in the middle of a handshake.
519 		 * See RFC 5246 sections 7.4 and 7.4.1.1.
520 		 */
521 		if (s->server) {
522 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
523 			ssl3_send_alert(s, SSL3_AL_FATAL,
524 			     SSL_AD_UNEXPECTED_MESSAGE);
525 			return -1;
526 		}
527 
528 		/* XXX - should also check frag offset/length. */
529 		if (hs_msg_hdr.msg_len != 0) {
530 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
531 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
532 			return -1;
533 		}
534 
535 		ssl_msg_callback(s, 0, SSL3_RT_HANDSHAKE, rr->data,
536 		    DTLS1_HM_HEADER_LENGTH);
537 
538 		rr->length = 0;
539 
540 		/*
541 		 * It should be impossible to hit this, but keep the safety
542 		 * harness for now...
543 		 */
544 		if (s->session == NULL || s->session->cipher == NULL)
545 			return 1;
546 
547 		/*
548 		 * Ignore this message if we're currently handshaking,
549 		 * renegotiation is already pending or renegotiation is disabled
550 		 * via flags.
551 		 */
552 		if (!SSL_is_init_finished(s) || s->s3->renegotiate ||
553 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0)
554 			return 1;
555 
556 		s->d1->handshake_read_seq++;
557 
558 		/* XXX - why is this set here but not in ssl3? */
559 		s->internal->new_session = 1;
560 
561 		if (!ssl3_renegotiate(s))
562 			return 1;
563 		if (!ssl3_renegotiate_check(s))
564 			return 1;
565 
566 	} else if (hs_msg_hdr.type == SSL3_MT_CLIENT_HELLO) {
567 		/*
568 		 * Incoming ClientHello messages should only be received by a
569 		 * server. A client may send these in response to server
570 		 * initiated renegotiation (HelloRequest) or in order to
571 		 * initiate renegotiation by the client. See RFC 5246 section
572 		 * 7.4.1.2.
573 		 */
574 		if (!s->server) {
575 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
576 			ssl3_send_alert(s, SSL3_AL_FATAL,
577 			     SSL_AD_UNEXPECTED_MESSAGE);
578 			return -1;
579 		}
580 
581 		/*
582 		 * A client should not be sending a ClientHello unless we're not
583 		 * currently handshaking.
584 		 */
585 		if (!SSL_is_init_finished(s)) {
586 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
587 			ssl3_send_alert(s, SSL3_AL_FATAL,
588 			    SSL_AD_UNEXPECTED_MESSAGE);
589 			return -1;
590 		}
591 
592 		if ((s->internal->options & SSL_OP_NO_CLIENT_RENEGOTIATION) != 0) {
593 			ssl3_send_alert(s, SSL3_AL_FATAL,
594 			    SSL_AD_NO_RENEGOTIATION);
595 			return -1;
596 		}
597 
598 		if (s->session == NULL || s->session->cipher == NULL) {
599 			SSLerror(s, ERR_R_INTERNAL_ERROR);
600 			return -1;
601 		}
602 
603 		/* Client requested renegotiation but it is not permitted. */
604 		if (!s->s3->send_connection_binding ||
605 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0) {
606 			ssl3_send_alert(s, SSL3_AL_WARNING,
607 			    SSL_AD_NO_RENEGOTIATION);
608 			return 1;
609 		}
610 
611 		s->s3->hs.state = SSL_ST_ACCEPT;
612 		s->internal->renegotiate = 1;
613 		s->internal->new_session = 1;
614 
615 	} else if (hs_msg_hdr.type == SSL3_MT_FINISHED && s->server) {
616 		/*
617 		 * If we are server, we may have a repeated FINISHED of the
618 		 * client here, then retransmit our CCS and FINISHED.
619 		 */
620 		if (dtls1_check_timeout_num(s) < 0)
621 			return -1;
622 
623 		/* XXX - should this be calling ssl_msg_callback()? */
624 
625 		dtls1_retransmit_buffered_messages(s);
626 
627 		rr->length = 0;
628 
629 		return 1;
630 
631 	} else {
632 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
633 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
634 		return -1;
635 	}
636 
637 	if ((ret = s->internal->handshake_func(s)) < 0)
638 		return ret;
639 	if (ret == 0) {
640 		SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
641 		return -1;
642 	}
643 
644 	if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
645 		if (s->s3->rbuf.left == 0) {
646 			ssl_force_want_read(s);
647 			return -1;
648 		}
649 	}
650 
651 	/*
652 	 * We either finished a handshake or ignored the request, now try again
653 	 * to obtain the (application) data we were asked for.
654 	 */
655 	return 1;
656 }
657 
658 /* Return up to 'len' payload bytes received in 'type' records.
659  * 'type' is one of the following:
660  *
661  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
662  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
663  *   -  0 (during a shutdown, no data has to be returned)
664  *
665  * If we don't have stored data to work from, read a SSL/TLS record first
666  * (possibly multiple records if we still don't have anything to return).
667  *
668  * This function must handle any surprises the peer may have for us, such as
669  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
670  * a surprise, but handled as if it were), or renegotiation requests.
671  * Also if record payloads contain fragments too small to process, we store
672  * them until there is enough for the respective protocol (the record protocol
673  * may use arbitrary fragmentation and even interleaving):
674  *     Change cipher spec protocol
675  *             just 1 byte needed, no need for keeping anything stored
676  *     Alert protocol
677  *             2 bytes needed (AlertLevel, AlertDescription)
678  *     Handshake protocol
679  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
680  *             to detect unexpected Client Hello and Hello Request messages
681  *             here, anything else is handled by higher layers
682  *     Application data protocol
683  *             none of our business
684  */
685 int
686 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
687 {
688 	SSL3_RECORD_INTERNAL *rr;
689 	int rrcount = 0;
690 	unsigned int n;
691 	int ret;
692 
693 	if (s->s3->rbuf.buf == NULL) {
694 		if (!ssl3_setup_buffers(s))
695 			return -1;
696 	}
697 
698 	if (len < 0) {
699 		SSLerror(s, ERR_R_INTERNAL_ERROR);
700 		return -1;
701 	}
702 
703 	if (type != 0 && type != SSL3_RT_APPLICATION_DATA &&
704 	    type != SSL3_RT_HANDSHAKE) {
705 		SSLerror(s, ERR_R_INTERNAL_ERROR);
706 		return -1;
707 	}
708 	if (peek && type != SSL3_RT_APPLICATION_DATA) {
709 		SSLerror(s, ERR_R_INTERNAL_ERROR);
710 		return -1;
711 	}
712 
713 	if (SSL_in_init(s) && !s->internal->in_handshake) {
714 		if ((ret = s->internal->handshake_func(s)) < 0)
715 			return ret;
716 		if (ret == 0) {
717 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
718 			return -1;
719 		}
720 	}
721 
722  start:
723 	/*
724 	 * Do not process more than three consecutive records, otherwise the
725 	 * peer can cause us to loop indefinitely. Instead, return with an
726 	 * SSL_ERROR_WANT_READ so the caller can choose when to handle further
727 	 * processing. In the future, the total number of non-handshake and
728 	 * non-application data records per connection should probably also be
729 	 * limited...
730 	 */
731 	if (rrcount++ >= 3) {
732 		ssl_force_want_read(s);
733 		return -1;
734 	}
735 
736 	s->internal->rwstate = SSL_NOTHING;
737 
738 	rr = &s->s3->rrec;
739 
740 	/*
741 	 * We are not handshaking and have no data yet, so process data buffered
742 	 * during the last handshake in advance, if any.
743 	 */
744 	if (s->s3->hs.state == SSL_ST_OK && rr->length == 0)
745 		dtls1_retrieve_buffered_record(s, &s->d1->buffered_app_data);
746 
747 	if (dtls1_handle_timeout(s) > 0)
748 		goto start;
749 
750 	if (rr->length == 0 || s->internal->rstate == SSL_ST_READ_BODY) {
751 		if ((ret = dtls1_get_record(s)) <= 0) {
752 			/* Anything other than a timeout is an error. */
753 			if ((ret = dtls1_read_failed(s, ret)) <= 0)
754 				return ret;
755 			goto start;
756 		}
757 	}
758 
759 	if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) {
760 		rr->length = 0;
761 		goto start;
762 	}
763 
764 	/* We now have a packet which can be read and processed. */
765 
766 	if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE) {
767 		/*
768 		 * We now have application data between CCS and Finished.
769 		 * Most likely the packets were reordered on their way, so
770 		 * buffer the application data for later processing rather
771 		 * than dropping the connection.
772 		 */
773 		if (dtls1_buffer_record(s, &s->d1->buffered_app_data,
774 		    rr->seq_num) < 0) {
775 			SSLerror(s, ERR_R_INTERNAL_ERROR);
776 			return (-1);
777 		}
778 		rr->length = 0;
779 		goto start;
780 	}
781 
782 	/*
783 	 * If the other end has shut down, throw anything we read away (even in
784 	 * 'peek' mode).
785 	 */
786 	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
787 		s->internal->rwstate = SSL_NOTHING;
788 		rr->length = 0;
789 		return 0;
790 	}
791 
792 	/* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
793 	if (type == rr->type) {
794 		/*
795 		 * Make sure that we are not getting application data when we
796 		 * are doing a handshake for the first time.
797 		 */
798 		if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
799 		    !tls12_record_layer_read_protected(s->internal->rl)) {
800 			SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
801 			ssl3_send_alert(s, SSL3_AL_FATAL,
802 			    SSL_AD_UNEXPECTED_MESSAGE);
803 			return -1;
804 		}
805 
806 		if (len <= 0)
807 			return len;
808 
809 		if ((unsigned int)len > rr->length)
810 			n = rr->length;
811 		else
812 			n = (unsigned int)len;
813 
814 		memcpy(buf, &rr->data[rr->off], n);
815 		if (!peek) {
816 			memset(&rr->data[rr->off], 0, n);
817 			rr->length -= n;
818 			rr->off += n;
819 			if (rr->length == 0) {
820 				s->internal->rstate = SSL_ST_READ_HEADER;
821 				rr->off = 0;
822 			}
823 		}
824 
825 		return n;
826 	}
827 
828 	/*
829 	 * If we get here, then type != rr->type; if we have a handshake
830 	 * message, then it was unexpected (Hello Request or Client Hello).
831 	 */
832 
833 	if (rr->type == SSL3_RT_ALERT) {
834 		if ((ret = ssl3_read_alert(s)) <= 0)
835 			return ret;
836 		goto start;
837 	}
838 
839 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) {
840 		s->internal->rwstate = SSL_NOTHING;
841 		rr->length = 0;
842 		return (0);
843 	}
844 
845 	if (rr->type == SSL3_RT_APPLICATION_DATA) {
846 		/*
847 		 * At this point, we were expecting handshake data, but have
848 		 * application data. If the library was running inside
849 		 * ssl3_read() (i.e. in_read_app_data is set) and it makes
850 		 * sense to read application data at this point (session
851 		 * renegotiation not yet started), we will indulge it.
852 		 */
853 		if (s->s3->in_read_app_data != 0 &&
854 		    s->s3->total_renegotiations != 0 &&
855 		    (((s->s3->hs.state & SSL_ST_CONNECT) &&
856 		    (s->s3->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
857 		    (s->s3->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
858 		    (s->s3->hs.state & SSL_ST_ACCEPT) &&
859 		    (s->s3->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
860 		    (s->s3->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
861 			s->s3->in_read_app_data = 2;
862 			return -1;
863 		} else {
864 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
865 			ssl3_send_alert(s, SSL3_AL_FATAL,
866 			    SSL_AD_UNEXPECTED_MESSAGE);
867 			return -1;
868 		}
869 	}
870 
871 	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
872 		if ((ret = ssl3_read_change_cipher_spec(s)) <= 0)
873 			return ret;
874 		goto start;
875 	}
876 
877 	if (rr->type == SSL3_RT_HANDSHAKE) {
878 		if ((ret = dtls1_read_handshake_unexpected(s)) <= 0)
879 			return ret;
880 		goto start;
881 	}
882 
883 	/* Unknown record type. */
884 	SSLerror(s, SSL_R_UNEXPECTED_RECORD);
885 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
886 	return -1;
887 }
888 
889 int
890 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
891 {
892 	int i;
893 
894 	if (SSL_in_init(s) && !s->internal->in_handshake)
895 	{
896 		i = s->internal->handshake_func(s);
897 		if (i < 0)
898 			return (i);
899 		if (i == 0) {
900 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
901 			return -1;
902 		}
903 	}
904 
905 	if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
906 		SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
907 		return -1;
908 	}
909 
910 	i = dtls1_write_bytes(s, type, buf_, len);
911 	return i;
912 }
913 
914 /* Call this to write data in records of type 'type'
915  * It will return <= 0 if not all data has been sent or non-blocking IO.
916  */
917 int
918 dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
919 {
920 	int i;
921 
922 	OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
923 	s->internal->rwstate = SSL_NOTHING;
924 	i = do_dtls1_write(s, type, buf, len);
925 	return i;
926 }
927 
928 int
929 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
930 {
931 	SSL3_BUFFER_INTERNAL *wb = &(s->s3->wbuf);
932 	size_t out_len;
933 	CBB cbb;
934 	int ret;
935 
936 	memset(&cbb, 0, sizeof(cbb));
937 
938 	/*
939 	 * First check if there is a SSL3_BUFFER_INTERNAL still being written
940 	 * out.  This will happen with non blocking IO.
941 	 */
942 	if (wb->left != 0) {
943 		OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
944 		return (ssl3_write_pending(s, type, buf, len));
945 	}
946 
947 	/* If we have an alert to send, let's send it */
948 	if (s->s3->alert_dispatch) {
949 		if ((ret = ssl3_dispatch_alert(s)) <= 0)
950 			return (ret);
951 		/* If it went, fall through and send more stuff. */
952 	}
953 
954 	if (len == 0)
955 		return 0;
956 
957 	wb->offset = 0;
958 
959 	if (!CBB_init_fixed(&cbb, wb->buf, wb->len))
960 		goto err;
961 
962 	tls12_record_layer_set_version(s->internal->rl, s->version);
963 
964 	if (!tls12_record_layer_seal_record(s->internal->rl, type, buf, len, &cbb))
965 		goto err;
966 
967 	if (!CBB_finish(&cbb, NULL, &out_len))
968 		goto err;
969 
970 	wb->left = out_len;
971 
972 	/*
973 	 * Memorize arguments so that ssl3_write_pending can detect
974 	 * bad write retries later.
975 	 */
976 	s->s3->wpend_tot = len;
977 	s->s3->wpend_buf = buf;
978 	s->s3->wpend_type = type;
979 	s->s3->wpend_ret = len;
980 
981 	/* We now just need to write the buffer. */
982 	return ssl3_write_pending(s, type, buf, len);
983 
984  err:
985 	CBB_cleanup(&cbb);
986 
987 	return -1;
988 }
989 
990 static int
991 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
992     const unsigned char *seq)
993 {
994 	unsigned int shift;
995 	int cmp;
996 
997 	cmp = satsub64be(seq, bitmap->max_seq_num);
998 	if (cmp > 0)
999 		return 1; /* this record in new */
1000 	shift = -cmp;
1001 	if (shift >= sizeof(bitmap->map)*8)
1002 		return 0; /* stale, outside the window */
1003 	else if (bitmap->map & (1UL << shift))
1004 		return 0; /* record previously received */
1005 
1006 	return 1;
1007 }
1008 
1009 static void
1010 dtls1_record_bitmap_update(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 		shift = cmp;
1019 		if (shift < sizeof(bitmap->map)*8)
1020 			bitmap->map <<= shift, bitmap->map |= 1UL;
1021 		else
1022 			bitmap->map = 1UL;
1023 		memcpy(bitmap->max_seq_num, seq, 8);
1024 	} else {
1025 		shift = -cmp;
1026 		if (shift < sizeof(bitmap->map) * 8)
1027 			bitmap->map |= 1UL << shift;
1028 	}
1029 }
1030 
1031 static DTLS1_BITMAP *
1032 dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr, unsigned int *is_next_epoch)
1033 {
1034 	uint16_t read_epoch, read_epoch_next;
1035 
1036 	*is_next_epoch = 0;
1037 
1038 	read_epoch = tls12_record_layer_read_epoch(s->internal->rl);
1039 	read_epoch_next = read_epoch + 1;
1040 
1041 	/* In current epoch, accept HM, CCS, DATA, & ALERT */
1042 	if (rr->epoch == read_epoch)
1043 		return &s->d1->bitmap;
1044 
1045 	/* Only HM and ALERT messages can be from the next epoch */
1046 	if (rr->epoch == read_epoch_next &&
1047 	    (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1048 		*is_next_epoch = 1;
1049 		return &s->d1->next_bitmap;
1050 	}
1051 
1052 	return NULL;
1053 }
1054 
1055 void
1056 dtls1_reset_read_seq_numbers(SSL *s)
1057 {
1058 	memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
1059 	memset(&(s->d1->next_bitmap), 0, sizeof(DTLS1_BITMAP));
1060 }
1061