xref: /openbsd-src/lib/libssl/d1_pkt.c (revision 387303bbbb9d754b4fb827b18476432ebdba1f40)
1*387303bbSjsing /* $OpenBSD: d1_pkt.c,v 1.129 2024/07/20 04:04:23 jsing Exp $ */
25650a0e1Sdjm /*
35650a0e1Sdjm  * DTLS implementation written by Nagendra Modadugu
45650a0e1Sdjm  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
55650a0e1Sdjm  */
65650a0e1Sdjm /* ====================================================================
75650a0e1Sdjm  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
85650a0e1Sdjm  *
95650a0e1Sdjm  * Redistribution and use in source and binary forms, with or without
105650a0e1Sdjm  * modification, are permitted provided that the following conditions
115650a0e1Sdjm  * are met:
125650a0e1Sdjm  *
135650a0e1Sdjm  * 1. Redistributions of source code must retain the above copyright
145650a0e1Sdjm  *    notice, this list of conditions and the following disclaimer.
155650a0e1Sdjm  *
165650a0e1Sdjm  * 2. Redistributions in binary form must reproduce the above copyright
175650a0e1Sdjm  *    notice, this list of conditions and the following disclaimer in
185650a0e1Sdjm  *    the documentation and/or other materials provided with the
195650a0e1Sdjm  *    distribution.
205650a0e1Sdjm  *
215650a0e1Sdjm  * 3. All advertising materials mentioning features or use of this
225650a0e1Sdjm  *    software must display the following acknowledgment:
235650a0e1Sdjm  *    "This product includes software developed by the OpenSSL Project
245650a0e1Sdjm  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
255650a0e1Sdjm  *
265650a0e1Sdjm  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
275650a0e1Sdjm  *    endorse or promote products derived from this software without
285650a0e1Sdjm  *    prior written permission. For written permission, please contact
295650a0e1Sdjm  *    openssl-core@openssl.org.
305650a0e1Sdjm  *
315650a0e1Sdjm  * 5. Products derived from this software may not be called "OpenSSL"
325650a0e1Sdjm  *    nor may "OpenSSL" appear in their names without prior written
335650a0e1Sdjm  *    permission of the OpenSSL Project.
345650a0e1Sdjm  *
355650a0e1Sdjm  * 6. Redistributions of any form whatsoever must retain the following
365650a0e1Sdjm  *    acknowledgment:
375650a0e1Sdjm  *    "This product includes software developed by the OpenSSL Project
385650a0e1Sdjm  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
395650a0e1Sdjm  *
405650a0e1Sdjm  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
415650a0e1Sdjm  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
425650a0e1Sdjm  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
435650a0e1Sdjm  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
445650a0e1Sdjm  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
455650a0e1Sdjm  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
465650a0e1Sdjm  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
475650a0e1Sdjm  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
485650a0e1Sdjm  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
495650a0e1Sdjm  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
505650a0e1Sdjm  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
515650a0e1Sdjm  * OF THE POSSIBILITY OF SUCH DAMAGE.
525650a0e1Sdjm  * ====================================================================
535650a0e1Sdjm  *
545650a0e1Sdjm  * This product includes cryptographic software written by Eric Young
555650a0e1Sdjm  * (eay@cryptsoft.com).  This product includes software written by Tim
565650a0e1Sdjm  * Hudson (tjh@cryptsoft.com).
575650a0e1Sdjm  *
585650a0e1Sdjm  */
595650a0e1Sdjm /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
605650a0e1Sdjm  * All rights reserved.
615650a0e1Sdjm  *
625650a0e1Sdjm  * This package is an SSL implementation written
635650a0e1Sdjm  * by Eric Young (eay@cryptsoft.com).
645650a0e1Sdjm  * The implementation was written so as to conform with Netscapes SSL.
655650a0e1Sdjm  *
665650a0e1Sdjm  * This library is free for commercial and non-commercial use as long as
675650a0e1Sdjm  * the following conditions are aheared to.  The following conditions
685650a0e1Sdjm  * apply to all code found in this distribution, be it the RC4, RSA,
695650a0e1Sdjm  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
705650a0e1Sdjm  * included with this distribution is covered by the same copyright terms
715650a0e1Sdjm  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
725650a0e1Sdjm  *
735650a0e1Sdjm  * Copyright remains Eric Young's, and as such any Copyright notices in
745650a0e1Sdjm  * the code are not to be removed.
755650a0e1Sdjm  * If this package is used in a product, Eric Young should be given attribution
765650a0e1Sdjm  * as the author of the parts of the library used.
775650a0e1Sdjm  * This can be in the form of a textual message at program startup or
785650a0e1Sdjm  * in documentation (online or textual) provided with the package.
795650a0e1Sdjm  *
805650a0e1Sdjm  * Redistribution and use in source and binary forms, with or without
815650a0e1Sdjm  * modification, are permitted provided that the following conditions
825650a0e1Sdjm  * are met:
835650a0e1Sdjm  * 1. Redistributions of source code must retain the copyright
845650a0e1Sdjm  *    notice, this list of conditions and the following disclaimer.
855650a0e1Sdjm  * 2. Redistributions in binary form must reproduce the above copyright
865650a0e1Sdjm  *    notice, this list of conditions and the following disclaimer in the
875650a0e1Sdjm  *    documentation and/or other materials provided with the distribution.
885650a0e1Sdjm  * 3. All advertising materials mentioning features or use of this software
895650a0e1Sdjm  *    must display the following acknowledgement:
905650a0e1Sdjm  *    "This product includes cryptographic software written by
915650a0e1Sdjm  *     Eric Young (eay@cryptsoft.com)"
925650a0e1Sdjm  *    The word 'cryptographic' can be left out if the rouines from the library
935650a0e1Sdjm  *    being used are not cryptographic related :-).
945650a0e1Sdjm  * 4. If you include any Windows specific code (or a derivative thereof) from
955650a0e1Sdjm  *    the apps directory (application code) you must include an acknowledgement:
965650a0e1Sdjm  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
975650a0e1Sdjm  *
985650a0e1Sdjm  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
995650a0e1Sdjm  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1005650a0e1Sdjm  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1015650a0e1Sdjm  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1025650a0e1Sdjm  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1035650a0e1Sdjm  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1045650a0e1Sdjm  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1055650a0e1Sdjm  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1065650a0e1Sdjm  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1075650a0e1Sdjm  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1085650a0e1Sdjm  * SUCH DAMAGE.
1095650a0e1Sdjm  *
1105650a0e1Sdjm  * The licence and distribution terms for any publically available version or
1115650a0e1Sdjm  * derivative of this code cannot be changed.  i.e. this code cannot simply be
1125650a0e1Sdjm  * copied and put under another distribution licence
1135650a0e1Sdjm  * [including the GNU Public Licence.]
1145650a0e1Sdjm  */
1155650a0e1Sdjm 
116b6c209beSbcook #include <endian.h>
117c5899dbcSjsing #include <errno.h>
118ee4250f6Sjsing #include <limits.h>
119c5899dbcSjsing #include <stdio.h>
120c5899dbcSjsing 
1215650a0e1Sdjm #include <openssl/buffer.h>
122c5899dbcSjsing #include <openssl/evp.h>
1235650a0e1Sdjm 
124bf304f22Sdoug #include "bytestring.h"
125c9675a23Stb #include "dtls_local.h"
1264b0cebd1Sjsing #include "pqueue.h"
127c9675a23Stb #include "ssl_local.h"
128ee4250f6Sjsing #include "tls_content.h"
12946859c4aSjsing 
1300a5d6edeSdjm /* mod 128 saturating subtract of two 64-bit values in big-endian order */
1314a47b859Sjsing static int
1324a47b859Sjsing satsub64be(const unsigned char *v1, const unsigned char *v2)
1334a47b859Sjsing {
1344a47b859Sjsing 	int ret, sat, brw, i;
1350a5d6edeSdjm 
1364a47b859Sjsing 	if (sizeof(long) == 8)
1374a47b859Sjsing 		do {
1380a5d6edeSdjm 			long l;
1390a5d6edeSdjm 
1404b3ddfedSmiod 			if (BYTE_ORDER == LITTLE_ENDIAN)
1414a47b859Sjsing 				break;
1420a5d6edeSdjm 			/* not reached on little-endians */
1430a5d6edeSdjm 			/* following test is redundant, because input is
1440a5d6edeSdjm 			 * always aligned, but I take no chances... */
1454a47b859Sjsing 			if (((size_t)v1 | (size_t)v2) & 0x7)
1464a47b859Sjsing 				break;
1470a5d6edeSdjm 
1480a5d6edeSdjm 			l  = *((long *)v1);
1490a5d6edeSdjm 			l -= *((long *)v2);
1504a47b859Sjsing 			if (l > 128)
1514a47b859Sjsing 				return 128;
1524a47b859Sjsing 			else if (l<-128)
1534a47b859Sjsing 				return -128;
1544a47b859Sjsing 			else
1554a47b859Sjsing 				return (int)l;
1560a5d6edeSdjm 		} while (0);
1570a5d6edeSdjm 
1580a5d6edeSdjm 	ret = (int)v1[7] - (int)v2[7];
1590a5d6edeSdjm 	sat = 0;
1600a5d6edeSdjm 	brw = ret >> 8;	/* brw is either 0 or -1 */
1614a47b859Sjsing 	if (ret & 0x80) {
1624a47b859Sjsing 		for (i = 6; i >= 0; i--) {
1634a47b859Sjsing 			brw += (int)v1[i]-(int)v2[i];
1640a5d6edeSdjm 			sat |= ~brw;
1650a5d6edeSdjm 			brw >>= 8;
1660a5d6edeSdjm 		}
1674a47b859Sjsing 	} else {
1684a47b859Sjsing 		for (i = 6; i >= 0; i--) {
1694a47b859Sjsing 			brw += (int)v1[i]-(int)v2[i];
1700a5d6edeSdjm 			sat |= brw;
1710a5d6edeSdjm 			brw >>= 8;
1720a5d6edeSdjm 		}
1730a5d6edeSdjm 	}
1740a5d6edeSdjm 	brw <<= 8;	/* brw is either 0 or -256 */
1750a5d6edeSdjm 
1764a47b859Sjsing 	if (sat & 0xff)
1774a47b859Sjsing 		return brw | 0x80;
1784a47b859Sjsing 	else
1794a47b859Sjsing 		return brw + (ret & 0xFF);
1800a5d6edeSdjm }
1810a5d6edeSdjm 
18217b41dffSjsing static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
18317b41dffSjsing     const unsigned char *seq);
18417b41dffSjsing static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap,
18517b41dffSjsing     const unsigned char *seq);
1866182911eSjsing static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr,
1875650a0e1Sdjm     unsigned int *is_next_epoch);
1885650a0e1Sdjm static int dtls1_buffer_record(SSL *s, record_pqueue *q,
1890a5d6edeSdjm     unsigned char *priority);
1905650a0e1Sdjm static int dtls1_process_record(SSL *s);
1915650a0e1Sdjm 
1925650a0e1Sdjm /* copy buffered record into SSL structure */
1935650a0e1Sdjm static int
194b11cfbadSjsing dtls1_copy_record(SSL *s, DTLS1_RECORD_DATA_INTERNAL *rdata)
1955650a0e1Sdjm {
19602876cc3Sjsing 	ssl3_release_buffer(&s->s3->rbuf);
1975650a0e1Sdjm 
1986f7f653bSjsing 	s->packet = rdata->packet;
1996f7f653bSjsing 	s->packet_length = rdata->packet_length;
20002876cc3Sjsing 	memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
20102876cc3Sjsing 	memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD_INTERNAL));
2025650a0e1Sdjm 
2035650a0e1Sdjm 	return (1);
2045650a0e1Sdjm }
2055650a0e1Sdjm 
2065650a0e1Sdjm static int
2070a5d6edeSdjm dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
2085650a0e1Sdjm {
209fb769bc0Stb 	DTLS1_RECORD_DATA_INTERNAL *rdata = NULL;
210fb769bc0Stb 	pitem *item = NULL;
2115650a0e1Sdjm 
2120a5d6edeSdjm 	/* Limit the size of the queue to prevent DOS attacks */
2130a5d6edeSdjm 	if (pqueue_size(queue->q) >= 100)
2140a5d6edeSdjm 		return 0;
2150a5d6edeSdjm 
216fb769bc0Stb 	if ((rdata = malloc(sizeof(*rdata))) == NULL)
217fb769bc0Stb 		goto init_err;
218fb769bc0Stb 	if ((item = pitem_new(priority, rdata)) == NULL)
2193221bfb8Sdoug 		goto init_err;
2205650a0e1Sdjm 
2216f7f653bSjsing 	rdata->packet = s->packet;
2226f7f653bSjsing 	rdata->packet_length = s->packet_length;
22302876cc3Sjsing 	memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER_INTERNAL));
22402876cc3Sjsing 	memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD_INTERNAL));
2255650a0e1Sdjm 
2265650a0e1Sdjm 	item->data = rdata;
2275650a0e1Sdjm 
2286f7f653bSjsing 	s->packet = NULL;
2296f7f653bSjsing 	s->packet_length = 0;
23002876cc3Sjsing 	memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER_INTERNAL));
23102876cc3Sjsing 	memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD_INTERNAL));
2325650a0e1Sdjm 
233865b1c6aSmiod 	if (!ssl3_setup_buffers(s))
234865b1c6aSmiod 		goto err;
235865b1c6aSmiod 
236865b1c6aSmiod 	/* insert should not fail, since duplicates are dropped */
237865b1c6aSmiod 	if (pqueue_insert(queue->q, item) == NULL)
238865b1c6aSmiod 		goto err;
239865b1c6aSmiod 
240865b1c6aSmiod 	return (1);
241865b1c6aSmiod 
242865b1c6aSmiod  err:
243435f94b7Sjsing 	ssl3_release_buffer(&rdata->rbuf);
2443221bfb8Sdoug 
2453221bfb8Sdoug  init_err:
246c9d7abb7Sbeck 	SSLerror(s, ERR_R_INTERNAL_ERROR);
2476f3a6cb1Sbeck 	free(rdata);
2485650a0e1Sdjm 	pitem_free(item);
2493221bfb8Sdoug 	return (-1);
2505650a0e1Sdjm }
2515650a0e1Sdjm 
252ee4250f6Sjsing static int
253ee4250f6Sjsing dtls1_buffer_rcontent(SSL *s, rcontent_pqueue *queue, unsigned char *priority)
254ee4250f6Sjsing {
255fb769bc0Stb 	DTLS1_RCONTENT_DATA_INTERNAL *rdata = NULL;
256fb769bc0Stb 	pitem *item = NULL;
257ee4250f6Sjsing 
258ee4250f6Sjsing 	/* Limit the size of the queue to prevent DOS attacks */
259ee4250f6Sjsing 	if (pqueue_size(queue->q) >= 100)
260ee4250f6Sjsing 		return 0;
261ee4250f6Sjsing 
262fb769bc0Stb 	if ((rdata = malloc(sizeof(*rdata))) == NULL)
263fb769bc0Stb 		goto init_err;
264fb769bc0Stb 	if ((item = pitem_new(priority, rdata)) == NULL)
265ee4250f6Sjsing 		goto init_err;
266ee4250f6Sjsing 
267ee4250f6Sjsing 	rdata->rcontent = s->s3->rcontent;
268ee4250f6Sjsing 	s->s3->rcontent = NULL;
269ee4250f6Sjsing 
270ee4250f6Sjsing 	item->data = rdata;
271ee4250f6Sjsing 
272ee4250f6Sjsing 	/* insert should not fail, since duplicates are dropped */
273ee4250f6Sjsing 	if (pqueue_insert(queue->q, item) == NULL)
274ee4250f6Sjsing 		goto err;
275ee4250f6Sjsing 
276ee4250f6Sjsing 	if ((s->s3->rcontent = tls_content_new()) == NULL)
277ee4250f6Sjsing 		goto err;
278ee4250f6Sjsing 
279ee4250f6Sjsing 	return (1);
280ee4250f6Sjsing 
281ee4250f6Sjsing  err:
282ee4250f6Sjsing 	tls_content_free(rdata->rcontent);
283ee4250f6Sjsing 
284ee4250f6Sjsing  init_err:
285ee4250f6Sjsing 	SSLerror(s, ERR_R_INTERNAL_ERROR);
286ee4250f6Sjsing 	free(rdata);
287ee4250f6Sjsing 	pitem_free(item);
288ee4250f6Sjsing 	return (-1);
289ee4250f6Sjsing }
2905650a0e1Sdjm 
2915650a0e1Sdjm static int
2925650a0e1Sdjm dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
2935650a0e1Sdjm {
2945650a0e1Sdjm 	pitem *item;
2955650a0e1Sdjm 
2965650a0e1Sdjm 	item = pqueue_pop(queue->q);
2974a47b859Sjsing 	if (item) {
298b11cfbadSjsing 		dtls1_copy_record(s, item->data);
2995650a0e1Sdjm 
3006f3a6cb1Sbeck 		free(item->data);
3015650a0e1Sdjm 		pitem_free(item);
3025650a0e1Sdjm 
3035650a0e1Sdjm 		return (1);
3045650a0e1Sdjm 	}
3055650a0e1Sdjm 
3065650a0e1Sdjm 	return (0);
3075650a0e1Sdjm }
3085650a0e1Sdjm 
3095650a0e1Sdjm static int
310ee4250f6Sjsing dtls1_retrieve_buffered_rcontent(SSL *s, rcontent_pqueue *queue)
311ee4250f6Sjsing {
312ee4250f6Sjsing 	DTLS1_RCONTENT_DATA_INTERNAL *rdata;
313ee4250f6Sjsing 	pitem *item;
314ee4250f6Sjsing 
315ee4250f6Sjsing 	item = pqueue_pop(queue->q);
316ee4250f6Sjsing 	if (item) {
317ee4250f6Sjsing 		rdata = item->data;
318ee4250f6Sjsing 
319ee4250f6Sjsing 		tls_content_free(s->s3->rcontent);
320ee4250f6Sjsing 		s->s3->rcontent = rdata->rcontent;
321ee4250f6Sjsing 		s->s3->rrec.epoch = tls_content_epoch(s->s3->rcontent);
322ee4250f6Sjsing 
323ee4250f6Sjsing 		free(item->data);
324ee4250f6Sjsing 		pitem_free(item);
325ee4250f6Sjsing 
326ee4250f6Sjsing 		return (1);
327ee4250f6Sjsing 	}
328ee4250f6Sjsing 
329ee4250f6Sjsing 	return (0);
330ee4250f6Sjsing }
331ee4250f6Sjsing 
332ee4250f6Sjsing static int
3336065f753Sjsing dtls1_process_buffered_record(SSL *s)
3345650a0e1Sdjm {
3355650a0e1Sdjm 	/* Check if epoch is current. */
336f19d9718Sjsing 	if (s->d1->unprocessed_rcds.epoch !=
3376f7f653bSjsing 	    tls12_record_layer_read_epoch(s->rl))
338704e6816Sjsing 		return (0);
3395650a0e1Sdjm 
3406065f753Sjsing 	/* Update epoch once all unprocessed records have been processed. */
341f19d9718Sjsing 	if (pqueue_peek(s->d1->unprocessed_rcds.q) == NULL) {
342f19d9718Sjsing 		s->d1->unprocessed_rcds.epoch =
3436f7f653bSjsing 		    tls12_record_layer_read_epoch(s->rl) + 1;
3446065f753Sjsing 		return (0);
3456065f753Sjsing 	}
3466065f753Sjsing 
3476065f753Sjsing 	/* Process one of the records. */
348f19d9718Sjsing 	if (!dtls1_retrieve_buffered_record(s, &s->d1->unprocessed_rcds))
3496065f753Sjsing 		return (-1);
3506065f753Sjsing 	if (!dtls1_process_record(s))
3516065f753Sjsing 		return (-1);
3525650a0e1Sdjm 
3535650a0e1Sdjm 	return (1);
3545650a0e1Sdjm }
3555650a0e1Sdjm 
3565650a0e1Sdjm static int
3575650a0e1Sdjm dtls1_process_record(SSL *s)
3585650a0e1Sdjm {
35902876cc3Sjsing 	SSL3_RECORD_INTERNAL *rr = &(s->s3->rrec);
36040038cb8Sjsing 	uint8_t alert_desc;
3615650a0e1Sdjm 
3626f7f653bSjsing 	tls12_record_layer_set_version(s->rl, s->version);
3635650a0e1Sdjm 
364ee4250f6Sjsing 	if (!tls12_record_layer_open_record(s->rl, s->packet, s->packet_length,
365ee4250f6Sjsing 	    s->s3->rcontent)) {
3666f7f653bSjsing 		tls12_record_layer_alert(s->rl, &alert_desc);
3675650a0e1Sdjm 
36840038cb8Sjsing 		if (alert_desc == 0)
36940038cb8Sjsing 			goto err;
3705650a0e1Sdjm 
371686c8b13Sjsing 		/*
372686c8b13Sjsing 		 * DTLS should silently discard invalid records, including those
373686c8b13Sjsing 		 * with a bad MAC, as per RFC 6347 section 4.1.2.1.
374686c8b13Sjsing 		 */
375ee4250f6Sjsing 		if (alert_desc == SSL_AD_BAD_RECORD_MAC)
376686c8b13Sjsing 			goto done;
377686c8b13Sjsing 
37840038cb8Sjsing 		if (alert_desc == SSL_AD_RECORD_OVERFLOW)
379c9d7abb7Sbeck 			SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
38040038cb8Sjsing 
381ba06b73eStb 		goto fatal_err;
3825650a0e1Sdjm 	}
3835650a0e1Sdjm 
384ee4250f6Sjsing 	/* XXX move to record layer. */
385ee4250f6Sjsing 	tls_content_set_epoch(s->s3->rcontent, rr->epoch);
3865650a0e1Sdjm 
387ee4250f6Sjsing  done:
3886f7f653bSjsing 	s->packet_length = 0;
38940038cb8Sjsing 
3905650a0e1Sdjm 	return (1);
3915650a0e1Sdjm 
392ba06b73eStb  fatal_err:
39340038cb8Sjsing 	ssl3_send_alert(s, SSL3_AL_FATAL, alert_desc);
3945650a0e1Sdjm  err:
3955650a0e1Sdjm 	return (0);
3965650a0e1Sdjm }
3975650a0e1Sdjm 
3985650a0e1Sdjm /* Call this to get a new input record.
3995650a0e1Sdjm  * It will return <= 0 if more data is needed, normally due to an error
4005650a0e1Sdjm  * or non-blocking IO.
4015650a0e1Sdjm  * When it finishes, one packet has been decoded and can be found in
4026f7f653bSjsing  * ssl->s3->rrec.type    - is the type of record
4036f7f653bSjsing  * ssl->s3->rrec.data, 	 - data
4046f7f653bSjsing  * ssl->s3->rrec.length, - number of bytes
4055650a0e1Sdjm  */
4065650a0e1Sdjm /* used only by dtls1_read_bytes */
4074a47b859Sjsing int
4084a47b859Sjsing dtls1_get_record(SSL *s)
4095650a0e1Sdjm {
41002876cc3Sjsing 	SSL3_RECORD_INTERNAL *rr = &(s->s3->rrec);
4110a5d6edeSdjm 	unsigned char *p = NULL;
4125650a0e1Sdjm 	DTLS1_BITMAP *bitmap;
4135650a0e1Sdjm 	unsigned int is_next_epoch;
4146065f753Sjsing 	int ret, n;
4155650a0e1Sdjm 
4166065f753Sjsing 	/* See if there are pending records that can now be processed. */
4176065f753Sjsing 	if ((ret = dtls1_process_buffered_record(s)) != 0)
4186065f753Sjsing 		return (ret);
4195650a0e1Sdjm 
4205650a0e1Sdjm 	/* get something from the wire */
421496d4919Sdoug 	if (0) {
4225650a0e1Sdjm  again:
423496d4919Sdoug 		/* dump this record on all retries */
424496d4919Sdoug 		rr->length = 0;
4256f7f653bSjsing 		s->packet_length = 0;
426496d4919Sdoug 	}
427496d4919Sdoug 
4285650a0e1Sdjm 	/* check if we have the header */
4296f7f653bSjsing 	if ((s->rstate != SSL_ST_READ_BODY) ||
4306f7f653bSjsing 	    (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
431bf304f22Sdoug 		CBS header, seq_no;
432bf304f22Sdoug 		uint16_t epoch, len, ssl_version;
433bf304f22Sdoug 		uint8_t type;
434bf304f22Sdoug 
4352b2d4a43Sjsing 		n = ssl3_packet_read(s, DTLS1_RT_HEADER_LENGTH);
4364a47b859Sjsing 		if (n <= 0)
4372b2d4a43Sjsing 			return (n);
4385650a0e1Sdjm 
4392b2d4a43Sjsing 		/* If this packet contained a partial record, dump it. */
4402b2d4a43Sjsing 		if (n != DTLS1_RT_HEADER_LENGTH)
4410a5d6edeSdjm 			goto again;
4425650a0e1Sdjm 
4436f7f653bSjsing 		s->rstate = SSL_ST_READ_BODY;
4445650a0e1Sdjm 
4456f7f653bSjsing 		CBS_init(&header, s->packet, s->packet_length);
4465650a0e1Sdjm 
4475650a0e1Sdjm 		/* Pull apart the header into the DTLS1_RECORD */
448bf304f22Sdoug 		if (!CBS_get_u8(&header, &type))
449bf304f22Sdoug 			goto again;
450bf304f22Sdoug 		if (!CBS_get_u16(&header, &ssl_version))
451bf304f22Sdoug 			goto again;
4525650a0e1Sdjm 
4537b597b5fSjsing 		/* Sequence number is 64 bits, with top 2 bytes = epoch. */
4547b597b5fSjsing 		if (!CBS_get_bytes(&header, &seq_no, SSL3_SEQUENCE_SIZE))
4557b597b5fSjsing 			goto again;
4567b597b5fSjsing 		if (!CBS_get_u16(&seq_no, &epoch))
4577b597b5fSjsing 			goto again;
4587b597b5fSjsing 		if (!CBS_write_bytes(&seq_no, &rr->seq_num[2],
4597b597b5fSjsing 		    sizeof(rr->seq_num) - 2, NULL))
460bf304f22Sdoug 			goto again;
4615650a0e1Sdjm 
46217b41dffSjsing 		if (!CBS_get_u16(&header, &len))
46317b41dffSjsing 			goto again;
46417b41dffSjsing 
465bf304f22Sdoug 		rr->type = type;
466bf304f22Sdoug 		rr->epoch = epoch;
467bf304f22Sdoug 		rr->length = len;
4685650a0e1Sdjm 
4690a5d6edeSdjm 		/* unexpected version, silently discard */
4706f7f653bSjsing 		if (!s->first_packet && ssl_version != s->version)
4710a5d6edeSdjm 			goto again;
4725650a0e1Sdjm 
4730a5d6edeSdjm 		/* wrong version, silently discard record */
474bf304f22Sdoug 		if ((ssl_version & 0xff00) != (s->version & 0xff00))
4750a5d6edeSdjm 			goto again;
4765650a0e1Sdjm 
4770a5d6edeSdjm 		/* record too long, silently discard it */
478bf304f22Sdoug 		if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
4790a5d6edeSdjm 			goto again;
4805650a0e1Sdjm 
4816f7f653bSjsing 		/* now s->rstate == SSL_ST_READ_BODY */
4826c0b0411Sdoug 		p = (unsigned char *)CBS_data(&header);
4835650a0e1Sdjm 	}
4845650a0e1Sdjm 
4856f7f653bSjsing 	/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
4865650a0e1Sdjm 
4872b2d4a43Sjsing 	n = ssl3_packet_extend(s, DTLS1_RT_HEADER_LENGTH + rr->length);
4884a47b859Sjsing 	if (n <= 0)
4892b2d4a43Sjsing 		return (n);
4905650a0e1Sdjm 
4912b2d4a43Sjsing 	/* If this packet contained a partial record, dump it. */
4922b2d4a43Sjsing 	if (n != DTLS1_RT_HEADER_LENGTH + rr->length)
4935650a0e1Sdjm 		goto again;
4945650a0e1Sdjm 
4956f7f653bSjsing 	s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
4965650a0e1Sdjm 
4975650a0e1Sdjm 	/* match epochs.  NULL means the packet is dropped on the floor */
4985650a0e1Sdjm 	bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
499496d4919Sdoug 	if (bitmap == NULL)
5004a47b859Sjsing 		goto again;
5015650a0e1Sdjm 
50222296082Sdoug 	/*
50322296082Sdoug 	 * Check whether this is a repeat, or aged record.
5040a5d6edeSdjm 	 * Don't check if we're listening and this message is
5050a5d6edeSdjm 	 * a ClientHello. They can look as if they're replayed,
5060a5d6edeSdjm 	 * since they arrive from different connections and
5070a5d6edeSdjm 	 * would be dropped unnecessarily.
5080a5d6edeSdjm 	 */
509f19d9718Sjsing 	if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
510bb69e32aSjsing 	    p != NULL && *p == SSL3_MT_CLIENT_HELLO) &&
51117b41dffSjsing 	    !dtls1_record_replay_check(s, bitmap, rr->seq_num))
5124a47b859Sjsing 		goto again;
5135650a0e1Sdjm 
5145650a0e1Sdjm 	/* just read a 0 length packet */
5154a47b859Sjsing 	if (rr->length == 0)
5164a47b859Sjsing 		goto again;
5175650a0e1Sdjm 
5180a5d6edeSdjm 	/* If this record is from the next epoch (either HM or ALERT),
5190a5d6edeSdjm 	 * and a handshake is currently in progress, buffer it since it
520c32db552Sdjm 	 * cannot be processed at this time. However, do not buffer
521c32db552Sdjm 	 * anything while listening.
522c32db552Sdjm 	 */
5234a47b859Sjsing 	if (is_next_epoch) {
5246f7f653bSjsing 		if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
525f19d9718Sjsing 			if (dtls1_buffer_record(s, &(s->d1->unprocessed_rcds),
5263221bfb8Sdoug 			    rr->seq_num) < 0)
5273221bfb8Sdoug 				return (-1);
5283221bfb8Sdoug 			/* Mark receipt of record. */
52917b41dffSjsing 			dtls1_record_bitmap_update(s, bitmap, rr->seq_num);
5300a5d6edeSdjm 		}
5315650a0e1Sdjm 		goto again;
5325650a0e1Sdjm 	}
5335650a0e1Sdjm 
534496d4919Sdoug 	if (!dtls1_process_record(s))
5354a47b859Sjsing 		goto again;
536496d4919Sdoug 
5373221bfb8Sdoug 	/* Mark receipt of record. */
53817b41dffSjsing 	dtls1_record_bitmap_update(s, bitmap, rr->seq_num);
5395650a0e1Sdjm 
5405650a0e1Sdjm 	return (1);
5415650a0e1Sdjm }
5425650a0e1Sdjm 
543225d6b92Sjsing static int
544225d6b92Sjsing dtls1_read_handshake_unexpected(SSL *s)
545225d6b92Sjsing {
546b51494a2Sjsing 	struct hm_header_st hs_msg_hdr;
547b51494a2Sjsing 	CBS cbs;
548b51494a2Sjsing 	int ret;
549225d6b92Sjsing 
5506f7f653bSjsing 	if (s->in_handshake) {
551225d6b92Sjsing 		SSLerror(s, ERR_R_INTERNAL_ERROR);
552225d6b92Sjsing 		return -1;
553225d6b92Sjsing 	}
554225d6b92Sjsing 
555b51494a2Sjsing 	/* Parse handshake message header. */
556ad58af2dStb 	CBS_dup(tls_content_cbs(s->s3->rcontent), &cbs);
557b51494a2Sjsing 	if (!dtls1_get_message_header(&cbs, &hs_msg_hdr))
558b51494a2Sjsing 		return -1; /* XXX - probably should drop/continue. */
559b51494a2Sjsing 
560b51494a2Sjsing 	/* This may just be a stale retransmit. */
561ee4250f6Sjsing 	if (tls_content_epoch(s->s3->rcontent) !=
562ee4250f6Sjsing 	    tls12_record_layer_read_epoch(s->rl)) {
563ee4250f6Sjsing 		tls_content_clear(s->s3->rcontent);
564ee4250f6Sjsing 		s->s3->rrec.length = 0;
565225d6b92Sjsing 		return 1;
566225d6b92Sjsing 	}
567225d6b92Sjsing 
568b51494a2Sjsing 	if (hs_msg_hdr.type == SSL3_MT_HELLO_REQUEST) {
569b51494a2Sjsing 		/*
570b51494a2Sjsing 		 * Incoming HelloRequest messages should only be received by a
571b51494a2Sjsing 		 * client. A server may send these at any time - a client should
572b51494a2Sjsing 		 * ignore the message if received in the middle of a handshake.
573b51494a2Sjsing 		 * See RFC 5246 sections 7.4 and 7.4.1.1.
574225d6b92Sjsing 		 */
575b51494a2Sjsing 		if (s->server) {
576b51494a2Sjsing 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
577b51494a2Sjsing 			ssl3_send_alert(s, SSL3_AL_FATAL,
578b51494a2Sjsing 			     SSL_AD_UNEXPECTED_MESSAGE);
579225d6b92Sjsing 			return -1;
580b51494a2Sjsing 		}
581225d6b92Sjsing 
582b51494a2Sjsing 		/* XXX - should also check frag offset/length. */
583b51494a2Sjsing 		if (hs_msg_hdr.msg_len != 0) {
584b51494a2Sjsing 			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
585b51494a2Sjsing 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
586b51494a2Sjsing 			return -1;
587b51494a2Sjsing 		}
588b51494a2Sjsing 
589ee4250f6Sjsing 		ssl_msg_callback_cbs(s, 0, SSL3_RT_HANDSHAKE,
590ee4250f6Sjsing 		    tls_content_cbs(s->s3->rcontent));
591b51494a2Sjsing 
592ee4250f6Sjsing 		tls_content_clear(s->s3->rcontent);
593ee4250f6Sjsing 		s->s3->rrec.length = 0;
594b51494a2Sjsing 
595b51494a2Sjsing 		/*
596b51494a2Sjsing 		 * It should be impossible to hit this, but keep the safety
597b51494a2Sjsing 		 * harness for now...
598b51494a2Sjsing 		 */
599*387303bbSjsing 		if (s->session == NULL || s->s3->hs.cipher == NULL)
600b51494a2Sjsing 			return 1;
601b51494a2Sjsing 
602b51494a2Sjsing 		/*
603b51494a2Sjsing 		 * Ignore this message if we're currently handshaking,
604b51494a2Sjsing 		 * renegotiation is already pending or renegotiation is disabled
605b51494a2Sjsing 		 * via flags.
606b51494a2Sjsing 		 */
607b51494a2Sjsing 		if (!SSL_is_init_finished(s) || s->s3->renegotiate ||
608b51494a2Sjsing 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0)
609b51494a2Sjsing 			return 1;
610b51494a2Sjsing 
611b51494a2Sjsing 		s->d1->handshake_read_seq++;
612b51494a2Sjsing 
613b51494a2Sjsing 		/* XXX - why is this set here but not in ssl3? */
6146f7f653bSjsing 		s->new_session = 1;
615b51494a2Sjsing 
616b51494a2Sjsing 		if (!ssl3_renegotiate(s))
617b51494a2Sjsing 			return 1;
618b51494a2Sjsing 		if (!ssl3_renegotiate_check(s))
619b51494a2Sjsing 			return 1;
620b51494a2Sjsing 
621b51494a2Sjsing 	} else if (hs_msg_hdr.type == SSL3_MT_CLIENT_HELLO) {
622b51494a2Sjsing 		/*
623b51494a2Sjsing 		 * Incoming ClientHello messages should only be received by a
624b51494a2Sjsing 		 * server. A client may send these in response to server
625b51494a2Sjsing 		 * initiated renegotiation (HelloRequest) or in order to
626b51494a2Sjsing 		 * initiate renegotiation by the client. See RFC 5246 section
627b51494a2Sjsing 		 * 7.4.1.2.
628b51494a2Sjsing 		 */
629b51494a2Sjsing 		if (!s->server) {
630b51494a2Sjsing 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
631b51494a2Sjsing 			ssl3_send_alert(s, SSL3_AL_FATAL,
632b51494a2Sjsing 			     SSL_AD_UNEXPECTED_MESSAGE);
633b51494a2Sjsing 			return -1;
634b51494a2Sjsing 		}
635b51494a2Sjsing 
636b51494a2Sjsing 		/*
637b51494a2Sjsing 		 * A client should not be sending a ClientHello unless we're not
638b51494a2Sjsing 		 * currently handshaking.
639b51494a2Sjsing 		 */
640b51494a2Sjsing 		if (!SSL_is_init_finished(s)) {
641b51494a2Sjsing 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
642b51494a2Sjsing 			ssl3_send_alert(s, SSL3_AL_FATAL,
643b51494a2Sjsing 			    SSL_AD_UNEXPECTED_MESSAGE);
644b51494a2Sjsing 			return -1;
645b51494a2Sjsing 		}
646b51494a2Sjsing 
6476f7f653bSjsing 		if ((s->options & SSL_OP_NO_CLIENT_RENEGOTIATION) != 0) {
648b51494a2Sjsing 			ssl3_send_alert(s, SSL3_AL_FATAL,
649b51494a2Sjsing 			    SSL_AD_NO_RENEGOTIATION);
650b51494a2Sjsing 			return -1;
651b51494a2Sjsing 		}
652b51494a2Sjsing 
653*387303bbSjsing 		if (s->session == NULL || s->s3->hs.cipher == NULL) {
654b51494a2Sjsing 			SSLerror(s, ERR_R_INTERNAL_ERROR);
655b51494a2Sjsing 			return -1;
656b51494a2Sjsing 		}
657b51494a2Sjsing 
658b51494a2Sjsing 		/* Client requested renegotiation but it is not permitted. */
659b51494a2Sjsing 		if (!s->s3->send_connection_binding ||
660b51494a2Sjsing 		    (s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) != 0) {
661b51494a2Sjsing 			ssl3_send_alert(s, SSL3_AL_WARNING,
662b51494a2Sjsing 			    SSL_AD_NO_RENEGOTIATION);
663225d6b92Sjsing 			return 1;
664225d6b92Sjsing 		}
665225d6b92Sjsing 
666b51494a2Sjsing 		s->s3->hs.state = SSL_ST_ACCEPT;
6676f7f653bSjsing 		s->renegotiate = 1;
6686f7f653bSjsing 		s->new_session = 1;
669b51494a2Sjsing 
670b51494a2Sjsing 	} else if (hs_msg_hdr.type == SSL3_MT_FINISHED && s->server) {
671b51494a2Sjsing 		/*
672b51494a2Sjsing 		 * If we are server, we may have a repeated FINISHED of the
673b51494a2Sjsing 		 * client here, then retransmit our CCS and FINISHED.
674b51494a2Sjsing 		 */
675b51494a2Sjsing 		if (dtls1_check_timeout_num(s) < 0)
676b51494a2Sjsing 			return -1;
677b51494a2Sjsing 
678b51494a2Sjsing 		/* XXX - should this be calling ssl_msg_callback()? */
679b51494a2Sjsing 
680b51494a2Sjsing 		dtls1_retransmit_buffered_messages(s);
681b51494a2Sjsing 
682ee4250f6Sjsing 		tls_content_clear(s->s3->rcontent);
683ee4250f6Sjsing 		s->s3->rrec.length = 0;
684b51494a2Sjsing 
685b51494a2Sjsing 		return 1;
686b51494a2Sjsing 
687b51494a2Sjsing 	} else {
688b51494a2Sjsing 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
689b51494a2Sjsing 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
690b51494a2Sjsing 		return -1;
691225d6b92Sjsing 	}
692b51494a2Sjsing 
6936f7f653bSjsing 	if ((ret = s->handshake_func(s)) < 0)
694b51494a2Sjsing 		return ret;
695b51494a2Sjsing 	if (ret == 0) {
696225d6b92Sjsing 		SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
697b51494a2Sjsing 		return -1;
698225d6b92Sjsing 	}
699225d6b92Sjsing 
7006f7f653bSjsing 	if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
701225d6b92Sjsing 		if (s->s3->rbuf.left == 0) {
702225d6b92Sjsing 			ssl_force_want_read(s);
703b51494a2Sjsing 			return -1;
704225d6b92Sjsing 		}
705225d6b92Sjsing 	}
706225d6b92Sjsing 
707b51494a2Sjsing 	/*
708b51494a2Sjsing 	 * We either finished a handshake or ignored the request, now try again
709b51494a2Sjsing 	 * to obtain the (application) data we were asked for.
710b51494a2Sjsing 	 */
711225d6b92Sjsing 	return 1;
712225d6b92Sjsing }
713225d6b92Sjsing 
7145650a0e1Sdjm /* Return up to 'len' payload bytes received in 'type' records.
7155650a0e1Sdjm  * 'type' is one of the following:
7165650a0e1Sdjm  *
7175650a0e1Sdjm  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
7185650a0e1Sdjm  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
7195650a0e1Sdjm  *   -  0 (during a shutdown, no data has to be returned)
7205650a0e1Sdjm  *
7215650a0e1Sdjm  * If we don't have stored data to work from, read a SSL/TLS record first
7225650a0e1Sdjm  * (possibly multiple records if we still don't have anything to return).
7235650a0e1Sdjm  *
7245650a0e1Sdjm  * This function must handle any surprises the peer may have for us, such as
7255650a0e1Sdjm  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
7265650a0e1Sdjm  * a surprise, but handled as if it were), or renegotiation requests.
7275650a0e1Sdjm  * Also if record payloads contain fragments too small to process, we store
7285650a0e1Sdjm  * them until there is enough for the respective protocol (the record protocol
7295650a0e1Sdjm  * may use arbitrary fragmentation and even interleaving):
7305650a0e1Sdjm  *     Change cipher spec protocol
7315650a0e1Sdjm  *             just 1 byte needed, no need for keeping anything stored
7325650a0e1Sdjm  *     Alert protocol
7335650a0e1Sdjm  *             2 bytes needed (AlertLevel, AlertDescription)
7345650a0e1Sdjm  *     Handshake protocol
7355650a0e1Sdjm  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
7365650a0e1Sdjm  *             to detect unexpected Client Hello and Hello Request messages
7375650a0e1Sdjm  *             here, anything else is handled by higher layers
7385650a0e1Sdjm  *     Application data protocol
7395650a0e1Sdjm  *             none of our business
7405650a0e1Sdjm  */
7414a47b859Sjsing int
7424a47b859Sjsing dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
7435650a0e1Sdjm {
744c2712b29Sjsing 	int rrcount = 0;
745ee4250f6Sjsing 	ssize_t ssret;
746824388bbSjsing 	int ret;
7475650a0e1Sdjm 
748824388bbSjsing 	if (s->s3->rbuf.buf == NULL) {
7495650a0e1Sdjm 		if (!ssl3_setup_buffers(s))
750824388bbSjsing 			return -1;
751824388bbSjsing 	}
7525650a0e1Sdjm 
753ee4250f6Sjsing 	if (s->s3->rcontent == NULL) {
754ee4250f6Sjsing 		if ((s->s3->rcontent = tls_content_new()) == NULL)
755ee4250f6Sjsing 			return -1;
756ee4250f6Sjsing 	}
757ee4250f6Sjsing 
758824388bbSjsing 	if (len < 0) {
759c9d7abb7Sbeck 		SSLerror(s, ERR_R_INTERNAL_ERROR);
7605650a0e1Sdjm 		return -1;
7615650a0e1Sdjm 	}
7625650a0e1Sdjm 
763824388bbSjsing 	if (type != 0 && type != SSL3_RT_APPLICATION_DATA &&
764824388bbSjsing 	    type != SSL3_RT_HANDSHAKE) {
765824388bbSjsing 		SSLerror(s, ERR_R_INTERNAL_ERROR);
766824388bbSjsing 		return -1;
767824388bbSjsing 	}
768824388bbSjsing 	if (peek && type != SSL3_RT_APPLICATION_DATA) {
769824388bbSjsing 		SSLerror(s, ERR_R_INTERNAL_ERROR);
770824388bbSjsing 		return -1;
771824388bbSjsing 	}
772824388bbSjsing 
7736f7f653bSjsing 	if (SSL_in_init(s) && !s->in_handshake) {
7746f7f653bSjsing 		if ((ret = s->handshake_func(s)) < 0)
775824388bbSjsing 			return ret;
776824388bbSjsing 		if (ret == 0) {
777c9d7abb7Sbeck 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
778824388bbSjsing 			return -1;
7795650a0e1Sdjm 		}
7805650a0e1Sdjm 	}
7815650a0e1Sdjm 
7825650a0e1Sdjm  start:
783c2712b29Sjsing 	/*
784c2712b29Sjsing 	 * Do not process more than three consecutive records, otherwise the
785c2712b29Sjsing 	 * peer can cause us to loop indefinitely. Instead, return with an
786c2712b29Sjsing 	 * SSL_ERROR_WANT_READ so the caller can choose when to handle further
787c2712b29Sjsing 	 * processing. In the future, the total number of non-handshake and
788c2712b29Sjsing 	 * non-application data records per connection should probably also be
789c2712b29Sjsing 	 * limited...
790c2712b29Sjsing 	 */
791c2712b29Sjsing 	if (rrcount++ >= 3) {
792c2712b29Sjsing 		ssl_force_want_read(s);
793c2712b29Sjsing 		return -1;
794c2712b29Sjsing 	}
795c2712b29Sjsing 
7966f7f653bSjsing 	s->rwstate = SSL_NOTHING;
7975650a0e1Sdjm 
798824388bbSjsing 	/*
799824388bbSjsing 	 * We are not handshaking and have no data yet, so process data buffered
800824388bbSjsing 	 * during the last handshake in advance, if any.
8010a5d6edeSdjm 	 */
802ee4250f6Sjsing 	if (s->s3->hs.state == SSL_ST_OK &&
803ee4250f6Sjsing 	    tls_content_remaining(s->s3->rcontent) == 0)
804ee4250f6Sjsing 		dtls1_retrieve_buffered_rcontent(s, &s->d1->buffered_app_data);
8050a5d6edeSdjm 
8060a5d6edeSdjm 	if (dtls1_handle_timeout(s) > 0)
8070a5d6edeSdjm 		goto start;
8080a5d6edeSdjm 
809ee4250f6Sjsing 	if (tls_content_remaining(s->s3->rcontent) == 0) {
810824388bbSjsing 		if ((ret = dtls1_get_record(s)) <= 0) {
811824388bbSjsing 			/* Anything other than a timeout is an error. */
812824388bbSjsing 			if ((ret = dtls1_read_failed(s, ret)) <= 0)
813824388bbSjsing 				return ret;
8145650a0e1Sdjm 			goto start;
8155650a0e1Sdjm 		}
8165650a0e1Sdjm 	}
8175650a0e1Sdjm 
818ee4250f6Sjsing 	if (s->d1->listen &&
819ee4250f6Sjsing 	    tls_content_type(s->s3->rcontent) != SSL3_RT_HANDSHAKE) {
820ee4250f6Sjsing 		tls_content_clear(s->s3->rcontent);
821ee4250f6Sjsing 		s->s3->rrec.length = 0;
82297222eddSmiod 		goto start;
82397222eddSmiod 	}
82497222eddSmiod 
825824388bbSjsing 	/* We now have a packet which can be read and processed. */
8265650a0e1Sdjm 
827ee4250f6Sjsing 	if (s->s3->change_cipher_spec &&
828ee4250f6Sjsing 	    tls_content_type(s->s3->rcontent) != SSL3_RT_HANDSHAKE) {
829824388bbSjsing 		/*
830824388bbSjsing 		 * We now have application data between CCS and Finished.
8310a5d6edeSdjm 		 * Most likely the packets were reordered on their way, so
8320a5d6edeSdjm 		 * buffer the application data for later processing rather
8330a5d6edeSdjm 		 * than dropping the connection.
8340a5d6edeSdjm 		 */
835ee4250f6Sjsing 		if (dtls1_buffer_rcontent(s, &s->d1->buffered_app_data,
836ee4250f6Sjsing 		    s->s3->rrec.seq_num) < 0) {
837c9d7abb7Sbeck 			SSLerror(s, ERR_R_INTERNAL_ERROR);
8383221bfb8Sdoug 			return (-1);
8393221bfb8Sdoug 		}
840ee4250f6Sjsing 		tls_content_clear(s->s3->rcontent);
841ee4250f6Sjsing 		s->s3->rrec.length = 0;
8420a5d6edeSdjm 		goto start;
8435650a0e1Sdjm 	}
8445650a0e1Sdjm 
845824388bbSjsing 	/*
846824388bbSjsing 	 * If the other end has shut down, throw anything we read away (even in
847824388bbSjsing 	 * 'peek' mode).
848824388bbSjsing 	 */
8496f7f653bSjsing 	if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
8506f7f653bSjsing 		s->rwstate = SSL_NOTHING;
851ee4250f6Sjsing 		tls_content_clear(s->s3->rcontent);
852ee4250f6Sjsing 		s->s3->rrec.length = 0;
853824388bbSjsing 		return 0;
8545650a0e1Sdjm 	}
8555650a0e1Sdjm 
8561365e68cSjsing 	/* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
857ee4250f6Sjsing 	if (tls_content_type(s->s3->rcontent) == type) {
858824388bbSjsing 		/*
859824388bbSjsing 		 * Make sure that we are not getting application data when we
860824388bbSjsing 		 * are doing a handshake for the first time.
861824388bbSjsing 		 */
8621365e68cSjsing 		if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
8636f7f653bSjsing 		    !tls12_record_layer_read_protected(s->rl)) {
864c9d7abb7Sbeck 			SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
865824388bbSjsing 			ssl3_send_alert(s, SSL3_AL_FATAL,
866824388bbSjsing 			    SSL_AD_UNEXPECTED_MESSAGE);
867824388bbSjsing 			return -1;
8685650a0e1Sdjm 		}
8695650a0e1Sdjm 
8704a47b859Sjsing 		if (len <= 0)
871824388bbSjsing 			return len;
8725650a0e1Sdjm 
873ee4250f6Sjsing 		if (peek) {
874ee4250f6Sjsing 			ssret = tls_content_peek(s->s3->rcontent, buf, len);
875ee4250f6Sjsing 		} else {
876ee4250f6Sjsing 			ssret = tls_content_read(s->s3->rcontent, buf, len);
877ee4250f6Sjsing 		}
878ee4250f6Sjsing 		if (ssret < INT_MIN || ssret > INT_MAX)
879ee4250f6Sjsing 			return -1;
880ee4250f6Sjsing 		if (ssret < 0)
881ee4250f6Sjsing 			return (int)ssret;
8825650a0e1Sdjm 
883ee4250f6Sjsing 		if (tls_content_remaining(s->s3->rcontent) == 0)
8846f7f653bSjsing 			s->rstate = SSL_ST_READ_HEADER;
885ee4250f6Sjsing 
886ee4250f6Sjsing 		return (int)ssret;
8875650a0e1Sdjm 	}
8885cdd308eSdjm 
889ee4250f6Sjsing 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_ALERT) {
89056fd52a7Sjsing 		if ((ret = ssl3_read_alert(s)) <= 0)
89156fd52a7Sjsing 			return ret;
8925650a0e1Sdjm 		goto start;
8935650a0e1Sdjm 	}
8945650a0e1Sdjm 
8956f7f653bSjsing 	if (s->shutdown & SSL_SENT_SHUTDOWN) {
8966f7f653bSjsing 		s->rwstate = SSL_NOTHING;
897ee4250f6Sjsing 		tls_content_clear(s->s3->rcontent);
898ee4250f6Sjsing 		s->s3->rrec.length = 0;
8995650a0e1Sdjm 		return (0);
9005650a0e1Sdjm 	}
9015650a0e1Sdjm 
902ee4250f6Sjsing 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_APPLICATION_DATA) {
903824388bbSjsing 		/*
904824388bbSjsing 		 * At this point, we were expecting handshake data, but have
905824388bbSjsing 		 * application data. If the library was running inside
906824388bbSjsing 		 * ssl3_read() (i.e. in_read_app_data is set) and it makes
907824388bbSjsing 		 * sense to read application data at this point (session
908824388bbSjsing 		 * renegotiation not yet started), we will indulge it.
909824388bbSjsing 		 */
910824388bbSjsing 		if (s->s3->in_read_app_data != 0 &&
911824388bbSjsing 		    s->s3->total_renegotiations != 0 &&
912824388bbSjsing 		    (((s->s3->hs.state & SSL_ST_CONNECT) &&
913824388bbSjsing 		    (s->s3->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
914824388bbSjsing 		    (s->s3->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
915824388bbSjsing 		    (s->s3->hs.state & SSL_ST_ACCEPT) &&
916824388bbSjsing 		    (s->s3->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
917824388bbSjsing 		    (s->s3->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
918824388bbSjsing 			s->s3->in_read_app_data = 2;
919824388bbSjsing 			return -1;
920824388bbSjsing 		} else {
921824388bbSjsing 			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
922824388bbSjsing 			ssl3_send_alert(s, SSL3_AL_FATAL,
923824388bbSjsing 			    SSL_AD_UNEXPECTED_MESSAGE);
924824388bbSjsing 			return -1;
925824388bbSjsing 		}
926824388bbSjsing 	}
927824388bbSjsing 
928ee4250f6Sjsing 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_CHANGE_CIPHER_SPEC) {
929b23067a6Sjsing 		if ((ret = ssl3_read_change_cipher_spec(s)) <= 0)
930b23067a6Sjsing 			return ret;
9315650a0e1Sdjm 		goto start;
9325650a0e1Sdjm 	}
9335650a0e1Sdjm 
934ee4250f6Sjsing 	if (tls_content_type(s->s3->rcontent) == SSL3_RT_HANDSHAKE) {
935225d6b92Sjsing 		if ((ret = dtls1_read_handshake_unexpected(s)) <= 0)
936225d6b92Sjsing 			return ret;
9375650a0e1Sdjm 		goto start;
9385650a0e1Sdjm 	}
9395650a0e1Sdjm 
940824388bbSjsing 	/* Unknown record type. */
941c9d7abb7Sbeck 	SSLerror(s, SSL_R_UNEXPECTED_RECORD);
942824388bbSjsing 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
943824388bbSjsing 	return -1;
9445650a0e1Sdjm }
9455650a0e1Sdjm 
9465650a0e1Sdjm int
9475650a0e1Sdjm dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
9485650a0e1Sdjm {
9495650a0e1Sdjm 	int i;
9505650a0e1Sdjm 
951ee4250f6Sjsing 	if (SSL_in_init(s) && !s->in_handshake) {
9526f7f653bSjsing 		i = s->handshake_func(s);
9534a47b859Sjsing 		if (i < 0)
9544a47b859Sjsing 			return (i);
9554a47b859Sjsing 		if (i == 0) {
956c9d7abb7Sbeck 			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
9575650a0e1Sdjm 			return -1;
9585650a0e1Sdjm 		}
9595650a0e1Sdjm 	}
9605650a0e1Sdjm 
9614a47b859Sjsing 	if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
962c9d7abb7Sbeck 		SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
9630a5d6edeSdjm 		return -1;
9640a5d6edeSdjm 	}
9650a5d6edeSdjm 
9665650a0e1Sdjm 	i = dtls1_write_bytes(s, type, buf_, len);
9670a5d6edeSdjm 	return i;
9685650a0e1Sdjm }
9695650a0e1Sdjm 
9705650a0e1Sdjm /* Call this to write data in records of type 'type'
9715650a0e1Sdjm  * It will return <= 0 if not all data has been sent or non-blocking IO.
9725650a0e1Sdjm  */
9734a47b859Sjsing int
9744a47b859Sjsing dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
9755650a0e1Sdjm {
9765650a0e1Sdjm 	int i;
9775650a0e1Sdjm 
9780a5d6edeSdjm 	OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
9796f7f653bSjsing 	s->rwstate = SSL_NOTHING;
980b47e8ef9Sjsing 	i = do_dtls1_write(s, type, buf, len);
9818214bb00Sdjm 	return i;
9825650a0e1Sdjm }
9835650a0e1Sdjm 
9844a47b859Sjsing int
985b47e8ef9Sjsing do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
9865650a0e1Sdjm {
98702876cc3Sjsing 	SSL3_BUFFER_INTERNAL *wb = &(s->s3->wbuf);
988d6d3cb6fSjsing 	size_t out_len;
989acef91a0Sjsing 	CBB cbb;
99054356378Sjsing 	int ret;
99191a6bd55Sjsing 
99291a6bd55Sjsing 	memset(&cbb, 0, sizeof(cbb));
9935650a0e1Sdjm 
99418691bb1Sjsing 	/*
99518691bb1Sjsing 	 * First check if there is a SSL3_BUFFER_INTERNAL still being written
99618691bb1Sjsing 	 * out.  This will happen with non blocking IO.
99718691bb1Sjsing 	 */
99854356378Sjsing 	if (wb->left != 0) {
9995650a0e1Sdjm 		OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
10005650a0e1Sdjm 		return (ssl3_write_pending(s, type, buf, len));
10015650a0e1Sdjm 	}
10025650a0e1Sdjm 
100318691bb1Sjsing 	/* If we have an alert to send, let's send it */
100402876cc3Sjsing 	if (s->s3->alert_dispatch) {
1005e3dbb073Sjsing 		if ((ret = ssl3_dispatch_alert(s)) <= 0)
100618691bb1Sjsing 			return (ret);
100718691bb1Sjsing 		/* If it went, fall through and send more stuff. */
10085650a0e1Sdjm 	}
10095650a0e1Sdjm 
1010b47e8ef9Sjsing 	if (len == 0)
10115650a0e1Sdjm 		return 0;
10125650a0e1Sdjm 
1013d6d3cb6fSjsing 	wb->offset = 0;
1014d6d3cb6fSjsing 
1015d6d3cb6fSjsing 	if (!CBB_init_fixed(&cbb, wb->buf, wb->len))
1016d6d3cb6fSjsing 		goto err;
1017d6d3cb6fSjsing 
10186f7f653bSjsing 	tls12_record_layer_set_version(s->rl, s->version);
1019d6d3cb6fSjsing 
10206f7f653bSjsing 	if (!tls12_record_layer_seal_record(s->rl, type, buf, len, &cbb))
102191a6bd55Sjsing 		goto err;
1022d6d3cb6fSjsing 
1023d6d3cb6fSjsing 	if (!CBB_finish(&cbb, NULL, &out_len))
102491a6bd55Sjsing 		goto err;
10255650a0e1Sdjm 
1026d6d3cb6fSjsing 	wb->left = out_len;
1027d6d3cb6fSjsing 
102854356378Sjsing 	/*
102954356378Sjsing 	 * Memorize arguments so that ssl3_write_pending can detect
103054356378Sjsing 	 * bad write retries later.
103154356378Sjsing 	 */
103202876cc3Sjsing 	s->s3->wpend_tot = len;
103302876cc3Sjsing 	s->s3->wpend_buf = buf;
103402876cc3Sjsing 	s->s3->wpend_type = type;
103502876cc3Sjsing 	s->s3->wpend_ret = len;
10365650a0e1Sdjm 
103754356378Sjsing 	/* We now just need to write the buffer. */
10385650a0e1Sdjm 	return ssl3_write_pending(s, type, buf, len);
103991a6bd55Sjsing 
10405650a0e1Sdjm  err:
104191a6bd55Sjsing 	CBB_cleanup(&cbb);
104291a6bd55Sjsing 
10435650a0e1Sdjm 	return -1;
10445650a0e1Sdjm }
10455650a0e1Sdjm 
10464a47b859Sjsing static int
104717b41dffSjsing dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap,
104817b41dffSjsing     const unsigned char *seq)
10495650a0e1Sdjm {
10500a5d6edeSdjm 	unsigned int shift;
105117b41dffSjsing 	int cmp;
10525650a0e1Sdjm 
10530a5d6edeSdjm 	cmp = satsub64be(seq, bitmap->max_seq_num);
105417b41dffSjsing 	if (cmp > 0)
10550a5d6edeSdjm 		return 1; /* this record in new */
10560a5d6edeSdjm 	shift = -cmp;
10570a5d6edeSdjm 	if (shift >= sizeof(bitmap->map)*8)
10585650a0e1Sdjm 		return 0; /* stale, outside the window */
10590a5d6edeSdjm 	else if (bitmap->map & (1UL << shift))
10605650a0e1Sdjm 		return 0; /* record previously received */
10615650a0e1Sdjm 
10625650a0e1Sdjm 	return 1;
10635650a0e1Sdjm }
10645650a0e1Sdjm 
10654a47b859Sjsing static void
106617b41dffSjsing dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap,
106717b41dffSjsing     const unsigned char *seq)
10685650a0e1Sdjm {
10695650a0e1Sdjm 	unsigned int shift;
107017b41dffSjsing 	int cmp;
10715650a0e1Sdjm 
10720a5d6edeSdjm 	cmp = satsub64be(seq, bitmap->max_seq_num);
10734a47b859Sjsing 	if (cmp > 0) {
10740a5d6edeSdjm 		shift = cmp;
10750a5d6edeSdjm 		if (shift < sizeof(bitmap->map)*8)
10760a5d6edeSdjm 			bitmap->map <<= shift, bitmap->map |= 1UL;
10775650a0e1Sdjm 		else
10780a5d6edeSdjm 			bitmap->map = 1UL;
10790a5d6edeSdjm 		memcpy(bitmap->max_seq_num, seq, 8);
10804a47b859Sjsing 	} else {
10810a5d6edeSdjm 		shift = -cmp;
10820a5d6edeSdjm 		if (shift < sizeof(bitmap->map) * 8)
10830a5d6edeSdjm 			bitmap->map |= 1UL << shift;
10840a5d6edeSdjm 	}
10855650a0e1Sdjm }
10865650a0e1Sdjm 
10875650a0e1Sdjm static DTLS1_BITMAP *
10886182911eSjsing dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr, unsigned int *is_next_epoch)
10895650a0e1Sdjm {
109044aae0c1Sjsing 	uint16_t read_epoch, read_epoch_next;
10915650a0e1Sdjm 
10925650a0e1Sdjm 	*is_next_epoch = 0;
10935650a0e1Sdjm 
10946f7f653bSjsing 	read_epoch = tls12_record_layer_read_epoch(s->rl);
109544aae0c1Sjsing 	read_epoch_next = read_epoch + 1;
109644aae0c1Sjsing 
10975650a0e1Sdjm 	/* In current epoch, accept HM, CCS, DATA, & ALERT */
109844aae0c1Sjsing 	if (rr->epoch == read_epoch)
1099f19d9718Sjsing 		return &s->d1->bitmap;
11005650a0e1Sdjm 
11015650a0e1Sdjm 	/* Only HM and ALERT messages can be from the next epoch */
110244aae0c1Sjsing 	if (rr->epoch == read_epoch_next &&
11034a47b859Sjsing 	    (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
11045650a0e1Sdjm 		*is_next_epoch = 1;
1105f19d9718Sjsing 		return &s->d1->next_bitmap;
11065650a0e1Sdjm 	}
11075650a0e1Sdjm 
11085650a0e1Sdjm 	return NULL;
11095650a0e1Sdjm }
11105650a0e1Sdjm 
11115650a0e1Sdjm void
11128950dd79Sjsing dtls1_reset_read_seq_numbers(SSL *s)
11135650a0e1Sdjm {
1114f19d9718Sjsing 	memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
1115f19d9718Sjsing 	memset(&(s->d1->next_bitmap), 0, sizeof(DTLS1_BITMAP));
11168950dd79Sjsing }
1117