1 /* $OpenBSD: d1_both.c,v 1.38 2015/09/11 18:08:21 jsing Exp $ */
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.]
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>
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) { \
135 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
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) { \
145 OPENSSL_assert((msg_len) > 0); \
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 void dtls1_set_message_header_int(SSL *s, unsigned char mt,
166 unsigned long len, unsigned short seq_num, unsigned long frag_off,
167 unsigned long frag_len);
168 static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max,
172 dtls1_hm_fragment_new(unsigned long frag_len, int reassembly)
174 hm_fragment *frag = NULL;
175 unsigned char *buf = NULL;
176 unsigned char *bitmask = NULL;
178 frag = malloc(sizeof(hm_fragment));
183 buf = malloc(frag_len);
190 /* zero length fragment gets zero frag->fragment */
191 frag->fragment = buf;
193 /* Initialize reassembly bitmask if necessary */
195 bitmask = malloc(RSMBLY_BITMASK_SIZE(frag_len));
196 if (bitmask == NULL) {
201 memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
204 frag->reassembly = bitmask;
210 dtls1_hm_fragment_free(hm_fragment *frag)
215 if (frag->msg_header.is_ccs) {
217 frag->msg_header.saved_retransmit_state.enc_write_ctx);
219 frag->msg_header.saved_retransmit_state.write_hash);
221 free(frag->fragment);
222 free(frag->reassembly);
226 /* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
228 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)) {
237 s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
238 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
241 * I've seen the kernel return bogus numbers when it
242 * doesn't know the MTU (ie., the initial write), so just
243 * make sure we have a reasonable number
245 if (s->d1->mtu < dtls1_min_mtu()) {
247 s->d1->mtu = dtls1_guess_mtu(s->d1->mtu);
248 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
253 OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu());
254 /* should have something reasonable now */
256 if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
257 OPENSSL_assert(s->init_num ==
258 (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
261 mac_size = EVP_MD_CTX_size(s->write_hash);
265 if (s->enc_write_ctx &&
266 (EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
267 blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
272 while (s->init_num) {
273 curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
274 DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
276 if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
277 /* grr.. we could get an error if MTU picked was wrong */
278 ret = BIO_flush(SSL_get_wbio(s));
281 curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH -
282 mac_size - blocksize;
285 if (s->init_num > curr_mtu)
291 /* XDTLS: this function is too long. split out the CCS part */
292 if (type == SSL3_RT_HANDSHAKE) {
293 if (s->init_off != 0) {
294 OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
295 s->init_off -= DTLS1_HM_HEADER_LENGTH;
296 s->init_num += DTLS1_HM_HEADER_LENGTH;
298 if (s->init_num > curr_mtu)
304 dtls1_fix_message_header(s, frag_off,
305 len - DTLS1_HM_HEADER_LENGTH);
307 dtls1_write_message_header(s,
308 (unsigned char *)&s->init_buf->data[s->init_off]);
310 OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
313 ret = dtls1_write_bytes(s, type,
314 &s->init_buf->data[s->init_off], len);
317 * Might need to update MTU here, but we don't know
318 * which previous packet caused the failure -- so
319 * can't really retransmit anything. continue as
320 * if everything is fine and wait for an alert to
321 * handle the retransmit
323 if (BIO_ctrl(SSL_get_wbio(s),
324 BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0)
325 s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
326 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
332 * Bad if this assert fails, only part of the
333 * handshake message got sent. but why would
336 OPENSSL_assert(len == (unsigned int)ret);
338 if (type == SSL3_RT_HANDSHAKE &&
339 !s->d1->retransmitting) {
341 * Should not be done for 'Hello Request's,
342 * but in that case we'll ignore the result
345 unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
346 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
351 * Reconstruct message header is if it
352 * is being sent in single fragment
354 *p++ = msg_hdr->type;
355 l2n3(msg_hdr->msg_len, p);
356 s2n (msg_hdr->seq, p);
358 l2n3(msg_hdr->msg_len, p);
359 p -= DTLS1_HM_HEADER_LENGTH;
362 p += DTLS1_HM_HEADER_LENGTH;
363 xlen = ret - DTLS1_HM_HEADER_LENGTH;
366 tls1_finish_mac(s, p, xlen);
369 if (ret == s->init_num) {
371 s->msg_callback(1, s->version, type,
373 (size_t)(s->init_off + s->init_num),
374 s, s->msg_callback_arg);
377 /* done writing this message */
384 frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
392 * Obtain handshake message of message type 'mt' (any if mt == -1),
393 * maximum acceptable body length 'max'.
394 * Read an entire handshake message. Handshake messages arrive in
398 dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
401 struct hm_header_st *msg_hdr;
403 unsigned long msg_len;
406 * s3->tmp is used to store messages that are unexpected, caused
407 * by the absence of an optional handshake message
409 if (s->s3->tmp.reuse_message) {
410 s->s3->tmp.reuse_message = 0;
411 if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
412 al = SSL_AD_UNEXPECTED_MESSAGE;
413 SSLerr(SSL_F_DTLS1_GET_MESSAGE,
414 SSL_R_UNEXPECTED_MESSAGE);
418 s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
419 s->init_num = (int)s->s3->tmp.message_size;
423 msg_hdr = &s->d1->r_msg_hdr;
424 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
427 i = dtls1_get_message_fragment(s, st1, stn, max, ok);
428 if (i == DTLS1_HM_BAD_FRAGMENT ||
429 i == DTLS1_HM_FRAGMENT_RETRY) /* bad fragment received */
431 else if (i <= 0 && !*ok)
434 p = (unsigned char *)s->init_buf->data;
435 msg_len = msg_hdr->msg_len;
437 /* reconstruct message header */
438 *(p++) = msg_hdr->type;
440 s2n (msg_hdr->seq, p);
444 p -= DTLS1_HM_HEADER_LENGTH;
445 msg_len += DTLS1_HM_HEADER_LENGTH;
447 tls1_finish_mac(s, p, msg_len);
449 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, msg_len,
450 s, s->msg_callback_arg);
452 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
454 /* Don't change sequence numbers while listening */
456 s->d1->handshake_read_seq++;
458 s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
462 ssl3_send_alert(s, SSL3_AL_FATAL, al);
469 dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr, int max)
471 size_t frag_off, frag_len, msg_len;
473 msg_len = msg_hdr->msg_len;
474 frag_off = msg_hdr->frag_off;
475 frag_len = msg_hdr->frag_len;
477 /* sanity checking */
478 if ((frag_off + frag_len) > msg_len) {
479 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,
480 SSL_R_EXCESSIVE_MESSAGE_SIZE);
481 return SSL_AD_ILLEGAL_PARAMETER;
484 if ((frag_off + frag_len) > (unsigned long)max) {
485 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,
486 SSL_R_EXCESSIVE_MESSAGE_SIZE);
487 return SSL_AD_ILLEGAL_PARAMETER;
490 if ( s->d1->r_msg_hdr.frag_off == 0) /* first fragment */
493 * msg_len is limited to 2^24, but is effectively checked
496 if (!BUF_MEM_grow_clean(s->init_buf,
497 msg_len + DTLS1_HM_HEADER_LENGTH)) {
498 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB);
499 return SSL_AD_INTERNAL_ERROR;
502 s->s3->tmp.message_size = msg_len;
503 s->d1->r_msg_hdr.msg_len = msg_len;
504 s->s3->tmp.message_type = msg_hdr->type;
505 s->d1->r_msg_hdr.type = msg_hdr->type;
506 s->d1->r_msg_hdr.seq = msg_hdr->seq;
507 } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
509 * They must be playing with us! BTW, failure to enforce
510 * upper limit would open possibility for buffer overrun.
512 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,
513 SSL_R_EXCESSIVE_MESSAGE_SIZE);
514 return SSL_AD_ILLEGAL_PARAMETER;
517 return 0; /* no error */
521 dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
524 * (0) check whether the desired fragment is available
526 * (1) copy over the fragment to s->init_buf->data[]
527 * (2) update s->init_num
534 item = pqueue_peek(s->d1->buffered_messages);
538 frag = (hm_fragment *)item->data;
540 /* Don't return if reassembly still in progress */
541 if (frag->reassembly != NULL)
544 if (s->d1->handshake_read_seq == frag->msg_header.seq) {
545 unsigned long frag_len = frag->msg_header.frag_len;
546 pqueue_pop(s->d1->buffered_messages);
548 al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
550 if (al == 0) /* no alert */
552 unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
553 memcpy(&p[frag->msg_header.frag_off],
554 frag->fragment, frag->msg_header.frag_len);
557 dtls1_hm_fragment_free(frag);
565 ssl3_send_alert(s, SSL3_AL_FATAL, al);
574 * dtls1_max_handshake_message_len returns the maximum number of bytes
575 * permitted in a DTLS handshake message for |s|. The minimum is 16KB,
576 * but may be greater if the maximum certificate list size requires it.
579 dtls1_max_handshake_message_len(const SSL *s)
581 unsigned long max_len;
583 max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
584 if (max_len < (unsigned long)s->max_cert_list)
585 return s->max_cert_list;
590 dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
592 hm_fragment *frag = NULL;
594 int i = -1, is_complete;
595 unsigned char seq64be[8];
596 unsigned long frag_len = msg_hdr->frag_len;
598 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
599 msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
603 i = DTLS1_HM_FRAGMENT_RETRY;
607 /* Try to find item in queue */
608 memset(seq64be, 0, sizeof(seq64be));
609 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
610 seq64be[7] = (unsigned char)msg_hdr->seq;
611 item = pqueue_find(s->d1->buffered_messages, seq64be);
614 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
617 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
618 frag->msg_header.frag_len = frag->msg_header.msg_len;
619 frag->msg_header.frag_off = 0;
621 frag = (hm_fragment*)item->data;
622 if (frag->msg_header.msg_len != msg_hdr->msg_len) {
630 * If message is already reassembled, this must be a
631 * retransmit and can be dropped.
633 if (frag->reassembly == NULL) {
634 unsigned char devnull [256];
637 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
638 devnull, frag_len > sizeof(devnull) ?
639 sizeof(devnull) : frag_len, 0);
644 i = DTLS1_HM_FRAGMENT_RETRY;
648 /* read the body of the fragment (header has already been read */
649 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
650 frag->fragment + msg_hdr->frag_off, frag_len, 0);
651 if (i <= 0 || (unsigned long)i != frag_len)
654 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
655 (long)(msg_hdr->frag_off + frag_len));
657 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
661 free(frag->reassembly);
662 frag->reassembly = NULL;
666 memset(seq64be, 0, sizeof(seq64be));
667 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
668 seq64be[7] = (unsigned char)(msg_hdr->seq);
670 item = pitem_new(seq64be, frag);
676 pqueue_insert(s->d1->buffered_messages, item);
679 return DTLS1_HM_FRAGMENT_RETRY;
682 if (item == NULL && frag != NULL)
683 dtls1_hm_fragment_free(frag);
690 dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
693 hm_fragment *frag = NULL;
695 unsigned char seq64be[8];
696 unsigned long frag_len = msg_hdr->frag_len;
698 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
701 /* Try to find item in queue, to prevent duplicate entries */
702 memset(seq64be, 0, sizeof(seq64be));
703 seq64be[6] = (unsigned char) (msg_hdr->seq >> 8);
704 seq64be[7] = (unsigned char) msg_hdr->seq;
705 item = pqueue_find(s->d1->buffered_messages, seq64be);
708 * If we already have an entry and this one is a fragment,
709 * don't discard it and rather try to reassemble it.
711 if (item != NULL && frag_len < msg_hdr->msg_len)
715 * Discard the message if sequence number was already there, is
716 * too far in the future, already in the queue or if we received
717 * a FINISHED before the SERVER_HELLO, which then must be a stale
720 if (msg_hdr->seq <= s->d1->handshake_read_seq ||
721 msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
722 (s->d1->handshake_read_seq == 0 &&
723 msg_hdr->type == SSL3_MT_FINISHED)) {
724 unsigned char devnull [256];
727 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
728 devnull, frag_len > sizeof(devnull) ?
729 sizeof(devnull) : frag_len, 0);
735 if (frag_len < msg_hdr->msg_len)
736 return dtls1_reassemble_fragment(s, msg_hdr, ok);
738 if (frag_len > dtls1_max_handshake_message_len(s))
741 frag = dtls1_hm_fragment_new(frag_len, 0);
745 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
748 /* read the body of the fragment (header has already been read */
749 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
750 frag->fragment, frag_len, 0);
751 if (i <= 0 || (unsigned long)i != frag_len)
755 memset(seq64be, 0, sizeof(seq64be));
756 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
757 seq64be[7] = (unsigned char)(msg_hdr->seq);
759 item = pitem_new(seq64be, frag);
763 pqueue_insert(s->d1->buffered_messages, item);
766 return DTLS1_HM_FRAGMENT_RETRY;
769 if (item == NULL && frag != NULL)
770 dtls1_hm_fragment_free(frag);
777 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
779 unsigned char wire[DTLS1_HM_HEADER_LENGTH];
780 unsigned long len, frag_off, frag_len;
782 struct hm_header_st msg_hdr;
785 /* see if we have the required fragment already */
786 if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
788 s->init_num = frag_len;
792 /* read handshake message header */
793 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
794 DTLS1_HM_HEADER_LENGTH, 0);
795 if (i <= 0) /* nbio, or an error */
797 s->rwstate = SSL_READING;
801 /* Handshake fails if message header is incomplete */
802 if (i != DTLS1_HM_HEADER_LENGTH ||
803 /* parse the message fragment header */
804 dtls1_get_message_header(wire, &msg_hdr) == 0) {
805 al = SSL_AD_UNEXPECTED_MESSAGE;
806 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
807 SSL_R_UNEXPECTED_MESSAGE);
812 * if this is a future (or stale) message it gets buffered
813 * (or dropped)--no further processing at this time
814 * While listening, we accept seq 1 (ClientHello with cookie)
815 * although we're still expecting seq 0 (ClientHello)
817 if (msg_hdr.seq != s->d1->handshake_read_seq &&
818 !(s->d1->listen && msg_hdr.seq == 1))
819 return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
821 len = msg_hdr.msg_len;
822 frag_off = msg_hdr.frag_off;
823 frag_len = msg_hdr.frag_len;
825 if (frag_len && frag_len < len)
826 return dtls1_reassemble_fragment(s, &msg_hdr, ok);
828 if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
829 wire[0] == SSL3_MT_HELLO_REQUEST) {
831 * The server may always send 'Hello Request' messages --
832 * we are doing a handshake anyway now, so ignore them
833 * if their format is correct. Does not count for
836 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
838 s->msg_callback(0, s->version,
839 SSL3_RT_HANDSHAKE, wire,
840 DTLS1_HM_HEADER_LENGTH, s,
841 s->msg_callback_arg);
846 else /* Incorrectly formated Hello request */
848 al = SSL_AD_UNEXPECTED_MESSAGE;
849 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
850 SSL_R_UNEXPECTED_MESSAGE);
855 if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
858 /* XDTLS: ressurect this when restart is in place */
862 unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
864 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
865 &p[frag_off], frag_len, 0);
866 /* XDTLS: fix this--message fragments cannot span multiple packets */
868 s->rwstate = SSL_READING;
876 * XDTLS: an incorrectly formatted fragment should cause the
879 if (i != (int)frag_len) {
880 al = SSL3_AD_ILLEGAL_PARAMETER;
881 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
882 SSL3_AD_ILLEGAL_PARAMETER);
889 * Note that s->init_num is *not* used as current offset in
890 * s->init_buf->data, but as a counter summing up fragments'
891 * lengths: as soon as they sum up to handshake packet
892 * length, we assume we have got all the fragments.
894 s->init_num = frag_len;
898 ssl3_send_alert(s, SSL3_AL_FATAL, al);
906 * for these 2 messages, we need to
907 * ssl->enc_read_ctx re-init
908 * ssl->s3->read_sequence zero
909 * ssl->s3->read_mac_secret re-init
910 * ssl->session->read_sym_enc assign
911 * ssl->session->read_hash assign
914 dtls1_send_change_cipher_spec(SSL *s, int a, int b)
919 p = (unsigned char *)s->init_buf->data;
921 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
922 s->init_num = DTLS1_CCS_HEADER_LENGTH;
926 dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
927 s->d1->handshake_write_seq, 0, 0);
929 /* buffer the message to handle re-xmits */
930 dtls1_buffer_message(s, 1);
935 /* SSL3_ST_CW_CHANGE_B */
936 return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
940 dtls1_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
945 n = i2d_X509(x, NULL);
946 if (!BUF_MEM_grow_clean(buf, n + (*l) + 3)) {
947 SSLerr(SSL_F_DTLS1_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
950 p = (unsigned char *)&(buf->data[*l]);
959 dtls1_output_cert_chain(SSL *s, X509 *x)
963 unsigned long l = 3 + DTLS1_HM_HEADER_LENGTH;
966 /* TLSv1 sends a chain with nothing in it, instead of an alert */
968 if (!BUF_MEM_grow_clean(buf, 10)) {
969 SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_BUF_LIB);
973 X509_STORE_CTX xs_ctx;
975 if (!X509_STORE_CTX_init(&xs_ctx, s->ctx->cert_store,
977 SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN, ERR_R_X509_LIB);
981 X509_verify_cert(&xs_ctx);
982 /* Don't leave errors in the queue */
984 for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
985 x = sk_X509_value(xs_ctx.chain, i);
987 if (!dtls1_add_cert_to_buf(buf, &l, x)) {
988 X509_STORE_CTX_cleanup(&xs_ctx);
992 X509_STORE_CTX_cleanup(&xs_ctx);
994 /* Thawte special :-) */
995 for (i = 0; i < sk_X509_num(s->ctx->extra_certs); i++) {
996 x = sk_X509_value(s->ctx->extra_certs, i);
997 if (!dtls1_add_cert_to_buf(buf, &l, x))
1001 l -= (3 + DTLS1_HM_HEADER_LENGTH);
1003 p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
1006 p = (unsigned char *)&(buf->data[0]);
1007 p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l);
1009 l += DTLS1_HM_HEADER_LENGTH;
1014 dtls1_read_failed(SSL *s, int code)
1018 fprintf(stderr, "invalid state reached %s:%d",
1019 __FILE__, __LINE__);
1024 if (!dtls1_is_timer_expired(s)) {
1026 * not a timeout, none of our business, let higher layers
1027 * handle this. in fact it's probably an error
1032 if (!SSL_in_init(s)) /* done, no need to send a retransmit */
1034 BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1038 return dtls1_handle_timeout(s);
1042 dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1045 * The index of the retransmission queue actually is the message
1046 * sequence number, since the queue only contains messages of a
1047 * single handshake. However, the ChangeCipherSpec has no message
1048 * sequence number and so using only the sequence will result in
1049 * the CCS and Finished having the same index. To prevent this, the
1050 * sequence number is multiplied by 2. In case of a CCS 1 is
1051 * subtracted. This does not only differ CSS and Finished, it also
1052 * maintains the order of the index (important for priority queues)
1053 * and fits in the unsigned short variable.
1055 return seq * 2 - is_ccs;
1059 dtls1_retransmit_buffered_messages(SSL *s)
1061 pqueue sent = s->d1->sent_messages;
1067 iter = pqueue_iterator(sent);
1069 for (item = pqueue_next(&iter); item != NULL;
1070 item = pqueue_next(&iter)) {
1071 frag = (hm_fragment *)item->data;
1072 if (dtls1_retransmit_message(s,
1073 (unsigned short)dtls1_get_queue_priority(
1074 frag->msg_header.seq, frag->msg_header.is_ccs), 0,
1075 &found) <= 0 && found) {
1077 fprintf(stderr, "dtls1_retransmit_message() failed\n");
1087 dtls1_buffer_message(SSL *s, int is_ccs)
1091 unsigned char seq64be[8];
1093 /* Buffer the messsage in order to handle DTLS retransmissions. */
1096 * This function is called immediately after a message has
1099 OPENSSL_assert(s->init_off == 0);
1101 frag = dtls1_hm_fragment_new(s->init_num, 0);
1105 memcpy(frag->fragment, s->init_buf->data, s->init_num);
1108 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1109 ((s->version == DTLS1_VERSION) ?
1110 DTLS1_CCS_HEADER_LENGTH : 3) == (unsigned int)s->init_num);
1112 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1113 DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1116 frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1117 frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1118 frag->msg_header.type = s->d1->w_msg_hdr.type;
1119 frag->msg_header.frag_off = 0;
1120 frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1121 frag->msg_header.is_ccs = is_ccs;
1123 /* save current state*/
1124 frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1125 frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1126 frag->msg_header.saved_retransmit_state.session = s->session;
1127 frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
1129 memset(seq64be, 0, sizeof(seq64be));
1130 seq64be[6] = (unsigned char)(dtls1_get_queue_priority(
1131 frag->msg_header.seq, frag->msg_header.is_ccs) >> 8);
1132 seq64be[7] = (unsigned char)(dtls1_get_queue_priority(
1133 frag->msg_header.seq, frag->msg_header.is_ccs));
1135 item = pitem_new(seq64be, frag);
1137 dtls1_hm_fragment_free(frag);
1141 pqueue_insert(s->d1->sent_messages, item);
1146 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
1150 /* XDTLS: for now assuming that read/writes are blocking */
1153 unsigned long header_length;
1154 unsigned char seq64be[8];
1155 struct dtls1_retransmit_state saved_state;
1156 unsigned char save_write_sequence[8];
1159 OPENSSL_assert(s->init_num == 0);
1160 OPENSSL_assert(s->init_off == 0);
1163 /* XDTLS: the requested message ought to be found, otherwise error */
1164 memset(seq64be, 0, sizeof(seq64be));
1165 seq64be[6] = (unsigned char)(seq >> 8);
1166 seq64be[7] = (unsigned char)seq;
1168 item = pqueue_find(s->d1->sent_messages, seq64be);
1171 fprintf(stderr, "retransmit: message %d non-existant\n", seq);
1178 frag = (hm_fragment *)item->data;
1180 if (frag->msg_header.is_ccs)
1181 header_length = DTLS1_CCS_HEADER_LENGTH;
1183 header_length = DTLS1_HM_HEADER_LENGTH;
1185 memcpy(s->init_buf->data, frag->fragment,
1186 frag->msg_header.msg_len + header_length);
1187 s->init_num = frag->msg_header.msg_len + header_length;
1189 dtls1_set_message_header_int(s, frag->msg_header.type,
1190 frag->msg_header.msg_len, frag->msg_header.seq, 0,
1191 frag->msg_header.frag_len);
1193 /* save current state */
1194 saved_state.enc_write_ctx = s->enc_write_ctx;
1195 saved_state.write_hash = s->write_hash;
1196 saved_state.session = s->session;
1197 saved_state.epoch = s->d1->w_epoch;
1199 s->d1->retransmitting = 1;
1201 /* restore state in which the message was originally sent */
1202 s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1203 s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1204 s->session = frag->msg_header.saved_retransmit_state.session;
1205 s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
1207 if (frag->msg_header.saved_retransmit_state.epoch ==
1208 saved_state.epoch - 1) {
1209 memcpy(save_write_sequence, s->s3->write_sequence,
1210 sizeof(s->s3->write_sequence));
1211 memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
1212 sizeof(s->s3->write_sequence));
1215 ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1216 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1218 /* restore current state */
1219 s->enc_write_ctx = saved_state.enc_write_ctx;
1220 s->write_hash = saved_state.write_hash;
1221 s->session = saved_state.session;
1222 s->d1->w_epoch = saved_state.epoch;
1224 if (frag->msg_header.saved_retransmit_state.epoch ==
1225 saved_state.epoch - 1) {
1226 memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
1227 sizeof(s->s3->write_sequence));
1228 memcpy(s->s3->write_sequence, save_write_sequence,
1229 sizeof(s->s3->write_sequence));
1232 s->d1->retransmitting = 0;
1234 (void)BIO_flush(SSL_get_wbio(s));
1238 /* call this function when the buffered messages are no longer needed */
1240 dtls1_clear_record_buffer(SSL *s)
1244 for(item = pqueue_pop(s->d1->sent_messages); item != NULL;
1245 item = pqueue_pop(s->d1->sent_messages)) {
1246 dtls1_hm_fragment_free((hm_fragment *)item->data);
1252 dtls1_set_message_header(SSL *s, unsigned char *p, unsigned char mt,
1253 unsigned long len, unsigned long frag_off, unsigned long frag_len)
1255 /* Don't change sequence numbers while listening */
1256 if (frag_off == 0 && !s->d1->listen) {
1257 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1258 s->d1->next_handshake_write_seq++;
1261 dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1262 frag_off, frag_len);
1264 return p += DTLS1_HM_HEADER_LENGTH;
1267 /* don't actually do the writing, wait till the MTU has been retrieved */
1269 dtls1_set_message_header_int(SSL *s, unsigned char mt, unsigned long len,
1270 unsigned short seq_num, unsigned long frag_off, unsigned long frag_len)
1272 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1275 msg_hdr->msg_len = len;
1276 msg_hdr->seq = seq_num;
1277 msg_hdr->frag_off = frag_off;
1278 msg_hdr->frag_len = frag_len;
1282 dtls1_fix_message_header(SSL *s, unsigned long frag_off, unsigned long frag_len)
1284 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1286 msg_hdr->frag_off = frag_off;
1287 msg_hdr->frag_len = frag_len;
1290 static unsigned char *
1291 dtls1_write_message_header(SSL *s, unsigned char *p)
1293 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1295 *p++ = msg_hdr->type;
1296 l2n3(msg_hdr->msg_len, p);
1298 s2n(msg_hdr->seq, p);
1299 l2n3(msg_hdr->frag_off, p);
1300 l2n3(msg_hdr->frag_len, p);
1308 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1309 sizeof(g_probable_mtu[0])) - 1]);
1313 dtls1_guess_mtu(unsigned int curr_mtu)
1318 return g_probable_mtu[0];
1320 for (i = 0; i < sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0]); i++)
1321 if (curr_mtu > g_probable_mtu[i])
1322 return g_probable_mtu[i];
1328 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1331 uint32_t msg_len, frag_off, frag_len;
1335 CBS_init(&header, data, sizeof(*msg_hdr));
1337 memset(msg_hdr, 0, sizeof(*msg_hdr));
1339 if (!CBS_get_u8(&header, &type))
1341 if (!CBS_get_u24(&header, &msg_len))
1343 if (!CBS_get_u16(&header, &seq))
1345 if (!CBS_get_u24(&header, &frag_off))
1347 if (!CBS_get_u24(&header, &frag_len))
1350 msg_hdr->type = type;
1351 msg_hdr->msg_len = msg_len;
1353 msg_hdr->frag_off = frag_off;
1354 msg_hdr->frag_len = frag_len;
1360 dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1362 memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
1364 ccs_hdr->type = *(data++);
1368 dtls1_shutdown(SSL *s)
1372 ret = ssl3_shutdown(s);