Unleashed v1.4
[unleashed.git] / lib / libssl / d1_both.c
blob95157630f502558128416dbb2eeee98fb0973c0f
1 /* $OpenBSD: d1_both.c,v 1.55 2018/09/05 16:58:59 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.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
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.
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/)"
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.
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.
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/)"
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 * ====================================================================
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).
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60 * All rights reserved.
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.
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).
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.
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)"
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.
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.]
116 #include <limits.h>
117 #include <stdio.h>
118 #include <string.h>
120 #include "ssl_locl.h"
122 #include <openssl/buffer.h>
123 #include <openssl/evp.h>
124 #include <openssl/objects.h>
125 #include <openssl/x509.h>
127 #include "pqueue.h"
128 #include "bytestring.h"
130 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
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)]; \
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; } }
151 static unsigned char bitmask_start_values[] = {
152 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80
154 static unsigned char bitmask_end_values[] = {
155 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f
158 /* XDTLS: figure out the right values */
159 static unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28};
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);
169 static hm_fragment *
170 dtls1_hm_fragment_new(unsigned long frag_len, int reassembly)
172 hm_fragment *frag = NULL;
173 unsigned char *buf = NULL;
174 unsigned char *bitmask = NULL;
176 frag = malloc(sizeof(hm_fragment));
177 if (frag == NULL)
178 return NULL;
180 if (frag_len) {
181 buf = malloc(frag_len);
182 if (buf == NULL) {
183 free(frag);
184 return NULL;
188 /* zero length fragment gets zero frag->fragment */
189 frag->fragment = buf;
191 /* Initialize reassembly bitmask if necessary */
192 if (reassembly) {
193 bitmask = malloc(RSMBLY_BITMASK_SIZE(frag_len));
194 if (bitmask == NULL) {
195 free(buf);
196 free(frag);
197 return NULL;
199 memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
202 frag->reassembly = bitmask;
204 return frag;
207 static void
208 dtls1_hm_fragment_free(hm_fragment *frag)
210 if (frag == NULL)
211 return;
213 if (frag->msg_header.is_ccs) {
214 EVP_CIPHER_CTX_free(
215 frag->msg_header.saved_retransmit_state.enc_write_ctx);
216 EVP_MD_CTX_free(
217 frag->msg_header.saved_retransmit_state.write_hash);
219 free(frag->fragment);
220 free(frag->reassembly);
221 free(frag);
224 /* send s->internal->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
226 dtls1_do_write(SSL *s, int type)
228 int ret;
229 int curr_mtu;
230 unsigned int len, frag_off, mac_size, blocksize;
232 /* AHA! Figure out the MTU, and stick to the right size */
233 if (D1I(s)->mtu < dtls1_min_mtu() &&
234 !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
235 D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s),
236 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
239 * I've seen the kernel return bogus numbers when it
240 * doesn't know the MTU (ie., the initial write), so just
241 * make sure we have a reasonable number
243 if (D1I(s)->mtu < dtls1_min_mtu()) {
244 D1I(s)->mtu = 0;
245 D1I(s)->mtu = dtls1_guess_mtu(D1I(s)->mtu);
246 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
247 D1I(s)->mtu, NULL);
251 OPENSSL_assert(D1I(s)->mtu >= dtls1_min_mtu());
252 /* should have something reasonable now */
254 if (s->internal->init_off == 0 && type == SSL3_RT_HANDSHAKE)
255 OPENSSL_assert(s->internal->init_num ==
256 (int)D1I(s)->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
258 if (s->internal->write_hash)
259 mac_size = EVP_MD_CTX_size(s->internal->write_hash);
260 else
261 mac_size = 0;
263 if (s->internal->enc_write_ctx &&
264 (EVP_CIPHER_mode( s->internal->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
265 blocksize = 2 * EVP_CIPHER_block_size(s->internal->enc_write_ctx->cipher);
266 else
267 blocksize = 0;
269 frag_off = 0;
270 while (s->internal->init_num) {
271 curr_mtu = D1I(s)->mtu - BIO_wpending(SSL_get_wbio(s)) -
272 DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
274 if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
275 /* grr.. we could get an error if MTU picked was wrong */
276 ret = BIO_flush(SSL_get_wbio(s));
277 if (ret <= 0)
278 return ret;
279 curr_mtu = D1I(s)->mtu - DTLS1_RT_HEADER_LENGTH -
280 mac_size - blocksize;
283 if (s->internal->init_num > curr_mtu)
284 len = curr_mtu;
285 else
286 len = s->internal->init_num;
289 /* XDTLS: this function is too long. split out the CCS part */
290 if (type == SSL3_RT_HANDSHAKE) {
291 if (s->internal->init_off != 0) {
292 OPENSSL_assert(s->internal->init_off > DTLS1_HM_HEADER_LENGTH);
293 s->internal->init_off -= DTLS1_HM_HEADER_LENGTH;
294 s->internal->init_num += DTLS1_HM_HEADER_LENGTH;
296 if (s->internal->init_num > curr_mtu)
297 len = curr_mtu;
298 else
299 len = s->internal->init_num;
302 dtls1_fix_message_header(s, frag_off,
303 len - DTLS1_HM_HEADER_LENGTH);
305 if (!dtls1_write_message_header(&D1I(s)->w_msg_hdr,
306 D1I(s)->w_msg_hdr.frag_off, D1I(s)->w_msg_hdr.frag_len,
307 (unsigned char *)&s->internal->init_buf->data[s->internal->init_off]))
308 return -1;
310 OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
313 ret = dtls1_write_bytes(s, type,
314 &s->internal->init_buf->data[s->internal->init_off], len);
315 if (ret < 0) {
317 * Might need to update MTU here, but we don't know
318 * which previous packet caused the failure -- so
319 * can't really retransmit anything. continue as
320 * if everything is fine and wait for an alert to
321 * handle the retransmit
323 if (BIO_ctrl(SSL_get_wbio(s),
324 BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0)
325 D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s),
326 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
327 else
328 return (-1);
329 } else {
332 * Bad if this assert fails, only part of the
333 * handshake message got sent. but why would
334 * this happen?
336 OPENSSL_assert(len == (unsigned int)ret);
338 if (type == SSL3_RT_HANDSHAKE &&
339 !D1I(s)->retransmitting) {
341 * Should not be done for 'Hello Request's,
342 * but in that case we'll ignore the result
343 * anyway
345 unsigned char *p = (unsigned char *)&s->internal->init_buf->data[s->internal->init_off];
346 const struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
347 int xlen;
349 if (frag_off == 0) {
351 * Reconstruct message header is if it
352 * is being sent in single fragment
354 if (!dtls1_write_message_header(msg_hdr,
355 0, msg_hdr->msg_len, p))
356 return (-1);
357 xlen = ret;
358 } else {
359 p += DTLS1_HM_HEADER_LENGTH;
360 xlen = ret - DTLS1_HM_HEADER_LENGTH;
363 tls1_finish_mac(s, p, xlen);
366 if (ret == s->internal->init_num) {
367 if (s->internal->msg_callback)
368 s->internal->msg_callback(1, s->version, type,
369 s->internal->init_buf->data,
370 (size_t)(s->internal->init_off + s->internal->init_num),
371 s, s->internal->msg_callback_arg);
373 s->internal->init_off = 0;
374 /* done writing this message */
375 s->internal->init_num = 0;
377 return (1);
379 s->internal->init_off += ret;
380 s->internal->init_num -= ret;
381 frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
384 return (0);
389 * Obtain handshake message of message type 'mt' (any if mt == -1),
390 * maximum acceptable body length 'max'.
391 * Read an entire handshake message. Handshake messages arrive in
392 * fragments.
394 long
395 dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
397 int i, al;
398 struct hm_header_st *msg_hdr;
399 unsigned char *p;
400 unsigned long msg_len;
403 * s3->internal->tmp is used to store messages that are unexpected, caused
404 * by the absence of an optional handshake message
406 if (S3I(s)->tmp.reuse_message) {
407 S3I(s)->tmp.reuse_message = 0;
408 if ((mt >= 0) && (S3I(s)->tmp.message_type != mt)) {
409 al = SSL_AD_UNEXPECTED_MESSAGE;
410 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
411 goto f_err;
413 *ok = 1;
414 s->internal->init_msg = s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
415 s->internal->init_num = (int)S3I(s)->tmp.message_size;
416 return s->internal->init_num;
419 msg_hdr = &D1I(s)->r_msg_hdr;
420 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
422 again:
423 i = dtls1_get_message_fragment(s, st1, stn, max, ok);
424 if (i == DTLS1_HM_BAD_FRAGMENT ||
425 i == DTLS1_HM_FRAGMENT_RETRY) /* bad fragment received */
426 goto again;
427 else if (i <= 0 && !*ok)
428 return i;
430 p = (unsigned char *)s->internal->init_buf->data;
431 msg_len = msg_hdr->msg_len;
433 /* reconstruct message header */
434 if (!dtls1_write_message_header(msg_hdr, 0, msg_len, p))
435 return -1;
437 msg_len += DTLS1_HM_HEADER_LENGTH;
439 tls1_finish_mac(s, p, msg_len);
440 if (s->internal->msg_callback)
441 s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, msg_len,
442 s, s->internal->msg_callback_arg);
444 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
446 /* Don't change sequence numbers while listening */
447 if (!D1I(s)->listen)
448 D1I(s)->handshake_read_seq++;
450 s->internal->init_msg = s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
451 return s->internal->init_num;
453 f_err:
454 ssl3_send_alert(s, SSL3_AL_FATAL, al);
455 *ok = 0;
456 return -1;
460 static int
461 dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr, int max)
463 size_t frag_off, frag_len, msg_len;
465 msg_len = msg_hdr->msg_len;
466 frag_off = msg_hdr->frag_off;
467 frag_len = msg_hdr->frag_len;
469 /* sanity checking */
470 if ((frag_off + frag_len) > msg_len) {
471 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
472 return SSL_AD_ILLEGAL_PARAMETER;
475 if ((frag_off + frag_len) > (unsigned long)max) {
476 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
477 return SSL_AD_ILLEGAL_PARAMETER;
480 if ( D1I(s)->r_msg_hdr.frag_off == 0) /* first fragment */
483 * msg_len is limited to 2^24, but is effectively checked
484 * against max above
486 if (!BUF_MEM_grow_clean(s->internal->init_buf,
487 msg_len + DTLS1_HM_HEADER_LENGTH)) {
488 SSLerror(s, ERR_R_BUF_LIB);
489 return SSL_AD_INTERNAL_ERROR;
492 S3I(s)->tmp.message_size = msg_len;
493 D1I(s)->r_msg_hdr.msg_len = msg_len;
494 S3I(s)->tmp.message_type = msg_hdr->type;
495 D1I(s)->r_msg_hdr.type = msg_hdr->type;
496 D1I(s)->r_msg_hdr.seq = msg_hdr->seq;
497 } else if (msg_len != D1I(s)->r_msg_hdr.msg_len) {
499 * They must be playing with us! BTW, failure to enforce
500 * upper limit would open possibility for buffer overrun.
502 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
503 return SSL_AD_ILLEGAL_PARAMETER;
506 return 0; /* no error */
509 static int
510 dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
513 * (0) check whether the desired fragment is available
514 * if so:
515 * (1) copy over the fragment to s->internal->init_buf->data[]
516 * (2) update s->internal->init_num
518 pitem *item;
519 hm_fragment *frag;
520 int al;
522 *ok = 0;
523 item = pqueue_peek(D1I(s)->buffered_messages);
524 if (item == NULL)
525 return 0;
527 frag = (hm_fragment *)item->data;
529 /* Don't return if reassembly still in progress */
530 if (frag->reassembly != NULL)
531 return 0;
533 if (D1I(s)->handshake_read_seq == frag->msg_header.seq) {
534 unsigned long frag_len = frag->msg_header.frag_len;
535 pqueue_pop(D1I(s)->buffered_messages);
537 al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
539 if (al == 0) /* no alert */
541 unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
542 memcpy(&p[frag->msg_header.frag_off],
543 frag->fragment, frag->msg_header.frag_len);
546 dtls1_hm_fragment_free(frag);
547 pitem_free(item);
549 if (al == 0) {
550 *ok = 1;
551 return frag_len;
554 ssl3_send_alert(s, SSL3_AL_FATAL, al);
555 s->internal->init_num = 0;
556 *ok = 0;
557 return -1;
558 } else
559 return 0;
563 * dtls1_max_handshake_message_len returns the maximum number of bytes
564 * permitted in a DTLS handshake message for |s|. The minimum is 16KB,
565 * but may be greater if the maximum certificate list size requires it.
567 static unsigned long
568 dtls1_max_handshake_message_len(const SSL *s)
570 unsigned long max_len;
572 max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
573 if (max_len < (unsigned long)s->internal->max_cert_list)
574 return s->internal->max_cert_list;
575 return max_len;
578 static int
579 dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
581 hm_fragment *frag = NULL;
582 pitem *item = NULL;
583 int i = -1, is_complete;
584 unsigned char seq64be[8];
585 unsigned long frag_len = msg_hdr->frag_len;
587 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
588 msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
589 goto err;
591 if (frag_len == 0) {
592 i = DTLS1_HM_FRAGMENT_RETRY;
593 goto err;
596 /* Try to find item in queue */
597 memset(seq64be, 0, sizeof(seq64be));
598 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
599 seq64be[7] = (unsigned char)msg_hdr->seq;
600 item = pqueue_find(D1I(s)->buffered_messages, seq64be);
602 if (item == NULL) {
603 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
604 if (frag == NULL)
605 goto err;
606 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
607 frag->msg_header.frag_len = frag->msg_header.msg_len;
608 frag->msg_header.frag_off = 0;
609 } else {
610 frag = (hm_fragment*)item->data;
611 if (frag->msg_header.msg_len != msg_hdr->msg_len) {
612 item = NULL;
613 frag = NULL;
614 goto err;
619 * If message is already reassembled, this must be a
620 * retransmit and can be dropped.
622 if (frag->reassembly == NULL) {
623 unsigned char devnull [256];
625 while (frag_len) {
626 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
627 devnull, frag_len > sizeof(devnull) ?
628 sizeof(devnull) : frag_len, 0);
629 if (i <= 0)
630 goto err;
631 frag_len -= i;
633 i = DTLS1_HM_FRAGMENT_RETRY;
634 goto err;
637 /* read the body of the fragment (header has already been read */
638 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
639 frag->fragment + msg_hdr->frag_off, frag_len, 0);
640 if (i <= 0 || (unsigned long)i != frag_len)
641 goto err;
643 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
644 (long)(msg_hdr->frag_off + frag_len));
646 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
647 is_complete);
649 if (is_complete) {
650 free(frag->reassembly);
651 frag->reassembly = NULL;
654 if (item == NULL) {
655 memset(seq64be, 0, sizeof(seq64be));
656 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
657 seq64be[7] = (unsigned char)(msg_hdr->seq);
659 item = pitem_new(seq64be, frag);
660 if (item == NULL) {
661 i = -1;
662 goto err;
665 pqueue_insert(D1I(s)->buffered_messages, item);
668 return DTLS1_HM_FRAGMENT_RETRY;
670 err:
671 if (item == NULL && frag != NULL)
672 dtls1_hm_fragment_free(frag);
673 *ok = 0;
674 return i;
678 static int
679 dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
681 int i = -1;
682 hm_fragment *frag = NULL;
683 pitem *item = NULL;
684 unsigned char seq64be[8];
685 unsigned long frag_len = msg_hdr->frag_len;
687 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
688 goto err;
690 /* Try to find item in queue, to prevent duplicate entries */
691 memset(seq64be, 0, sizeof(seq64be));
692 seq64be[6] = (unsigned char) (msg_hdr->seq >> 8);
693 seq64be[7] = (unsigned char) msg_hdr->seq;
694 item = pqueue_find(D1I(s)->buffered_messages, seq64be);
697 * If we already have an entry and this one is a fragment,
698 * don't discard it and rather try to reassemble it.
700 if (item != NULL && frag_len < msg_hdr->msg_len)
701 item = NULL;
704 * Discard the message if sequence number was already there, is
705 * too far in the future, already in the queue or if we received
706 * a FINISHED before the SERVER_HELLO, which then must be a stale
707 * retransmit.
709 if (msg_hdr->seq <= D1I(s)->handshake_read_seq ||
710 msg_hdr->seq > D1I(s)->handshake_read_seq + 10 || item != NULL ||
711 (D1I(s)->handshake_read_seq == 0 &&
712 msg_hdr->type == SSL3_MT_FINISHED)) {
713 unsigned char devnull [256];
715 while (frag_len) {
716 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
717 devnull, frag_len > sizeof(devnull) ?
718 sizeof(devnull) : frag_len, 0);
719 if (i <= 0)
720 goto err;
721 frag_len -= i;
723 } else {
724 if (frag_len < msg_hdr->msg_len)
725 return dtls1_reassemble_fragment(s, msg_hdr, ok);
727 if (frag_len > dtls1_max_handshake_message_len(s))
728 goto err;
730 frag = dtls1_hm_fragment_new(frag_len, 0);
731 if (frag == NULL)
732 goto err;
734 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
736 if (frag_len) {
737 /* read the body of the fragment (header has already been read */
738 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
739 frag->fragment, frag_len, 0);
740 if (i <= 0 || (unsigned long)i != frag_len)
741 goto err;
744 memset(seq64be, 0, sizeof(seq64be));
745 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
746 seq64be[7] = (unsigned char)(msg_hdr->seq);
748 item = pitem_new(seq64be, frag);
749 if (item == NULL)
750 goto err;
752 pqueue_insert(D1I(s)->buffered_messages, item);
755 return DTLS1_HM_FRAGMENT_RETRY;
757 err:
758 if (item == NULL && frag != NULL)
759 dtls1_hm_fragment_free(frag);
760 *ok = 0;
761 return i;
765 static long
766 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
768 unsigned char wire[DTLS1_HM_HEADER_LENGTH];
769 unsigned long len, frag_off, frag_len;
770 int i, al;
771 struct hm_header_st msg_hdr;
773 again:
774 /* see if we have the required fragment already */
775 if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
776 if (*ok)
777 s->internal->init_num = frag_len;
778 return frag_len;
781 /* read handshake message header */
782 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
783 DTLS1_HM_HEADER_LENGTH, 0);
784 if (i <= 0) /* nbio, or an error */
786 s->internal->rwstate = SSL_READING;
787 *ok = 0;
788 return i;
790 /* Handshake fails if message header is incomplete */
791 if (i != DTLS1_HM_HEADER_LENGTH ||
792 /* parse the message fragment header */
793 dtls1_get_message_header(wire, &msg_hdr) == 0) {
794 al = SSL_AD_UNEXPECTED_MESSAGE;
795 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
796 goto f_err;
800 * if this is a future (or stale) message it gets buffered
801 * (or dropped)--no further processing at this time
802 * While listening, we accept seq 1 (ClientHello with cookie)
803 * although we're still expecting seq 0 (ClientHello)
805 if (msg_hdr.seq != D1I(s)->handshake_read_seq &&
806 !(D1I(s)->listen && msg_hdr.seq == 1))
807 return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
809 len = msg_hdr.msg_len;
810 frag_off = msg_hdr.frag_off;
811 frag_len = msg_hdr.frag_len;
813 if (frag_len && frag_len < len)
814 return dtls1_reassemble_fragment(s, &msg_hdr, ok);
816 if (!s->server && D1I(s)->r_msg_hdr.frag_off == 0 &&
817 wire[0] == SSL3_MT_HELLO_REQUEST) {
819 * The server may always send 'Hello Request' messages --
820 * we are doing a handshake anyway now, so ignore them
821 * if their format is correct. Does not count for
822 * 'Finished' MAC.
824 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
825 if (s->internal->msg_callback)
826 s->internal->msg_callback(0, s->version,
827 SSL3_RT_HANDSHAKE, wire,
828 DTLS1_HM_HEADER_LENGTH, s,
829 s->internal->msg_callback_arg);
831 s->internal->init_num = 0;
832 goto again;
834 else /* Incorrectly formated Hello request */
836 al = SSL_AD_UNEXPECTED_MESSAGE;
837 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
838 goto f_err;
842 if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
843 goto f_err;
845 /* XDTLS: ressurect this when restart is in place */
846 S3I(s)->hs.state = stn;
848 if (frag_len > 0) {
849 unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
851 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
852 &p[frag_off], frag_len, 0);
853 /* XDTLS: fix this--message fragments cannot span multiple packets */
854 if (i <= 0) {
855 s->internal->rwstate = SSL_READING;
856 *ok = 0;
857 return i;
859 } else
860 i = 0;
863 * XDTLS: an incorrectly formatted fragment should cause the
864 * handshake to fail
866 if (i != (int)frag_len) {
867 al = SSL3_AD_ILLEGAL_PARAMETER;
868 SSLerror(s, SSL3_AD_ILLEGAL_PARAMETER);
869 goto f_err;
872 *ok = 1;
875 * Note that s->internal->init_num is *not* used as current offset in
876 * s->internal->init_buf->data, but as a counter summing up fragments'
877 * lengths: as soon as they sum up to handshake packet
878 * length, we assume we have got all the fragments.
880 s->internal->init_num = frag_len;
881 return frag_len;
883 f_err:
884 ssl3_send_alert(s, SSL3_AL_FATAL, al);
885 s->internal->init_num = 0;
887 *ok = 0;
888 return (-1);
892 dtls1_read_failed(SSL *s, int code)
894 if (code > 0) {
895 #ifdef DEBUG
896 fprintf(stderr, "invalid state reached %s:%d",
897 __FILE__, __LINE__);
898 #endif
899 return 1;
902 if (!dtls1_is_timer_expired(s)) {
904 * not a timeout, none of our business, let higher layers
905 * handle this. in fact it's probably an error
907 return code;
910 if (!SSL_in_init(s)) /* done, no need to send a retransmit */
912 BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
913 return code;
916 return dtls1_handle_timeout(s);
920 dtls1_get_queue_priority(unsigned short seq, int is_ccs)
923 * The index of the retransmission queue actually is the message
924 * sequence number, since the queue only contains messages of a
925 * single handshake. However, the ChangeCipherSpec has no message
926 * sequence number and so using only the sequence will result in
927 * the CCS and Finished having the same index. To prevent this, the
928 * sequence number is multiplied by 2. In case of a CCS 1 is
929 * subtracted. This does not only differ CSS and Finished, it also
930 * maintains the order of the index (important for priority queues)
931 * and fits in the unsigned short variable.
933 return seq * 2 - is_ccs;
937 dtls1_retransmit_buffered_messages(SSL *s)
939 pqueue sent = s->d1->sent_messages;
940 piterator iter;
941 pitem *item;
942 hm_fragment *frag;
943 int found = 0;
945 iter = pqueue_iterator(sent);
947 for (item = pqueue_next(&iter); item != NULL;
948 item = pqueue_next(&iter)) {
949 frag = (hm_fragment *)item->data;
950 if (dtls1_retransmit_message(s,
951 (unsigned short)dtls1_get_queue_priority(
952 frag->msg_header.seq, frag->msg_header.is_ccs), 0,
953 &found) <= 0 && found) {
954 #ifdef DEBUG
955 fprintf(stderr, "dtls1_retransmit_message() failed\n");
956 #endif
957 return -1;
961 return 1;
965 dtls1_buffer_message(SSL *s, int is_ccs)
967 pitem *item;
968 hm_fragment *frag;
969 unsigned char seq64be[8];
971 /* Buffer the messsage in order to handle DTLS retransmissions. */
974 * This function is called immediately after a message has
975 * been serialized
977 OPENSSL_assert(s->internal->init_off == 0);
979 frag = dtls1_hm_fragment_new(s->internal->init_num, 0);
980 if (frag == NULL)
981 return 0;
983 memcpy(frag->fragment, s->internal->init_buf->data, s->internal->init_num);
985 if (is_ccs) {
986 OPENSSL_assert(D1I(s)->w_msg_hdr.msg_len +
987 ((s->version == DTLS1_VERSION) ?
988 DTLS1_CCS_HEADER_LENGTH : 3) == (unsigned int)s->internal->init_num);
989 } else {
990 OPENSSL_assert(D1I(s)->w_msg_hdr.msg_len +
991 DTLS1_HM_HEADER_LENGTH == (unsigned int)s->internal->init_num);
994 frag->msg_header.msg_len = D1I(s)->w_msg_hdr.msg_len;
995 frag->msg_header.seq = D1I(s)->w_msg_hdr.seq;
996 frag->msg_header.type = D1I(s)->w_msg_hdr.type;
997 frag->msg_header.frag_off = 0;
998 frag->msg_header.frag_len = D1I(s)->w_msg_hdr.msg_len;
999 frag->msg_header.is_ccs = is_ccs;
1001 /* save current state*/
1002 frag->msg_header.saved_retransmit_state.enc_write_ctx = s->internal->enc_write_ctx;
1003 frag->msg_header.saved_retransmit_state.write_hash = s->internal->write_hash;
1004 frag->msg_header.saved_retransmit_state.session = s->session;
1005 frag->msg_header.saved_retransmit_state.epoch = D1I(s)->w_epoch;
1007 memset(seq64be, 0, sizeof(seq64be));
1008 seq64be[6] = (unsigned char)(dtls1_get_queue_priority(
1009 frag->msg_header.seq, frag->msg_header.is_ccs) >> 8);
1010 seq64be[7] = (unsigned char)(dtls1_get_queue_priority(
1011 frag->msg_header.seq, frag->msg_header.is_ccs));
1013 item = pitem_new(seq64be, frag);
1014 if (item == NULL) {
1015 dtls1_hm_fragment_free(frag);
1016 return 0;
1019 pqueue_insert(s->d1->sent_messages, item);
1020 return 1;
1024 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1025 int *found)
1027 int ret;
1028 /* XDTLS: for now assuming that read/writes are blocking */
1029 pitem *item;
1030 hm_fragment *frag;
1031 unsigned long header_length;
1032 unsigned char seq64be[8];
1033 struct dtls1_retransmit_state saved_state;
1034 unsigned char save_write_sequence[8];
1037 OPENSSL_assert(s->internal->init_num == 0);
1038 OPENSSL_assert(s->internal->init_off == 0);
1041 /* XDTLS: the requested message ought to be found, otherwise error */
1042 memset(seq64be, 0, sizeof(seq64be));
1043 seq64be[6] = (unsigned char)(seq >> 8);
1044 seq64be[7] = (unsigned char)seq;
1046 item = pqueue_find(s->d1->sent_messages, seq64be);
1047 if (item == NULL) {
1048 #ifdef DEBUG
1049 fprintf(stderr, "retransmit: message %d non-existant\n", seq);
1050 #endif
1051 *found = 0;
1052 return 0;
1055 *found = 1;
1056 frag = (hm_fragment *)item->data;
1058 if (frag->msg_header.is_ccs)
1059 header_length = DTLS1_CCS_HEADER_LENGTH;
1060 else
1061 header_length = DTLS1_HM_HEADER_LENGTH;
1063 memcpy(s->internal->init_buf->data, frag->fragment,
1064 frag->msg_header.msg_len + header_length);
1065 s->internal->init_num = frag->msg_header.msg_len + header_length;
1067 dtls1_set_message_header_int(s, frag->msg_header.type,
1068 frag->msg_header.msg_len, frag->msg_header.seq, 0,
1069 frag->msg_header.frag_len);
1071 /* save current state */
1072 saved_state.enc_write_ctx = s->internal->enc_write_ctx;
1073 saved_state.write_hash = s->internal->write_hash;
1074 saved_state.session = s->session;
1075 saved_state.epoch = D1I(s)->w_epoch;
1077 D1I(s)->retransmitting = 1;
1079 /* restore state in which the message was originally sent */
1080 s->internal->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1081 s->internal->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1082 s->session = frag->msg_header.saved_retransmit_state.session;
1083 D1I(s)->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1085 if (frag->msg_header.saved_retransmit_state.epoch ==
1086 saved_state.epoch - 1) {
1087 memcpy(save_write_sequence, S3I(s)->write_sequence,
1088 sizeof(S3I(s)->write_sequence));
1089 memcpy(S3I(s)->write_sequence, D1I(s)->last_write_sequence,
1090 sizeof(S3I(s)->write_sequence));
1093 ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1094 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1096 /* restore current state */
1097 s->internal->enc_write_ctx = saved_state.enc_write_ctx;
1098 s->internal->write_hash = saved_state.write_hash;
1099 s->session = saved_state.session;
1100 D1I(s)->w_epoch = saved_state.epoch;
1102 if (frag->msg_header.saved_retransmit_state.epoch ==
1103 saved_state.epoch - 1) {
1104 memcpy(D1I(s)->last_write_sequence, S3I(s)->write_sequence,
1105 sizeof(S3I(s)->write_sequence));
1106 memcpy(S3I(s)->write_sequence, save_write_sequence,
1107 sizeof(S3I(s)->write_sequence));
1110 D1I(s)->retransmitting = 0;
1112 (void)BIO_flush(SSL_get_wbio(s));
1113 return ret;
1116 /* call this function when the buffered messages are no longer needed */
1117 void
1118 dtls1_clear_record_buffer(SSL *s)
1120 pitem *item;
1122 for(item = pqueue_pop(s->d1->sent_messages); item != NULL;
1123 item = pqueue_pop(s->d1->sent_messages)) {
1124 dtls1_hm_fragment_free((hm_fragment *)item->data);
1125 pitem_free(item);
1129 void
1130 dtls1_set_message_header(SSL *s, unsigned char mt, unsigned long len,
1131 unsigned long frag_off, unsigned long frag_len)
1133 /* Don't change sequence numbers while listening */
1134 if (frag_off == 0 && !D1I(s)->listen) {
1135 D1I(s)->handshake_write_seq = D1I(s)->next_handshake_write_seq;
1136 D1I(s)->next_handshake_write_seq++;
1139 dtls1_set_message_header_int(s, mt, len, D1I(s)->handshake_write_seq,
1140 frag_off, frag_len);
1143 /* don't actually do the writing, wait till the MTU has been retrieved */
1144 void
1145 dtls1_set_message_header_int(SSL *s, unsigned char mt, unsigned long len,
1146 unsigned short seq_num, unsigned long frag_off, unsigned long frag_len)
1148 struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
1150 msg_hdr->type = mt;
1151 msg_hdr->msg_len = len;
1152 msg_hdr->seq = seq_num;
1153 msg_hdr->frag_off = frag_off;
1154 msg_hdr->frag_len = frag_len;
1157 static void
1158 dtls1_fix_message_header(SSL *s, unsigned long frag_off, unsigned long frag_len)
1160 struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
1162 msg_hdr->frag_off = frag_off;
1163 msg_hdr->frag_len = frag_len;
1166 static int
1167 dtls1_write_message_header(const struct hm_header_st *msg_hdr,
1168 unsigned long frag_off, unsigned long frag_len, unsigned char *p)
1170 CBB cbb;
1172 /* We assume DTLS1_HM_HEADER_LENGTH bytes are available for now... */
1173 if (!CBB_init_fixed(&cbb, p, DTLS1_HM_HEADER_LENGTH))
1174 return 0;
1175 if (!CBB_add_u8(&cbb, msg_hdr->type))
1176 goto err;
1177 if (!CBB_add_u24(&cbb, msg_hdr->msg_len))
1178 goto err;
1179 if (!CBB_add_u16(&cbb, msg_hdr->seq))
1180 goto err;
1181 if (!CBB_add_u24(&cbb, frag_off))
1182 goto err;
1183 if (!CBB_add_u24(&cbb, frag_len))
1184 goto err;
1185 if (!CBB_finish(&cbb, NULL, NULL))
1186 goto err;
1188 return 1;
1190 err:
1191 CBB_cleanup(&cbb);
1192 return 0;
1195 unsigned int
1196 dtls1_min_mtu(void)
1198 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1199 sizeof(g_probable_mtu[0])) - 1]);
1202 static unsigned int
1203 dtls1_guess_mtu(unsigned int curr_mtu)
1205 unsigned int i;
1207 if (curr_mtu == 0)
1208 return g_probable_mtu[0];
1210 for (i = 0; i < sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0]); i++)
1211 if (curr_mtu > g_probable_mtu[i])
1212 return g_probable_mtu[i];
1214 return curr_mtu;
1218 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1220 CBS header;
1221 uint32_t msg_len, frag_off, frag_len;
1222 uint16_t seq;
1223 uint8_t type;
1225 CBS_init(&header, data, sizeof(*msg_hdr));
1227 memset(msg_hdr, 0, sizeof(*msg_hdr));
1229 if (!CBS_get_u8(&header, &type))
1230 return 0;
1231 if (!CBS_get_u24(&header, &msg_len))
1232 return 0;
1233 if (!CBS_get_u16(&header, &seq))
1234 return 0;
1235 if (!CBS_get_u24(&header, &frag_off))
1236 return 0;
1237 if (!CBS_get_u24(&header, &frag_len))
1238 return 0;
1240 msg_hdr->type = type;
1241 msg_hdr->msg_len = msg_len;
1242 msg_hdr->seq = seq;
1243 msg_hdr->frag_off = frag_off;
1244 msg_hdr->frag_len = frag_len;
1246 return 1;
1249 void
1250 dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1252 memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
1254 ccs_hdr->type = *(data++);