2 * Copyright 2005-2022 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
14 #include "../ssl_local.h"
15 #include "statem_local.h"
16 #include "internal/cryptlib.h"
17 #include <openssl/buffer.h>
18 #include <openssl/objects.h>
19 #include <openssl/evp.h>
20 #include <openssl/x509.h>
22 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
24 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
25 if ((end) - (start) <= 8) { \
27 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
30 bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
31 for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
32 bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
35 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
38 if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
39 if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
40 if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
42 static unsigned char bitmask_start_values[] =
43 { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
44 static unsigned char bitmask_end_values[] =
45 { 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f };
47 static void dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off,
49 static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,
51 static void dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,
53 unsigned short seq_num,
56 static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
59 static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)
61 hm_fragment *frag = NULL;
62 unsigned char *buf = NULL;
63 unsigned char *bitmask = NULL;
65 if ((frag = OPENSSL_malloc(sizeof(*frag))) == NULL)
69 if ((buf = OPENSSL_malloc(frag_len)) == NULL) {
75 /* zero length fragment gets zero frag->fragment */
78 /* Initialize reassembly bitmask if necessary */
80 bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len));
81 if (bitmask == NULL) {
88 frag->reassembly = bitmask;
93 void dtls1_hm_fragment_free(hm_fragment *frag)
97 if (frag->msg_header.is_ccs) {
99 * If we're freeing the CCS then we're done with the old wrl and it
102 if (frag->msg_header.saved_retransmit_state.wrlmethod != NULL)
103 frag->msg_header.saved_retransmit_state.wrlmethod->free(frag->msg_header.saved_retransmit_state.wrl);
105 OPENSSL_free(frag->fragment);
106 OPENSSL_free(frag->reassembly);
111 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
112 * SSL3_RT_CHANGE_CIPHER_SPEC)
114 int dtls1_do_write(SSL_CONNECTION *s, int type)
120 size_t len, frag_off, overhead, used_len;
121 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
123 if (!dtls1_query_mtu(s))
126 if (s->d1->mtu < dtls1_min_mtu(s))
127 /* should have something reasonable now */
130 if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
131 if (!ossl_assert(s->init_num ==
132 s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH))
136 overhead = s->rlayer.wrlmethod->get_max_record_overhead(s->rlayer.wrl);
139 s->rwstate = SSL_NOTHING;
141 /* s->init_num shouldn't ever be < 0...but just in case */
142 while (s->init_num > 0) {
143 if (type == SSL3_RT_HANDSHAKE && s->init_off != 0) {
144 /* We must be writing a fragment other than the first one */
147 /* This is the first attempt at writing out this fragment */
149 if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {
151 * Each fragment that was already sent must at least have
152 * contained the message header plus one other byte.
153 * Therefore |init_off| must have progressed by at least
154 * |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went
161 * Adjust |init_off| and |init_num| to allow room for a new
162 * message header for this fragment.
164 s->init_off -= DTLS1_HM_HEADER_LENGTH;
165 s->init_num += DTLS1_HM_HEADER_LENGTH;
168 * We must have been called again after a retry so use the
169 * fragment offset from our last attempt. We do not need
170 * to adjust |init_off| and |init_num| as above, because
171 * that should already have been done before the retry.
173 frag_off = s->d1->w_msg_hdr.frag_off;
177 used_len = BIO_wpending(s->wbio) + overhead;
178 if (s->d1->mtu > used_len)
179 curr_mtu = s->d1->mtu - used_len;
183 if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
185 * grr.. we could get an error if MTU picked was wrong
187 ret = BIO_flush(s->wbio);
189 s->rwstate = SSL_WRITING;
192 if (s->d1->mtu > overhead + DTLS1_HM_HEADER_LENGTH) {
193 curr_mtu = s->d1->mtu - overhead;
195 /* Shouldn't happen */
201 * We just checked that s->init_num > 0 so this cast should be safe
203 if (((unsigned int)s->init_num) > curr_mtu)
208 if (len > ssl_get_max_send_fragment(s))
209 len = ssl_get_max_send_fragment(s);
212 * XDTLS: this function is too long. split out the CCS part
214 if (type == SSL3_RT_HANDSHAKE) {
215 if (len < DTLS1_HM_HEADER_LENGTH) {
217 * len is so small that we really can't do anything sensible
222 dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);
224 dtls1_write_message_header(s,
225 (unsigned char *)&s->init_buf->
229 ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,
233 * might need to update MTU here, but we don't know which
234 * previous packet caused the failure -- so can't really
235 * retransmit anything. continue as if everything is fine and
236 * wait for an alert to handle the retransmit
238 if (retry && BIO_ctrl(SSL_get_wbio(ssl),
239 BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
240 if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
241 if (!dtls1_query_mtu(s))
243 /* Have one more go */
253 * bad if this assert fails, only part of the handshake message
254 * got sent. but why would this happen?
256 if (!ossl_assert(len == written))
260 * We should not exceed the MTU size. If compression is in use
261 * then the max record overhead calculation is unreliable so we do
262 * not check in that case. We use assert rather than ossl_assert
263 * because in a production build, if this assert were ever to fail,
264 * then the best thing to do is probably carry on regardless.
266 assert(s->s3.tmp.new_compression != NULL
267 || BIO_wpending(s->wbio) <= (int)s->d1->mtu);
269 if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
271 * should not be done for 'Hello Request's, but in that case
272 * we'll ignore the result anyway
275 (unsigned char *)&s->init_buf->data[s->init_off];
276 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
279 if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
281 * reconstruct message header is if it is being sent in
284 *p++ = msg_hdr->type;
285 l2n3(msg_hdr->msg_len, p);
286 s2n(msg_hdr->seq, p);
288 l2n3(msg_hdr->msg_len, p);
289 p -= DTLS1_HM_HEADER_LENGTH;
292 p += DTLS1_HM_HEADER_LENGTH;
293 xlen = written - DTLS1_HM_HEADER_LENGTH;
296 if (!ssl3_finish_mac(s, p, xlen))
300 if (written == s->init_num) {
302 s->msg_callback(1, s->version, type, s->init_buf->data,
303 (size_t)(s->init_off + s->init_num), ssl,
304 s->msg_callback_arg);
306 s->init_off = 0; /* done writing this message */
311 s->init_off += written;
312 s->init_num -= written;
313 written -= DTLS1_HM_HEADER_LENGTH;
317 * We save the fragment offset for the next fragment so we have it
318 * available in case of an IO retry. We don't know the length of the
319 * next fragment yet so just set that to 0 for now. It will be
320 * updated again later.
322 dtls1_fix_message_header(s, frag_off, 0);
328 int dtls_get_message(SSL_CONNECTION *s, int *mt)
330 struct hm_header_st *msg_hdr;
336 msg_hdr = &s->d1->r_msg_hdr;
337 memset(msg_hdr, 0, sizeof(*msg_hdr));
340 if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
341 if (errtype == DTLS1_HM_BAD_FRAGMENT
342 || errtype == DTLS1_HM_FRAGMENT_RETRY) {
343 /* bad fragment received */
349 *mt = s->s3.tmp.message_type;
351 p = (unsigned char *)s->init_buf->data;
353 if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
354 if (s->msg_callback) {
355 s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
356 p, 1, SSL_CONNECTION_GET_SSL(s),
357 s->msg_callback_arg);
360 * This isn't a real handshake message so skip the processing below.
365 msg_len = msg_hdr->msg_len;
367 /* reconstruct message header */
368 *(p++) = msg_hdr->type;
370 s2n(msg_hdr->seq, p);
374 memset(msg_hdr, 0, sizeof(*msg_hdr));
376 s->d1->handshake_read_seq++;
378 s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
384 * Actually we already have the message body - but this is an opportunity for
385 * DTLS to do any further processing it wants at the same point that TLS would
386 * be asked for the message body.
388 int dtls_get_message_body(SSL_CONNECTION *s, size_t *len)
390 unsigned char *msg = (unsigned char *)s->init_buf->data;
391 size_t msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;
393 if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
394 /* Nothing to be done */
398 * If receiving Finished, record MAC of prior handshake messages for
399 * Finished verification.
401 if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
402 /* SSLfatal() already called */
406 if (s->version == DTLS1_BAD_VER) {
407 msg += DTLS1_HM_HEADER_LENGTH;
408 msg_len -= DTLS1_HM_HEADER_LENGTH;
411 if (!ssl3_finish_mac(s, msg, msg_len))
415 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
416 s->init_buf->data, s->init_num + DTLS1_HM_HEADER_LENGTH,
417 SSL_CONNECTION_GET_SSL(s), s->msg_callback_arg);
425 * dtls1_max_handshake_message_len returns the maximum number of bytes
426 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
427 * may be greater if the maximum certificate list size requires it.
429 static size_t dtls1_max_handshake_message_len(const SSL_CONNECTION *s)
431 size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
432 if (max_len < s->max_cert_list)
433 return s->max_cert_list;
437 static int dtls1_preprocess_fragment(SSL_CONNECTION *s,
438 struct hm_header_st *msg_hdr)
440 size_t frag_off, frag_len, msg_len;
442 msg_len = msg_hdr->msg_len;
443 frag_off = msg_hdr->frag_off;
444 frag_len = msg_hdr->frag_len;
446 /* sanity checking */
447 if ((frag_off + frag_len) > msg_len
448 || msg_len > dtls1_max_handshake_message_len(s)) {
449 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
453 if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
455 * msg_len is limited to 2^24, but is effectively checked against
456 * dtls_max_handshake_message_len(s) above
458 if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
459 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
463 s->s3.tmp.message_size = msg_len;
464 s->d1->r_msg_hdr.msg_len = msg_len;
465 s->s3.tmp.message_type = msg_hdr->type;
466 s->d1->r_msg_hdr.type = msg_hdr->type;
467 s->d1->r_msg_hdr.seq = msg_hdr->seq;
468 } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
470 * They must be playing with us! BTW, failure to enforce upper limit
471 * would open possibility for buffer overrun.
473 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
481 * Returns 1 if there is a buffered fragment available, 0 if not, or -1 on a
484 static int dtls1_retrieve_buffered_fragment(SSL_CONNECTION *s, size_t *len)
487 * (0) check whether the desired fragment is available
489 * (1) copy over the fragment to s->init_buf->data[]
490 * (2) update s->init_num
498 iter = pqueue_iterator(s->d1->buffered_messages);
500 item = pqueue_next(&iter);
504 frag = (hm_fragment *)item->data;
506 if (frag->msg_header.seq < s->d1->handshake_read_seq) {
508 hm_fragment *nextfrag;
511 || frag->msg_header.seq != 0
512 || s->d1->handshake_read_seq != 1
513 || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
515 * This is a stale message that has been buffered so clear it.
516 * It is safe to pop this message from the queue even though
517 * we have an active iterator
519 pqueue_pop(s->d1->buffered_messages);
520 dtls1_hm_fragment_free(frag);
526 * We have fragments for a ClientHello without a cookie,
527 * even though we have sent a HelloVerifyRequest. It is possible
528 * that the HelloVerifyRequest got lost and this is a
529 * retransmission of the original ClientHello
531 next = pqueue_next(&iter);
533 nextfrag = (hm_fragment *)next->data;
534 if (nextfrag->msg_header.seq == s->d1->handshake_read_seq) {
536 * We have fragments for both a ClientHello without
537 * cookie and one with. Ditch the one without.
539 pqueue_pop(s->d1->buffered_messages);
540 dtls1_hm_fragment_free(frag);
552 } while (item == NULL);
554 /* Don't return if reassembly still in progress */
555 if (frag->reassembly != NULL)
558 if (s->d1->handshake_read_seq == frag->msg_header.seq || chretran) {
559 size_t frag_len = frag->msg_header.frag_len;
560 pqueue_pop(s->d1->buffered_messages);
562 /* Calls SSLfatal() as required */
563 ret = dtls1_preprocess_fragment(s, &frag->msg_header);
565 if (ret && frag->msg_header.frag_len > 0) {
567 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
568 memcpy(&p[frag->msg_header.frag_off], frag->fragment,
569 frag->msg_header.frag_len);
572 dtls1_hm_fragment_free(frag);
578 * We got a new ClientHello with a message sequence of 0.
579 * Reset the read/write sequences back to the beginning.
580 * We process it like this is the first time we've seen a
581 * ClientHello from the client.
583 s->d1->handshake_read_seq = 0;
584 s->d1->next_handshake_write_seq = 0;
598 static int dtls1_reassemble_fragment(SSL_CONNECTION *s,
599 const struct hm_header_st *msg_hdr)
601 hm_fragment *frag = NULL;
603 int i = -1, is_complete;
604 unsigned char seq64be[8];
605 size_t frag_len = msg_hdr->frag_len;
607 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
609 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
610 msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
614 return DTLS1_HM_FRAGMENT_RETRY;
617 /* Try to find item in queue */
618 memset(seq64be, 0, sizeof(seq64be));
619 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
620 seq64be[7] = (unsigned char)msg_hdr->seq;
621 item = pqueue_find(s->d1->buffered_messages, seq64be);
624 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
627 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
628 frag->msg_header.frag_len = frag->msg_header.msg_len;
629 frag->msg_header.frag_off = 0;
631 frag = (hm_fragment *)item->data;
632 if (frag->msg_header.msg_len != msg_hdr->msg_len) {
640 * If message is already reassembled, this must be a retransmit and can
641 * be dropped. In this case item != NULL and so frag does not need to be
644 if (frag->reassembly == NULL) {
645 unsigned char devnull[256];
648 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
651 sizeof(devnull) ? sizeof(devnull) :
652 frag_len, 0, &readbytes);
655 frag_len -= readbytes;
657 return DTLS1_HM_FRAGMENT_RETRY;
660 /* read the body of the fragment (header has already been read */
661 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
662 frag->fragment + msg_hdr->frag_off,
663 frag_len, 0, &readbytes);
664 if (i <= 0 || readbytes != frag_len)
669 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
670 (long)(msg_hdr->frag_off + frag_len));
672 if (!ossl_assert(msg_hdr->msg_len > 0))
674 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
678 OPENSSL_free(frag->reassembly);
679 frag->reassembly = NULL;
683 item = pitem_new(seq64be, frag);
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 if (!ossl_assert(item != NULL))
700 return DTLS1_HM_FRAGMENT_RETRY;
704 dtls1_hm_fragment_free(frag);
708 static int dtls1_process_out_of_seq_message(SSL_CONNECTION *s,
709 const struct hm_header_st *msg_hdr)
712 hm_fragment *frag = NULL;
714 unsigned char seq64be[8];
715 size_t frag_len = msg_hdr->frag_len;
717 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
719 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
722 /* Try to find item in queue, to prevent duplicate entries */
723 memset(seq64be, 0, sizeof(seq64be));
724 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
725 seq64be[7] = (unsigned char)msg_hdr->seq;
726 item = pqueue_find(s->d1->buffered_messages, seq64be);
729 * If we already have an entry and this one is a fragment, don't discard
730 * it and rather try to reassemble it.
732 if (item != NULL && frag_len != msg_hdr->msg_len)
736 * Discard the message if sequence number was already there, is too far
737 * in the future, already in the queue or if we received a FINISHED
738 * before the SERVER_HELLO, which then must be a stale retransmit.
740 if (msg_hdr->seq <= s->d1->handshake_read_seq ||
741 msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
742 (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED)) {
743 unsigned char devnull[256];
746 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
749 sizeof(devnull) ? sizeof(devnull) :
750 frag_len, 0, &readbytes);
753 frag_len -= readbytes;
756 if (frag_len != msg_hdr->msg_len) {
757 return dtls1_reassemble_fragment(s, msg_hdr);
760 if (frag_len > dtls1_max_handshake_message_len(s))
763 frag = dtls1_hm_fragment_new(frag_len, 0);
767 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
771 * read the body of the fragment (header has already been read
773 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
774 frag->fragment, frag_len, 0,
776 if (i<=0 || readbytes != frag_len)
782 item = pitem_new(seq64be, frag);
786 item = pqueue_insert(s->d1->buffered_messages, item);
788 * pqueue_insert fails iff a duplicate item is inserted. However,
789 * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
790 * would have returned it. Then, either |frag_len| !=
791 * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
792 * have been processed with |dtls1_reassemble_fragment|, above, or
793 * the record will have been discarded.
795 if (!ossl_assert(item != NULL))
799 return DTLS1_HM_FRAGMENT_RETRY;
803 dtls1_hm_fragment_free(frag);
807 static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
810 unsigned char wire[DTLS1_HM_HEADER_LENGTH];
811 size_t mlen, frag_off, frag_len;
812 int i, ret, recvd_type;
813 struct hm_header_st msg_hdr;
815 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
821 /* see if we have the required fragment already */
822 ret = dtls1_retrieve_buffered_fragment(s, &frag_len);
824 /* SSLfatal() already called */
828 s->init_num = frag_len;
833 /* read handshake message header */
834 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type, wire,
835 DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
836 if (i <= 0) { /* nbio, or an error */
837 s->rwstate = SSL_READING;
841 if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
842 if (wire[0] != SSL3_MT_CCS) {
843 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
844 SSL_R_BAD_CHANGE_CIPHER_SPEC);
848 memcpy(s->init_buf->data, wire, readbytes);
849 s->init_num = readbytes - 1;
850 s->init_msg = s->init_buf->data + 1;
851 s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
852 s->s3.tmp.message_size = readbytes - 1;
853 *len = readbytes - 1;
857 /* Handshake fails if message header is incomplete */
858 if (readbytes != DTLS1_HM_HEADER_LENGTH) {
859 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
863 /* parse the message fragment header */
864 dtls1_get_message_header(wire, &msg_hdr);
866 mlen = msg_hdr.msg_len;
867 frag_off = msg_hdr.frag_off;
868 frag_len = msg_hdr.frag_len;
871 * We must have at least frag_len bytes left in the record to be read.
872 * Fragments must not span records.
874 if (frag_len > s->rlayer.tlsrecs[s->rlayer.curr_rec].length) {
875 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
880 * if this is a future (or stale) message it gets buffered
881 * (or dropped)--no further processing at this time
882 * While listening, we accept seq 1 (ClientHello with cookie)
883 * although we're still expecting seq 0 (ClientHello)
885 if (msg_hdr.seq != s->d1->handshake_read_seq) {
888 || s->d1->handshake_read_seq != 1
889 || wire[0] != SSL3_MT_CLIENT_HELLO
890 || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
891 *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
895 * We received a ClientHello and sent back a HelloVerifyRequest. We
896 * now seem to have received a retransmitted initial ClientHello. That
897 * is allowed (possibly our HelloVerifyRequest got lost).
902 if (frag_len && frag_len < mlen) {
903 *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
908 && s->d1->r_msg_hdr.frag_off == 0
909 && s->statem.hand_state != TLS_ST_OK
910 && wire[0] == SSL3_MT_HELLO_REQUEST) {
912 * The server may always send 'Hello Request' messages -- we are
913 * doing a handshake anyway now, so ignore them if their format is
914 * correct. Does not count for 'Finished' MAC.
916 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
918 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
919 wire, DTLS1_HM_HEADER_LENGTH, ssl,
920 s->msg_callback_arg);
924 } else { /* Incorrectly formatted Hello request */
926 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
931 if (!dtls1_preprocess_fragment(s, &msg_hdr)) {
932 /* SSLfatal() already called */
938 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
940 i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
941 &p[frag_off], frag_len, 0, &readbytes);
944 * This shouldn't ever fail due to NBIO because we already checked
945 * that we have enough data in the record
948 s->rwstate = SSL_READING;
957 * XDTLS: an incorrectly formatted fragment should cause the handshake
960 if (readbytes != frag_len) {
961 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
967 * We got a new ClientHello with a message sequence of 0.
968 * Reset the read/write sequences back to the beginning.
969 * We process it like this is the first time we've seen a ClientHello
972 s->d1->handshake_read_seq = 0;
973 s->d1->next_handshake_write_seq = 0;
977 * Note that s->init_num is *not* used as current offset in
978 * s->init_buf->data, but as a counter summing up fragments' lengths: as
979 * soon as they sum up to handshake packet length, we assume we have got
982 *len = s->init_num = frag_len;
992 * for these 2 messages, we need to
993 * ssl->session->read_sym_enc assign
994 * ssl->session->read_compression assign
995 * ssl->session->read_hash assign
997 CON_FUNC_RETURN dtls_construct_change_cipher_spec(SSL_CONNECTION *s,
1000 if (s->version == DTLS1_BAD_VER) {
1001 s->d1->next_handshake_write_seq++;
1003 if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {
1004 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1005 return CON_FUNC_ERROR;
1009 return CON_FUNC_SUCCESS;
1012 #ifndef OPENSSL_NO_SCTP
1014 * Wait for a dry event. Should only be called at a point in the handshake
1015 * where we are not expecting any data from the peer except an alert.
1017 WORK_STATE dtls_wait_for_dry(SSL_CONNECTION *s)
1021 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1023 /* read app data until dry event */
1024 ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(ssl));
1026 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1032 * We're not expecting any more messages from the peer at this point -
1033 * but we could get an alert. If an alert is waiting then we will never
1034 * return successfully. Therefore we attempt to read a message. This
1035 * should never succeed but will process any waiting alerts.
1037 if (dtls_get_reassembled_message(s, &errtype, &len)) {
1038 /* The call succeeded! This should never happen */
1039 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1043 s->s3.in_read_app_data = 2;
1044 s->rwstate = SSL_READING;
1045 BIO_clear_retry_flags(SSL_get_rbio(ssl));
1046 BIO_set_retry_read(SSL_get_rbio(ssl));
1049 return WORK_FINISHED_CONTINUE;
1053 int dtls1_read_failed(SSL_CONNECTION *s, int code)
1055 SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1058 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1062 if (!dtls1_is_timer_expired(s) || ossl_statem_in_error(s)) {
1064 * not a timeout, none of our business, let higher layers handle
1065 * this. in fact it's probably an error
1069 /* done, no need to send a retransmit */
1070 if (!SSL_in_init(ssl))
1072 BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);
1076 return dtls1_handle_timeout(s);
1079 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1082 * The index of the retransmission queue actually is the message sequence
1083 * number, since the queue only contains messages of a single handshake.
1084 * However, the ChangeCipherSpec has no message sequence number and so
1085 * using only the sequence will result in the CCS and Finished having the
1086 * same index. To prevent this, the sequence number is multiplied by 2.
1087 * In case of a CCS 1 is subtracted. This does not only differ CSS and
1088 * Finished, it also maintains the order of the index (important for
1089 * priority queues) and fits in the unsigned short variable.
1091 return seq * 2 - is_ccs;
1094 int dtls1_retransmit_buffered_messages(SSL_CONNECTION *s)
1096 pqueue *sent = s->d1->sent_messages;
1102 iter = pqueue_iterator(sent);
1104 for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1105 frag = (hm_fragment *)item->data;
1106 if (dtls1_retransmit_message(s, (unsigned short)
1107 dtls1_get_queue_priority
1108 (frag->msg_header.seq,
1109 frag->msg_header.is_ccs), &found) <= 0)
1116 int dtls1_buffer_message(SSL_CONNECTION *s, int is_ccs)
1120 unsigned char seq64be[8];
1123 * this function is called immediately after a message has been
1126 if (!ossl_assert(s->init_off == 0))
1129 frag = dtls1_hm_fragment_new(s->init_num, 0);
1133 memcpy(frag->fragment, s->init_buf->data, s->init_num);
1136 /* For DTLS1_BAD_VER the header length is non-standard */
1137 if (!ossl_assert(s->d1->w_msg_hdr.msg_len +
1139 DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH)
1140 == (unsigned int)s->init_num)) {
1141 dtls1_hm_fragment_free(frag);
1145 if (!ossl_assert(s->d1->w_msg_hdr.msg_len +
1146 DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num)) {
1147 dtls1_hm_fragment_free(frag);
1152 frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1153 frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1154 frag->msg_header.type = s->d1->w_msg_hdr.type;
1155 frag->msg_header.frag_off = 0;
1156 frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1157 frag->msg_header.is_ccs = is_ccs;
1159 /* save current state */
1160 frag->msg_header.saved_retransmit_state.wrlmethod = s->rlayer.wrlmethod;
1161 frag->msg_header.saved_retransmit_state.wrl = s->rlayer.wrl;
1164 memset(seq64be, 0, sizeof(seq64be));
1167 char)(dtls1_get_queue_priority(frag->msg_header.seq,
1168 frag->msg_header.is_ccs) >> 8);
1171 char)(dtls1_get_queue_priority(frag->msg_header.seq,
1172 frag->msg_header.is_ccs));
1174 item = pitem_new(seq64be, frag);
1176 dtls1_hm_fragment_free(frag);
1180 pqueue_insert(s->d1->sent_messages, item);
1184 int dtls1_retransmit_message(SSL_CONNECTION *s, unsigned short seq, int *found)
1187 /* XDTLS: for now assuming that read/writes are blocking */
1190 unsigned long header_length;
1191 unsigned char seq64be[8];
1192 struct dtls1_retransmit_state saved_state;
1194 /* XDTLS: the requested message ought to be found, otherwise error */
1195 memset(seq64be, 0, sizeof(seq64be));
1196 seq64be[6] = (unsigned char)(seq >> 8);
1197 seq64be[7] = (unsigned char)seq;
1199 item = pqueue_find(s->d1->sent_messages, seq64be);
1201 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1207 frag = (hm_fragment *)item->data;
1209 if (frag->msg_header.is_ccs)
1210 header_length = DTLS1_CCS_HEADER_LENGTH;
1212 header_length = DTLS1_HM_HEADER_LENGTH;
1214 memcpy(s->init_buf->data, frag->fragment,
1215 frag->msg_header.msg_len + header_length);
1216 s->init_num = frag->msg_header.msg_len + header_length;
1218 dtls1_set_message_header_int(s, frag->msg_header.type,
1219 frag->msg_header.msg_len,
1220 frag->msg_header.seq, 0,
1221 frag->msg_header.frag_len);
1223 /* save current state */
1224 saved_state.wrlmethod = s->rlayer.wrlmethod;
1225 saved_state.wrl = s->rlayer.wrl;
1227 s->d1->retransmitting = 1;
1229 /* restore state in which the message was originally sent */
1230 s->rlayer.wrlmethod = frag->msg_header.saved_retransmit_state.wrlmethod;
1231 s->rlayer.wrl = frag->msg_header.saved_retransmit_state.wrl;
1234 * The old wrl may be still pointing at an old BIO. Update it to what we're
1237 s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
1239 ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1240 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1242 /* restore current state */
1243 s->rlayer.wrlmethod = saved_state.wrlmethod;
1244 s->rlayer.wrl = saved_state.wrl;
1246 s->d1->retransmitting = 0;
1248 (void)BIO_flush(s->wbio);
1252 void dtls1_set_message_header(SSL_CONNECTION *s,
1253 unsigned char mt, size_t len,
1254 size_t frag_off, size_t frag_len)
1256 if (frag_off == 0) {
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);
1265 /* don't actually do the writing, wait till the MTU has been retrieved */
1267 dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,
1268 size_t len, unsigned short seq_num,
1269 size_t frag_off, size_t frag_len)
1271 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1274 msg_hdr->msg_len = len;
1275 msg_hdr->seq = seq_num;
1276 msg_hdr->frag_off = frag_off;
1277 msg_hdr->frag_len = frag_len;
1281 dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off, size_t frag_len)
1283 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1285 msg_hdr->frag_off = frag_off;
1286 msg_hdr->frag_len = frag_len;
1289 static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,
1292 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1294 *p++ = msg_hdr->type;
1295 l2n3(msg_hdr->msg_len, p);
1297 s2n(msg_hdr->seq, p);
1298 l2n3(msg_hdr->frag_off, p);
1299 l2n3(msg_hdr->frag_len, p);
1304 void dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1306 memset(msg_hdr, 0, sizeof(*msg_hdr));
1307 msg_hdr->type = *(data++);
1308 n2l3(data, msg_hdr->msg_len);
1310 n2s(data, msg_hdr->seq);
1311 n2l3(data, msg_hdr->frag_off);
1312 n2l3(data, msg_hdr->frag_len);
1315 int dtls1_set_handshake_header(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1317 unsigned char *header;
1319 if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {
1320 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1321 dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1322 s->d1->handshake_write_seq, 0, 0);
1323 if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))
1326 dtls1_set_message_header(s, htype, 0, 0, 0);
1328 * We allocate space at the start for the message header. This gets
1331 if (!WPACKET_allocate_bytes(pkt, DTLS1_HM_HEADER_LENGTH, &header)
1332 || !WPACKET_start_sub_packet(pkt))
1339 int dtls1_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1343 if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
1344 || !WPACKET_get_length(pkt, &msglen)
1345 || msglen > INT_MAX)
1348 if (htype != SSL3_MT_CHANGE_CIPHER_SPEC) {
1349 s->d1->w_msg_hdr.msg_len = msglen - DTLS1_HM_HEADER_LENGTH;
1350 s->d1->w_msg_hdr.frag_len = msglen - DTLS1_HM_HEADER_LENGTH;
1352 s->init_num = (int)msglen;
1355 if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST) {
1356 /* Buffer the message to handle re-xmits */
1357 if (!dtls1_buffer_message(s, htype == SSL3_MT_CHANGE_CIPHER_SPEC