3 * DTLS implementation written by Nagendra Modadugu
4 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
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
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
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
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
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
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.]
119 #include "ssl_locl.h"
120 #include <openssl/buffer.h>
121 #include <openssl/rand.h>
122 #include <openssl/objects.h>
123 #include <openssl/evp.h>
124 #include <openssl/x509.h>
126 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
128 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
129 if ((end) - (start) <= 8) { \
131 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
134 bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
135 for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
136 bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
139 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
141 OPENSSL_assert((msg_len) > 0); \
143 if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
144 if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
145 if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
148 # define RSMBLY_BITMASK_PRINT(bitmask, msg_len) { \
150 printf("bitmask: "); for (ii = 0; ii < (msg_len); ii++) \
151 printf("%d ", (bitmask[ii >> 3] & (1 << (ii & 7))) >> (ii & 7)); \
155 static unsigned char bitmask_start_values[] =
156 { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
157 static unsigned char bitmask_end_values[] =
158 { 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f };
160 /* XDTLS: figure out the right values */
161 static unsigned int g_probable_mtu[] = { 1500 - 28, 512 - 28, 256 - 28 };
163 static unsigned int dtls1_guess_mtu(unsigned int curr_mtu);
164 static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
165 unsigned long frag_len);
166 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
167 static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
169 unsigned short seq_num,
170 unsigned long frag_off,
171 unsigned long frag_len);
172 static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max,
175 static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
178 hm_fragment *frag = NULL;
179 unsigned char *buf = NULL;
180 unsigned char *bitmask = NULL;
182 frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
187 buf = (unsigned char *)OPENSSL_malloc(frag_len);
194 /* zero length fragment gets zero frag->fragment */
195 frag->fragment = buf;
197 /* Initialize reassembly bitmask if necessary */
200 (unsigned char *)OPENSSL_malloc(RSMBLY_BITMASK_SIZE(frag_len));
201 if (bitmask == NULL) {
207 memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
210 frag->reassembly = bitmask;
215 static void dtls1_hm_fragment_free(hm_fragment *frag)
218 OPENSSL_free(frag->fragment);
219 if (frag->reassembly)
220 OPENSSL_free(frag->reassembly);
225 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
226 * SSL3_RT_CHANGE_CIPHER_SPEC)
228 int dtls1_do_write(SSL *s, int type)
232 unsigned int len, frag_off, mac_size, blocksize;
234 /* AHA! Figure out the MTU, and stick to the right size */
235 if (s->d1->mtu < dtls1_min_mtu()
236 && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
238 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
241 * I've seen the kernel return bogus numbers when it doesn't know
242 * (initial write), so just make sure we have a reasonable number
244 if (s->d1->mtu < dtls1_min_mtu()) {
246 s->d1->mtu = dtls1_guess_mtu(s->d1->mtu);
247 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
254 fprintf(stderr, "using MTU = %d\n", mtu);
256 mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
258 curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s));
262 else if ((ret = BIO_flush(SSL_get_wbio(s))) <= 0)
265 if (BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu) {
266 ret = BIO_flush(SSL_get_wbio(s));
269 mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
273 OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something
276 if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
277 OPENSSL_assert(s->init_num ==
278 (int)s->d1->w_msg_hdr.msg_len +
279 DTLS1_HM_HEADER_LENGTH);
282 mac_size = EVP_MD_size(s->write_hash);
286 if (s->enc_write_ctx &&
287 (EVP_CIPHER_mode(s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
288 blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
293 while (s->init_num) {
294 curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
295 DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
297 if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
299 * grr.. we could get an error if MTU picked was wrong
301 ret = BIO_flush(SSL_get_wbio(s));
304 curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH -
305 mac_size - blocksize;
308 if (s->init_num > curr_mtu)
314 * XDTLS: this function is too long. split out the CCS part
316 if (type == SSL3_RT_HANDSHAKE) {
317 if (s->init_off != 0) {
318 OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
319 s->init_off -= DTLS1_HM_HEADER_LENGTH;
320 s->init_num += DTLS1_HM_HEADER_LENGTH;
322 if (s->init_num > curr_mtu)
328 dtls1_fix_message_header(s, frag_off,
329 len - DTLS1_HM_HEADER_LENGTH);
331 dtls1_write_message_header(s,
332 (unsigned char *)&s->init_buf->
335 OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
338 ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off],
342 * might need to update MTU here, but we don't know which
343 * previous packet caused the failure -- so can't really
344 * retransmit anything. continue as if everything is fine and
345 * wait for an alert to handle the retransmit
347 if (BIO_ctrl(SSL_get_wbio(s),
348 BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0)
349 s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
350 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
356 * bad if this assert fails, only part of the handshake message
357 * got sent. but why would this happen?
359 OPENSSL_assert(len == (unsigned int)ret);
361 if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
363 * should not be done for 'Hello Request's, but in that case
364 * we'll ignore the result anyway
367 (unsigned char *)&s->init_buf->data[s->init_off];
368 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
371 if (frag_off == 0 && s->client_version != DTLS1_BAD_VER) {
373 * reconstruct message header is if it is being sent in
376 *p++ = msg_hdr->type;
377 l2n3(msg_hdr->msg_len, p);
378 s2n(msg_hdr->seq, p);
380 l2n3(msg_hdr->msg_len, p);
381 p -= DTLS1_HM_HEADER_LENGTH;
384 p += DTLS1_HM_HEADER_LENGTH;
385 xlen = ret - DTLS1_HM_HEADER_LENGTH;
388 ssl3_finish_mac(s, p, xlen);
391 if (ret == s->init_num) {
393 s->msg_callback(1, s->version, type, s->init_buf->data,
394 (size_t)(s->init_off + s->init_num), s,
395 s->msg_callback_arg);
397 s->init_off = 0; /* done writing this message */
404 frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
411 * Obtain handshake message of message type 'mt' (any if mt == -1), maximum
412 * acceptable body length 'max'. Read an entire handshake message. Handshake
413 * messages arrive in fragments.
415 long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
418 struct hm_header_st *msg_hdr;
420 unsigned long msg_len;
423 * s3->tmp is used to store messages that are unexpected, caused by the
424 * absence of an optional handshake message
426 if (s->s3->tmp.reuse_message) {
427 s->s3->tmp.reuse_message = 0;
428 if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
429 al = SSL_AD_UNEXPECTED_MESSAGE;
430 SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
434 s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
435 s->init_num = (int)s->s3->tmp.message_size;
439 msg_hdr = &s->d1->r_msg_hdr;
440 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
443 i = dtls1_get_message_fragment(s, st1, stn, max, ok);
444 if (i == DTLS1_HM_BAD_FRAGMENT || i == DTLS1_HM_FRAGMENT_RETRY) {
445 /* bad fragment received */
447 } else if (i <= 0 && !*ok) {
451 p = (unsigned char *)s->init_buf->data;
452 msg_len = msg_hdr->msg_len;
454 /* reconstruct message header */
455 *(p++) = msg_hdr->type;
457 s2n(msg_hdr->seq, p);
460 if (s->version != DTLS1_BAD_VER) {
461 p -= DTLS1_HM_HEADER_LENGTH;
462 msg_len += DTLS1_HM_HEADER_LENGTH;
465 ssl3_finish_mac(s, p, msg_len);
467 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
468 p, msg_len, s, s->msg_callback_arg);
470 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
472 /* Don't change sequence numbers while listening */
474 s->d1->handshake_read_seq++;
476 s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
480 ssl3_send_alert(s, SSL3_AL_FATAL, al);
485 static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr,
488 size_t frag_off, frag_len, msg_len;
490 msg_len = msg_hdr->msg_len;
491 frag_off = msg_hdr->frag_off;
492 frag_len = msg_hdr->frag_len;
494 /* sanity checking */
495 if ((frag_off + frag_len) > msg_len) {
496 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
497 return SSL_AD_ILLEGAL_PARAMETER;
500 if ((frag_off + frag_len) > (unsigned long)max) {
501 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
502 return SSL_AD_ILLEGAL_PARAMETER;
505 if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
507 * msg_len is limited to 2^24, but is effectively checked against max
510 if (!BUF_MEM_grow_clean
511 (s->init_buf, (int)msg_len + DTLS1_HM_HEADER_LENGTH)) {
512 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB);
513 return SSL_AD_INTERNAL_ERROR;
516 s->s3->tmp.message_size = msg_len;
517 s->d1->r_msg_hdr.msg_len = msg_len;
518 s->s3->tmp.message_type = msg_hdr->type;
519 s->d1->r_msg_hdr.type = msg_hdr->type;
520 s->d1->r_msg_hdr.seq = msg_hdr->seq;
521 } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
523 * They must be playing with us! BTW, failure to enforce upper limit
524 * would open possibility for buffer overrun.
526 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
527 return SSL_AD_ILLEGAL_PARAMETER;
530 return 0; /* no error */
533 static int dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
536 * (0) check whether the desired fragment is available
538 * (1) copy over the fragment to s->init_buf->data[]
539 * (2) update s->init_num
546 item = pqueue_peek(s->d1->buffered_messages);
550 frag = (hm_fragment *)item->data;
552 /* Don't return if reassembly still in progress */
553 if (frag->reassembly != NULL)
556 if (s->d1->handshake_read_seq == frag->msg_header.seq) {
557 unsigned long frag_len = frag->msg_header.frag_len;
558 pqueue_pop(s->d1->buffered_messages);
560 al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
562 if (al == 0) { /* no alert */
564 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
565 memcpy(&p[frag->msg_header.frag_off], frag->fragment,
566 frag->msg_header.frag_len);
569 dtls1_hm_fragment_free(frag);
577 ssl3_send_alert(s, SSL3_AL_FATAL, al);
586 * dtls1_max_handshake_message_len returns the maximum number of bytes
587 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
588 * may be greater if the maximum certificate list size requires it.
590 static unsigned long dtls1_max_handshake_message_len(const SSL *s)
592 unsigned long max_len =
593 DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
594 if (max_len < (unsigned long)s->max_cert_list)
595 return s->max_cert_list;
600 dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
602 hm_fragment *frag = NULL;
604 int i = -1, is_complete;
606 unsigned long frag_len = msg_hdr->frag_len;
608 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
609 msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
613 return DTLS1_HM_FRAGMENT_RETRY;
615 /* Try to find item in queue */
616 pq_64bit_init(&seq64);
617 pq_64bit_assign_word(&seq64, msg_hdr->seq);
618 item = pqueue_find(s->d1->buffered_messages, seq64);
619 pq_64bit_free(&seq64);
622 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
625 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
626 frag->msg_header.frag_len = frag->msg_header.msg_len;
627 frag->msg_header.frag_off = 0;
629 frag = (hm_fragment *)item->data;
630 if (frag->msg_header.msg_len != msg_hdr->msg_len) {
638 * If message is already reassembled, this must be a retransmit and can
639 * be dropped. In this case item != NULL and so frag does not need to be
642 if (frag->reassembly == NULL) {
643 unsigned char devnull[256];
646 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
649 sizeof(devnull) ? sizeof(devnull) :
655 return DTLS1_HM_FRAGMENT_RETRY;
658 /* read the body of the fragment (header has already been read */
659 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
660 frag->fragment + msg_hdr->frag_off,
662 if ((unsigned long)i != frag_len)
667 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
668 (long)(msg_hdr->frag_off + frag_len));
670 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
674 OPENSSL_free(frag->reassembly);
675 frag->reassembly = NULL;
679 pq_64bit_init(&seq64);
680 pq_64bit_assign_word(&seq64, msg_hdr->seq);
681 item = pitem_new(seq64, frag);
682 pq_64bit_free(&seq64);
689 item = pqueue_insert(s->d1->buffered_messages, item);
691 * pqueue_insert fails iff a duplicate item is inserted. However,
692 * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
693 * would have returned it and control would never have reached this
696 OPENSSL_assert(item != NULL);
699 return DTLS1_HM_FRAGMENT_RETRY;
702 if (frag != NULL && item == NULL)
703 dtls1_hm_fragment_free(frag);
709 dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
713 hm_fragment *frag = NULL;
716 unsigned long frag_len = msg_hdr->frag_len;
718 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
721 /* Try to find item in queue, to prevent duplicate entries */
722 pq_64bit_init(&seq64);
723 pq_64bit_assign_word(&seq64, msg_hdr->seq);
724 item = pqueue_find(s->d1->buffered_messages, seq64);
725 pq_64bit_free(&seq64);
728 * If we already have an entry and this one is a fragment, don't discard
729 * it and rather try to reassemble it.
731 if (item != NULL && frag_len != msg_hdr->msg_len)
735 * Discard the message if sequence number was already there, is too far
736 * in the future, already in the queue or if we received a FINISHED
737 * before the SERVER_HELLO, which then must be a stale retransmit.
739 if (msg_hdr->seq <= s->d1->handshake_read_seq ||
740 msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
741 (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
743 unsigned char devnull[256];
746 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
749 sizeof(devnull) ? sizeof(devnull) :
756 if (frag_len != msg_hdr->msg_len)
757 return dtls1_reassemble_fragment(s, msg_hdr, ok);
759 if (frag_len > dtls1_max_handshake_message_len(s))
762 frag = dtls1_hm_fragment_new(frag_len, 0);
766 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
770 * read the body of the fragment (header has already been read)
772 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
773 frag->fragment, frag_len, 0);
774 if ((unsigned long)i != frag_len)
780 pq_64bit_init(&seq64);
781 pq_64bit_assign_word(&seq64, msg_hdr->seq);
783 item = pitem_new(seq64, frag);
784 pq_64bit_free(&seq64);
788 item = pqueue_insert(s->d1->buffered_messages, item);
790 * pqueue_insert fails iff a duplicate item is inserted. However,
791 * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
792 * would have returned it. Then, either |frag_len| !=
793 * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
794 * have been processed with |dtls1_reassemble_fragment|, above, or
795 * the record will have been discarded.
797 OPENSSL_assert(item != NULL);
800 return DTLS1_HM_FRAGMENT_RETRY;
803 if (frag != NULL && item == NULL)
804 dtls1_hm_fragment_free(frag);
810 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
812 unsigned char wire[DTLS1_HM_HEADER_LENGTH];
813 unsigned long len, frag_off, frag_len;
815 struct hm_header_st msg_hdr;
818 /* see if we have the required fragment already */
819 if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
821 s->init_num = frag_len;
825 /* read handshake message header */
826 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
827 DTLS1_HM_HEADER_LENGTH, 0);
828 if (i <= 0) { /* nbio, or an error */
829 s->rwstate = SSL_READING;
833 /* Handshake fails if message header is incomplete */
834 if (i != DTLS1_HM_HEADER_LENGTH) {
835 al = SSL_AD_UNEXPECTED_MESSAGE;
836 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_UNEXPECTED_MESSAGE);
840 /* parse the message fragment header */
841 dtls1_get_message_header(wire, &msg_hdr);
844 * if this is a future (or stale) message it gets buffered
845 * (or dropped)--no further processing at this time
846 * While listening, we accept seq 1 (ClientHello with cookie)
847 * although we're still expecting seq 0 (ClientHello)
849 if (msg_hdr.seq != s->d1->handshake_read_seq
850 && !(s->d1->listen && msg_hdr.seq == 1))
851 return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
853 len = msg_hdr.msg_len;
854 frag_off = msg_hdr.frag_off;
855 frag_len = msg_hdr.frag_len;
857 if (frag_len && frag_len < len)
858 return dtls1_reassemble_fragment(s, &msg_hdr, ok);
860 if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
861 wire[0] == SSL3_MT_HELLO_REQUEST) {
863 * The server may always send 'Hello Request' messages -- we are
864 * doing a handshake anyway now, so ignore them if their format is
865 * correct. Does not count for 'Finished' MAC.
867 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
869 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
870 wire, DTLS1_HM_HEADER_LENGTH, s,
871 s->msg_callback_arg);
875 } else { /* Incorrectly formated Hello request */
877 al = SSL_AD_UNEXPECTED_MESSAGE;
878 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
879 SSL_R_UNEXPECTED_MESSAGE);
884 if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
887 /* XDTLS: ressurect this when restart is in place */
892 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
894 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
895 &p[frag_off], frag_len, 0);
897 * XDTLS: fix this--message fragments cannot span multiple packets
900 s->rwstate = SSL_READING;
908 * XDTLS: an incorrectly formatted fragment should cause the handshake
911 if (i != (int)frag_len) {
912 al = SSL3_AD_ILLEGAL_PARAMETER;
913 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL3_AD_ILLEGAL_PARAMETER);
920 * Note that s->init_num is *not* used as current offset in
921 * s->init_buf->data, but as a counter summing up fragments' lengths: as
922 * soon as they sum up to handshake packet length, we assume we have got
925 s->init_num = frag_len;
929 ssl3_send_alert(s, SSL3_AL_FATAL, al);
936 int dtls1_send_finished(SSL *s, int a, int b, const char *sender, int slen)
938 unsigned char *p, *d;
943 d = (unsigned char *)s->init_buf->data;
944 p = &(d[DTLS1_HM_HEADER_LENGTH]);
946 i = s->method->ssl3_enc->final_finish_mac(s,
947 &(s->s3->finish_dgst1),
948 &(s->s3->finish_dgst2),
950 s->s3->tmp.finish_md);
951 s->s3->tmp.finish_md_len = i;
952 memcpy(p, s->s3->tmp.finish_md, i);
957 * Copy the finished so we can use it for renegotiation checks
959 if (s->type == SSL_ST_CONNECT) {
960 OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
961 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md, i);
962 s->s3->previous_client_finished_len = i;
964 OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
965 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md, i);
966 s->s3->previous_server_finished_len = i;
969 #ifdef OPENSSL_SYS_WIN16
971 * MSVC 1.5 does not clear the top bytes of the word unless I do
977 d = dtls1_set_message_header(s, d, SSL3_MT_FINISHED, l, 0, l);
978 s->init_num = (int)l + DTLS1_HM_HEADER_LENGTH;
981 /* buffer the message to handle re-xmits */
982 dtls1_buffer_message(s, 0);
987 /* SSL3_ST_SEND_xxxxxx_HELLO_B */
988 return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
992 * for these 2 messages, we need to
993 * ssl->enc_read_ctx re-init
994 * ssl->s3->read_sequence zero
995 * ssl->s3->read_mac_secret re-init
996 * ssl->session->read_sym_enc assign
997 * ssl->session->read_compression assign
998 * ssl->session->read_hash assign
1000 int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
1004 if (s->state == a) {
1005 p = (unsigned char *)s->init_buf->data;
1007 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1008 s->init_num = DTLS1_CCS_HEADER_LENGTH;
1010 if (s->client_version == DTLS1_BAD_VER) {
1011 s->d1->next_handshake_write_seq++;
1012 s2n(s->d1->handshake_write_seq, p);
1018 dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1019 s->d1->handshake_write_seq, 0, 0);
1021 /* buffer the message to handle re-xmits */
1022 dtls1_buffer_message(s, 1);
1027 /* SSL3_ST_CW_CHANGE_B */
1028 return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
1031 static int dtls1_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
1036 n = i2d_X509(x, NULL);
1037 if (!BUF_MEM_grow_clean(buf, (int)(n + (*l) + 3))) {
1038 SSLerr(SSL_F_DTLS1_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
1041 p = (unsigned char *)&(buf->data[*l]);
1049 unsigned long dtls1_output_cert_chain(SSL *s, X509 *x)
1053 unsigned long l = 3 + DTLS1_HM_HEADER_LENGTH;
1056 /* TLSv1 sends a chain with nothing in it, instead of an alert */
1058 if (!BUF_MEM_grow_clean(buf, 10)) {
1059 SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_BUF_LIB);
1063 X509_STORE_CTX xs_ctx;
1065 if (!X509_STORE_CTX_init(&xs_ctx, s->ctx->cert_store, x, NULL)) {
1066 SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_X509_LIB);
1070 X509_verify_cert(&xs_ctx);
1071 /* Don't leave errors in the queue */
1073 for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
1074 x = sk_X509_value(xs_ctx.chain, i);
1076 if (!dtls1_add_cert_to_buf(buf, &l, x)) {
1077 X509_STORE_CTX_cleanup(&xs_ctx);
1081 X509_STORE_CTX_cleanup(&xs_ctx);
1083 /* Thawte special :-) */
1084 for (i = 0; i < sk_X509_num(s->ctx->extra_certs); i++) {
1085 x = sk_X509_value(s->ctx->extra_certs, i);
1086 if (!dtls1_add_cert_to_buf(buf, &l, x))
1090 l -= (3 + DTLS1_HM_HEADER_LENGTH);
1092 p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
1095 p = (unsigned char *)&(buf->data[0]);
1096 p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l);
1098 l += DTLS1_HM_HEADER_LENGTH;
1102 int dtls1_read_failed(SSL *s, int code)
1105 fprintf(stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
1109 if (!dtls1_is_timer_expired(s)) {
1111 * not a timeout, none of our business, let higher layers handle
1112 * this. in fact it's probably an error
1117 /* done, no need to send a retransmit */
1118 if (!SSL_in_init(s)) {
1119 BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1122 #if 0 /* for now, each alert contains only one
1124 item = pqueue_peek(state->rcvd_records);
1126 /* send an alert immediately for all the missing records */
1130 #if 0 /* no more alert sending, just retransmit the
1131 * last set of messages */
1132 if (state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT)
1133 ssl3_send_alert(s, SSL3_AL_WARNING,
1134 DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1137 return dtls1_handle_timeout(s);
1140 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1143 * The index of the retransmission queue actually is the message sequence
1144 * number, since the queue only contains messages of a single handshake.
1145 * However, the ChangeCipherSpec has no message sequence number and so
1146 * using only the sequence will result in the CCS and Finished having the
1147 * same index. To prevent this, the sequence number is multiplied by 2.
1148 * In case of a CCS 1 is subtracted. This does not only differ CSS and
1149 * Finished, it also maintains the order of the index (important for
1150 * priority queues) and fits in the unsigned short variable.
1152 return seq * 2 - is_ccs;
1155 int dtls1_retransmit_buffered_messages(SSL *s)
1157 pqueue sent = s->d1->sent_messages;
1163 iter = pqueue_iterator(sent);
1165 for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1166 frag = (hm_fragment *)item->data;
1167 if (dtls1_retransmit_message(s, (unsigned short)
1168 dtls1_get_queue_priority
1169 (frag->msg_header.seq,
1170 frag->msg_header.is_ccs), 0,
1171 &found) <= 0 && found) {
1172 fprintf(stderr, "dtls1_retransmit_message() failed\n");
1180 int dtls1_buffer_message(SSL *s, int is_ccs)
1187 * this function is called immediately after a message has been
1190 OPENSSL_assert(s->init_off == 0);
1192 frag = dtls1_hm_fragment_new(s->init_num, 0);
1196 memcpy(frag->fragment, s->init_buf->data, s->init_num);
1199 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1200 DTLS1_CCS_HEADER_LENGTH <= (unsigned int)s->init_num);
1202 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1203 DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1206 frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1207 frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1208 frag->msg_header.type = s->d1->w_msg_hdr.type;
1209 frag->msg_header.frag_off = 0;
1210 frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1211 frag->msg_header.is_ccs = is_ccs;
1213 /* save current state */
1214 frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1215 frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1216 frag->msg_header.saved_retransmit_state.compress = s->compress;
1217 frag->msg_header.saved_retransmit_state.session = s->session;
1218 frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
1220 pq_64bit_init(&seq64);
1222 pq_64bit_assign_word(&seq64,
1223 dtls1_get_queue_priority(frag->msg_header.seq,
1224 frag->msg_header.is_ccs));
1226 item = pitem_new(seq64, frag);
1227 pq_64bit_free(&seq64);
1229 dtls1_hm_fragment_free(frag);
1233 fprintf(stderr, "buffered messge: \ttype = %xx\n", msg_buf->type);
1234 fprintf(stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len);
1235 fprintf(stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num);
1238 pqueue_insert(s->d1->sent_messages, item);
1243 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1247 /* XDTLS: for now assuming that read/writes are blocking */
1250 unsigned long header_length;
1252 struct dtls1_retransmit_state saved_state;
1253 unsigned char save_write_sequence[8];
1256 OPENSSL_assert(s->init_num == 0);
1257 OPENSSL_assert(s->init_off == 0);
1260 /* XDTLS: the requested message ought to be found, otherwise error */
1261 pq_64bit_init(&seq64);
1262 pq_64bit_assign_word(&seq64, seq);
1264 item = pqueue_find(s->d1->sent_messages, seq64);
1265 pq_64bit_free(&seq64);
1267 fprintf(stderr, "retransmit: message %d non-existant\n", seq);
1273 frag = (hm_fragment *)item->data;
1275 if (frag->msg_header.is_ccs)
1276 header_length = DTLS1_CCS_HEADER_LENGTH;
1278 header_length = DTLS1_HM_HEADER_LENGTH;
1280 memcpy(s->init_buf->data, frag->fragment,
1281 frag->msg_header.msg_len + header_length);
1282 s->init_num = frag->msg_header.msg_len + header_length;
1284 dtls1_set_message_header_int(s, frag->msg_header.type,
1285 frag->msg_header.msg_len,
1286 frag->msg_header.seq, 0,
1287 frag->msg_header.frag_len);
1289 /* save current state */
1290 saved_state.enc_write_ctx = s->enc_write_ctx;
1291 saved_state.write_hash = s->write_hash;
1292 saved_state.compress = s->compress;
1293 saved_state.session = s->session;
1294 saved_state.epoch = s->d1->w_epoch;
1295 saved_state.epoch = s->d1->w_epoch;
1297 s->d1->retransmitting = 1;
1299 /* restore state in which the message was originally sent */
1300 s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1301 s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1302 s->compress = frag->msg_header.saved_retransmit_state.compress;
1303 s->session = frag->msg_header.saved_retransmit_state.session;
1304 s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1306 if (frag->msg_header.saved_retransmit_state.epoch ==
1307 saved_state.epoch - 1) {
1308 memcpy(save_write_sequence, s->s3->write_sequence,
1309 sizeof(s->s3->write_sequence));
1310 memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
1311 sizeof(s->s3->write_sequence));
1314 ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1315 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1317 /* restore current state */
1318 s->enc_write_ctx = saved_state.enc_write_ctx;
1319 s->write_hash = saved_state.write_hash;
1320 s->compress = saved_state.compress;
1321 s->session = saved_state.session;
1322 s->d1->w_epoch = saved_state.epoch;
1324 if (frag->msg_header.saved_retransmit_state.epoch ==
1325 saved_state.epoch - 1) {
1326 memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
1327 sizeof(s->s3->write_sequence));
1328 memcpy(s->s3->write_sequence, save_write_sequence,
1329 sizeof(s->s3->write_sequence));
1332 s->d1->retransmitting = 0;
1334 (void)BIO_flush(SSL_get_wbio(s));
1338 /* call this function when the buffered messages are no longer needed */
1339 void dtls1_clear_record_buffer(SSL *s)
1343 for (item = pqueue_pop(s->d1->sent_messages);
1344 item != NULL; item = pqueue_pop(s->d1->sent_messages)) {
1345 dtls1_hm_fragment_free((hm_fragment *)item->data);
1350 unsigned char *dtls1_set_message_header(SSL *s, unsigned char *p,
1351 unsigned char mt, unsigned long len,
1352 unsigned long frag_off,
1353 unsigned long frag_len)
1355 /* Don't change sequence numbers while listening */
1356 if (frag_off == 0 && !s->d1->listen) {
1357 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1358 s->d1->next_handshake_write_seq++;
1361 dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1362 frag_off, frag_len);
1364 return p += DTLS1_HM_HEADER_LENGTH;
1367 /* don't actually do the writing, wait till the MTU has been retrieved */
1369 dtls1_set_message_header_int(SSL *s, unsigned char mt,
1370 unsigned long len, unsigned short seq_num,
1371 unsigned long frag_off, unsigned long frag_len)
1373 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1376 msg_hdr->msg_len = len;
1377 msg_hdr->seq = seq_num;
1378 msg_hdr->frag_off = frag_off;
1379 msg_hdr->frag_len = frag_len;
1383 dtls1_fix_message_header(SSL *s, unsigned long frag_off,
1384 unsigned long frag_len)
1386 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1388 msg_hdr->frag_off = frag_off;
1389 msg_hdr->frag_len = frag_len;
1392 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p)
1394 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1396 *p++ = msg_hdr->type;
1397 l2n3(msg_hdr->msg_len, p);
1399 s2n(msg_hdr->seq, p);
1400 l2n3(msg_hdr->frag_off, p);
1401 l2n3(msg_hdr->frag_len, p);
1406 unsigned int dtls1_min_mtu(void)
1408 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1409 sizeof(g_probable_mtu[0])) - 1]);
1412 static unsigned int dtls1_guess_mtu(unsigned int curr_mtu)
1417 return g_probable_mtu[0];
1419 for (i = 0; i < sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0]); i++)
1420 if (curr_mtu > g_probable_mtu[i])
1421 return g_probable_mtu[i];
1427 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1429 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
1430 msg_hdr->type = *(data++);
1431 n2l3(data, msg_hdr->msg_len);
1433 n2s(data, msg_hdr->seq);
1434 n2l3(data, msg_hdr->frag_off);
1435 n2l3(data, msg_hdr->frag_len);
1438 void dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1440 memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
1442 ccs_hdr->type = *(data++);