1 /* $OpenBSD: d1_pkt.c,v 1.90 2021/01/19 19:07:39 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 <machine/endian.h> 117 118 #include <errno.h> 119 #include <stdio.h> 120 121 #include "ssl_locl.h" 122 123 #include <openssl/buffer.h> 124 #include <openssl/evp.h> 125 126 #include "pqueue.h" 127 #include "bytestring.h" 128 129 static int do_dtls1_write(SSL *s, int type, const unsigned char *buf, 130 unsigned int len); 131 132 133 /* mod 128 saturating subtract of two 64-bit values in big-endian order */ 134 static int 135 satsub64be(const unsigned char *v1, const unsigned char *v2) 136 { 137 int ret, sat, brw, i; 138 139 if (sizeof(long) == 8) 140 do { 141 long l; 142 143 if (BYTE_ORDER == LITTLE_ENDIAN) 144 break; 145 /* not reached on little-endians */ 146 /* following test is redundant, because input is 147 * always aligned, but I take no chances... */ 148 if (((size_t)v1 | (size_t)v2) & 0x7) 149 break; 150 151 l = *((long *)v1); 152 l -= *((long *)v2); 153 if (l > 128) 154 return 128; 155 else if (l<-128) 156 return -128; 157 else 158 return (int)l; 159 } while (0); 160 161 ret = (int)v1[7] - (int)v2[7]; 162 sat = 0; 163 brw = ret >> 8; /* brw is either 0 or -1 */ 164 if (ret & 0x80) { 165 for (i = 6; i >= 0; i--) { 166 brw += (int)v1[i]-(int)v2[i]; 167 sat |= ~brw; 168 brw >>= 8; 169 } 170 } else { 171 for (i = 6; i >= 0; i--) { 172 brw += (int)v1[i]-(int)v2[i]; 173 sat |= brw; 174 brw >>= 8; 175 } 176 } 177 brw <<= 8; /* brw is either 0 or -256 */ 178 179 if (sat & 0xff) 180 return brw | 0x80; 181 else 182 return brw + (ret & 0xFF); 183 } 184 185 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, 186 int len, int peek); 187 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap, 188 const unsigned char *seq); 189 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap, 190 const unsigned char *seq); 191 static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr, 192 unsigned int *is_next_epoch); 193 static int dtls1_buffer_record(SSL *s, record_pqueue *q, 194 unsigned char *priority); 195 static int dtls1_process_record(SSL *s); 196 197 /* copy buffered record into SSL structure */ 198 static int 199 dtls1_copy_record(SSL *s, DTLS1_RECORD_DATA_INTERNAL *rdata) 200 { 201 ssl3_release_buffer(&S3I(s)->rbuf); 202 203 s->internal->packet = rdata->packet; 204 s->internal->packet_length = rdata->packet_length; 205 memcpy(&(S3I(s)->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER_INTERNAL)); 206 memcpy(&(S3I(s)->rrec), &(rdata->rrec), sizeof(SSL3_RECORD_INTERNAL)); 207 208 /* Set proper sequence number for mac calculation */ 209 memcpy(&(S3I(s)->read_sequence[2]), &(rdata->packet[5]), 6); 210 211 return (1); 212 } 213 214 static int 215 dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) 216 { 217 DTLS1_RECORD_DATA_INTERNAL *rdata; 218 pitem *item; 219 220 /* Limit the size of the queue to prevent DOS attacks */ 221 if (pqueue_size(queue->q) >= 100) 222 return 0; 223 224 rdata = malloc(sizeof(DTLS1_RECORD_DATA_INTERNAL)); 225 item = pitem_new(priority, rdata); 226 if (rdata == NULL || item == NULL) 227 goto init_err; 228 229 rdata->packet = s->internal->packet; 230 rdata->packet_length = s->internal->packet_length; 231 memcpy(&(rdata->rbuf), &(S3I(s)->rbuf), sizeof(SSL3_BUFFER_INTERNAL)); 232 memcpy(&(rdata->rrec), &(S3I(s)->rrec), sizeof(SSL3_RECORD_INTERNAL)); 233 234 item->data = rdata; 235 236 s->internal->packet = NULL; 237 s->internal->packet_length = 0; 238 memset(&(S3I(s)->rbuf), 0, sizeof(SSL3_BUFFER_INTERNAL)); 239 memset(&(S3I(s)->rrec), 0, sizeof(SSL3_RECORD_INTERNAL)); 240 241 if (!ssl3_setup_buffers(s)) 242 goto err; 243 244 /* insert should not fail, since duplicates are dropped */ 245 if (pqueue_insert(queue->q, item) == NULL) 246 goto err; 247 248 return (1); 249 250 err: 251 ssl3_release_buffer(&rdata->rbuf); 252 253 init_err: 254 SSLerror(s, ERR_R_INTERNAL_ERROR); 255 free(rdata); 256 pitem_free(item); 257 return (-1); 258 } 259 260 261 static int 262 dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue) 263 { 264 pitem *item; 265 266 item = pqueue_pop(queue->q); 267 if (item) { 268 dtls1_copy_record(s, item->data); 269 270 free(item->data); 271 pitem_free(item); 272 273 return (1); 274 } 275 276 return (0); 277 } 278 279 static int 280 dtls1_process_buffered_records(SSL *s) 281 { 282 pitem *item; 283 284 item = pqueue_peek(D1I(s)->unprocessed_rcds.q); 285 if (item) { 286 /* Check if epoch is current. */ 287 if (D1I(s)->unprocessed_rcds.epoch != D1I(s)->r_epoch) 288 return (1); 289 /* Nothing to do. */ 290 291 /* Process all the records. */ 292 while (pqueue_peek(D1I(s)->unprocessed_rcds.q)) { 293 if (!dtls1_retrieve_buffered_record((s), 294 &((D1I(s))->unprocessed_rcds))) 295 return (0); 296 if (!dtls1_process_record(s)) 297 return (0); 298 if (dtls1_buffer_record(s, &(D1I(s)->processed_rcds), 299 S3I(s)->rrec.seq_num) < 0) 300 return (-1); 301 } 302 } 303 304 /* sync epoch numbers once all the unprocessed records 305 * have been processed */ 306 D1I(s)->processed_rcds.epoch = D1I(s)->r_epoch; 307 D1I(s)->unprocessed_rcds.epoch = D1I(s)->r_epoch + 1; 308 309 return (1); 310 } 311 312 static int 313 dtls1_process_record(SSL *s) 314 { 315 SSL3_RECORD_INTERNAL *rr = &(S3I(s)->rrec); 316 uint8_t alert_desc; 317 uint8_t *out; 318 size_t out_len; 319 320 tls12_record_layer_set_version(s->internal->rl, s->version); 321 322 if (!tls12_record_layer_open_record(s->internal->rl, s->internal->packet, 323 s->internal->packet_length, &out, &out_len)) { 324 tls12_record_layer_alert(s->internal->rl, &alert_desc); 325 326 if (alert_desc == 0) 327 goto err; 328 329 if (alert_desc == SSL_AD_RECORD_OVERFLOW) 330 SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG); 331 else if (alert_desc == SSL_AD_BAD_RECORD_MAC) 332 SSLerror(s, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); 333 334 goto f_err; 335 } 336 337 rr->data = out; 338 rr->length = out_len; 339 rr->off = 0; 340 341 s->internal->packet_length = 0; 342 343 return (1); 344 345 f_err: 346 ssl3_send_alert(s, SSL3_AL_FATAL, alert_desc); 347 err: 348 return (0); 349 } 350 351 352 /* Call this to get a new input record. 353 * It will return <= 0 if more data is needed, normally due to an error 354 * or non-blocking IO. 355 * When it finishes, one packet has been decoded and can be found in 356 * ssl->s3->internal->rrec.type - is the type of record 357 * ssl->s3->internal->rrec.data, - data 358 * ssl->s3->internal->rrec.length, - number of bytes 359 */ 360 /* used only by dtls1_read_bytes */ 361 int 362 dtls1_get_record(SSL *s) 363 { 364 SSL3_RECORD_INTERNAL *rr; 365 unsigned char *p = NULL; 366 DTLS1_BITMAP *bitmap; 367 unsigned int is_next_epoch; 368 int n; 369 370 rr = &(S3I(s)->rrec); 371 372 /* The epoch may have changed. If so, process all the 373 * pending records. This is a non-blocking operation. */ 374 if (dtls1_process_buffered_records(s) < 0) 375 return (-1); 376 377 /* if we're renegotiating, then there may be buffered records */ 378 if (dtls1_retrieve_buffered_record((s), &((D1I(s))->processed_rcds))) 379 return 1; 380 381 /* get something from the wire */ 382 if (0) { 383 again: 384 /* dump this record on all retries */ 385 rr->length = 0; 386 s->internal->packet_length = 0; 387 } 388 389 /* check if we have the header */ 390 if ((s->internal->rstate != SSL_ST_READ_BODY) || 391 (s->internal->packet_length < DTLS1_RT_HEADER_LENGTH)) { 392 CBS header, seq_no; 393 uint16_t epoch, len, ssl_version; 394 uint8_t type; 395 396 n = ssl3_packet_read(s, DTLS1_RT_HEADER_LENGTH); 397 if (n <= 0) 398 return (n); 399 400 /* If this packet contained a partial record, dump it. */ 401 if (n != DTLS1_RT_HEADER_LENGTH) 402 goto again; 403 404 s->internal->rstate = SSL_ST_READ_BODY; 405 406 CBS_init(&header, s->internal->packet, s->internal->packet_length); 407 408 /* Pull apart the header into the DTLS1_RECORD */ 409 if (!CBS_get_u8(&header, &type)) 410 goto again; 411 if (!CBS_get_u16(&header, &ssl_version)) 412 goto again; 413 414 /* sequence number is 64 bits, with top 2 bytes = epoch */ 415 if (!CBS_get_u16(&header, &epoch) || 416 !CBS_get_bytes(&header, &seq_no, 6)) 417 goto again; 418 419 if (!CBS_get_u16(&header, &len)) 420 goto again; 421 422 if (!CBS_write_bytes(&seq_no, &(S3I(s)->read_sequence[2]), 423 sizeof(S3I(s)->read_sequence) - 2, NULL)) 424 goto again; 425 426 if (!CBS_write_bytes(&seq_no, &rr->seq_num[2], 427 sizeof(rr->seq_num) - 2, NULL)) 428 goto again; 429 430 rr->type = type; 431 rr->epoch = epoch; 432 rr->length = len; 433 434 /* unexpected version, silently discard */ 435 if (!s->internal->first_packet && ssl_version != s->version) 436 goto again; 437 438 /* wrong version, silently discard record */ 439 if ((ssl_version & 0xff00) != (s->version & 0xff00)) 440 goto again; 441 442 /* record too long, silently discard it */ 443 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) 444 goto again; 445 446 /* now s->internal->rstate == SSL_ST_READ_BODY */ 447 p = (unsigned char *)CBS_data(&header); 448 } 449 450 /* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */ 451 452 n = ssl3_packet_extend(s, DTLS1_RT_HEADER_LENGTH + rr->length); 453 if (n <= 0) 454 return (n); 455 456 /* If this packet contained a partial record, dump it. */ 457 if (n != DTLS1_RT_HEADER_LENGTH + rr->length) 458 goto again; 459 460 s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */ 461 462 /* match epochs. NULL means the packet is dropped on the floor */ 463 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); 464 if (bitmap == NULL) 465 goto again; 466 467 /* 468 * Check whether this is a repeat, or aged record. 469 * Don't check if we're listening and this message is 470 * a ClientHello. They can look as if they're replayed, 471 * since they arrive from different connections and 472 * would be dropped unnecessarily. 473 */ 474 if (!(D1I(s)->listen && rr->type == SSL3_RT_HANDSHAKE && 475 p != NULL && *p == SSL3_MT_CLIENT_HELLO) && 476 !dtls1_record_replay_check(s, bitmap, rr->seq_num)) 477 goto again; 478 479 /* just read a 0 length packet */ 480 if (rr->length == 0) 481 goto again; 482 483 /* If this record is from the next epoch (either HM or ALERT), 484 * and a handshake is currently in progress, buffer it since it 485 * cannot be processed at this time. However, do not buffer 486 * anything while listening. 487 */ 488 if (is_next_epoch) { 489 if ((SSL_in_init(s) || s->internal->in_handshake) && !D1I(s)->listen) { 490 if (dtls1_buffer_record(s, &(D1I(s)->unprocessed_rcds), 491 rr->seq_num) < 0) 492 return (-1); 493 /* Mark receipt of record. */ 494 dtls1_record_bitmap_update(s, bitmap, rr->seq_num); 495 } 496 goto again; 497 } 498 499 if (!dtls1_process_record(s)) 500 goto again; 501 502 /* Mark receipt of record. */ 503 dtls1_record_bitmap_update(s, bitmap, rr->seq_num); 504 505 return (1); 506 } 507 508 /* Return up to 'len' payload bytes received in 'type' records. 509 * 'type' is one of the following: 510 * 511 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us) 512 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us) 513 * - 0 (during a shutdown, no data has to be returned) 514 * 515 * If we don't have stored data to work from, read a SSL/TLS record first 516 * (possibly multiple records if we still don't have anything to return). 517 * 518 * This function must handle any surprises the peer may have for us, such as 519 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really 520 * a surprise, but handled as if it were), or renegotiation requests. 521 * Also if record payloads contain fragments too small to process, we store 522 * them until there is enough for the respective protocol (the record protocol 523 * may use arbitrary fragmentation and even interleaving): 524 * Change cipher spec protocol 525 * just 1 byte needed, no need for keeping anything stored 526 * Alert protocol 527 * 2 bytes needed (AlertLevel, AlertDescription) 528 * Handshake protocol 529 * 4 bytes needed (HandshakeType, uint24 length) -- we just have 530 * to detect unexpected Client Hello and Hello Request messages 531 * here, anything else is handled by higher layers 532 * Application data protocol 533 * none of our business 534 */ 535 int 536 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) 537 { 538 int al, i, j, ret; 539 unsigned int n; 540 SSL3_RECORD_INTERNAL *rr; 541 void (*cb)(const SSL *ssl, int type2, int val) = NULL; 542 543 if (S3I(s)->rbuf.buf == NULL) /* Not initialized yet */ 544 if (!ssl3_setup_buffers(s)) 545 return (-1); 546 547 if ((type && 548 type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) || 549 (peek && (type != SSL3_RT_APPLICATION_DATA))) { 550 SSLerror(s, ERR_R_INTERNAL_ERROR); 551 return -1; 552 } 553 554 /* check whether there's a handshake message (client hello?) waiting */ 555 if ((ret = have_handshake_fragment(s, type, buf, len, peek))) 556 return ret; 557 558 /* Now D1I(s)->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ 559 560 if (!s->internal->in_handshake && SSL_in_init(s)) 561 { 562 /* type == SSL3_RT_APPLICATION_DATA */ 563 i = s->internal->handshake_func(s); 564 if (i < 0) 565 return (i); 566 if (i == 0) { 567 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE); 568 return (-1); 569 } 570 } 571 572 start: 573 s->internal->rwstate = SSL_NOTHING; 574 575 /* S3I(s)->rrec.type - is the type of record 576 * S3I(s)->rrec.data, - data 577 * S3I(s)->rrec.off, - offset into 'data' for next read 578 * S3I(s)->rrec.length, - number of bytes. */ 579 rr = &(S3I(s)->rrec); 580 581 /* We are not handshaking and have no data yet, 582 * so process data buffered during the last handshake 583 * in advance, if any. 584 */ 585 if (S3I(s)->hs.state == SSL_ST_OK && rr->length == 0) { 586 pitem *item; 587 item = pqueue_pop(D1I(s)->buffered_app_data.q); 588 if (item) { 589 dtls1_copy_record(s, item->data); 590 591 free(item->data); 592 pitem_free(item); 593 } 594 } 595 596 /* Check for timeout */ 597 if (dtls1_handle_timeout(s) > 0) 598 goto start; 599 600 /* get new packet if necessary */ 601 if ((rr->length == 0) || (s->internal->rstate == SSL_ST_READ_BODY)) { 602 ret = dtls1_get_record(s); 603 if (ret <= 0) { 604 ret = dtls1_read_failed(s, ret); 605 /* anything other than a timeout is an error */ 606 if (ret <= 0) 607 return (ret); 608 else 609 goto start; 610 } 611 } 612 613 if (D1I(s)->listen && rr->type != SSL3_RT_HANDSHAKE) { 614 rr->length = 0; 615 goto start; 616 } 617 618 /* we now have a packet which can be read and processed */ 619 620 if (S3I(s)->change_cipher_spec /* set when we receive ChangeCipherSpec, 621 * reset by ssl3_get_finished */ 622 && (rr->type != SSL3_RT_HANDSHAKE)) { 623 /* We now have application data between CCS and Finished. 624 * Most likely the packets were reordered on their way, so 625 * buffer the application data for later processing rather 626 * than dropping the connection. 627 */ 628 if (dtls1_buffer_record(s, &(D1I(s)->buffered_app_data), 629 rr->seq_num) < 0) { 630 SSLerror(s, ERR_R_INTERNAL_ERROR); 631 return (-1); 632 } 633 rr->length = 0; 634 goto start; 635 } 636 637 /* If the other end has shut down, throw anything we read away 638 * (even in 'peek' mode) */ 639 if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) { 640 rr->length = 0; 641 s->internal->rwstate = SSL_NOTHING; 642 return (0); 643 } 644 645 /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ 646 if (type == rr->type) { 647 /* make sure that we are not getting application data when we 648 * are doing a handshake for the first time */ 649 if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA && 650 !tls12_record_layer_read_protected(s->internal->rl)) { 651 al = SSL_AD_UNEXPECTED_MESSAGE; 652 SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE); 653 goto f_err; 654 } 655 656 if (len <= 0) 657 return (len); 658 659 if ((unsigned int)len > rr->length) 660 n = rr->length; 661 else 662 n = (unsigned int)len; 663 664 memcpy(buf, &(rr->data[rr->off]), n); 665 if (!peek) { 666 rr->length -= n; 667 rr->off += n; 668 if (rr->length == 0) { 669 s->internal->rstate = SSL_ST_READ_HEADER; 670 rr->off = 0; 671 } 672 } 673 674 return (n); 675 } 676 677 678 /* If we get here, then type != rr->type; if we have a handshake 679 * message, then it was unexpected (Hello Request or Client Hello). */ 680 681 /* In case of record types for which we have 'fragment' storage, 682 * fill that so that we can process the data at a fixed place. 683 */ 684 { 685 unsigned int k, dest_maxlen = 0; 686 unsigned char *dest = NULL; 687 unsigned int *dest_len = NULL; 688 689 if (rr->type == SSL3_RT_HANDSHAKE) { 690 dest_maxlen = sizeof D1I(s)->handshake_fragment; 691 dest = D1I(s)->handshake_fragment; 692 dest_len = &D1I(s)->handshake_fragment_len; 693 } else if (rr->type == SSL3_RT_ALERT) { 694 dest_maxlen = sizeof(D1I(s)->alert_fragment); 695 dest = D1I(s)->alert_fragment; 696 dest_len = &D1I(s)->alert_fragment_len; 697 } 698 /* else it's a CCS message, or application data or wrong */ 699 else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { 700 /* Application data while renegotiating 701 * is allowed. Try again reading. 702 */ 703 if (rr->type == SSL3_RT_APPLICATION_DATA) { 704 BIO *bio; 705 S3I(s)->in_read_app_data = 2; 706 bio = SSL_get_rbio(s); 707 s->internal->rwstate = SSL_READING; 708 BIO_clear_retry_flags(bio); 709 BIO_set_retry_read(bio); 710 return (-1); 711 } 712 713 /* Not certain if this is the right error handling */ 714 al = SSL_AD_UNEXPECTED_MESSAGE; 715 SSLerror(s, SSL_R_UNEXPECTED_RECORD); 716 goto f_err; 717 } 718 719 if (dest_maxlen > 0) { 720 /* XDTLS: In a pathalogical case, the Client Hello 721 * may be fragmented--don't always expect dest_maxlen bytes */ 722 if (rr->length < dest_maxlen) { 723 s->internal->rstate = SSL_ST_READ_HEADER; 724 rr->length = 0; 725 goto start; 726 } 727 728 /* now move 'n' bytes: */ 729 for ( k = 0; k < dest_maxlen; k++) { 730 dest[k] = rr->data[rr->off++]; 731 rr->length--; 732 } 733 *dest_len = dest_maxlen; 734 } 735 } 736 737 /* D1I(s)->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; 738 * D1I(s)->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. 739 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ 740 741 /* If we are a client, check for an incoming 'Hello Request': */ 742 if ((!s->server) && 743 (D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && 744 (D1I(s)->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && 745 (s->session != NULL) && (s->session->cipher != NULL)) { 746 D1I(s)->handshake_fragment_len = 0; 747 748 if ((D1I(s)->handshake_fragment[1] != 0) || 749 (D1I(s)->handshake_fragment[2] != 0) || 750 (D1I(s)->handshake_fragment[3] != 0)) { 751 al = SSL_AD_DECODE_ERROR; 752 SSLerror(s, SSL_R_BAD_HELLO_REQUEST); 753 goto f_err; 754 } 755 756 /* no need to check sequence number on HELLO REQUEST messages */ 757 758 if (s->internal->msg_callback) 759 s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, 760 D1I(s)->handshake_fragment, 4, s, s->internal->msg_callback_arg); 761 762 if (SSL_is_init_finished(s) && 763 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && 764 !S3I(s)->renegotiate) { 765 D1I(s)->handshake_read_seq++; 766 s->internal->new_session = 1; 767 ssl3_renegotiate(s); 768 if (ssl3_renegotiate_check(s)) { 769 i = s->internal->handshake_func(s); 770 if (i < 0) 771 return (i); 772 if (i == 0) { 773 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE); 774 return (-1); 775 } 776 777 if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) { 778 if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */ 779 { 780 BIO *bio; 781 /* In the case where we try to read application data, 782 * but we trigger an SSL handshake, we return -1 with 783 * the retry option set. Otherwise renegotiation may 784 * cause nasty problems in the blocking world */ 785 s->internal->rwstate = SSL_READING; 786 bio = SSL_get_rbio(s); 787 BIO_clear_retry_flags(bio); 788 BIO_set_retry_read(bio); 789 return (-1); 790 } 791 } 792 } 793 } 794 /* we either finished a handshake or ignored the request, 795 * now try again to obtain the (application) data we were asked for */ 796 goto start; 797 } 798 799 if (D1I(s)->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { 800 int alert_level = D1I(s)->alert_fragment[0]; 801 int alert_descr = D1I(s)->alert_fragment[1]; 802 803 D1I(s)->alert_fragment_len = 0; 804 805 if (s->internal->msg_callback) 806 s->internal->msg_callback(0, s->version, SSL3_RT_ALERT, 807 D1I(s)->alert_fragment, 2, s, s->internal->msg_callback_arg); 808 809 if (s->internal->info_callback != NULL) 810 cb = s->internal->info_callback; 811 else if (s->ctx->internal->info_callback != NULL) 812 cb = s->ctx->internal->info_callback; 813 814 if (cb != NULL) { 815 j = (alert_level << 8) | alert_descr; 816 cb(s, SSL_CB_READ_ALERT, j); 817 } 818 819 if (alert_level == 1) /* warning */ 820 { 821 S3I(s)->warn_alert = alert_descr; 822 if (alert_descr == SSL_AD_CLOSE_NOTIFY) { 823 s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN; 824 return (0); 825 } 826 } else if (alert_level == 2) /* fatal */ 827 { 828 s->internal->rwstate = SSL_NOTHING; 829 S3I(s)->fatal_alert = alert_descr; 830 SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr); 831 ERR_asprintf_error_data("SSL alert number %d", 832 alert_descr); 833 s->internal->shutdown|=SSL_RECEIVED_SHUTDOWN; 834 SSL_CTX_remove_session(s->ctx, s->session); 835 return (0); 836 } else { 837 al = SSL_AD_ILLEGAL_PARAMETER; 838 SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE); 839 goto f_err; 840 } 841 842 goto start; 843 } 844 845 if (s->internal->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ 846 { 847 s->internal->rwstate = SSL_NOTHING; 848 rr->length = 0; 849 return (0); 850 } 851 852 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { 853 struct ccs_header_st ccs_hdr; 854 unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; 855 856 dtls1_get_ccs_header(rr->data, &ccs_hdr); 857 858 /* 'Change Cipher Spec' is just a single byte, so we know 859 * exactly what the record payload has to look like */ 860 /* XDTLS: check that epoch is consistent */ 861 if ((rr->length != ccs_hdr_len) || 862 (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { 863 al = SSL_AD_DECODE_ERROR; 864 SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC); 865 goto f_err; 866 } 867 868 rr->length = 0; 869 870 if (s->internal->msg_callback) 871 s->internal->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, 872 rr->data, 1, s, s->internal->msg_callback_arg); 873 874 /* We can't process a CCS now, because previous handshake 875 * messages are still missing, so just drop it. 876 */ 877 if (!D1I(s)->change_cipher_spec_ok) { 878 goto start; 879 } 880 881 D1I(s)->change_cipher_spec_ok = 0; 882 883 S3I(s)->change_cipher_spec = 1; 884 if (!ssl3_do_change_cipher_spec(s)) 885 goto err; 886 887 /* do this whenever CCS is processed */ 888 dtls1_reset_seq_numbers(s, SSL3_CC_READ); 889 890 goto start; 891 } 892 893 /* Unexpected handshake message (Client Hello, or protocol violation) */ 894 if ((D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && 895 !s->internal->in_handshake) { 896 struct hm_header_st msg_hdr; 897 898 /* this may just be a stale retransmit */ 899 if (!dtls1_get_message_header(rr->data, &msg_hdr)) 900 return -1; 901 if (rr->epoch != D1I(s)->r_epoch) { 902 rr->length = 0; 903 goto start; 904 } 905 906 /* If we are server, we may have a repeated FINISHED of the 907 * client here, then retransmit our CCS and FINISHED. 908 */ 909 if (msg_hdr.type == SSL3_MT_FINISHED) { 910 if (dtls1_check_timeout_num(s) < 0) 911 return -1; 912 913 dtls1_retransmit_buffered_messages(s); 914 rr->length = 0; 915 goto start; 916 } 917 918 if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) && 919 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { 920 S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; 921 s->internal->renegotiate = 1; 922 s->internal->new_session = 1; 923 } 924 i = s->internal->handshake_func(s); 925 if (i < 0) 926 return (i); 927 if (i == 0) { 928 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE); 929 return (-1); 930 } 931 932 if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) { 933 if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */ 934 { 935 BIO *bio; 936 /* In the case where we try to read application data, 937 * but we trigger an SSL handshake, we return -1 with 938 * the retry option set. Otherwise renegotiation may 939 * cause nasty problems in the blocking world */ 940 s->internal->rwstate = SSL_READING; 941 bio = SSL_get_rbio(s); 942 BIO_clear_retry_flags(bio); 943 BIO_set_retry_read(bio); 944 return (-1); 945 } 946 } 947 goto start; 948 } 949 950 switch (rr->type) { 951 default: 952 /* TLS just ignores unknown message types */ 953 if (s->version == TLS1_VERSION) { 954 rr->length = 0; 955 goto start; 956 } 957 al = SSL_AD_UNEXPECTED_MESSAGE; 958 SSLerror(s, SSL_R_UNEXPECTED_RECORD); 959 goto f_err; 960 case SSL3_RT_CHANGE_CIPHER_SPEC: 961 case SSL3_RT_ALERT: 962 case SSL3_RT_HANDSHAKE: 963 /* we already handled all of these, with the possible exception 964 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that 965 * should not happen when type != rr->type */ 966 al = SSL_AD_UNEXPECTED_MESSAGE; 967 SSLerror(s, ERR_R_INTERNAL_ERROR); 968 goto f_err; 969 case SSL3_RT_APPLICATION_DATA: 970 /* At this point, we were expecting handshake data, 971 * but have application data. If the library was 972 * running inside ssl3_read() (i.e. in_read_app_data 973 * is set) and it makes sense to read application data 974 * at this point (session renegotiation not yet started), 975 * we will indulge it. 976 */ 977 if (S3I(s)->in_read_app_data && 978 (S3I(s)->total_renegotiations != 0) && 979 (((S3I(s)->hs.state & SSL_ST_CONNECT) && 980 (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) && 981 (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || ( 982 (S3I(s)->hs.state & SSL_ST_ACCEPT) && 983 (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) && 984 (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) { 985 S3I(s)->in_read_app_data = 2; 986 return (-1); 987 } else { 988 al = SSL_AD_UNEXPECTED_MESSAGE; 989 SSLerror(s, SSL_R_UNEXPECTED_RECORD); 990 goto f_err; 991 } 992 } 993 /* not reached */ 994 995 f_err: 996 ssl3_send_alert(s, SSL3_AL_FATAL, al); 997 err: 998 return (-1); 999 } 1000 1001 int 1002 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len) 1003 { 1004 int i; 1005 1006 if (SSL_in_init(s) && !s->internal->in_handshake) 1007 { 1008 i = s->internal->handshake_func(s); 1009 if (i < 0) 1010 return (i); 1011 if (i == 0) { 1012 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE); 1013 return -1; 1014 } 1015 } 1016 1017 if (len > SSL3_RT_MAX_PLAIN_LENGTH) { 1018 SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG); 1019 return -1; 1020 } 1021 1022 i = dtls1_write_bytes(s, type, buf_, len); 1023 return i; 1024 } 1025 1026 1027 /* this only happens when a client hello is received and a handshake 1028 * is started. */ 1029 static int 1030 have_handshake_fragment(SSL *s, int type, unsigned char *buf, 1031 int len, int peek) 1032 { 1033 1034 if ((type == SSL3_RT_HANDSHAKE) && (D1I(s)->handshake_fragment_len > 0)) 1035 /* (partially) satisfy request from storage */ 1036 { 1037 unsigned char *src = D1I(s)->handshake_fragment; 1038 unsigned char *dst = buf; 1039 unsigned int k, n; 1040 1041 /* peek == 0 */ 1042 n = 0; 1043 while ((len > 0) && (D1I(s)->handshake_fragment_len > 0)) { 1044 *dst++ = *src++; 1045 len--; 1046 D1I(s)->handshake_fragment_len--; 1047 n++; 1048 } 1049 /* move any remaining fragment bytes: */ 1050 for (k = 0; k < D1I(s)->handshake_fragment_len; k++) 1051 D1I(s)->handshake_fragment[k] = *src++; 1052 return n; 1053 } 1054 1055 return 0; 1056 } 1057 1058 1059 /* Call this to write data in records of type 'type' 1060 * It will return <= 0 if not all data has been sent or non-blocking IO. 1061 */ 1062 int 1063 dtls1_write_bytes(SSL *s, int type, const void *buf, int len) 1064 { 1065 int i; 1066 1067 OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH); 1068 s->internal->rwstate = SSL_NOTHING; 1069 i = do_dtls1_write(s, type, buf, len); 1070 return i; 1071 } 1072 1073 int 1074 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len) 1075 { 1076 SSL3_BUFFER_INTERNAL *wb = &(S3I(s)->wbuf); 1077 size_t out_len; 1078 CBB cbb; 1079 int ret; 1080 1081 memset(&cbb, 0, sizeof(cbb)); 1082 1083 /* 1084 * First check if there is a SSL3_BUFFER_INTERNAL still being written 1085 * out. This will happen with non blocking IO. 1086 */ 1087 if (wb->left != 0) { 1088 OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */ 1089 return (ssl3_write_pending(s, type, buf, len)); 1090 } 1091 1092 /* If we have an alert to send, let's send it */ 1093 if (S3I(s)->alert_dispatch) { 1094 if ((ret = s->method->ssl_dispatch_alert(s)) <= 0) 1095 return (ret); 1096 /* If it went, fall through and send more stuff. */ 1097 } 1098 1099 if (len == 0) 1100 return 0; 1101 1102 wb->offset = 0; 1103 1104 if (!CBB_init_fixed(&cbb, wb->buf, wb->len)) 1105 goto err; 1106 1107 tls12_record_layer_set_version(s->internal->rl, s->version); 1108 1109 if (!tls12_record_layer_seal_record(s->internal->rl, type, buf, len, &cbb)) 1110 goto err; 1111 1112 if (!CBB_finish(&cbb, NULL, &out_len)) 1113 goto err; 1114 1115 wb->left = out_len; 1116 1117 /* 1118 * Memorize arguments so that ssl3_write_pending can detect 1119 * bad write retries later. 1120 */ 1121 S3I(s)->wpend_tot = len; 1122 S3I(s)->wpend_buf = buf; 1123 S3I(s)->wpend_type = type; 1124 S3I(s)->wpend_ret = len; 1125 1126 /* We now just need to write the buffer. */ 1127 return ssl3_write_pending(s, type, buf, len); 1128 1129 err: 1130 CBB_cleanup(&cbb); 1131 1132 return -1; 1133 } 1134 1135 static int 1136 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap, 1137 const unsigned char *seq) 1138 { 1139 unsigned int shift; 1140 int cmp; 1141 1142 cmp = satsub64be(seq, bitmap->max_seq_num); 1143 if (cmp > 0) 1144 return 1; /* this record in new */ 1145 shift = -cmp; 1146 if (shift >= sizeof(bitmap->map)*8) 1147 return 0; /* stale, outside the window */ 1148 else if (bitmap->map & (1UL << shift)) 1149 return 0; /* record previously received */ 1150 1151 return 1; 1152 } 1153 1154 static void 1155 dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap, 1156 const unsigned char *seq) 1157 { 1158 unsigned int shift; 1159 int cmp; 1160 1161 cmp = satsub64be(seq, bitmap->max_seq_num); 1162 if (cmp > 0) { 1163 shift = cmp; 1164 if (shift < sizeof(bitmap->map)*8) 1165 bitmap->map <<= shift, bitmap->map |= 1UL; 1166 else 1167 bitmap->map = 1UL; 1168 memcpy(bitmap->max_seq_num, seq, 8); 1169 } else { 1170 shift = -cmp; 1171 if (shift < sizeof(bitmap->map) * 8) 1172 bitmap->map |= 1UL << shift; 1173 } 1174 } 1175 1176 int 1177 dtls1_dispatch_alert(SSL *s) 1178 { 1179 int i, j; 1180 void (*cb)(const SSL *ssl, int type, int val) = NULL; 1181 unsigned char buf[DTLS1_AL_HEADER_LENGTH]; 1182 unsigned char *ptr = &buf[0]; 1183 1184 S3I(s)->alert_dispatch = 0; 1185 1186 memset(buf, 0, sizeof(buf)); 1187 *ptr++ = S3I(s)->send_alert[0]; 1188 *ptr++ = S3I(s)->send_alert[1]; 1189 1190 i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf)); 1191 if (i <= 0) { 1192 S3I(s)->alert_dispatch = 1; 1193 /* fprintf( stderr, "not done with alert\n" ); */ 1194 } else { 1195 if (S3I(s)->send_alert[0] == SSL3_AL_FATAL) 1196 (void)BIO_flush(s->wbio); 1197 1198 if (s->internal->msg_callback) 1199 s->internal->msg_callback(1, s->version, SSL3_RT_ALERT, 1200 S3I(s)->send_alert, 2, s, s->internal->msg_callback_arg); 1201 1202 if (s->internal->info_callback != NULL) 1203 cb = s->internal->info_callback; 1204 else if (s->ctx->internal->info_callback != NULL) 1205 cb = s->ctx->internal->info_callback; 1206 1207 if (cb != NULL) { 1208 j = (S3I(s)->send_alert[0]<<8)|S3I(s)->send_alert[1]; 1209 cb(s, SSL_CB_WRITE_ALERT, j); 1210 } 1211 } 1212 return (i); 1213 } 1214 1215 1216 static DTLS1_BITMAP * 1217 dtls1_get_bitmap(SSL *s, SSL3_RECORD_INTERNAL *rr, unsigned int *is_next_epoch) 1218 { 1219 1220 *is_next_epoch = 0; 1221 1222 /* In current epoch, accept HM, CCS, DATA, & ALERT */ 1223 if (rr->epoch == D1I(s)->r_epoch) 1224 return &D1I(s)->bitmap; 1225 1226 /* Only HM and ALERT messages can be from the next epoch */ 1227 else if (rr->epoch == (unsigned long)(D1I(s)->r_epoch + 1) && 1228 (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) { 1229 *is_next_epoch = 1; 1230 return &D1I(s)->next_bitmap; 1231 } 1232 1233 return NULL; 1234 } 1235 1236 void 1237 dtls1_reset_seq_numbers(SSL *s, int rw) 1238 { 1239 if (rw & SSL3_CC_READ) { 1240 D1I(s)->r_epoch++; 1241 memcpy(&(D1I(s)->bitmap), &(D1I(s)->next_bitmap), 1242 sizeof(DTLS1_BITMAP)); 1243 memset(&(D1I(s)->next_bitmap), 0, sizeof(DTLS1_BITMAP)); 1244 memset(S3I(s)->read_sequence, 0, sizeof(S3I(s)->read_sequence)); 1245 } else { 1246 D1I(s)->w_epoch++; 1247 tls12_record_layer_set_write_epoch(s->internal->rl, D1I(s)->w_epoch); 1248 memcpy(D1I(s)->last_write_sequence, S3I(s)->write_sequence, 1249 sizeof(S3I(s)->write_sequence)); 1250 memset(S3I(s)->write_sequence, 0, sizeof(S3I(s)->write_sequence)); 1251 } 1252 } 1253