1 /* $OpenBSD: d1_both.c,v 1.75 2021/06/11 17:29:48 jsing Exp $ */ 2 /* 3 * DTLS implementation written by Nagendra Modadugu 4 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. 5 */ 6 /* ==================================================================== 7 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved. 8 * 9 * Redistribution and use in source and binary forms, with or without 10 * modification, are permitted provided that the following conditions 11 * are met: 12 * 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in 18 * the documentation and/or other materials provided with the 19 * distribution. 20 * 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/)" 25 * 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. 30 * 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. 34 * 35 * 6. Redistributions of any form whatsoever must retain the following 36 * acknowledgment: 37 * "This product includes software developed by the OpenSSL Project 38 * for use in the OpenSSL Toolkit (http://www.openssl.org/)" 39 * 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 * ==================================================================== 53 * 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). 57 * 58 */ 59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) 60 * All rights reserved. 61 * 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. 65 * 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). 72 * 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. 79 * 80 * Redistribution and use in source and binary forms, with or without 81 * modification, are permitted provided that the following conditions 82 * are met: 83 * 1. Redistributions of source code must retain the copyright 84 * notice, this list of conditions and the following disclaimer. 85 * 2. Redistributions in binary form must reproduce the above copyright 86 * notice, this list of conditions and the following disclaimer in the 87 * documentation and/or other materials provided with the distribution. 88 * 3. All advertising materials mentioning features or use of this software 89 * must display the following acknowledgement: 90 * "This product includes cryptographic software written by 91 * Eric Young (eay@cryptsoft.com)" 92 * The word 'cryptographic' can be left out if the rouines from the library 93 * being used are not cryptographic related :-). 94 * 4. If you include any Windows specific code (or a derivative thereof) from 95 * the apps directory (application code) you must include an acknowledgement: 96 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" 97 * 98 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND 99 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 100 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 101 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 102 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 103 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 104 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 105 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 106 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 107 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 108 * SUCH DAMAGE. 109 * 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.] 114 */ 115 116 #include <limits.h> 117 #include <stdio.h> 118 #include <string.h> 119 120 #include <openssl/buffer.h> 121 #include <openssl/evp.h> 122 #include <openssl/objects.h> 123 #include <openssl/x509.h> 124 125 #include "bytestring.h" 126 #include "dtls_locl.h" 127 #include "pqueue.h" 128 #include "ssl_locl.h" 129 130 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8) 131 132 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \ 133 if ((end) - (start) <= 8) { \ 134 long ii; \ 135 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \ 136 } else { \ 137 long ii; \ 138 bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \ 139 for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \ 140 bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \ 141 } } 142 143 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \ 144 long ii; \ 145 OPENSSL_assert((msg_len) > 0); \ 146 is_complete = 1; \ 147 if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \ 148 if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \ 149 if (bitmask[ii] != 0xff) { is_complete = 0; break; } } 150 151 static const unsigned char bitmask_start_values[] = { 152 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 153 }; 154 static const unsigned char bitmask_end_values[] = { 155 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f 156 }; 157 158 /* XDTLS: figure out the right values */ 159 static const unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28}; 160 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 int dtls1_write_message_header(const struct hm_header_st *msg_hdr, 165 unsigned long frag_off, unsigned long frag_len, unsigned char *p); 166 static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, 167 int *ok); 168 169 void dtls1_hm_fragment_free(hm_fragment *frag); 170 171 static hm_fragment * 172 dtls1_hm_fragment_new(unsigned long frag_len, int reassembly) 173 { 174 hm_fragment *frag; 175 176 if ((frag = calloc(1, sizeof(*frag))) == NULL) 177 goto err; 178 179 if (frag_len > 0) { 180 if ((frag->fragment = calloc(1, frag_len)) == NULL) 181 goto err; 182 } 183 184 /* Initialize reassembly bitmask if necessary. */ 185 if (reassembly) { 186 if ((frag->reassembly = calloc(1, 187 RSMBLY_BITMASK_SIZE(frag_len))) == NULL) 188 goto err; 189 } 190 191 return frag; 192 193 err: 194 dtls1_hm_fragment_free(frag); 195 return NULL; 196 } 197 198 void 199 dtls1_hm_fragment_free(hm_fragment *frag) 200 { 201 if (frag == NULL) 202 return; 203 204 free(frag->fragment); 205 free(frag->reassembly); 206 free(frag); 207 } 208 209 /* send s->internal->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */ 210 int 211 dtls1_do_write(SSL *s, int type) 212 { 213 int ret; 214 int curr_mtu; 215 unsigned int len, frag_off; 216 size_t overhead; 217 218 /* AHA! Figure out the MTU, and stick to the right size */ 219 if (D1I(s)->mtu < dtls1_min_mtu() && 220 !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) { 221 D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s), 222 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); 223 224 /* 225 * I've seen the kernel return bogus numbers when it 226 * doesn't know the MTU (ie., the initial write), so just 227 * make sure we have a reasonable number 228 */ 229 if (D1I(s)->mtu < dtls1_min_mtu()) { 230 D1I(s)->mtu = 0; 231 D1I(s)->mtu = dtls1_guess_mtu(D1I(s)->mtu); 232 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, 233 D1I(s)->mtu, NULL); 234 } 235 } 236 237 OPENSSL_assert(D1I(s)->mtu >= dtls1_min_mtu()); 238 /* should have something reasonable now */ 239 240 if (s->internal->init_off == 0 && type == SSL3_RT_HANDSHAKE) 241 OPENSSL_assert(s->internal->init_num == 242 (int)D1I(s)->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH); 243 244 if (!tls12_record_layer_write_overhead(s->internal->rl, &overhead)) 245 return -1; 246 247 frag_off = 0; 248 while (s->internal->init_num) { 249 curr_mtu = D1I(s)->mtu - BIO_wpending(SSL_get_wbio(s)) - 250 DTLS1_RT_HEADER_LENGTH - overhead; 251 252 if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) { 253 /* grr.. we could get an error if MTU picked was wrong */ 254 ret = BIO_flush(SSL_get_wbio(s)); 255 if (ret <= 0) 256 return ret; 257 curr_mtu = D1I(s)->mtu - DTLS1_RT_HEADER_LENGTH - 258 overhead; 259 } 260 261 if (s->internal->init_num > curr_mtu) 262 len = curr_mtu; 263 else 264 len = s->internal->init_num; 265 266 /* XDTLS: this function is too long. split out the CCS part */ 267 if (type == SSL3_RT_HANDSHAKE) { 268 if (s->internal->init_off != 0) { 269 OPENSSL_assert(s->internal->init_off > DTLS1_HM_HEADER_LENGTH); 270 s->internal->init_off -= DTLS1_HM_HEADER_LENGTH; 271 s->internal->init_num += DTLS1_HM_HEADER_LENGTH; 272 273 if (s->internal->init_num > curr_mtu) 274 len = curr_mtu; 275 else 276 len = s->internal->init_num; 277 } 278 279 dtls1_fix_message_header(s, frag_off, 280 len - DTLS1_HM_HEADER_LENGTH); 281 282 if (!dtls1_write_message_header(&D1I(s)->w_msg_hdr, 283 D1I(s)->w_msg_hdr.frag_off, D1I(s)->w_msg_hdr.frag_len, 284 (unsigned char *)&s->internal->init_buf->data[s->internal->init_off])) 285 return -1; 286 287 OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH); 288 } 289 290 ret = dtls1_write_bytes(s, type, 291 &s->internal->init_buf->data[s->internal->init_off], len); 292 if (ret < 0) { 293 /* 294 * Might need to update MTU here, but we don't know 295 * which previous packet caused the failure -- so 296 * can't really retransmit anything. continue as 297 * if everything is fine and wait for an alert to 298 * handle the retransmit 299 */ 300 if (BIO_ctrl(SSL_get_wbio(s), 301 BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) 302 D1I(s)->mtu = BIO_ctrl(SSL_get_wbio(s), 303 BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); 304 else 305 return (-1); 306 } else { 307 308 /* 309 * Bad if this assert fails, only part of the 310 * handshake message got sent. but why would 311 * this happen? 312 */ 313 OPENSSL_assert(len == (unsigned int)ret); 314 315 if (type == SSL3_RT_HANDSHAKE && 316 !D1I(s)->retransmitting) { 317 /* 318 * Should not be done for 'Hello Request's, 319 * but in that case we'll ignore the result 320 * anyway 321 */ 322 unsigned char *p = (unsigned char *)&s->internal->init_buf->data[s->internal->init_off]; 323 const struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr; 324 int xlen; 325 326 if (frag_off == 0) { 327 /* 328 * Reconstruct message header is if it 329 * is being sent in single fragment 330 */ 331 if (!dtls1_write_message_header(msg_hdr, 332 0, msg_hdr->msg_len, p)) 333 return (-1); 334 xlen = ret; 335 } else { 336 p += DTLS1_HM_HEADER_LENGTH; 337 xlen = ret - DTLS1_HM_HEADER_LENGTH; 338 } 339 340 tls1_transcript_record(s, p, xlen); 341 } 342 343 if (ret == s->internal->init_num) { 344 if (s->internal->msg_callback) 345 s->internal->msg_callback(1, s->version, type, 346 s->internal->init_buf->data, 347 (size_t)(s->internal->init_off + s->internal->init_num), 348 s, s->internal->msg_callback_arg); 349 350 s->internal->init_off = 0; 351 /* done writing this message */ 352 s->internal->init_num = 0; 353 354 return (1); 355 } 356 s->internal->init_off += ret; 357 s->internal->init_num -= ret; 358 frag_off += (ret -= DTLS1_HM_HEADER_LENGTH); 359 } 360 } 361 return (0); 362 } 363 364 365 /* 366 * Obtain handshake message of message type 'mt' (any if mt == -1), 367 * maximum acceptable body length 'max'. 368 * Read an entire handshake message. Handshake messages arrive in 369 * fragments. 370 */ 371 long 372 dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) 373 { 374 int i, al; 375 struct hm_header_st *msg_hdr; 376 unsigned char *p; 377 unsigned long msg_len; 378 379 /* 380 * s3->internal->tmp is used to store messages that are unexpected, caused 381 * by the absence of an optional handshake message 382 */ 383 if (S3I(s)->hs.tls12.reuse_message) { 384 S3I(s)->hs.tls12.reuse_message = 0; 385 if ((mt >= 0) && (S3I(s)->hs.tls12.message_type != mt)) { 386 al = SSL_AD_UNEXPECTED_MESSAGE; 387 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE); 388 goto fatal_err; 389 } 390 *ok = 1; 391 s->internal->init_msg = s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH; 392 s->internal->init_num = (int)S3I(s)->hs.tls12.message_size; 393 return s->internal->init_num; 394 } 395 396 msg_hdr = &D1I(s)->r_msg_hdr; 397 memset(msg_hdr, 0, sizeof(struct hm_header_st)); 398 399 again: 400 i = dtls1_get_message_fragment(s, st1, stn, max, ok); 401 if (i == DTLS1_HM_BAD_FRAGMENT || 402 i == DTLS1_HM_FRAGMENT_RETRY) /* bad fragment received */ 403 goto again; 404 else if (i <= 0 && !*ok) 405 return i; 406 407 p = (unsigned char *)s->internal->init_buf->data; 408 msg_len = msg_hdr->msg_len; 409 410 /* reconstruct message header */ 411 if (!dtls1_write_message_header(msg_hdr, 0, msg_len, p)) 412 return -1; 413 414 msg_len += DTLS1_HM_HEADER_LENGTH; 415 416 tls1_transcript_record(s, p, msg_len); 417 if (s->internal->msg_callback) 418 s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, msg_len, 419 s, s->internal->msg_callback_arg); 420 421 memset(msg_hdr, 0, sizeof(struct hm_header_st)); 422 423 /* Don't change sequence numbers while listening */ 424 if (!D1I(s)->listen) 425 D1I(s)->handshake_read_seq++; 426 427 s->internal->init_msg = s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH; 428 return s->internal->init_num; 429 430 fatal_err: 431 ssl3_send_alert(s, SSL3_AL_FATAL, al); 432 *ok = 0; 433 return -1; 434 } 435 436 437 static int 438 dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr, int max) 439 { 440 size_t frag_off, frag_len, msg_len; 441 442 msg_len = msg_hdr->msg_len; 443 frag_off = msg_hdr->frag_off; 444 frag_len = msg_hdr->frag_len; 445 446 /* sanity checking */ 447 if ((frag_off + frag_len) > msg_len) { 448 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE); 449 return SSL_AD_ILLEGAL_PARAMETER; 450 } 451 452 if ((frag_off + frag_len) > (unsigned long)max) { 453 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE); 454 return SSL_AD_ILLEGAL_PARAMETER; 455 } 456 457 if ( D1I(s)->r_msg_hdr.frag_off == 0) /* first fragment */ 458 { 459 /* 460 * msg_len is limited to 2^24, but is effectively checked 461 * against max above 462 */ 463 if (!BUF_MEM_grow_clean(s->internal->init_buf, 464 msg_len + DTLS1_HM_HEADER_LENGTH)) { 465 SSLerror(s, ERR_R_BUF_LIB); 466 return SSL_AD_INTERNAL_ERROR; 467 } 468 469 S3I(s)->hs.tls12.message_size = msg_len; 470 D1I(s)->r_msg_hdr.msg_len = msg_len; 471 S3I(s)->hs.tls12.message_type = msg_hdr->type; 472 D1I(s)->r_msg_hdr.type = msg_hdr->type; 473 D1I(s)->r_msg_hdr.seq = msg_hdr->seq; 474 } else if (msg_len != D1I(s)->r_msg_hdr.msg_len) { 475 /* 476 * They must be playing with us! BTW, failure to enforce 477 * upper limit would open possibility for buffer overrun. 478 */ 479 SSLerror(s, SSL_R_EXCESSIVE_MESSAGE_SIZE); 480 return SSL_AD_ILLEGAL_PARAMETER; 481 } 482 483 return 0; /* no error */ 484 } 485 486 static int 487 dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok) 488 { 489 /* 490 * (0) check whether the desired fragment is available 491 * if so: 492 * (1) copy over the fragment to s->internal->init_buf->data[] 493 * (2) update s->internal->init_num 494 */ 495 pitem *item; 496 hm_fragment *frag; 497 int al; 498 499 *ok = 0; 500 item = pqueue_peek(D1I(s)->buffered_messages); 501 if (item == NULL) 502 return 0; 503 504 frag = (hm_fragment *)item->data; 505 506 /* Don't return if reassembly still in progress */ 507 if (frag->reassembly != NULL) 508 return 0; 509 510 if (D1I(s)->handshake_read_seq == frag->msg_header.seq) { 511 unsigned long frag_len = frag->msg_header.frag_len; 512 pqueue_pop(D1I(s)->buffered_messages); 513 514 al = dtls1_preprocess_fragment(s, &frag->msg_header, max); 515 516 if (al == 0) /* no alert */ 517 { 518 unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH; 519 memcpy(&p[frag->msg_header.frag_off], 520 frag->fragment, frag->msg_header.frag_len); 521 } 522 523 dtls1_hm_fragment_free(frag); 524 pitem_free(item); 525 526 if (al == 0) { 527 *ok = 1; 528 return frag_len; 529 } 530 531 ssl3_send_alert(s, SSL3_AL_FATAL, al); 532 s->internal->init_num = 0; 533 *ok = 0; 534 return -1; 535 } else 536 return 0; 537 } 538 539 /* 540 * dtls1_max_handshake_message_len returns the maximum number of bytes 541 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, 542 * but may be greater if the maximum certificate list size requires it. 543 */ 544 static unsigned long 545 dtls1_max_handshake_message_len(const SSL *s) 546 { 547 unsigned long max_len; 548 549 max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH; 550 if (max_len < (unsigned long)s->internal->max_cert_list) 551 return s->internal->max_cert_list; 552 return max_len; 553 } 554 555 static int 556 dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok) 557 { 558 hm_fragment *frag = NULL; 559 pitem *item = NULL; 560 int i = -1, is_complete; 561 unsigned char seq64be[8]; 562 unsigned long frag_len = msg_hdr->frag_len; 563 564 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len || 565 msg_hdr->msg_len > dtls1_max_handshake_message_len(s)) 566 goto err; 567 568 if (frag_len == 0) { 569 i = DTLS1_HM_FRAGMENT_RETRY; 570 goto err; 571 } 572 573 /* Try to find item in queue */ 574 memset(seq64be, 0, sizeof(seq64be)); 575 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8); 576 seq64be[7] = (unsigned char)msg_hdr->seq; 577 item = pqueue_find(D1I(s)->buffered_messages, seq64be); 578 579 if (item == NULL) { 580 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1); 581 if (frag == NULL) 582 goto err; 583 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr)); 584 frag->msg_header.frag_len = frag->msg_header.msg_len; 585 frag->msg_header.frag_off = 0; 586 } else { 587 frag = (hm_fragment*)item->data; 588 if (frag->msg_header.msg_len != msg_hdr->msg_len) { 589 item = NULL; 590 frag = NULL; 591 goto err; 592 } 593 } 594 595 /* 596 * If message is already reassembled, this must be a 597 * retransmit and can be dropped. 598 */ 599 if (frag->reassembly == NULL) { 600 unsigned char devnull [256]; 601 602 while (frag_len) { 603 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, 604 devnull, frag_len > sizeof(devnull) ? 605 sizeof(devnull) : frag_len, 0); 606 if (i <= 0) 607 goto err; 608 frag_len -= i; 609 } 610 i = DTLS1_HM_FRAGMENT_RETRY; 611 goto err; 612 } 613 614 /* read the body of the fragment (header has already been read */ 615 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, 616 frag->fragment + msg_hdr->frag_off, frag_len, 0); 617 if (i <= 0 || (unsigned long)i != frag_len) 618 goto err; 619 620 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off, 621 (long)(msg_hdr->frag_off + frag_len)); 622 623 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len, 624 is_complete); 625 626 if (is_complete) { 627 free(frag->reassembly); 628 frag->reassembly = NULL; 629 } 630 631 if (item == NULL) { 632 memset(seq64be, 0, sizeof(seq64be)); 633 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8); 634 seq64be[7] = (unsigned char)(msg_hdr->seq); 635 636 item = pitem_new(seq64be, frag); 637 if (item == NULL) { 638 i = -1; 639 goto err; 640 } 641 642 pqueue_insert(D1I(s)->buffered_messages, item); 643 } 644 645 return DTLS1_HM_FRAGMENT_RETRY; 646 647 err: 648 if (item == NULL && frag != NULL) 649 dtls1_hm_fragment_free(frag); 650 *ok = 0; 651 return i; 652 } 653 654 655 static int 656 dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok) 657 { 658 int i = -1; 659 hm_fragment *frag = NULL; 660 pitem *item = NULL; 661 unsigned char seq64be[8]; 662 unsigned long frag_len = msg_hdr->frag_len; 663 664 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len) 665 goto err; 666 667 /* Try to find item in queue, to prevent duplicate entries */ 668 memset(seq64be, 0, sizeof(seq64be)); 669 seq64be[6] = (unsigned char) (msg_hdr->seq >> 8); 670 seq64be[7] = (unsigned char) msg_hdr->seq; 671 item = pqueue_find(D1I(s)->buffered_messages, seq64be); 672 673 /* 674 * If we already have an entry and this one is a fragment, 675 * don't discard it and rather try to reassemble it. 676 */ 677 if (item != NULL && frag_len < msg_hdr->msg_len) 678 item = NULL; 679 680 /* 681 * Discard the message if sequence number was already there, is 682 * too far in the future, already in the queue or if we received 683 * a FINISHED before the SERVER_HELLO, which then must be a stale 684 * retransmit. 685 */ 686 if (msg_hdr->seq <= D1I(s)->handshake_read_seq || 687 msg_hdr->seq > D1I(s)->handshake_read_seq + 10 || item != NULL || 688 (D1I(s)->handshake_read_seq == 0 && 689 msg_hdr->type == SSL3_MT_FINISHED)) { 690 unsigned char devnull [256]; 691 692 while (frag_len) { 693 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, 694 devnull, frag_len > sizeof(devnull) ? 695 sizeof(devnull) : frag_len, 0); 696 if (i <= 0) 697 goto err; 698 frag_len -= i; 699 } 700 } else { 701 if (frag_len < msg_hdr->msg_len) 702 return dtls1_reassemble_fragment(s, msg_hdr, ok); 703 704 if (frag_len > dtls1_max_handshake_message_len(s)) 705 goto err; 706 707 frag = dtls1_hm_fragment_new(frag_len, 0); 708 if (frag == NULL) 709 goto err; 710 711 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr)); 712 713 if (frag_len) { 714 /* read the body of the fragment (header has already been read */ 715 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, 716 frag->fragment, frag_len, 0); 717 if (i <= 0 || (unsigned long)i != frag_len) 718 goto err; 719 } 720 721 memset(seq64be, 0, sizeof(seq64be)); 722 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8); 723 seq64be[7] = (unsigned char)(msg_hdr->seq); 724 725 item = pitem_new(seq64be, frag); 726 if (item == NULL) 727 goto err; 728 729 pqueue_insert(D1I(s)->buffered_messages, item); 730 } 731 732 return DTLS1_HM_FRAGMENT_RETRY; 733 734 err: 735 if (item == NULL && frag != NULL) 736 dtls1_hm_fragment_free(frag); 737 *ok = 0; 738 return i; 739 } 740 741 742 static long 743 dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok) 744 { 745 unsigned char wire[DTLS1_HM_HEADER_LENGTH]; 746 unsigned long len, frag_off, frag_len; 747 int i, al; 748 struct hm_header_st msg_hdr; 749 750 again: 751 /* see if we have the required fragment already */ 752 if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) { 753 if (*ok) 754 s->internal->init_num = frag_len; 755 return frag_len; 756 } 757 758 /* read handshake message header */ 759 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire, 760 DTLS1_HM_HEADER_LENGTH, 0); 761 if (i <= 0) /* nbio, or an error */ 762 { 763 s->internal->rwstate = SSL_READING; 764 *ok = 0; 765 return i; 766 } 767 /* Handshake fails if message header is incomplete */ 768 if (i != DTLS1_HM_HEADER_LENGTH || 769 /* parse the message fragment header */ 770 dtls1_get_message_header(wire, &msg_hdr) == 0) { 771 al = SSL_AD_UNEXPECTED_MESSAGE; 772 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE); 773 goto fatal_err; 774 } 775 776 /* 777 * if this is a future (or stale) message it gets buffered 778 * (or dropped)--no further processing at this time 779 * While listening, we accept seq 1 (ClientHello with cookie) 780 * although we're still expecting seq 0 (ClientHello) 781 */ 782 if (msg_hdr.seq != D1I(s)->handshake_read_seq && 783 !(D1I(s)->listen && msg_hdr.seq == 1)) 784 return dtls1_process_out_of_seq_message(s, &msg_hdr, ok); 785 786 len = msg_hdr.msg_len; 787 frag_off = msg_hdr.frag_off; 788 frag_len = msg_hdr.frag_len; 789 790 if (frag_len && frag_len < len) 791 return dtls1_reassemble_fragment(s, &msg_hdr, ok); 792 793 if (!s->server && D1I(s)->r_msg_hdr.frag_off == 0 && 794 wire[0] == SSL3_MT_HELLO_REQUEST) { 795 /* 796 * The server may always send 'Hello Request' messages -- 797 * we are doing a handshake anyway now, so ignore them 798 * if their format is correct. Does not count for 799 * 'Finished' MAC. 800 */ 801 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) { 802 if (s->internal->msg_callback) 803 s->internal->msg_callback(0, s->version, 804 SSL3_RT_HANDSHAKE, wire, 805 DTLS1_HM_HEADER_LENGTH, s, 806 s->internal->msg_callback_arg); 807 808 s->internal->init_num = 0; 809 goto again; 810 } 811 else /* Incorrectly formated Hello request */ 812 { 813 al = SSL_AD_UNEXPECTED_MESSAGE; 814 SSLerror(s, SSL_R_UNEXPECTED_MESSAGE); 815 goto fatal_err; 816 } 817 } 818 819 if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max))) 820 goto fatal_err; 821 822 /* XDTLS: ressurect this when restart is in place */ 823 S3I(s)->hs.state = stn; 824 825 if (frag_len > 0) { 826 unsigned char *p = (unsigned char *)s->internal->init_buf->data + DTLS1_HM_HEADER_LENGTH; 827 828 i = s->method->internal->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, 829 &p[frag_off], frag_len, 0); 830 /* XDTLS: fix this--message fragments cannot span multiple packets */ 831 if (i <= 0) { 832 s->internal->rwstate = SSL_READING; 833 *ok = 0; 834 return i; 835 } 836 } else 837 i = 0; 838 839 /* 840 * XDTLS: an incorrectly formatted fragment should cause the 841 * handshake to fail 842 */ 843 if (i != (int)frag_len) { 844 al = SSL_AD_ILLEGAL_PARAMETER; 845 SSLerror(s, SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER); 846 goto fatal_err; 847 } 848 849 *ok = 1; 850 851 /* 852 * Note that s->internal->init_num is *not* used as current offset in 853 * s->internal->init_buf->data, but as a counter summing up fragments' 854 * lengths: as soon as they sum up to handshake packet 855 * length, we assume we have got all the fragments. 856 */ 857 s->internal->init_num = frag_len; 858 return frag_len; 859 860 fatal_err: 861 ssl3_send_alert(s, SSL3_AL_FATAL, al); 862 s->internal->init_num = 0; 863 864 *ok = 0; 865 return (-1); 866 } 867 868 int 869 dtls1_read_failed(SSL *s, int code) 870 { 871 if (code > 0) { 872 #ifdef DEBUG 873 fprintf(stderr, "invalid state reached %s:%d", 874 __FILE__, __LINE__); 875 #endif 876 return 1; 877 } 878 879 if (!dtls1_is_timer_expired(s)) { 880 /* 881 * not a timeout, none of our business, let higher layers 882 * handle this. in fact it's probably an error 883 */ 884 return code; 885 } 886 887 if (!SSL_in_init(s)) /* done, no need to send a retransmit */ 888 { 889 BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ); 890 return code; 891 } 892 893 return dtls1_handle_timeout(s); 894 } 895 896 int 897 dtls1_get_queue_priority(unsigned short seq, int is_ccs) 898 { 899 /* 900 * The index of the retransmission queue actually is the message 901 * sequence number, since the queue only contains messages of a 902 * single handshake. However, the ChangeCipherSpec has no message 903 * sequence number and so using only the sequence will result in 904 * the CCS and Finished having the same index. To prevent this, the 905 * sequence number is multiplied by 2. In case of a CCS 1 is 906 * subtracted. This does not only differ CSS and Finished, it also 907 * maintains the order of the index (important for priority queues) 908 * and fits in the unsigned short variable. 909 */ 910 return seq * 2 - is_ccs; 911 } 912 913 int 914 dtls1_retransmit_buffered_messages(SSL *s) 915 { 916 pqueue sent = s->d1->sent_messages; 917 piterator iter; 918 pitem *item; 919 hm_fragment *frag; 920 int found = 0; 921 922 iter = pqueue_iterator(sent); 923 924 for (item = pqueue_next(&iter); item != NULL; 925 item = pqueue_next(&iter)) { 926 frag = (hm_fragment *)item->data; 927 if (dtls1_retransmit_message(s, 928 (unsigned short)dtls1_get_queue_priority( 929 frag->msg_header.seq, frag->msg_header.is_ccs), 0, 930 &found) <= 0 && found) { 931 #ifdef DEBUG 932 fprintf(stderr, "dtls1_retransmit_message() failed\n"); 933 #endif 934 return -1; 935 } 936 } 937 938 return 1; 939 } 940 941 int 942 dtls1_buffer_message(SSL *s, int is_ccs) 943 { 944 pitem *item; 945 hm_fragment *frag; 946 unsigned char seq64be[8]; 947 948 /* Buffer the messsage in order to handle DTLS retransmissions. */ 949 950 /* 951 * This function is called immediately after a message has 952 * been serialized 953 */ 954 OPENSSL_assert(s->internal->init_off == 0); 955 956 frag = dtls1_hm_fragment_new(s->internal->init_num, 0); 957 if (frag == NULL) 958 return 0; 959 960 memcpy(frag->fragment, s->internal->init_buf->data, s->internal->init_num); 961 962 OPENSSL_assert(D1I(s)->w_msg_hdr.msg_len + 963 (is_ccs ? DTLS1_CCS_HEADER_LENGTH : DTLS1_HM_HEADER_LENGTH) == 964 (unsigned int)s->internal->init_num); 965 966 frag->msg_header.msg_len = D1I(s)->w_msg_hdr.msg_len; 967 frag->msg_header.seq = D1I(s)->w_msg_hdr.seq; 968 frag->msg_header.type = D1I(s)->w_msg_hdr.type; 969 frag->msg_header.frag_off = 0; 970 frag->msg_header.frag_len = D1I(s)->w_msg_hdr.msg_len; 971 frag->msg_header.is_ccs = is_ccs; 972 973 /* save current state*/ 974 frag->msg_header.saved_retransmit_state.session = s->session; 975 frag->msg_header.saved_retransmit_state.epoch = 976 tls12_record_layer_write_epoch(s->internal->rl); 977 978 memset(seq64be, 0, sizeof(seq64be)); 979 seq64be[6] = (unsigned char)(dtls1_get_queue_priority( 980 frag->msg_header.seq, frag->msg_header.is_ccs) >> 8); 981 seq64be[7] = (unsigned char)(dtls1_get_queue_priority( 982 frag->msg_header.seq, frag->msg_header.is_ccs)); 983 984 item = pitem_new(seq64be, frag); 985 if (item == NULL) { 986 dtls1_hm_fragment_free(frag); 987 return 0; 988 } 989 990 pqueue_insert(s->d1->sent_messages, item); 991 return 1; 992 } 993 994 int 995 dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off, 996 int *found) 997 { 998 int ret; 999 /* XDTLS: for now assuming that read/writes are blocking */ 1000 pitem *item; 1001 hm_fragment *frag; 1002 unsigned long header_length; 1003 unsigned char seq64be[8]; 1004 struct dtls1_retransmit_state saved_state; 1005 1006 /* 1007 OPENSSL_assert(s->internal->init_num == 0); 1008 OPENSSL_assert(s->internal->init_off == 0); 1009 */ 1010 1011 /* XDTLS: the requested message ought to be found, otherwise error */ 1012 memset(seq64be, 0, sizeof(seq64be)); 1013 seq64be[6] = (unsigned char)(seq >> 8); 1014 seq64be[7] = (unsigned char)seq; 1015 1016 item = pqueue_find(s->d1->sent_messages, seq64be); 1017 if (item == NULL) { 1018 #ifdef DEBUG 1019 fprintf(stderr, "retransmit: message %d non-existent\n", seq); 1020 #endif 1021 *found = 0; 1022 return 0; 1023 } 1024 1025 *found = 1; 1026 frag = (hm_fragment *)item->data; 1027 1028 if (frag->msg_header.is_ccs) 1029 header_length = DTLS1_CCS_HEADER_LENGTH; 1030 else 1031 header_length = DTLS1_HM_HEADER_LENGTH; 1032 1033 memcpy(s->internal->init_buf->data, frag->fragment, 1034 frag->msg_header.msg_len + header_length); 1035 s->internal->init_num = frag->msg_header.msg_len + header_length; 1036 1037 dtls1_set_message_header_int(s, frag->msg_header.type, 1038 frag->msg_header.msg_len, frag->msg_header.seq, 0, 1039 frag->msg_header.frag_len); 1040 1041 /* save current state */ 1042 saved_state.session = s->session; 1043 saved_state.epoch = tls12_record_layer_write_epoch(s->internal->rl); 1044 1045 D1I(s)->retransmitting = 1; 1046 1047 /* restore state in which the message was originally sent */ 1048 s->session = frag->msg_header.saved_retransmit_state.session; 1049 if (!tls12_record_layer_use_write_epoch(s->internal->rl, 1050 frag->msg_header.saved_retransmit_state.epoch)) 1051 return 0; 1052 1053 ret = dtls1_do_write(s, frag->msg_header.is_ccs ? 1054 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE); 1055 1056 /* restore current state */ 1057 s->session = saved_state.session; 1058 if (!tls12_record_layer_use_write_epoch(s->internal->rl, 1059 saved_state.epoch)) 1060 return 0; 1061 1062 D1I(s)->retransmitting = 0; 1063 1064 (void)BIO_flush(SSL_get_wbio(s)); 1065 return ret; 1066 } 1067 1068 /* call this function when the buffered messages are no longer needed */ 1069 void 1070 dtls1_clear_record_buffer(SSL *s) 1071 { 1072 hm_fragment *frag; 1073 pitem *item; 1074 1075 for(item = pqueue_pop(s->d1->sent_messages); item != NULL; 1076 item = pqueue_pop(s->d1->sent_messages)) { 1077 frag = item->data; 1078 if (frag->msg_header.is_ccs) 1079 tls12_record_layer_write_epoch_done(s->internal->rl, 1080 frag->msg_header.saved_retransmit_state.epoch); 1081 dtls1_hm_fragment_free(frag); 1082 pitem_free(item); 1083 } 1084 } 1085 1086 void 1087 dtls1_set_message_header(SSL *s, unsigned char mt, unsigned long len, 1088 unsigned long frag_off, unsigned long frag_len) 1089 { 1090 /* Don't change sequence numbers while listening */ 1091 if (frag_off == 0 && !D1I(s)->listen) { 1092 D1I(s)->handshake_write_seq = D1I(s)->next_handshake_write_seq; 1093 D1I(s)->next_handshake_write_seq++; 1094 } 1095 1096 dtls1_set_message_header_int(s, mt, len, D1I(s)->handshake_write_seq, 1097 frag_off, frag_len); 1098 } 1099 1100 /* don't actually do the writing, wait till the MTU has been retrieved */ 1101 void 1102 dtls1_set_message_header_int(SSL *s, unsigned char mt, unsigned long len, 1103 unsigned short seq_num, unsigned long frag_off, unsigned long frag_len) 1104 { 1105 struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr; 1106 1107 msg_hdr->type = mt; 1108 msg_hdr->msg_len = len; 1109 msg_hdr->seq = seq_num; 1110 msg_hdr->frag_off = frag_off; 1111 msg_hdr->frag_len = frag_len; 1112 } 1113 1114 static void 1115 dtls1_fix_message_header(SSL *s, unsigned long frag_off, unsigned long frag_len) 1116 { 1117 struct hm_header_st *msg_hdr = &D1I(s)->w_msg_hdr; 1118 1119 msg_hdr->frag_off = frag_off; 1120 msg_hdr->frag_len = frag_len; 1121 } 1122 1123 static int 1124 dtls1_write_message_header(const struct hm_header_st *msg_hdr, 1125 unsigned long frag_off, unsigned long frag_len, unsigned char *p) 1126 { 1127 CBB cbb; 1128 1129 /* We assume DTLS1_HM_HEADER_LENGTH bytes are available for now... */ 1130 if (!CBB_init_fixed(&cbb, p, DTLS1_HM_HEADER_LENGTH)) 1131 return 0; 1132 if (!CBB_add_u8(&cbb, msg_hdr->type)) 1133 goto err; 1134 if (!CBB_add_u24(&cbb, msg_hdr->msg_len)) 1135 goto err; 1136 if (!CBB_add_u16(&cbb, msg_hdr->seq)) 1137 goto err; 1138 if (!CBB_add_u24(&cbb, frag_off)) 1139 goto err; 1140 if (!CBB_add_u24(&cbb, frag_len)) 1141 goto err; 1142 if (!CBB_finish(&cbb, NULL, NULL)) 1143 goto err; 1144 1145 return 1; 1146 1147 err: 1148 CBB_cleanup(&cbb); 1149 return 0; 1150 } 1151 1152 unsigned int 1153 dtls1_min_mtu(void) 1154 { 1155 return (g_probable_mtu[(sizeof(g_probable_mtu) / 1156 sizeof(g_probable_mtu[0])) - 1]); 1157 } 1158 1159 static unsigned int 1160 dtls1_guess_mtu(unsigned int curr_mtu) 1161 { 1162 unsigned int i; 1163 1164 if (curr_mtu == 0) 1165 return g_probable_mtu[0]; 1166 1167 for (i = 0; i < sizeof(g_probable_mtu) / sizeof(g_probable_mtu[0]); i++) 1168 if (curr_mtu > g_probable_mtu[i]) 1169 return g_probable_mtu[i]; 1170 1171 return curr_mtu; 1172 } 1173 1174 int 1175 dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr) 1176 { 1177 CBS header; 1178 uint32_t msg_len, frag_off, frag_len; 1179 uint16_t seq; 1180 uint8_t type; 1181 1182 CBS_init(&header, data, sizeof(*msg_hdr)); 1183 1184 memset(msg_hdr, 0, sizeof(*msg_hdr)); 1185 1186 if (!CBS_get_u8(&header, &type)) 1187 return 0; 1188 if (!CBS_get_u24(&header, &msg_len)) 1189 return 0; 1190 if (!CBS_get_u16(&header, &seq)) 1191 return 0; 1192 if (!CBS_get_u24(&header, &frag_off)) 1193 return 0; 1194 if (!CBS_get_u24(&header, &frag_len)) 1195 return 0; 1196 1197 msg_hdr->type = type; 1198 msg_hdr->msg_len = msg_len; 1199 msg_hdr->seq = seq; 1200 msg_hdr->frag_off = frag_off; 1201 msg_hdr->frag_len = frag_len; 1202 1203 return 1; 1204 } 1205 1206 void 1207 dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr) 1208 { 1209 memset(ccs_hdr, 0, sizeof(struct ccs_header_st)); 1210 1211 ccs_hdr->type = *(data++); 1212 } 1213