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