xref: /dragonfly/crypto/libressl/ssl/d1_both.c (revision 8edacedf)
1 /* $OpenBSD: d1_both.c,v 1.60 2020/09/26 14:43:17 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 <limits.h>
117 #include <stdio.h>
118 #include <string.h>
119 
120 #include "ssl_locl.h"
121 
122 #include <openssl/buffer.h>
123 #include <openssl/evp.h>
124 #include <openssl/objects.h>
125 #include <openssl/x509.h>
126 
127 #include "pqueue.h"
128 #include "bytestring.h"
129 
130 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
131 
132 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
133 			if ((end) - (start) <= 8) { \
134 				long ii; \
135 				for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
136 			} else { \
137 				long ii; \
138 				bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
139 				for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
140 				bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
141 			} }
142 
143 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
144 			long ii; \
145 			OPENSSL_assert((msg_len) > 0); \
146 			is_complete = 1; \
147 			if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
148 			if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
149 				if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
150 
151 static unsigned char bitmask_start_values[] = {
152 	0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80
153 };
154 static unsigned char bitmask_end_values[] = {
155 	0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f
156 };
157 
158 /* XDTLS:  figure out the right values */
159 static unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28};
160 
161 static unsigned int dtls1_guess_mtu(unsigned int curr_mtu);
162 static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
163     unsigned long frag_len);
164 static int dtls1_write_message_header(const struct hm_header_st *msg_hdr,
165     unsigned long frag_off, unsigned long frag_len, unsigned char *p);
166 static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max,
167     int *ok);
168 
169 void dtls1_hm_fragment_free(hm_fragment *frag);
170 
171 static hm_fragment *
172 dtls1_hm_fragment_new(unsigned long frag_len, int reassembly)
173 {
174 	hm_fragment *frag;
175 
176 	if ((frag = calloc(1, sizeof(*frag))) == NULL)
177 		goto err;
178 
179 	if (frag_len > 0) {
180 		if ((frag->fragment = calloc(1, frag_len)) == NULL)
181 			goto err;
182 	}
183 
184 	/* Initialize reassembly bitmask if necessary. */
185 	if (reassembly) {
186 		if ((frag->reassembly = calloc(1,
187 		    RSMBLY_BITMASK_SIZE(frag_len))) == NULL)
188 			goto err;
189 	}
190 
191 	return frag;
192 
193  err:
194 	dtls1_hm_fragment_free(frag);
195 	return NULL;
196 }
197 
198 void
199 dtls1_hm_fragment_free(hm_fragment *frag)
200 {
201 	if (frag == NULL)
202 		return;
203 
204 	if (frag->msg_header.is_ccs) {
205 		EVP_CIPHER_CTX_free(
206 		    frag->msg_header.saved_retransmit_state.enc_write_ctx);
207 		EVP_MD_CTX_free(
208 		    frag->msg_header.saved_retransmit_state.write_hash);
209 	}
210 	free(frag->fragment);
211 	free(frag->reassembly);
212 	free(frag);
213 }
214 
215 /* send s->internal->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
216 int
217 dtls1_do_write(SSL *s, int type)
218 {
219 	int ret;
220 	int curr_mtu;
221 	unsigned int len, frag_off, mac_size, blocksize;
222 
223 	/* AHA!  Figure out the MTU, and stick to the right size */
224 	if (D1I(s)->mtu < dtls1_min_mtu() &&
225 	    !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
226 		D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s),
227 		    BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
228 
229 		/*
230 		 * I've seen the kernel return bogus numbers when it
231 		 * doesn't know the MTU (ie., the initial write), so just
232 		 * make sure we have a reasonable number
233 		 */
234 		if (D1I(s)->mtu < dtls1_min_mtu()) {
235 			D1I(s)->mtu = 0;
236 			D1I(s)->mtu = dtls1_guess_mtu(D1I(s)->mtu);
237 			BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
238 			    D1I(s)->mtu, NULL);
239 		}
240 	}
241 
242 	OPENSSL_assert(D1I(s)->mtu >= dtls1_min_mtu());
243 	/* should have something reasonable now */
244 
245 	if (s->internal->init_off == 0  && type == SSL3_RT_HANDSHAKE)
246 		OPENSSL_assert(s->internal->init_num ==
247 		    (int)D1I(s)->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
248 
249 	if (s->internal->write_hash)
250 		mac_size = EVP_MD_CTX_size(s->internal->write_hash);
251 	else
252 		mac_size = 0;
253 
254 	if (s->internal->enc_write_ctx &&
255 	    (EVP_CIPHER_mode( s->internal->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
256 		blocksize = 2 * EVP_CIPHER_block_size(s->internal->enc_write_ctx->cipher);
257 	else
258 		blocksize = 0;
259 
260 	frag_off = 0;
261 	while (s->internal->init_num) {
262 		curr_mtu = D1I(s)->mtu - BIO_wpending(SSL_get_wbio(s)) -
263 		    DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
264 
265 		if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
266 			/* grr.. we could get an error if MTU picked was wrong */
267 			ret = BIO_flush(SSL_get_wbio(s));
268 			if (ret <= 0)
269 				return ret;
270 			curr_mtu = D1I(s)->mtu - DTLS1_RT_HEADER_LENGTH -
271 			    mac_size - blocksize;
272 		}
273 
274 		if (s->internal->init_num > curr_mtu)
275 			len = curr_mtu;
276 		else
277 			len = s->internal->init_num;
278 
279 
280 		/* XDTLS: this function is too long.  split out the CCS part */
281 		if (type == SSL3_RT_HANDSHAKE) {
282 			if (s->internal->init_off != 0) {
283 				OPENSSL_assert(s->internal->init_off > DTLS1_HM_HEADER_LENGTH);
284 				s->internal->init_off -= DTLS1_HM_HEADER_LENGTH;
285 				s->internal->init_num += DTLS1_HM_HEADER_LENGTH;
286 
287 				if (s->internal->init_num > curr_mtu)
288 					len = curr_mtu;
289 				else
290 					len = s->internal->init_num;
291 			}
292 
293 			dtls1_fix_message_header(s, frag_off,
294 			    len - DTLS1_HM_HEADER_LENGTH);
295 
296 			if (!dtls1_write_message_header(&D1I(s)->w_msg_hdr,
297 			    D1I(s)->w_msg_hdr.frag_off, D1I(s)->w_msg_hdr.frag_len,
298 			    (unsigned char *)&s->internal->init_buf->data[s->internal->init_off]))
299 				return -1;
300 
301 			OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
302 		}
303 
304 		ret = dtls1_write_bytes(s, type,
305 		    &s->internal->init_buf->data[s->internal->init_off], len);
306 		if (ret < 0) {
307 			/*
308 			 * Might need to update MTU here, but we don't know
309 			 * which previous packet caused the failure -- so
310 			 * can't really retransmit anything.  continue as
311 			 * if everything is fine and wait for an alert to
312 			 * handle the retransmit
313 			 */
314 			if (BIO_ctrl(SSL_get_wbio(s),
315 			    BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0)
316 				D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s),
317 				    BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
318 			else
319 				return (-1);
320 		} else {
321 
322 			/*
323 			 * Bad if this assert fails, only part of the
324 			 * handshake message got sent.  but why would
325 			 * this happen?
326 			 */
327 			OPENSSL_assert(len == (unsigned int)ret);
328 
329 			if (type == SSL3_RT_HANDSHAKE &&
330 			    !D1I(s)->retransmitting) {
331 				/*
332 				 * Should not be done for 'Hello Request's,
333 				 * but in that case we'll ignore the result
334 				 * anyway
335 				 */
336 				unsigned char *p = (unsigned char *)&s->internal->init_buf->data[s->internal->init_off];
337 				const struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
338 				int xlen;
339 
340 				if (frag_off == 0) {
341 					/*
342 					 * Reconstruct message header is if it
343 					 * is being sent in single fragment
344 					 */
345 					if (!dtls1_write_message_header(msg_hdr,
346 					    0, msg_hdr->msg_len, p))
347 						return (-1);
348 					xlen = ret;
349 				} else {
350 					p += DTLS1_HM_HEADER_LENGTH;
351 					xlen = ret - DTLS1_HM_HEADER_LENGTH;
352 				}
353 
354 				tls1_transcript_record(s, p, xlen);
355 			}
356 
357 			if (ret == s->internal->init_num) {
358 				if (s->internal->msg_callback)
359 					s->internal->msg_callback(1, s->version, type,
360 					    s->internal->init_buf->data,
361 					    (size_t)(s->internal->init_off + s->internal->init_num),
362 					    s, s->internal->msg_callback_arg);
363 
364 				s->internal->init_off = 0;
365 				/* done writing this message */
366 				s->internal->init_num = 0;
367 
368 				return (1);
369 			}
370 			s->internal->init_off += ret;
371 			s->internal->init_num -= ret;
372 			frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
373 		}
374 	}
375 	return (0);
376 }
377 
378 
379 /*
380  * Obtain handshake message of message type 'mt' (any if mt == -1),
381  * maximum acceptable body length 'max'.
382  * Read an entire handshake message.  Handshake messages arrive in
383  * fragments.
384  */
385 long
386 dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
387 {
388 	int i, al;
389 	struct hm_header_st *msg_hdr;
390 	unsigned char *p;
391 	unsigned long msg_len;
392 
393 	/*
394 	 * s3->internal->tmp is used to store messages that are unexpected, caused
395 	 * by the absence of an optional handshake message
396 	 */
397 	if (S3I(s)->tmp.reuse_message) {
398 		S3I(s)->tmp.reuse_message = 0;
399 		if ((mt >= 0) && (S3I(s)->tmp.message_type != mt)) {
400 			al = SSL_AD_UNEXPECTED_MESSAGE;
401 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
402 			goto f_err;
403 		}
404 		*ok = 1;
405 		s->internal->init_msg = s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
406 		s->internal->init_num = (int)S3I(s)->tmp.message_size;
407 		return s->internal->init_num;
408 	}
409 
410 	msg_hdr = &D1I(s)->r_msg_hdr;
411 	memset(msg_hdr, 0, sizeof(struct hm_header_st));
412 
413 again:
414 	i = dtls1_get_message_fragment(s, st1, stn, max, ok);
415 	if (i == DTLS1_HM_BAD_FRAGMENT ||
416 	    i == DTLS1_HM_FRAGMENT_RETRY)  /* bad fragment received */
417 		goto again;
418 	else if (i <= 0 && !*ok)
419 		return i;
420 
421 	p = (unsigned char *)s->internal->init_buf->data;
422 	msg_len = msg_hdr->msg_len;
423 
424 	/* reconstruct message header */
425 	if (!dtls1_write_message_header(msg_hdr, 0, msg_len, p))
426 		return -1;
427 
428 	msg_len += DTLS1_HM_HEADER_LENGTH;
429 
430 	tls1_transcript_record(s, p, msg_len);
431 	if (s->internal->msg_callback)
432 		s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, msg_len,
433 		    s, s->internal->msg_callback_arg);
434 
435 	memset(msg_hdr, 0, sizeof(struct hm_header_st));
436 
437 	/* Don't change sequence numbers while listening */
438 	if (!D1I(s)->listen)
439 		D1I(s)->handshake_read_seq++;
440 
441 	s->internal->init_msg = s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
442 	return s->internal->init_num;
443 
444 f_err:
445 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
446 	*ok = 0;
447 	return -1;
448 }
449 
450 
451 static int
452 dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr, int max)
453 {
454 	size_t frag_off, frag_len, msg_len;
455 
456 	msg_len = msg_hdr->msg_len;
457 	frag_off = msg_hdr->frag_off;
458 	frag_len = msg_hdr->frag_len;
459 
460 	/* sanity checking */
461 	if ((frag_off + frag_len) > msg_len) {
462 		SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
463 		return SSL_AD_ILLEGAL_PARAMETER;
464 	}
465 
466 	if ((frag_off + frag_len) > (unsigned long)max) {
467 		SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
468 		return SSL_AD_ILLEGAL_PARAMETER;
469 	}
470 
471 	if ( D1I(s)->r_msg_hdr.frag_off == 0) /* first fragment */
472 	{
473 		/*
474 		 * msg_len is limited to 2^24, but is effectively checked
475 		 * against max above
476 		 */
477 		if (!BUF_MEM_grow_clean(s->internal->init_buf,
478 		    msg_len + DTLS1_HM_HEADER_LENGTH)) {
479 			SSLerror(s, ERR_R_BUF_LIB);
480 			return SSL_AD_INTERNAL_ERROR;
481 		}
482 
483 		S3I(s)->tmp.message_size = msg_len;
484 		D1I(s)->r_msg_hdr.msg_len = msg_len;
485 		S3I(s)->tmp.message_type = msg_hdr->type;
486 		D1I(s)->r_msg_hdr.type = msg_hdr->type;
487 		D1I(s)->r_msg_hdr.seq = msg_hdr->seq;
488 	} else if (msg_len != D1I(s)->r_msg_hdr.msg_len) {
489 		/*
490 		 * They must be playing with us! BTW, failure to enforce
491 		 * upper limit would open possibility for buffer overrun.
492 		 */
493 		SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
494 		return SSL_AD_ILLEGAL_PARAMETER;
495 	}
496 
497 	return 0; /* no error */
498 }
499 
500 static int
501 dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
502 {
503 	/*
504 	 * (0) check whether the desired fragment is available
505 	 * if so:
506 	 * (1) copy over the fragment to s->internal->init_buf->data[]
507 	 * (2) update s->internal->init_num
508 	 */
509 	pitem *item;
510 	hm_fragment *frag;
511 	int al;
512 
513 	*ok = 0;
514 	item = pqueue_peek(D1I(s)->buffered_messages);
515 	if (item == NULL)
516 		return 0;
517 
518 	frag = (hm_fragment *)item->data;
519 
520 	/* Don't return if reassembly still in progress */
521 	if (frag->reassembly != NULL)
522 		return 0;
523 
524 	if (D1I(s)->handshake_read_seq == frag->msg_header.seq) {
525 		unsigned long frag_len = frag->msg_header.frag_len;
526 		pqueue_pop(D1I(s)->buffered_messages);
527 
528 		al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
529 
530 		if (al == 0) /* no alert */
531 		{
532 			unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
533 			memcpy(&p[frag->msg_header.frag_off],
534 			    frag->fragment, frag->msg_header.frag_len);
535 		}
536 
537 		dtls1_hm_fragment_free(frag);
538 		pitem_free(item);
539 
540 		if (al == 0) {
541 			*ok = 1;
542 			return frag_len;
543 		}
544 
545 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
546 		s->internal->init_num = 0;
547 		*ok = 0;
548 		return -1;
549 	} else
550 		return 0;
551 }
552 
553 /*
554  * dtls1_max_handshake_message_len returns the maximum number of bytes
555  * permitted in a DTLS handshake message for |s|. The minimum is 16KB,
556  * but may be greater if the maximum certificate list size requires it.
557  */
558 static unsigned long
559 dtls1_max_handshake_message_len(const SSL *s)
560 {
561 	unsigned long max_len;
562 
563 	max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
564 	if (max_len < (unsigned long)s->internal->max_cert_list)
565 		return s->internal->max_cert_list;
566 	return max_len;
567 }
568 
569 static int
570 dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
571 {
572 	hm_fragment *frag = NULL;
573 	pitem *item = NULL;
574 	int i = -1, is_complete;
575 	unsigned char seq64be[8];
576 	unsigned long frag_len = msg_hdr->frag_len;
577 
578 	if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
579 	    msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
580 		goto err;
581 
582 	if (frag_len == 0) {
583 		i = DTLS1_HM_FRAGMENT_RETRY;
584 		goto err;
585 	}
586 
587 	/* Try to find item in queue */
588 	memset(seq64be, 0, sizeof(seq64be));
589 	seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
590 	seq64be[7] = (unsigned char)msg_hdr->seq;
591 	item = pqueue_find(D1I(s)->buffered_messages, seq64be);
592 
593 	if (item == NULL) {
594 		frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
595 		if (frag == NULL)
596 			goto err;
597 		memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
598 		frag->msg_header.frag_len = frag->msg_header.msg_len;
599 		frag->msg_header.frag_off = 0;
600 	} else {
601 		frag = (hm_fragment*)item->data;
602 		if (frag->msg_header.msg_len != msg_hdr->msg_len) {
603 			item = NULL;
604 			frag = NULL;
605 			goto err;
606 		}
607 	}
608 
609 	/*
610 	 * If message is already reassembled, this must be a
611 	 * retransmit and can be dropped.
612 	 */
613 	if (frag->reassembly == NULL) {
614 		unsigned char devnull [256];
615 
616 		while (frag_len) {
617 			i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
618 			    devnull, frag_len > sizeof(devnull) ?
619 			    sizeof(devnull) : frag_len, 0);
620 			if (i <= 0)
621 				goto err;
622 			frag_len -= i;
623 		}
624 		i = DTLS1_HM_FRAGMENT_RETRY;
625 		goto err;
626 	}
627 
628 	/* read the body of the fragment (header has already been read */
629 	i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
630 	    frag->fragment + msg_hdr->frag_off, frag_len, 0);
631 	if (i <= 0 || (unsigned long)i != frag_len)
632 		goto err;
633 
634 	RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
635 	    (long)(msg_hdr->frag_off + frag_len));
636 
637 	RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
638 	    is_complete);
639 
640 	if (is_complete) {
641 		free(frag->reassembly);
642 		frag->reassembly = NULL;
643 	}
644 
645 	if (item == NULL) {
646 		memset(seq64be, 0, sizeof(seq64be));
647 		seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
648 		seq64be[7] = (unsigned char)(msg_hdr->seq);
649 
650 		item = pitem_new(seq64be, frag);
651 		if (item == NULL) {
652 			i = -1;
653 			goto err;
654 		}
655 
656 		pqueue_insert(D1I(s)->buffered_messages, item);
657 	}
658 
659 	return DTLS1_HM_FRAGMENT_RETRY;
660 
661 err:
662 	if (item == NULL && frag != NULL)
663 		dtls1_hm_fragment_free(frag);
664 	*ok = 0;
665 	return i;
666 }
667 
668 
669 static int
670 dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
671 {
672 	int i = -1;
673 	hm_fragment *frag = NULL;
674 	pitem *item = NULL;
675 	unsigned char seq64be[8];
676 	unsigned long frag_len = msg_hdr->frag_len;
677 
678 	if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
679 		goto err;
680 
681 	/* Try to find item in queue, to prevent duplicate entries */
682 	memset(seq64be, 0, sizeof(seq64be));
683 	seq64be[6] = (unsigned char) (msg_hdr->seq >> 8);
684 	seq64be[7] = (unsigned char) msg_hdr->seq;
685 	item = pqueue_find(D1I(s)->buffered_messages, seq64be);
686 
687 	/*
688 	 * If we already have an entry and this one is a fragment,
689 	 * don't discard it and rather try to reassemble it.
690 	 */
691 	if (item != NULL && frag_len < msg_hdr->msg_len)
692 		item = NULL;
693 
694 	/*
695 	 * Discard the message if sequence number was already there, is
696 	 * too far in the future, already in the queue or if we received
697 	 * a FINISHED before the SERVER_HELLO, which then must be a stale
698 	 * retransmit.
699 	 */
700 	if (msg_hdr->seq <= D1I(s)->handshake_read_seq ||
701 	    msg_hdr->seq > D1I(s)->handshake_read_seq + 10 || item != NULL ||
702 	    (D1I(s)->handshake_read_seq == 0 &&
703 	    msg_hdr->type == SSL3_MT_FINISHED)) {
704 		unsigned char devnull [256];
705 
706 		while (frag_len) {
707 			i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
708 			    devnull, frag_len > sizeof(devnull) ?
709 			    sizeof(devnull) : frag_len, 0);
710 			if (i <= 0)
711 				goto err;
712 			frag_len -= i;
713 		}
714 	} else {
715 		if (frag_len < msg_hdr->msg_len)
716 			return dtls1_reassemble_fragment(s, msg_hdr, ok);
717 
718 		if (frag_len > dtls1_max_handshake_message_len(s))
719 			goto err;
720 
721 		frag = dtls1_hm_fragment_new(frag_len, 0);
722 		if (frag == NULL)
723 			goto err;
724 
725 		memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
726 
727 		if (frag_len) {
728 			/* read the body of the fragment (header has already been read */
729 			i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
730 			    frag->fragment, frag_len, 0);
731 			if (i <= 0 || (unsigned long)i != frag_len)
732 				goto err;
733 		}
734 
735 		memset(seq64be, 0, sizeof(seq64be));
736 		seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
737 		seq64be[7] = (unsigned char)(msg_hdr->seq);
738 
739 		item = pitem_new(seq64be, frag);
740 		if (item == NULL)
741 			goto err;
742 
743 		pqueue_insert(D1I(s)->buffered_messages, item);
744 	}
745 
746 	return DTLS1_HM_FRAGMENT_RETRY;
747 
748 err:
749 	if (item == NULL && frag != NULL)
750 		dtls1_hm_fragment_free(frag);
751 	*ok = 0;
752 	return i;
753 }
754 
755 
756 static long
757 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
758 {
759 	unsigned char wire[DTLS1_HM_HEADER_LENGTH];
760 	unsigned long len, frag_off, frag_len;
761 	int i, al;
762 	struct hm_header_st msg_hdr;
763 
764 again:
765 	/* see if we have the required fragment already */
766 	if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
767 		if (*ok)
768 			s->internal->init_num = frag_len;
769 		return frag_len;
770 	}
771 
772 	/* read handshake message header */
773 	i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
774 	    DTLS1_HM_HEADER_LENGTH, 0);
775 	if (i <= 0) 	/* nbio, or an error */
776 	{
777 		s->internal->rwstate = SSL_READING;
778 		*ok = 0;
779 		return i;
780 	}
781 	/* Handshake fails if message header is incomplete */
782 	if (i != DTLS1_HM_HEADER_LENGTH ||
783 	    /* parse the message fragment header */
784 	    dtls1_get_message_header(wire, &msg_hdr) == 0) {
785 		al = SSL_AD_UNEXPECTED_MESSAGE;
786 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
787 		goto f_err;
788 	}
789 
790 	/*
791 	 * if this is a future (or stale) message it gets buffered
792 	 * (or dropped)--no further processing at this time
793 	 * While listening, we accept seq 1 (ClientHello with cookie)
794 	 * although we're still expecting seq 0 (ClientHello)
795 	 */
796 	if (msg_hdr.seq != D1I(s)->handshake_read_seq &&
797 	    !(D1I(s)->listen && msg_hdr.seq == 1))
798 		return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
799 
800 	len = msg_hdr.msg_len;
801 	frag_off = msg_hdr.frag_off;
802 	frag_len = msg_hdr.frag_len;
803 
804 	if (frag_len && frag_len < len)
805 		return dtls1_reassemble_fragment(s, &msg_hdr, ok);
806 
807 	if (!s->server && D1I(s)->r_msg_hdr.frag_off == 0 &&
808 	    wire[0] == SSL3_MT_HELLO_REQUEST) {
809 		/*
810 		 * The server may always send 'Hello Request' messages --
811 		 * we are doing a handshake anyway now, so ignore them
812 		 * if their format is correct. Does not count for
813 		 * 'Finished' MAC.
814 		 */
815 		if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
816 			if (s->internal->msg_callback)
817 				s->internal->msg_callback(0, s->version,
818 				    SSL3_RT_HANDSHAKE, wire,
819 				    DTLS1_HM_HEADER_LENGTH, s,
820 				    s->internal->msg_callback_arg);
821 
822 			s->internal->init_num = 0;
823 			goto again;
824 		}
825 		else /* Incorrectly formated Hello request */
826 		{
827 			al = SSL_AD_UNEXPECTED_MESSAGE;
828 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
829 			goto f_err;
830 		}
831 	}
832 
833 	if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
834 		goto f_err;
835 
836 	/* XDTLS:  ressurect this when restart is in place */
837 	S3I(s)->hs.state = stn;
838 
839 	if (frag_len > 0) {
840 		unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
841 
842 		i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
843 		    &p[frag_off], frag_len, 0);
844 		/* XDTLS:  fix this--message fragments cannot span multiple packets */
845 		if (i <= 0) {
846 			s->internal->rwstate = SSL_READING;
847 			*ok = 0;
848 			return i;
849 		}
850 	} else
851 		i = 0;
852 
853 	/*
854 	 * XDTLS:  an incorrectly formatted fragment should cause the
855 	 * handshake to fail
856 	 */
857 	if (i != (int)frag_len) {
858 		al = SSL3_AD_ILLEGAL_PARAMETER;
859 		SSLerror(s, SSL3_AD_ILLEGAL_PARAMETER);
860 		goto f_err;
861 	}
862 
863 	*ok = 1;
864 
865 	/*
866 	 * Note that s->internal->init_num is *not* used as current offset in
867 	 * s->internal->init_buf->data, but as a counter summing up fragments'
868 	 * lengths: as soon as they sum up to handshake packet
869 	 * length, we assume we have got all the fragments.
870 	 */
871 	s->internal->init_num = frag_len;
872 	return frag_len;
873 
874 f_err:
875 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
876 	s->internal->init_num = 0;
877 
878 	*ok = 0;
879 	return (-1);
880 }
881 
882 int
883 dtls1_read_failed(SSL *s, int code)
884 {
885 	if (code > 0) {
886 #ifdef DEBUG
887 		fprintf(stderr, "invalid state reached %s:%d",
888 		    __FILE__, __LINE__);
889 #endif
890 		return 1;
891 	}
892 
893 	if (!dtls1_is_timer_expired(s)) {
894 		/*
895 		 * not a timeout, none of our business, let higher layers
896 		 * handle this.  in fact it's probably an error
897 		 */
898 		return code;
899 	}
900 
901 	if (!SSL_in_init(s))  /* done, no need to send a retransmit */
902 	{
903 		BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
904 		return code;
905 	}
906 
907 	return dtls1_handle_timeout(s);
908 }
909 
910 int
911 dtls1_get_queue_priority(unsigned short seq, int is_ccs)
912 {
913 	/*
914 	 * The index of the retransmission queue actually is the message
915 	 * sequence number, since the queue only contains messages of a
916 	 * single handshake. However, the ChangeCipherSpec has no message
917 	 * sequence number and so using only the sequence will result in
918 	 * the CCS and Finished having the same index. To prevent this, the
919 	 * sequence number is multiplied by 2. In case of a CCS 1 is
920 	 * subtracted.  This does not only differ CSS and Finished, it also
921 	 * maintains the order of the index (important for priority queues)
922 	 * and fits in the unsigned short variable.
923 	 */
924 	return seq * 2 - is_ccs;
925 }
926 
927 int
928 dtls1_retransmit_buffered_messages(SSL *s)
929 {
930 	pqueue sent = s->d1->sent_messages;
931 	piterator iter;
932 	pitem *item;
933 	hm_fragment *frag;
934 	int found = 0;
935 
936 	iter = pqueue_iterator(sent);
937 
938 	for (item = pqueue_next(&iter); item != NULL;
939 	    item = pqueue_next(&iter)) {
940 		frag = (hm_fragment *)item->data;
941 		if (dtls1_retransmit_message(s,
942 		    (unsigned short)dtls1_get_queue_priority(
943 		    frag->msg_header.seq, frag->msg_header.is_ccs), 0,
944 		    &found) <= 0 && found) {
945 #ifdef DEBUG
946 			fprintf(stderr, "dtls1_retransmit_message() failed\n");
947 #endif
948 			return -1;
949 		}
950 	}
951 
952 	return 1;
953 }
954 
955 int
956 dtls1_buffer_message(SSL *s, int is_ccs)
957 {
958 	pitem *item;
959 	hm_fragment *frag;
960 	unsigned char seq64be[8];
961 
962 	/* Buffer the messsage in order to handle DTLS retransmissions. */
963 
964 	/*
965 	 * This function is called immediately after a message has
966 	 * been serialized
967 	 */
968 	OPENSSL_assert(s->internal->init_off == 0);
969 
970 	frag = dtls1_hm_fragment_new(s->internal->init_num, 0);
971 	if (frag == NULL)
972 		return 0;
973 
974 	memcpy(frag->fragment, s->internal->init_buf->data, s->internal->init_num);
975 
976 	if (is_ccs) {
977 		OPENSSL_assert(D1I(s)->w_msg_hdr.msg_len +
978 		    ((s->version == DTLS1_VERSION) ?
979 		    DTLS1_CCS_HEADER_LENGTH : 3) == (unsigned int)s->internal->init_num);
980 	} else {
981 		OPENSSL_assert(D1I(s)->w_msg_hdr.msg_len +
982 		    DTLS1_HM_HEADER_LENGTH == (unsigned int)s->internal->init_num);
983 	}
984 
985 	frag->msg_header.msg_len = D1I(s)->w_msg_hdr.msg_len;
986 	frag->msg_header.seq = D1I(s)->w_msg_hdr.seq;
987 	frag->msg_header.type = D1I(s)->w_msg_hdr.type;
988 	frag->msg_header.frag_off = 0;
989 	frag->msg_header.frag_len = D1I(s)->w_msg_hdr.msg_len;
990 	frag->msg_header.is_ccs = is_ccs;
991 
992 	/* save current state*/
993 	frag->msg_header.saved_retransmit_state.enc_write_ctx = s->internal->enc_write_ctx;
994 	frag->msg_header.saved_retransmit_state.write_hash = s->internal->write_hash;
995 	frag->msg_header.saved_retransmit_state.session = s->session;
996 	frag->msg_header.saved_retransmit_state.epoch = D1I(s)->w_epoch;
997 
998 	memset(seq64be, 0, sizeof(seq64be));
999 	seq64be[6] = (unsigned char)(dtls1_get_queue_priority(
1000 	    frag->msg_header.seq, frag->msg_header.is_ccs) >> 8);
1001 	seq64be[7] = (unsigned char)(dtls1_get_queue_priority(
1002 	    frag->msg_header.seq, frag->msg_header.is_ccs));
1003 
1004 	item = pitem_new(seq64be, frag);
1005 	if (item == NULL) {
1006 		dtls1_hm_fragment_free(frag);
1007 		return 0;
1008 	}
1009 
1010 	pqueue_insert(s->d1->sent_messages, item);
1011 	return 1;
1012 }
1013 
1014 int
1015 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1016     int *found)
1017 {
1018 	int ret;
1019 	/* XDTLS: for now assuming that read/writes are blocking */
1020 	pitem *item;
1021 	hm_fragment *frag;
1022 	unsigned long header_length;
1023 	unsigned char seq64be[8];
1024 	struct dtls1_retransmit_state saved_state;
1025 	unsigned char save_write_sequence[8];
1026 
1027 	/*
1028 	  OPENSSL_assert(s->internal->init_num == 0);
1029 	  OPENSSL_assert(s->internal->init_off == 0);
1030 	 */
1031 
1032 	/* XDTLS:  the requested message ought to be found, otherwise error */
1033 	memset(seq64be, 0, sizeof(seq64be));
1034 	seq64be[6] = (unsigned char)(seq >> 8);
1035 	seq64be[7] = (unsigned char)seq;
1036 
1037 	item = pqueue_find(s->d1->sent_messages, seq64be);
1038 	if (item == NULL) {
1039 #ifdef DEBUG
1040 		fprintf(stderr, "retransmit:  message %d non-existent\n", seq);
1041 #endif
1042 		*found = 0;
1043 		return 0;
1044 	}
1045 
1046 	*found = 1;
1047 	frag = (hm_fragment *)item->data;
1048 
1049 	if (frag->msg_header.is_ccs)
1050 		header_length = DTLS1_CCS_HEADER_LENGTH;
1051 	else
1052 		header_length = DTLS1_HM_HEADER_LENGTH;
1053 
1054 	memcpy(s->internal->init_buf->data, frag->fragment,
1055 	    frag->msg_header.msg_len + header_length);
1056 	s->internal->init_num = frag->msg_header.msg_len + header_length;
1057 
1058 	dtls1_set_message_header_int(s, frag->msg_header.type,
1059 	    frag->msg_header.msg_len, frag->msg_header.seq, 0,
1060 	    frag->msg_header.frag_len);
1061 
1062 	/* save current state */
1063 	saved_state.enc_write_ctx = s->internal->enc_write_ctx;
1064 	saved_state.write_hash = s->internal->write_hash;
1065 	saved_state.session = s->session;
1066 	saved_state.epoch = D1I(s)->w_epoch;
1067 
1068 	D1I(s)->retransmitting = 1;
1069 
1070 	/* restore state in which the message was originally sent */
1071 	s->internal->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1072 	s->internal->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1073 	s->session = frag->msg_header.saved_retransmit_state.session;
1074 	D1I(s)->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1075 
1076 	if (frag->msg_header.saved_retransmit_state.epoch ==
1077 	    saved_state.epoch - 1) {
1078 		memcpy(save_write_sequence, S3I(s)->write_sequence,
1079 		    sizeof(S3I(s)->write_sequence));
1080 		memcpy(S3I(s)->write_sequence, D1I(s)->last_write_sequence,
1081 		    sizeof(S3I(s)->write_sequence));
1082 	}
1083 
1084 	ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1085 	    SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1086 
1087 	/* restore current state */
1088 	s->internal->enc_write_ctx = saved_state.enc_write_ctx;
1089 	s->internal->write_hash = saved_state.write_hash;
1090 	s->session = saved_state.session;
1091 	D1I(s)->w_epoch = saved_state.epoch;
1092 
1093 	if (frag->msg_header.saved_retransmit_state.epoch ==
1094 	    saved_state.epoch - 1) {
1095 		memcpy(D1I(s)->last_write_sequence, S3I(s)->write_sequence,
1096 		    sizeof(S3I(s)->write_sequence));
1097 		memcpy(S3I(s)->write_sequence, save_write_sequence,
1098 		    sizeof(S3I(s)->write_sequence));
1099 	}
1100 
1101 	D1I(s)->retransmitting = 0;
1102 
1103 	(void)BIO_flush(SSL_get_wbio(s));
1104 	return ret;
1105 }
1106 
1107 /* call this function when the buffered messages are no longer needed */
1108 void
1109 dtls1_clear_record_buffer(SSL *s)
1110 {
1111 	pitem *item;
1112 
1113 	for(item = pqueue_pop(s->d1->sent_messages); item != NULL;
1114 	    item = pqueue_pop(s->d1->sent_messages)) {
1115 		dtls1_hm_fragment_free((hm_fragment *)item->data);
1116 		pitem_free(item);
1117 	}
1118 }
1119 
1120 void
1121 dtls1_set_message_header(SSL *s, unsigned char mt, unsigned long len,
1122     unsigned long frag_off, unsigned long frag_len)
1123 {
1124 	/* Don't change sequence numbers while listening */
1125 	if (frag_off == 0 && !D1I(s)->listen) {
1126 		D1I(s)->handshake_write_seq = D1I(s)->next_handshake_write_seq;
1127 		D1I(s)->next_handshake_write_seq++;
1128 	}
1129 
1130 	dtls1_set_message_header_int(s, mt, len, D1I(s)->handshake_write_seq,
1131 	    frag_off, frag_len);
1132 }
1133 
1134 /* don't actually do the writing, wait till the MTU has been retrieved */
1135 void
1136 dtls1_set_message_header_int(SSL *s, unsigned char mt, unsigned long len,
1137     unsigned short seq_num, unsigned long frag_off, unsigned long frag_len)
1138 {
1139 	struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
1140 
1141 	msg_hdr->type = mt;
1142 	msg_hdr->msg_len = len;
1143 	msg_hdr->seq = seq_num;
1144 	msg_hdr->frag_off = frag_off;
1145 	msg_hdr->frag_len = frag_len;
1146 }
1147 
1148 static void
1149 dtls1_fix_message_header(SSL *s, unsigned long frag_off, unsigned long frag_len)
1150 {
1151 	struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
1152 
1153 	msg_hdr->frag_off = frag_off;
1154 	msg_hdr->frag_len = frag_len;
1155 }
1156 
1157 static int
1158 dtls1_write_message_header(const struct hm_header_st *msg_hdr,
1159     unsigned long frag_off, unsigned long frag_len, unsigned char *p)
1160 {
1161 	CBB cbb;
1162 
1163 	/* We assume DTLS1_HM_HEADER_LENGTH bytes are available for now... */
1164 	if (!CBB_init_fixed(&cbb, p, DTLS1_HM_HEADER_LENGTH))
1165 		return 0;
1166 	if (!CBB_add_u8(&cbb, msg_hdr->type))
1167 		goto err;
1168 	if (!CBB_add_u24(&cbb, msg_hdr->msg_len))
1169 		goto err;
1170 	if (!CBB_add_u16(&cbb, msg_hdr->seq))
1171 		goto err;
1172 	if (!CBB_add_u24(&cbb, frag_off))
1173 		goto err;
1174 	if (!CBB_add_u24(&cbb, frag_len))
1175 		goto err;
1176 	if (!CBB_finish(&cbb, NULL, NULL))
1177 		goto err;
1178 
1179 	return 1;
1180 
1181  err:
1182 	CBB_cleanup(&cbb);
1183 	return 0;
1184 }
1185 
1186 unsigned int
1187 dtls1_min_mtu(void)
1188 {
1189 	return (g_probable_mtu[(sizeof(g_probable_mtu) /
1190 	    sizeof(g_probable_mtu[0])) - 1]);
1191 }
1192 
1193 static unsigned int
1194 dtls1_guess_mtu(unsigned int curr_mtu)
1195 {
1196 	unsigned int i;
1197 
1198 	if (curr_mtu == 0)
1199 		return g_probable_mtu[0];
1200 
1201 	for (i = 0; i < sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0]); i++)
1202 		if (curr_mtu > g_probable_mtu[i])
1203 			return g_probable_mtu[i];
1204 
1205 	return curr_mtu;
1206 }
1207 
1208 int
1209 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1210 {
1211 	CBS header;
1212 	uint32_t msg_len, frag_off, frag_len;
1213 	uint16_t seq;
1214 	uint8_t type;
1215 
1216 	CBS_init(&header, data, sizeof(*msg_hdr));
1217 
1218 	memset(msg_hdr, 0, sizeof(*msg_hdr));
1219 
1220 	if (!CBS_get_u8(&header, &type))
1221 		return 0;
1222 	if (!CBS_get_u24(&header, &msg_len))
1223 		return 0;
1224 	if (!CBS_get_u16(&header, &seq))
1225 		return 0;
1226 	if (!CBS_get_u24(&header, &frag_off))
1227 		return 0;
1228 	if (!CBS_get_u24(&header, &frag_len))
1229 		return 0;
1230 
1231 	msg_hdr->type = type;
1232 	msg_hdr->msg_len = msg_len;
1233 	msg_hdr->seq = seq;
1234 	msg_hdr->frag_off = frag_off;
1235 	msg_hdr->frag_len = frag_len;
1236 
1237 	return 1;
1238 }
1239 
1240 void
1241 dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1242 {
1243 	memset(ccs_hdr, 0, sizeof(struct ccs_header_st));
1244 
1245 	ccs_hdr->type = *(data++);
1246 }
1247