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