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