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