update libressl to v2.7.4
[unleashed.git] / lib / libssl / d1_both.c
blob42f8cbd5370a288b852450c2ff74328758a7926c
1 /* $OpenBSD: d1_both.c,v 1.52 2017/10/08 16:24:02 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 unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
165 static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max,
166 int *ok);
168 static hm_fragment *
169 dtls1_hm_fragment_new(unsigned long frag_len, int reassembly)
171 hm_fragment *frag = NULL;
172 unsigned char *buf = NULL;
173 unsigned char *bitmask = NULL;
175 frag = malloc(sizeof(hm_fragment));
176 if (frag == NULL)
177 return NULL;
179 if (frag_len) {
180 buf = malloc(frag_len);
181 if (buf == NULL) {
182 free(frag);
183 return NULL;
187 /* zero length fragment gets zero frag->fragment */
188 frag->fragment = buf;
190 /* Initialize reassembly bitmask if necessary */
191 if (reassembly) {
192 bitmask = malloc(RSMBLY_BITMASK_SIZE(frag_len));
193 if (bitmask == NULL) {
194 free(buf);
195 free(frag);
196 return NULL;
198 memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
201 frag->reassembly = bitmask;
203 return frag;
206 static void
207 dtls1_hm_fragment_free(hm_fragment *frag)
209 if (frag == NULL)
210 return;
212 if (frag->msg_header.is_ccs) {
213 EVP_CIPHER_CTX_free(
214 frag->msg_header.saved_retransmit_state.enc_write_ctx);
215 EVP_MD_CTX_destroy(
216 frag->msg_header.saved_retransmit_state.write_hash);
218 free(frag->fragment);
219 free(frag->reassembly);
220 free(frag);
223 /* send s->internal->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
225 dtls1_do_write(SSL *s, int type)
227 int ret;
228 int curr_mtu;
229 unsigned int len, frag_off, mac_size, blocksize;
231 /* AHA! Figure out the MTU, and stick to the right size */
232 if (D1I(s)->mtu < dtls1_min_mtu() &&
233 !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
234 D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s),
235 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
238 * I've seen the kernel return bogus numbers when it
239 * doesn't know the MTU (ie., the initial write), so just
240 * make sure we have a reasonable number
242 if (D1I(s)->mtu < dtls1_min_mtu()) {
243 D1I(s)->mtu = 0;
244 D1I(s)->mtu = dtls1_guess_mtu(D1I(s)->mtu);
245 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
246 D1I(s)->mtu, NULL);
250 OPENSSL_assert(D1I(s)->mtu >= dtls1_min_mtu());
251 /* should have something reasonable now */
253 if (s->internal->init_off == 0 && type == SSL3_RT_HANDSHAKE)
254 OPENSSL_assert(s->internal->init_num ==
255 (int)D1I(s)->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
257 if (s->internal->write_hash)
258 mac_size = EVP_MD_CTX_size(s->internal->write_hash);
259 else
260 mac_size = 0;
262 if (s->internal->enc_write_ctx &&
263 (EVP_CIPHER_mode( s->internal->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
264 blocksize = 2 * EVP_CIPHER_block_size(s->internal->enc_write_ctx->cipher);
265 else
266 blocksize = 0;
268 frag_off = 0;
269 while (s->internal->init_num) {
270 curr_mtu = D1I(s)->mtu - BIO_wpending(SSL_get_wbio(s)) -
271 DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
273 if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
274 /* grr.. we could get an error if MTU picked was wrong */
275 ret = BIO_flush(SSL_get_wbio(s));
276 if (ret <= 0)
277 return ret;
278 curr_mtu = D1I(s)->mtu - DTLS1_RT_HEADER_LENGTH -
279 mac_size - blocksize;
282 if (s->internal->init_num > curr_mtu)
283 len = curr_mtu;
284 else
285 len = s->internal->init_num;
288 /* XDTLS: this function is too long. split out the CCS part */
289 if (type == SSL3_RT_HANDSHAKE) {
290 if (s->internal->init_off != 0) {
291 OPENSSL_assert(s->internal->init_off > DTLS1_HM_HEADER_LENGTH);
292 s->internal->init_off -= DTLS1_HM_HEADER_LENGTH;
293 s->internal->init_num += DTLS1_HM_HEADER_LENGTH;
295 if (s->internal->init_num > curr_mtu)
296 len = curr_mtu;
297 else
298 len = s->internal->init_num;
301 dtls1_fix_message_header(s, frag_off,
302 len - DTLS1_HM_HEADER_LENGTH);
304 dtls1_write_message_header(s,
305 (unsigned char *)&s->internal->init_buf->data[s->internal->init_off]);
307 OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
310 ret = dtls1_write_bytes(s, type,
311 &s->internal->init_buf->data[s->internal->init_off], len);
312 if (ret < 0) {
314 * Might need to update MTU here, but we don't know
315 * which previous packet caused the failure -- so
316 * can't really retransmit anything. continue as
317 * if everything is fine and wait for an alert to
318 * handle the retransmit
320 if (BIO_ctrl(SSL_get_wbio(s),
321 BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0)
322 D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s),
323 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
324 else
325 return (-1);
326 } else {
329 * Bad if this assert fails, only part of the
330 * handshake message got sent. but why would
331 * this happen?
333 OPENSSL_assert(len == (unsigned int)ret);
335 if (type == SSL3_RT_HANDSHAKE &&
336 !D1I(s)->retransmitting) {
338 * Should not be done for 'Hello Request's,
339 * but in that case we'll ignore the result
340 * anyway
342 unsigned char *p = (unsigned char *)&s->internal->init_buf->data[s->internal->init_off];
343 const struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
344 int xlen;
346 if (frag_off == 0) {
348 * Reconstruct message header is if it
349 * is being sent in single fragment
351 *p++ = msg_hdr->type;
352 l2n3(msg_hdr->msg_len, p);
353 s2n (msg_hdr->seq, p);
354 l2n3(0, p);
355 l2n3(msg_hdr->msg_len, p);
356 p -= DTLS1_HM_HEADER_LENGTH;
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 *(p++) = msg_hdr->type;
435 l2n3(msg_len, p);
436 s2n (msg_hdr->seq, p);
437 l2n3(0, p);
438 l2n3(msg_len, p);
440 p -= DTLS1_HM_HEADER_LENGTH;
441 msg_len += DTLS1_HM_HEADER_LENGTH;
443 tls1_finish_mac(s, p, msg_len);
444 if (s->internal->msg_callback)
445 s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, msg_len,
446 s, s->internal->msg_callback_arg);
448 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
450 /* Don't change sequence numbers while listening */
451 if (!D1I(s)->listen)
452 D1I(s)->handshake_read_seq++;
454 s->internal->init_msg = s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
455 return s->internal->init_num;
457 f_err:
458 ssl3_send_alert(s, SSL3_AL_FATAL, al);
459 *ok = 0;
460 return -1;
464 static int
465 dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr, int max)
467 size_t frag_off, frag_len, msg_len;
469 msg_len = msg_hdr->msg_len;
470 frag_off = msg_hdr->frag_off;
471 frag_len = msg_hdr->frag_len;
473 /* sanity checking */
474 if ((frag_off + frag_len) > msg_len) {
475 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
476 return SSL_AD_ILLEGAL_PARAMETER;
479 if ((frag_off + frag_len) > (unsigned long)max) {
480 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
481 return SSL_AD_ILLEGAL_PARAMETER;
484 if ( D1I(s)->r_msg_hdr.frag_off == 0) /* first fragment */
487 * msg_len is limited to 2^24, but is effectively checked
488 * against max above
490 if (!BUF_MEM_grow_clean(s->internal->init_buf,
491 msg_len + DTLS1_HM_HEADER_LENGTH)) {
492 SSLerror(s, ERR_R_BUF_LIB);
493 return SSL_AD_INTERNAL_ERROR;
496 S3I(s)->tmp.message_size = msg_len;
497 D1I(s)->r_msg_hdr.msg_len = msg_len;
498 S3I(s)->tmp.message_type = msg_hdr->type;
499 D1I(s)->r_msg_hdr.type = msg_hdr->type;
500 D1I(s)->r_msg_hdr.seq = msg_hdr->seq;
501 } else if (msg_len != D1I(s)->r_msg_hdr.msg_len) {
503 * They must be playing with us! BTW, failure to enforce
504 * upper limit would open possibility for buffer overrun.
506 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE);
507 return SSL_AD_ILLEGAL_PARAMETER;
510 return 0; /* no error */
513 static int
514 dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
517 * (0) check whether the desired fragment is available
518 * if so:
519 * (1) copy over the fragment to s->internal->init_buf->data[]
520 * (2) update s->internal->init_num
522 pitem *item;
523 hm_fragment *frag;
524 int al;
526 *ok = 0;
527 item = pqueue_peek(D1I(s)->buffered_messages);
528 if (item == NULL)
529 return 0;
531 frag = (hm_fragment *)item->data;
533 /* Don't return if reassembly still in progress */
534 if (frag->reassembly != NULL)
535 return 0;
537 if (D1I(s)->handshake_read_seq == frag->msg_header.seq) {
538 unsigned long frag_len = frag->msg_header.frag_len;
539 pqueue_pop(D1I(s)->buffered_messages);
541 al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
543 if (al == 0) /* no alert */
545 unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
546 memcpy(&p[frag->msg_header.frag_off],
547 frag->fragment, frag->msg_header.frag_len);
550 dtls1_hm_fragment_free(frag);
551 pitem_free(item);
553 if (al == 0) {
554 *ok = 1;
555 return frag_len;
558 ssl3_send_alert(s, SSL3_AL_FATAL, al);
559 s->internal->init_num = 0;
560 *ok = 0;
561 return -1;
562 } else
563 return 0;
567 * dtls1_max_handshake_message_len returns the maximum number of bytes
568 * permitted in a DTLS handshake message for |s|. The minimum is 16KB,
569 * but may be greater if the maximum certificate list size requires it.
571 static unsigned long
572 dtls1_max_handshake_message_len(const SSL *s)
574 unsigned long max_len;
576 max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
577 if (max_len < (unsigned long)s->internal->max_cert_list)
578 return s->internal->max_cert_list;
579 return max_len;
582 static int
583 dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
585 hm_fragment *frag = NULL;
586 pitem *item = NULL;
587 int i = -1, is_complete;
588 unsigned char seq64be[8];
589 unsigned long frag_len = msg_hdr->frag_len;
591 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
592 msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
593 goto err;
595 if (frag_len == 0) {
596 i = DTLS1_HM_FRAGMENT_RETRY;
597 goto err;
600 /* Try to find item in queue */
601 memset(seq64be, 0, sizeof(seq64be));
602 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
603 seq64be[7] = (unsigned char)msg_hdr->seq;
604 item = pqueue_find(D1I(s)->buffered_messages, seq64be);
606 if (item == NULL) {
607 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
608 if (frag == NULL)
609 goto err;
610 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
611 frag->msg_header.frag_len = frag->msg_header.msg_len;
612 frag->msg_header.frag_off = 0;
613 } else {
614 frag = (hm_fragment*)item->data;
615 if (frag->msg_header.msg_len != msg_hdr->msg_len) {
616 item = NULL;
617 frag = NULL;
618 goto err;
623 * If message is already reassembled, this must be a
624 * retransmit and can be dropped.
626 if (frag->reassembly == NULL) {
627 unsigned char devnull [256];
629 while (frag_len) {
630 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
631 devnull, frag_len > sizeof(devnull) ?
632 sizeof(devnull) : frag_len, 0);
633 if (i <= 0)
634 goto err;
635 frag_len -= i;
637 i = DTLS1_HM_FRAGMENT_RETRY;
638 goto err;
641 /* read the body of the fragment (header has already been read */
642 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
643 frag->fragment + msg_hdr->frag_off, frag_len, 0);
644 if (i <= 0 || (unsigned long)i != frag_len)
645 goto err;
647 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
648 (long)(msg_hdr->frag_off + frag_len));
650 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
651 is_complete);
653 if (is_complete) {
654 free(frag->reassembly);
655 frag->reassembly = NULL;
658 if (item == NULL) {
659 memset(seq64be, 0, sizeof(seq64be));
660 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
661 seq64be[7] = (unsigned char)(msg_hdr->seq);
663 item = pitem_new(seq64be, frag);
664 if (item == NULL) {
665 i = -1;
666 goto err;
669 pqueue_insert(D1I(s)->buffered_messages, item);
672 return DTLS1_HM_FRAGMENT_RETRY;
674 err:
675 if (item == NULL && frag != NULL)
676 dtls1_hm_fragment_free(frag);
677 *ok = 0;
678 return i;
682 static int
683 dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
685 int i = -1;
686 hm_fragment *frag = NULL;
687 pitem *item = NULL;
688 unsigned char seq64be[8];
689 unsigned long frag_len = msg_hdr->frag_len;
691 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
692 goto err;
694 /* Try to find item in queue, to prevent duplicate entries */
695 memset(seq64be, 0, sizeof(seq64be));
696 seq64be[6] = (unsigned char) (msg_hdr->seq >> 8);
697 seq64be[7] = (unsigned char) msg_hdr->seq;
698 item = pqueue_find(D1I(s)->buffered_messages, seq64be);
701 * If we already have an entry and this one is a fragment,
702 * don't discard it and rather try to reassemble it.
704 if (item != NULL && frag_len < msg_hdr->msg_len)
705 item = NULL;
708 * Discard the message if sequence number was already there, is
709 * too far in the future, already in the queue or if we received
710 * a FINISHED before the SERVER_HELLO, which then must be a stale
711 * retransmit.
713 if (msg_hdr->seq <= D1I(s)->handshake_read_seq ||
714 msg_hdr->seq > D1I(s)->handshake_read_seq + 10 || item != NULL ||
715 (D1I(s)->handshake_read_seq == 0 &&
716 msg_hdr->type == SSL3_MT_FINISHED)) {
717 unsigned char devnull [256];
719 while (frag_len) {
720 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
721 devnull, frag_len > sizeof(devnull) ?
722 sizeof(devnull) : frag_len, 0);
723 if (i <= 0)
724 goto err;
725 frag_len -= i;
727 } else {
728 if (frag_len < msg_hdr->msg_len)
729 return dtls1_reassemble_fragment(s, msg_hdr, ok);
731 if (frag_len > dtls1_max_handshake_message_len(s))
732 goto err;
734 frag = dtls1_hm_fragment_new(frag_len, 0);
735 if (frag == NULL)
736 goto err;
738 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
740 if (frag_len) {
741 /* read the body of the fragment (header has already been read */
742 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
743 frag->fragment, frag_len, 0);
744 if (i <= 0 || (unsigned long)i != frag_len)
745 goto err;
748 memset(seq64be, 0, sizeof(seq64be));
749 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
750 seq64be[7] = (unsigned char)(msg_hdr->seq);
752 item = pitem_new(seq64be, frag);
753 if (item == NULL)
754 goto err;
756 pqueue_insert(D1I(s)->buffered_messages, item);
759 return DTLS1_HM_FRAGMENT_RETRY;
761 err:
762 if (item == NULL && frag != NULL)
763 dtls1_hm_fragment_free(frag);
764 *ok = 0;
765 return i;
769 static long
770 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
772 unsigned char wire[DTLS1_HM_HEADER_LENGTH];
773 unsigned long len, frag_off, frag_len;
774 int i, al;
775 struct hm_header_st msg_hdr;
777 again:
778 /* see if we have the required fragment already */
779 if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
780 if (*ok)
781 s->internal->init_num = frag_len;
782 return frag_len;
785 /* read handshake message header */
786 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
787 DTLS1_HM_HEADER_LENGTH, 0);
788 if (i <= 0) /* nbio, or an error */
790 s->internal->rwstate = SSL_READING;
791 *ok = 0;
792 return i;
794 /* Handshake fails if message header is incomplete */
795 if (i != DTLS1_HM_HEADER_LENGTH ||
796 /* parse the message fragment header */
797 dtls1_get_message_header(wire, &msg_hdr) == 0) {
798 al = SSL_AD_UNEXPECTED_MESSAGE;
799 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
800 goto f_err;
804 * if this is a future (or stale) message it gets buffered
805 * (or dropped)--no further processing at this time
806 * While listening, we accept seq 1 (ClientHello with cookie)
807 * although we're still expecting seq 0 (ClientHello)
809 if (msg_hdr.seq != D1I(s)->handshake_read_seq &&
810 !(D1I(s)->listen && msg_hdr.seq == 1))
811 return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
813 len = msg_hdr.msg_len;
814 frag_off = msg_hdr.frag_off;
815 frag_len = msg_hdr.frag_len;
817 if (frag_len && frag_len < len)
818 return dtls1_reassemble_fragment(s, &msg_hdr, ok);
820 if (!s->server && D1I(s)->r_msg_hdr.frag_off == 0 &&
821 wire[0] == SSL3_MT_HELLO_REQUEST) {
823 * The server may always send 'Hello Request' messages --
824 * we are doing a handshake anyway now, so ignore them
825 * if their format is correct. Does not count for
826 * 'Finished' MAC.
828 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
829 if (s->internal->msg_callback)
830 s->internal->msg_callback(0, s->version,
831 SSL3_RT_HANDSHAKE, wire,
832 DTLS1_HM_HEADER_LENGTH, s,
833 s->internal->msg_callback_arg);
835 s->internal->init_num = 0;
836 goto again;
838 else /* Incorrectly formated Hello request */
840 al = SSL_AD_UNEXPECTED_MESSAGE;
841 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
842 goto f_err;
846 if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
847 goto f_err;
849 /* XDTLS: ressurect this when restart is in place */
850 S3I(s)->hs.state = stn;
852 if (frag_len > 0) {
853 unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH;
855 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
856 &p[frag_off], frag_len, 0);
857 /* XDTLS: fix this--message fragments cannot span multiple packets */
858 if (i <= 0) {
859 s->internal->rwstate = SSL_READING;
860 *ok = 0;
861 return i;
863 } else
864 i = 0;
867 * XDTLS: an incorrectly formatted fragment should cause the
868 * handshake to fail
870 if (i != (int)frag_len) {
871 al = SSL3_AD_ILLEGAL_PARAMETER;
872 SSLerror(s, SSL3_AD_ILLEGAL_PARAMETER);
873 goto f_err;
876 *ok = 1;
879 * Note that s->internal->init_num is *not* used as current offset in
880 * s->internal->init_buf->data, but as a counter summing up fragments'
881 * lengths: as soon as they sum up to handshake packet
882 * length, we assume we have got all the fragments.
884 s->internal->init_num = frag_len;
885 return frag_len;
887 f_err:
888 ssl3_send_alert(s, SSL3_AL_FATAL, al);
889 s->internal->init_num = 0;
891 *ok = 0;
892 return (-1);
896 dtls1_read_failed(SSL *s, int code)
898 if (code > 0) {
899 #ifdef DEBUG
900 fprintf(stderr, "invalid state reached %s:%d",
901 __FILE__, __LINE__);
902 #endif
903 return 1;
906 if (!dtls1_is_timer_expired(s)) {
908 * not a timeout, none of our business, let higher layers
909 * handle this. in fact it's probably an error
911 return code;
914 if (!SSL_in_init(s)) /* done, no need to send a retransmit */
916 BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
917 return code;
920 return dtls1_handle_timeout(s);
924 dtls1_get_queue_priority(unsigned short seq, int is_ccs)
927 * The index of the retransmission queue actually is the message
928 * sequence number, since the queue only contains messages of a
929 * single handshake. However, the ChangeCipherSpec has no message
930 * sequence number and so using only the sequence will result in
931 * the CCS and Finished having the same index. To prevent this, the
932 * sequence number is multiplied by 2. In case of a CCS 1 is
933 * subtracted. This does not only differ CSS and Finished, it also
934 * maintains the order of the index (important for priority queues)
935 * and fits in the unsigned short variable.
937 return seq * 2 - is_ccs;
941 dtls1_retransmit_buffered_messages(SSL *s)
943 pqueue sent = s->d1->sent_messages;
944 piterator iter;
945 pitem *item;
946 hm_fragment *frag;
947 int found = 0;
949 iter = pqueue_iterator(sent);
951 for (item = pqueue_next(&iter); item != NULL;
952 item = pqueue_next(&iter)) {
953 frag = (hm_fragment *)item->data;
954 if (dtls1_retransmit_message(s,
955 (unsigned short)dtls1_get_queue_priority(
956 frag->msg_header.seq, frag->msg_header.is_ccs), 0,
957 &found) <= 0 && found) {
958 #ifdef DEBUG
959 fprintf(stderr, "dtls1_retransmit_message() failed\n");
960 #endif
961 return -1;
965 return 1;
969 dtls1_buffer_message(SSL *s, int is_ccs)
971 pitem *item;
972 hm_fragment *frag;
973 unsigned char seq64be[8];
975 /* Buffer the messsage in order to handle DTLS retransmissions. */
978 * This function is called immediately after a message has
979 * been serialized
981 OPENSSL_assert(s->internal->init_off == 0);
983 frag = dtls1_hm_fragment_new(s->internal->init_num, 0);
984 if (frag == NULL)
985 return 0;
987 memcpy(frag->fragment, s->internal->init_buf->data, s->internal->init_num);
989 if (is_ccs) {
990 OPENSSL_assert(D1I(s)->w_msg_hdr.msg_len +
991 ((s->version == DTLS1_VERSION) ?
992 DTLS1_CCS_HEADER_LENGTH : 3) == (unsigned int)s->internal->init_num);
993 } else {
994 OPENSSL_assert(D1I(s)->w_msg_hdr.msg_len +
995 DTLS1_HM_HEADER_LENGTH == (unsigned int)s->internal->init_num);
998 frag->msg_header.msg_len = D1I(s)->w_msg_hdr.msg_len;
999 frag->msg_header.seq = D1I(s)->w_msg_hdr.seq;
1000 frag->msg_header.type = D1I(s)->w_msg_hdr.type;
1001 frag->msg_header.frag_off = 0;
1002 frag->msg_header.frag_len = D1I(s)->w_msg_hdr.msg_len;
1003 frag->msg_header.is_ccs = is_ccs;
1005 /* save current state*/
1006 frag->msg_header.saved_retransmit_state.enc_write_ctx = s->internal->enc_write_ctx;
1007 frag->msg_header.saved_retransmit_state.write_hash = s->internal->write_hash;
1008 frag->msg_header.saved_retransmit_state.session = s->session;
1009 frag->msg_header.saved_retransmit_state.epoch = D1I(s)->w_epoch;
1011 memset(seq64be, 0, sizeof(seq64be));
1012 seq64be[6] = (unsigned char)(dtls1_get_queue_priority(
1013 frag->msg_header.seq, frag->msg_header.is_ccs) >> 8);
1014 seq64be[7] = (unsigned char)(dtls1_get_queue_priority(
1015 frag->msg_header.seq, frag->msg_header.is_ccs));
1017 item = pitem_new(seq64be, frag);
1018 if (item == NULL) {
1019 dtls1_hm_fragment_free(frag);
1020 return 0;
1023 pqueue_insert(s->d1->sent_messages, item);
1024 return 1;
1028 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1029 int *found)
1031 int ret;
1032 /* XDTLS: for now assuming that read/writes are blocking */
1033 pitem *item;
1034 hm_fragment *frag;
1035 unsigned long header_length;
1036 unsigned char seq64be[8];
1037 struct dtls1_retransmit_state saved_state;
1038 unsigned char save_write_sequence[8];
1041 OPENSSL_assert(s->internal->init_num == 0);
1042 OPENSSL_assert(s->internal->init_off == 0);
1045 /* XDTLS: the requested message ought to be found, otherwise error */
1046 memset(seq64be, 0, sizeof(seq64be));
1047 seq64be[6] = (unsigned char)(seq >> 8);
1048 seq64be[7] = (unsigned char)seq;
1050 item = pqueue_find(s->d1->sent_messages, seq64be);
1051 if (item == NULL) {
1052 #ifdef DEBUG
1053 fprintf(stderr, "retransmit: message %d non-existant\n", seq);
1054 #endif
1055 *found = 0;
1056 return 0;
1059 *found = 1;
1060 frag = (hm_fragment *)item->data;
1062 if (frag->msg_header.is_ccs)
1063 header_length = DTLS1_CCS_HEADER_LENGTH;
1064 else
1065 header_length = DTLS1_HM_HEADER_LENGTH;
1067 memcpy(s->internal->init_buf->data, frag->fragment,
1068 frag->msg_header.msg_len + header_length);
1069 s->internal->init_num = frag->msg_header.msg_len + header_length;
1071 dtls1_set_message_header_int(s, frag->msg_header.type,
1072 frag->msg_header.msg_len, frag->msg_header.seq, 0,
1073 frag->msg_header.frag_len);
1075 /* save current state */
1076 saved_state.enc_write_ctx = s->internal->enc_write_ctx;
1077 saved_state.write_hash = s->internal->write_hash;
1078 saved_state.session = s->session;
1079 saved_state.epoch = D1I(s)->w_epoch;
1081 D1I(s)->retransmitting = 1;
1083 /* restore state in which the message was originally sent */
1084 s->internal->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1085 s->internal->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1086 s->session = frag->msg_header.saved_retransmit_state.session;
1087 D1I(s)->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1089 if (frag->msg_header.saved_retransmit_state.epoch ==
1090 saved_state.epoch - 1) {
1091 memcpy(save_write_sequence, S3I(s)->write_sequence,
1092 sizeof(S3I(s)->write_sequence));
1093 memcpy(S3I(s)->write_sequence, D1I(s)->last_write_sequence,
1094 sizeof(S3I(s)->write_sequence));
1097 ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1098 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1100 /* restore current state */
1101 s->internal->enc_write_ctx = saved_state.enc_write_ctx;
1102 s->internal->write_hash = saved_state.write_hash;
1103 s->session = saved_state.session;
1104 D1I(s)->w_epoch = saved_state.epoch;
1106 if (frag->msg_header.saved_retransmit_state.epoch ==
1107 saved_state.epoch - 1) {
1108 memcpy(D1I(s)->last_write_sequence, S3I(s)->write_sequence,
1109 sizeof(S3I(s)->write_sequence));
1110 memcpy(S3I(s)->write_sequence, save_write_sequence,
1111 sizeof(S3I(s)->write_sequence));
1114 D1I(s)->retransmitting = 0;
1116 (void)BIO_flush(SSL_get_wbio(s));
1117 return ret;
1120 /* call this function when the buffered messages are no longer needed */
1121 void
1122 dtls1_clear_record_buffer(SSL *s)
1124 pitem *item;
1126 for(item = pqueue_pop(s->d1->sent_messages); item != NULL;
1127 item = pqueue_pop(s->d1->sent_messages)) {
1128 dtls1_hm_fragment_free((hm_fragment *)item->data);
1129 pitem_free(item);
1133 void
1134 dtls1_set_message_header(SSL *s, unsigned char mt, unsigned long len,
1135 unsigned long frag_off, unsigned long frag_len)
1137 /* Don't change sequence numbers while listening */
1138 if (frag_off == 0 && !D1I(s)->listen) {
1139 D1I(s)->handshake_write_seq = D1I(s)->next_handshake_write_seq;
1140 D1I(s)->next_handshake_write_seq++;
1143 dtls1_set_message_header_int(s, mt, len, D1I(s)->handshake_write_seq,
1144 frag_off, frag_len);
1147 /* don't actually do the writing, wait till the MTU has been retrieved */
1148 void
1149 dtls1_set_message_header_int(SSL *s, unsigned char mt, unsigned long len,
1150 unsigned short seq_num, unsigned long frag_off, unsigned long frag_len)
1152 struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
1154 msg_hdr->type = mt;
1155 msg_hdr->msg_len = len;
1156 msg_hdr->seq = seq_num;
1157 msg_hdr->frag_off = frag_off;
1158 msg_hdr->frag_len = frag_len;
1161 static void
1162 dtls1_fix_message_header(SSL *s, unsigned long frag_off, unsigned long frag_len)
1164 struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
1166 msg_hdr->frag_off = frag_off;
1167 msg_hdr->frag_len = frag_len;
1170 static unsigned char *
1171 dtls1_write_message_header(SSL *s, unsigned char *p)
1173 struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr;
1175 *p++ = msg_hdr->type;
1176 l2n3(msg_hdr->msg_len, p);
1178 s2n(msg_hdr->seq, p);
1179 l2n3(msg_hdr->frag_off, p);
1180 l2n3(msg_hdr->frag_len, p);
1182 return p;
1185 unsigned int
1186 dtls1_min_mtu(void)
1188 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1189 sizeof(g_probable_mtu[0])) - 1]);
1192 static unsigned int
1193 dtls1_guess_mtu(unsigned int curr_mtu)
1195 unsigned int i;
1197 if (curr_mtu == 0)
1198 return g_probable_mtu[0];
1200 for (i = 0; i < sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0]); i++)
1201 if (curr_mtu > g_probable_mtu[i])
1202 return g_probable_mtu[i];
1204 return curr_mtu;
1208 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1210 CBS header;
1211 uint32_t msg_len, frag_off, frag_len;
1212 uint16_t seq;
1213 uint8_t type;
1215 CBS_init(&header, data, sizeof(*msg_hdr));
1217 memset(msg_hdr, 0, sizeof(*msg_hdr));
1219 if (!CBS_get_u8(&header, &type))
1220 return 0;
1221 if (!CBS_get_u24(&header, &msg_len))
1222 return 0;
1223 if (!CBS_get_u16(&header, &seq))
1224 return 0;
1225 if (!CBS_get_u24(&header, &frag_off))
1226 return 0;
1227 if (!CBS_get_u24(&header, &frag_len))
1228 return 0;
1230 msg_hdr->type = type;
1231 msg_hdr->msg_len = msg_len;
1232 msg_hdr->seq = seq;
1233 msg_hdr->frag_off = frag_off;
1234 msg_hdr->frag_len = frag_len;
1236 return 1;
1239 void
1240 dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1242 memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
1244 ccs_hdr->type = *(data++);
1248 dtls1_shutdown(SSL *s)
1250 int ret;
1252 ret = ssl3_shutdown(s);
1253 return ret;