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
547 item = pqueue_peek(s->d1->buffered_messages);
551 frag = (hm_fragment *)item->data;
553 if (frag->msg_header.seq < s->d1->handshake_read_seq) {
554 /* This is a stale message that has been buffered so clear it */
555 pqueue_pop(s->d1->buffered_messages);
556 dtls1_hm_fragment_free(frag);
561 } while (item == NULL);
564 /* Don't return if reassembly still in progress */
565 if (frag->reassembly != NULL)
568 if (s->d1->handshake_read_seq == frag->msg_header.seq) {
569 unsigned long frag_len = frag->msg_header.frag_len;
570 pqueue_pop(s->d1->buffered_messages);
572 al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
574 if (al == 0) { /* no alert */
576 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
577 memcpy(&p[frag->msg_header.frag_off], frag->fragment,
578 frag->msg_header.frag_len);
581 dtls1_hm_fragment_free(frag);
589 ssl3_send_alert(s, SSL3_AL_FATAL, al);
598 * dtls1_max_handshake_message_len returns the maximum number of bytes
599 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
600 * may be greater if the maximum certificate list size requires it.
602 static unsigned long dtls1_max_handshake_message_len(const SSL *s)
604 unsigned long max_len =
605 DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
606 if (max_len < (unsigned long)s->max_cert_list)
607 return s->max_cert_list;
612 dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
614 hm_fragment *frag = NULL;
616 int i = -1, is_complete;
618 unsigned long frag_len = msg_hdr->frag_len;
620 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
621 msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
625 return DTLS1_HM_FRAGMENT_RETRY;
627 /* Try to find item in queue */
628 pq_64bit_init(&seq64);
629 pq_64bit_assign_word(&seq64, msg_hdr->seq);
630 item = pqueue_find(s->d1->buffered_messages, seq64);
631 pq_64bit_free(&seq64);
634 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
637 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
638 frag->msg_header.frag_len = frag->msg_header.msg_len;
639 frag->msg_header.frag_off = 0;
641 frag = (hm_fragment *)item->data;
642 if (frag->msg_header.msg_len != msg_hdr->msg_len) {
650 * If message is already reassembled, this must be a retransmit and can
651 * be dropped. In this case item != NULL and so frag does not need to be
654 if (frag->reassembly == NULL) {
655 unsigned char devnull[256];
658 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
661 sizeof(devnull) ? sizeof(devnull) :
667 return DTLS1_HM_FRAGMENT_RETRY;
670 /* read the body of the fragment (header has already been read */
671 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
672 frag->fragment + msg_hdr->frag_off,
674 if ((unsigned long)i != frag_len)
679 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
680 (long)(msg_hdr->frag_off + frag_len));
682 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
686 OPENSSL_free(frag->reassembly);
687 frag->reassembly = NULL;
691 pq_64bit_init(&seq64);
692 pq_64bit_assign_word(&seq64, msg_hdr->seq);
693 item = pitem_new(seq64, frag);
694 pq_64bit_free(&seq64);
701 item = pqueue_insert(s->d1->buffered_messages, item);
703 * pqueue_insert fails iff a duplicate item is inserted. However,
704 * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
705 * would have returned it and control would never have reached this
708 OPENSSL_assert(item != NULL);
711 return DTLS1_HM_FRAGMENT_RETRY;
714 if (frag != NULL && item == NULL)
715 dtls1_hm_fragment_free(frag);
721 dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
725 hm_fragment *frag = NULL;
728 unsigned long frag_len = msg_hdr->frag_len;
730 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
733 /* Try to find item in queue, to prevent duplicate entries */
734 pq_64bit_init(&seq64);
735 pq_64bit_assign_word(&seq64, msg_hdr->seq);
736 item = pqueue_find(s->d1->buffered_messages, seq64);
737 pq_64bit_free(&seq64);
740 * If we already have an entry and this one is a fragment, don't discard
741 * it and rather try to reassemble it.
743 if (item != NULL && frag_len != msg_hdr->msg_len)
747 * Discard the message if sequence number was already there, is too far
748 * in the future, already in the queue or if we received a FINISHED
749 * before the SERVER_HELLO, which then must be a stale retransmit.
751 if (msg_hdr->seq <= s->d1->handshake_read_seq ||
752 msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
753 (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
755 unsigned char devnull[256];
758 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
761 sizeof(devnull) ? sizeof(devnull) :
768 if (frag_len != msg_hdr->msg_len)
769 return dtls1_reassemble_fragment(s, msg_hdr, ok);
771 if (frag_len > dtls1_max_handshake_message_len(s))
774 frag = dtls1_hm_fragment_new(frag_len, 0);
778 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
782 * read the body of the fragment (header has already been read)
784 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
785 frag->fragment, frag_len, 0);
786 if ((unsigned long)i != frag_len)
792 pq_64bit_init(&seq64);
793 pq_64bit_assign_word(&seq64, msg_hdr->seq);
795 item = pitem_new(seq64, frag);
796 pq_64bit_free(&seq64);
800 item = pqueue_insert(s->d1->buffered_messages, item);
802 * pqueue_insert fails iff a duplicate item is inserted. However,
803 * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
804 * would have returned it. Then, either |frag_len| !=
805 * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
806 * have been processed with |dtls1_reassemble_fragment|, above, or
807 * the record will have been discarded.
809 OPENSSL_assert(item != NULL);
812 return DTLS1_HM_FRAGMENT_RETRY;
815 if (frag != NULL && item == NULL)
816 dtls1_hm_fragment_free(frag);
822 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
824 unsigned char wire[DTLS1_HM_HEADER_LENGTH];
825 unsigned long len, frag_off, frag_len;
827 struct hm_header_st msg_hdr;
830 /* see if we have the required fragment already */
831 if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
833 s->init_num = frag_len;
837 /* read handshake message header */
838 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
839 DTLS1_HM_HEADER_LENGTH, 0);
840 if (i <= 0) { /* nbio, or an error */
841 s->rwstate = SSL_READING;
845 /* Handshake fails if message header is incomplete */
846 if (i != DTLS1_HM_HEADER_LENGTH) {
847 al = SSL_AD_UNEXPECTED_MESSAGE;
848 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_UNEXPECTED_MESSAGE);
852 /* parse the message fragment header */
853 dtls1_get_message_header(wire, &msg_hdr);
856 * if this is a future (or stale) message it gets buffered
857 * (or dropped)--no further processing at this time
858 * While listening, we accept seq 1 (ClientHello with cookie)
859 * although we're still expecting seq 0 (ClientHello)
861 if (msg_hdr.seq != s->d1->handshake_read_seq
862 && !(s->d1->listen && msg_hdr.seq == 1))
863 return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
865 len = msg_hdr.msg_len;
866 frag_off = msg_hdr.frag_off;
867 frag_len = msg_hdr.frag_len;
869 if (frag_len && frag_len < len)
870 return dtls1_reassemble_fragment(s, &msg_hdr, ok);
872 if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
873 wire[0] == SSL3_MT_HELLO_REQUEST) {
875 * The server may always send 'Hello Request' messages -- we are
876 * doing a handshake anyway now, so ignore them if their format is
877 * correct. Does not count for 'Finished' MAC.
879 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
881 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
882 wire, DTLS1_HM_HEADER_LENGTH, s,
883 s->msg_callback_arg);
887 } else { /* Incorrectly formated Hello request */
889 al = SSL_AD_UNEXPECTED_MESSAGE;
890 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
891 SSL_R_UNEXPECTED_MESSAGE);
896 if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
899 /* XDTLS: ressurect this when restart is in place */
904 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
906 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
907 &p[frag_off], frag_len, 0);
909 * XDTLS: fix this--message fragments cannot span multiple packets
912 s->rwstate = SSL_READING;
920 * XDTLS: an incorrectly formatted fragment should cause the handshake
923 if (i != (int)frag_len) {
924 al = SSL3_AD_ILLEGAL_PARAMETER;
925 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL3_AD_ILLEGAL_PARAMETER);
932 * Note that s->init_num is *not* used as current offset in
933 * s->init_buf->data, but as a counter summing up fragments' lengths: as
934 * soon as they sum up to handshake packet length, we assume we have got
937 s->init_num = frag_len;
941 ssl3_send_alert(s, SSL3_AL_FATAL, al);
948 int dtls1_send_finished(SSL *s, int a, int b, const char *sender, int slen)
950 unsigned char *p, *d;
955 d = (unsigned char *)s->init_buf->data;
956 p = &(d[DTLS1_HM_HEADER_LENGTH]);
958 i = s->method->ssl3_enc->final_finish_mac(s,
959 &(s->s3->finish_dgst1),
960 &(s->s3->finish_dgst2),
962 s->s3->tmp.finish_md);
963 s->s3->tmp.finish_md_len = i;
964 memcpy(p, s->s3->tmp.finish_md, i);
969 * Copy the finished so we can use it for renegotiation checks
971 if (s->type == SSL_ST_CONNECT) {
972 OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
973 memcpy(s->s3->previous_client_finished, s->s3->tmp.finish_md, i);
974 s->s3->previous_client_finished_len = i;
976 OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
977 memcpy(s->s3->previous_server_finished, s->s3->tmp.finish_md, i);
978 s->s3->previous_server_finished_len = i;
981 #ifdef OPENSSL_SYS_WIN16
983 * MSVC 1.5 does not clear the top bytes of the word unless I do
989 d = dtls1_set_message_header(s, d, SSL3_MT_FINISHED, l, 0, l);
990 s->init_num = (int)l + DTLS1_HM_HEADER_LENGTH;
993 /* buffer the message to handle re-xmits */
994 dtls1_buffer_message(s, 0);
999 /* SSL3_ST_SEND_xxxxxx_HELLO_B */
1000 return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1004 * for these 2 messages, we need to
1005 * ssl->enc_read_ctx re-init
1006 * ssl->s3->read_sequence zero
1007 * ssl->s3->read_mac_secret re-init
1008 * ssl->session->read_sym_enc assign
1009 * ssl->session->read_compression assign
1010 * ssl->session->read_hash assign
1012 int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
1016 if (s->state == a) {
1017 p = (unsigned char *)s->init_buf->data;
1019 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1020 s->init_num = DTLS1_CCS_HEADER_LENGTH;
1022 if (s->client_version == DTLS1_BAD_VER) {
1023 s->d1->next_handshake_write_seq++;
1024 s2n(s->d1->handshake_write_seq, p);
1030 dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1031 s->d1->handshake_write_seq, 0, 0);
1033 /* buffer the message to handle re-xmits */
1034 dtls1_buffer_message(s, 1);
1039 /* SSL3_ST_CW_CHANGE_B */
1040 return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
1043 static int dtls1_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
1048 n = i2d_X509(x, NULL);
1049 if (!BUF_MEM_grow_clean(buf, (int)(n + (*l) + 3))) {
1050 SSLerr(SSL_F_DTLS1_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
1053 p = (unsigned char *)&(buf->data[*l]);
1061 unsigned long dtls1_output_cert_chain(SSL *s, X509 *x)
1065 unsigned long l = 3 + DTLS1_HM_HEADER_LENGTH;
1068 /* TLSv1 sends a chain with nothing in it, instead of an alert */
1070 if (!BUF_MEM_grow_clean(buf, 10)) {
1071 SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_BUF_LIB);
1075 X509_STORE_CTX xs_ctx;
1077 if (!X509_STORE_CTX_init(&xs_ctx, s->ctx->cert_store, x, NULL)) {
1078 SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_X509_LIB);
1082 X509_verify_cert(&xs_ctx);
1083 /* Don't leave errors in the queue */
1085 for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
1086 x = sk_X509_value(xs_ctx.chain, i);
1088 if (!dtls1_add_cert_to_buf(buf, &l, x)) {
1089 X509_STORE_CTX_cleanup(&xs_ctx);
1093 X509_STORE_CTX_cleanup(&xs_ctx);
1095 /* Thawte special :-) */
1096 for (i = 0; i < sk_X509_num(s->ctx->extra_certs); i++) {
1097 x = sk_X509_value(s->ctx->extra_certs, i);
1098 if (!dtls1_add_cert_to_buf(buf, &l, x))
1102 l -= (3 + DTLS1_HM_HEADER_LENGTH);
1104 p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
1107 p = (unsigned char *)&(buf->data[0]);
1108 p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l);
1110 l += DTLS1_HM_HEADER_LENGTH;
1114 int dtls1_read_failed(SSL *s, int code)
1117 fprintf(stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
1121 if (!dtls1_is_timer_expired(s)) {
1123 * not a timeout, none of our business, let higher layers handle
1124 * this. in fact it's probably an error
1129 /* done, no need to send a retransmit */
1130 if (!SSL_in_init(s)) {
1131 BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1134 #if 0 /* for now, each alert contains only one
1136 item = pqueue_peek(state->rcvd_records);
1138 /* send an alert immediately for all the missing records */
1142 #if 0 /* no more alert sending, just retransmit the
1143 * last set of messages */
1144 if (state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT)
1145 ssl3_send_alert(s, SSL3_AL_WARNING,
1146 DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1149 return dtls1_handle_timeout(s);
1152 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1155 * The index of the retransmission queue actually is the message sequence
1156 * number, since the queue only contains messages of a single handshake.
1157 * However, the ChangeCipherSpec has no message sequence number and so
1158 * using only the sequence will result in the CCS and Finished having the
1159 * same index. To prevent this, the sequence number is multiplied by 2.
1160 * In case of a CCS 1 is subtracted. This does not only differ CSS and
1161 * Finished, it also maintains the order of the index (important for
1162 * priority queues) and fits in the unsigned short variable.
1164 return seq * 2 - is_ccs;
1167 int dtls1_retransmit_buffered_messages(SSL *s)
1169 pqueue sent = s->d1->sent_messages;
1175 iter = pqueue_iterator(sent);
1177 for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1178 frag = (hm_fragment *)item->data;
1179 if (dtls1_retransmit_message(s, (unsigned short)
1180 dtls1_get_queue_priority
1181 (frag->msg_header.seq,
1182 frag->msg_header.is_ccs), 0,
1183 &found) <= 0 && found) {
1184 fprintf(stderr, "dtls1_retransmit_message() failed\n");
1192 int dtls1_buffer_message(SSL *s, int is_ccs)
1199 * this function is called immediately after a message has been
1202 OPENSSL_assert(s->init_off == 0);
1204 frag = dtls1_hm_fragment_new(s->init_num, 0);
1208 memcpy(frag->fragment, s->init_buf->data, s->init_num);
1211 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1212 DTLS1_CCS_HEADER_LENGTH <= (unsigned int)s->init_num);
1214 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1215 DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1218 frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1219 frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1220 frag->msg_header.type = s->d1->w_msg_hdr.type;
1221 frag->msg_header.frag_off = 0;
1222 frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1223 frag->msg_header.is_ccs = is_ccs;
1225 /* save current state */
1226 frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1227 frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1228 frag->msg_header.saved_retransmit_state.compress = s->compress;
1229 frag->msg_header.saved_retransmit_state.session = s->session;
1230 frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
1232 pq_64bit_init(&seq64);
1234 pq_64bit_assign_word(&seq64,
1235 dtls1_get_queue_priority(frag->msg_header.seq,
1236 frag->msg_header.is_ccs));
1238 item = pitem_new(seq64, frag);
1239 pq_64bit_free(&seq64);
1241 dtls1_hm_fragment_free(frag);
1245 fprintf(stderr, "buffered messge: \ttype = %xx\n", msg_buf->type);
1246 fprintf(stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len);
1247 fprintf(stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num);
1250 pqueue_insert(s->d1->sent_messages, item);
1255 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1259 /* XDTLS: for now assuming that read/writes are blocking */
1262 unsigned long header_length;
1264 struct dtls1_retransmit_state saved_state;
1265 unsigned char save_write_sequence[8];
1268 OPENSSL_assert(s->init_num == 0);
1269 OPENSSL_assert(s->init_off == 0);
1272 /* XDTLS: the requested message ought to be found, otherwise error */
1273 pq_64bit_init(&seq64);
1274 pq_64bit_assign_word(&seq64, seq);
1276 item = pqueue_find(s->d1->sent_messages, seq64);
1277 pq_64bit_free(&seq64);
1279 fprintf(stderr, "retransmit: message %d non-existant\n", seq);
1285 frag = (hm_fragment *)item->data;
1287 if (frag->msg_header.is_ccs)
1288 header_length = DTLS1_CCS_HEADER_LENGTH;
1290 header_length = DTLS1_HM_HEADER_LENGTH;
1292 memcpy(s->init_buf->data, frag->fragment,
1293 frag->msg_header.msg_len + header_length);
1294 s->init_num = frag->msg_header.msg_len + header_length;
1296 dtls1_set_message_header_int(s, frag->msg_header.type,
1297 frag->msg_header.msg_len,
1298 frag->msg_header.seq, 0,
1299 frag->msg_header.frag_len);
1301 /* save current state */
1302 saved_state.enc_write_ctx = s->enc_write_ctx;
1303 saved_state.write_hash = s->write_hash;
1304 saved_state.compress = s->compress;
1305 saved_state.session = s->session;
1306 saved_state.epoch = s->d1->w_epoch;
1307 saved_state.epoch = s->d1->w_epoch;
1309 s->d1->retransmitting = 1;
1311 /* restore state in which the message was originally sent */
1312 s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1313 s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1314 s->compress = frag->msg_header.saved_retransmit_state.compress;
1315 s->session = frag->msg_header.saved_retransmit_state.session;
1316 s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1318 if (frag->msg_header.saved_retransmit_state.epoch ==
1319 saved_state.epoch - 1) {
1320 memcpy(save_write_sequence, s->s3->write_sequence,
1321 sizeof(s->s3->write_sequence));
1322 memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
1323 sizeof(s->s3->write_sequence));
1326 ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1327 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1329 /* restore current state */
1330 s->enc_write_ctx = saved_state.enc_write_ctx;
1331 s->write_hash = saved_state.write_hash;
1332 s->compress = saved_state.compress;
1333 s->session = saved_state.session;
1334 s->d1->w_epoch = saved_state.epoch;
1336 if (frag->msg_header.saved_retransmit_state.epoch ==
1337 saved_state.epoch - 1) {
1338 memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
1339 sizeof(s->s3->write_sequence));
1340 memcpy(s->s3->write_sequence, save_write_sequence,
1341 sizeof(s->s3->write_sequence));
1344 s->d1->retransmitting = 0;
1346 (void)BIO_flush(SSL_get_wbio(s));
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++);