1 /* $OpenBSD: d1_pkt.c,v 1.58 2017/01/23 14:35:42 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 *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, pitem *item) 198 { 199 DTLS1_RECORD_DATA *rdata; 200 201 rdata = (DTLS1_RECORD_DATA *)item->data; 202 203 free(s->s3->rbuf.buf); 204 205 s->internal->packet = rdata->packet; 206 s->internal->packet_length = rdata->packet_length; 207 memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER)); 208 memcpy(&(S3I(s)->rrec), &(rdata->rrec), sizeof(SSL3_RECORD)); 209 210 /* Set proper sequence number for mac calculation */ 211 memcpy(&(S3I(s)->read_sequence[2]), &(rdata->packet[5]), 6); 212 213 return (1); 214 } 215 216 217 static int 218 dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority) 219 { 220 DTLS1_RECORD_DATA *rdata; 221 pitem *item; 222 223 /* Limit the size of the queue to prevent DOS attacks */ 224 if (pqueue_size(queue->q) >= 100) 225 return 0; 226 227 rdata = malloc(sizeof(DTLS1_RECORD_DATA)); 228 item = pitem_new(priority, rdata); 229 if (rdata == NULL || item == NULL) 230 goto init_err; 231 232 rdata->packet = s->internal->packet; 233 rdata->packet_length = s->internal->packet_length; 234 memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER)); 235 memcpy(&(rdata->rrec), &(S3I(s)->rrec), sizeof(SSL3_RECORD)); 236 237 item->data = rdata; 238 239 240 s->internal->packet = NULL; 241 s->internal->packet_length = 0; 242 memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER)); 243 memset(&(S3I(s)->rrec), 0, sizeof(SSL3_RECORD)); 244 245 if (!ssl3_setup_buffers(s)) 246 goto err; 247 248 /* insert should not fail, since duplicates are dropped */ 249 if (pqueue_insert(queue->q, item) == NULL) 250 goto err; 251 252 return (1); 253 254 err: 255 free(rdata->rbuf.buf); 256 257 init_err: 258 SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR); 259 free(rdata); 260 pitem_free(item); 261 return (-1); 262 } 263 264 265 static int 266 dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue) 267 { 268 pitem *item; 269 270 item = pqueue_pop(queue->q); 271 if (item) { 272 dtls1_copy_record(s, item); 273 274 free(item->data); 275 pitem_free(item); 276 277 return (1); 278 } 279 280 return (0); 281 } 282 283 284 /* retrieve a buffered record that belongs to the new epoch, i.e., not processed 285 * yet */ 286 #define dtls1_get_unprocessed_record(s) \ 287 dtls1_retrieve_buffered_record((s), \ 288 &((D1I(s))->unprocessed_rcds)) 289 290 /* retrieve a buffered record that belongs to the current epoch, ie, processed */ 291 #define dtls1_get_processed_record(s) \ 292 dtls1_retrieve_buffered_record((s), \ 293 &((D1I(s))->processed_rcds)) 294 295 static int 296 dtls1_process_buffered_records(SSL *s) 297 { 298 pitem *item; 299 300 item = pqueue_peek(D1I(s)->unprocessed_rcds.q); 301 if (item) { 302 /* Check if epoch is current. */ 303 if (D1I(s)->unprocessed_rcds.epoch != D1I(s)->r_epoch) 304 return (1); 305 /* Nothing to do. */ 306 307 /* Process all the records. */ 308 while (pqueue_peek(D1I(s)->unprocessed_rcds.q)) { 309 dtls1_get_unprocessed_record(s); 310 if (! dtls1_process_record(s)) 311 return (0); 312 if (dtls1_buffer_record(s, &(D1I(s)->processed_rcds), 313 S3I(s)->rrec.seq_num) < 0) 314 return (-1); 315 } 316 } 317 318 /* sync epoch numbers once all the unprocessed records 319 * have been processed */ 320 D1I(s)->processed_rcds.epoch = D1I(s)->r_epoch; 321 D1I(s)->unprocessed_rcds.epoch = D1I(s)->r_epoch + 1; 322 323 return (1); 324 } 325 326 static int 327 dtls1_process_record(SSL *s) 328 { 329 int i, al; 330 int enc_err; 331 SSL_SESSION *sess; 332 SSL3_RECORD *rr; 333 unsigned int mac_size, orig_len; 334 unsigned char md[EVP_MAX_MD_SIZE]; 335 336 rr = &(S3I(s)->rrec); 337 sess = s->session; 338 339 /* At this point, s->internal->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, 340 * and we have that many bytes in s->internal->packet 341 */ 342 rr->input = &(s->internal->packet[DTLS1_RT_HEADER_LENGTH]); 343 344 /* ok, we can now read from 's->internal->packet' data into 'rr' 345 * rr->input points at rr->length bytes, which 346 * need to be copied into rr->data by either 347 * the decryption or by the decompression 348 * When the data is 'copied' into the rr->data buffer, 349 * rr->input will be pointed at the new buffer */ 350 351 /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] 352 * rr->length bytes of encrypted compressed stuff. */ 353 354 /* check is not needed I believe */ 355 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { 356 al = SSL_AD_RECORD_OVERFLOW; 357 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG); 358 goto f_err; 359 } 360 361 /* decrypt in place in 'rr->input' */ 362 rr->data = rr->input; 363 364 enc_err = s->method->internal->ssl3_enc->enc(s, 0); 365 /* enc_err is: 366 * 0: (in non-constant time) if the record is publically invalid. 367 * 1: if the padding is valid 368 * -1: if the padding is invalid */ 369 if (enc_err == 0) { 370 /* For DTLS we simply ignore bad packets. */ 371 rr->length = 0; 372 s->internal->packet_length = 0; 373 goto err; 374 } 375 376 377 /* r->length is now the compressed data plus mac */ 378 if ((sess != NULL) && (s->enc_read_ctx != NULL) && 379 (EVP_MD_CTX_md(s->read_hash) != NULL)) { 380 /* s->read_hash != NULL => mac_size != -1 */ 381 unsigned char *mac = NULL; 382 unsigned char mac_tmp[EVP_MAX_MD_SIZE]; 383 mac_size = EVP_MD_CTX_size(s->read_hash); 384 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); 385 386 /* kludge: *_cbc_remove_padding passes padding length in rr->type */ 387 orig_len = rr->length + ((unsigned int)rr->type >> 8); 388 389 /* orig_len is the length of the record before any padding was 390 * removed. This is public information, as is the MAC in use, 391 * therefore we can safely process the record in a different 392 * amount of time if it's too short to possibly contain a MAC. 393 */ 394 if (orig_len < mac_size || 395 /* CBC records must have a padding length byte too. */ 396 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && 397 orig_len < mac_size + 1)) { 398 al = SSL_AD_DECODE_ERROR; 399 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT); 400 goto f_err; 401 } 402 403 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { 404 /* We update the length so that the TLS header bytes 405 * can be constructed correctly but we need to extract 406 * the MAC in constant time from within the record, 407 * without leaking the contents of the padding bytes. 408 * */ 409 mac = mac_tmp; 410 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len); 411 rr->length -= mac_size; 412 } else { 413 /* In this case there's no padding, so |orig_len| 414 * equals |rec->length| and we checked that there's 415 * enough bytes for |mac_size| above. */ 416 rr->length -= mac_size; 417 mac = &rr->data[rr->length]; 418 } 419 420 i = s->method->internal->ssl3_enc->mac(s, md, 0 /* not send */); 421 if (i < 0 || mac == NULL || timingsafe_memcmp(md, mac, (size_t)mac_size) != 0) 422 enc_err = -1; 423 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size) 424 enc_err = -1; 425 } 426 427 if (enc_err < 0) { 428 /* decryption failed, silently discard message */ 429 rr->length = 0; 430 s->internal->packet_length = 0; 431 goto err; 432 } 433 434 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { 435 al = SSL_AD_RECORD_OVERFLOW; 436 SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG); 437 goto f_err; 438 } 439 440 rr->off = 0; 441 /* So at this point the following is true 442 * ssl->s3->internal->rrec.type is the type of record 443 * ssl->s3->internal->rrec.length == number of bytes in record 444 * ssl->s3->internal->rrec.off == offset to first valid byte 445 * ssl->s3->internal->rrec.data == where to take bytes from, increment 446 * after use :-). 447 */ 448 449 /* we have pulled in a full packet so zero things */ 450 s->internal->packet_length = 0; 451 return (1); 452 453 f_err: 454 ssl3_send_alert(s, SSL3_AL_FATAL, al); 455 err: 456 return (0); 457 } 458 459 460 /* Call this to get a new input record. 461 * It will return <= 0 if more data is needed, normally due to an error 462 * or non-blocking IO. 463 * When it finishes, one packet has been decoded and can be found in 464 * ssl->s3->internal->rrec.type - is the type of record 465 * ssl->s3->internal->rrec.data, - data 466 * ssl->s3->internal->rrec.length, - number of bytes 467 */ 468 /* used only by dtls1_read_bytes */ 469 int 470 dtls1_get_record(SSL *s) 471 { 472 int i, n; 473 SSL3_RECORD *rr; 474 unsigned char *p = NULL; 475 DTLS1_BITMAP *bitmap; 476 unsigned int is_next_epoch; 477 478 rr = &(S3I(s)->rrec); 479 480 /* The epoch may have changed. If so, process all the 481 * pending records. This is a non-blocking operation. */ 482 if (dtls1_process_buffered_records(s) < 0) 483 return (-1); 484 485 /* if we're renegotiating, then there may be buffered records */ 486 if (dtls1_get_processed_record(s)) 487 return 1; 488 489 /* get something from the wire */ 490 if (0) { 491 again: 492 /* dump this record on all retries */ 493 rr->length = 0; 494 s->internal->packet_length = 0; 495 } 496 497 /* check if we have the header */ 498 if ((s->internal->rstate != SSL_ST_READ_BODY) || 499 (s->internal->packet_length < DTLS1_RT_HEADER_LENGTH)) { 500 CBS header, seq_no; 501 uint16_t epoch, len, ssl_version; 502 uint8_t type; 503 504 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); 505 /* read timeout is handled by dtls1_read_bytes */ 506 if (n <= 0) 507 return(n); /* error or non-blocking */ 508 509 /* this packet contained a partial record, dump it */ 510 if (s->internal->packet_length != DTLS1_RT_HEADER_LENGTH) 511 goto again; 512 513 s->internal->rstate = SSL_ST_READ_BODY; 514 515 CBS_init(&header, s->internal->packet, s->internal->packet_length); 516 517 /* Pull apart the header into the DTLS1_RECORD */ 518 if (!CBS_get_u8(&header, &type)) 519 goto again; 520 if (!CBS_get_u16(&header, &ssl_version)) 521 goto again; 522 523 /* sequence number is 64 bits, with top 2 bytes = epoch */ 524 if (!CBS_get_u16(&header, &epoch) || 525 !CBS_get_bytes(&header, &seq_no, 6)) 526 goto again; 527 528 if (!CBS_write_bytes(&seq_no, &(S3I(s)->read_sequence[2]), 529 sizeof(S3I(s)->read_sequence) - 2, NULL)) 530 goto again; 531 if (!CBS_get_u16(&header, &len)) 532 goto again; 533 534 rr->type = type; 535 rr->epoch = epoch; 536 rr->length = len; 537 538 /* unexpected version, silently discard */ 539 if (!s->internal->first_packet && ssl_version != s->version) 540 goto again; 541 542 /* wrong version, silently discard record */ 543 if ((ssl_version & 0xff00) != (s->version & 0xff00)) 544 goto again; 545 546 /* record too long, silently discard it */ 547 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) 548 goto again; 549 550 /* now s->internal->rstate == SSL_ST_READ_BODY */ 551 p = (unsigned char *)CBS_data(&header); 552 } 553 554 /* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */ 555 556 if (rr->length > s->internal->packet_length - DTLS1_RT_HEADER_LENGTH) { 557 /* now s->internal->packet_length == DTLS1_RT_HEADER_LENGTH */ 558 i = rr->length; 559 n = ssl3_read_n(s, i, i, 1); 560 if (n <= 0) 561 return(n); /* error or non-blocking io */ 562 563 /* this packet contained a partial record, dump it */ 564 if (n != i) 565 goto again; 566 567 /* now n == rr->length, 568 * and s->internal->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */ 569 } 570 s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */ 571 572 /* match epochs. NULL means the packet is dropped on the floor */ 573 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); 574 if (bitmap == NULL) 575 goto again; 576 577 /* 578 * Check whether this is a repeat, or aged record. 579 * Don't check if we're listening and this message is 580 * a ClientHello. They can look as if they're replayed, 581 * since they arrive from different connections and 582 * would be dropped unnecessarily. 583 */ 584 if (!(D1I(s)->listen && rr->type == SSL3_RT_HANDSHAKE && 585 p != NULL && *p == SSL3_MT_CLIENT_HELLO) && 586 !dtls1_record_replay_check(s, bitmap)) 587 goto again; 588 589 /* just read a 0 length packet */ 590 if (rr->length == 0) 591 goto again; 592 593 /* If this record is from the next epoch (either HM or ALERT), 594 * and a handshake is currently in progress, buffer it since it 595 * cannot be processed at this time. However, do not buffer 596 * anything while listening. 597 */ 598 if (is_next_epoch) { 599 if ((SSL_in_init(s) || s->internal->in_handshake) && !D1I(s)->listen) { 600 if (dtls1_buffer_record(s, &(D1I(s)->unprocessed_rcds), 601 rr->seq_num) < 0) 602 return (-1); 603 /* Mark receipt of record. */ 604 dtls1_record_bitmap_update(s, bitmap); 605 } 606 goto again; 607 } 608 609 if (!dtls1_process_record(s)) 610 goto again; 611 612 /* Mark receipt of record. */ 613 dtls1_record_bitmap_update(s, bitmap); 614 615 return (1); 616 } 617 618 /* Return up to 'len' payload bytes received in 'type' records. 619 * 'type' is one of the following: 620 * 621 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us) 622 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us) 623 * - 0 (during a shutdown, no data has to be returned) 624 * 625 * If we don't have stored data to work from, read a SSL/TLS record first 626 * (possibly multiple records if we still don't have anything to return). 627 * 628 * This function must handle any surprises the peer may have for us, such as 629 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really 630 * a surprise, but handled as if it were), or renegotiation requests. 631 * Also if record payloads contain fragments too small to process, we store 632 * them until there is enough for the respective protocol (the record protocol 633 * may use arbitrary fragmentation and even interleaving): 634 * Change cipher spec protocol 635 * just 1 byte needed, no need for keeping anything stored 636 * Alert protocol 637 * 2 bytes needed (AlertLevel, AlertDescription) 638 * Handshake protocol 639 * 4 bytes needed (HandshakeType, uint24 length) -- we just have 640 * to detect unexpected Client Hello and Hello Request messages 641 * here, anything else is handled by higher layers 642 * Application data protocol 643 * none of our business 644 */ 645 int 646 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) 647 { 648 int al, i, j, ret; 649 unsigned int n; 650 SSL3_RECORD *rr; 651 void (*cb)(const SSL *ssl, int type2, int val) = NULL; 652 653 if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ 654 if (!ssl3_setup_buffers(s)) 655 return (-1); 656 657 if ((type && 658 type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) || 659 (peek && (type != SSL3_RT_APPLICATION_DATA))) { 660 SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); 661 return -1; 662 } 663 664 /* check whether there's a handshake message (client hello?) waiting */ 665 if ((ret = have_handshake_fragment(s, type, buf, len, peek))) 666 return ret; 667 668 /* Now D1I(s)->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ 669 670 if (!s->internal->in_handshake && SSL_in_init(s)) 671 { 672 /* type == SSL3_RT_APPLICATION_DATA */ 673 i = s->internal->handshake_func(s); 674 if (i < 0) 675 return (i); 676 if (i == 0) { 677 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); 678 return (-1); 679 } 680 } 681 682 start: 683 s->internal->rwstate = SSL_NOTHING; 684 685 /* S3I(s)->rrec.type - is the type of record 686 * S3I(s)->rrec.data, - data 687 * S3I(s)->rrec.off, - offset into 'data' for next read 688 * S3I(s)->rrec.length, - number of bytes. */ 689 rr = &(S3I(s)->rrec); 690 691 /* We are not handshaking and have no data yet, 692 * so process data buffered during the last handshake 693 * in advance, if any. 694 */ 695 if (s->internal->state == SSL_ST_OK && rr->length == 0) { 696 pitem *item; 697 item = pqueue_pop(D1I(s)->buffered_app_data.q); 698 if (item) { 699 700 dtls1_copy_record(s, item); 701 702 free(item->data); 703 pitem_free(item); 704 } 705 } 706 707 /* Check for timeout */ 708 if (dtls1_handle_timeout(s) > 0) 709 goto start; 710 711 /* get new packet if necessary */ 712 if ((rr->length == 0) || (s->internal->rstate == SSL_ST_READ_BODY)) { 713 ret = dtls1_get_record(s); 714 if (ret <= 0) { 715 ret = dtls1_read_failed(s, ret); 716 /* anything other than a timeout is an error */ 717 if (ret <= 0) 718 return (ret); 719 else 720 goto start; 721 } 722 } 723 724 if (D1I(s)->listen && rr->type != SSL3_RT_HANDSHAKE) { 725 rr->length = 0; 726 goto start; 727 } 728 729 /* we now have a packet which can be read and processed */ 730 731 if (S3I(s)->change_cipher_spec /* set when we receive ChangeCipherSpec, 732 * reset by ssl3_get_finished */ 733 && (rr->type != SSL3_RT_HANDSHAKE)) { 734 /* We now have application data between CCS and Finished. 735 * Most likely the packets were reordered on their way, so 736 * buffer the application data for later processing rather 737 * than dropping the connection. 738 */ 739 if (dtls1_buffer_record(s, &(D1I(s)->buffered_app_data), 740 rr->seq_num) < 0) { 741 SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); 742 return (-1); 743 } 744 rr->length = 0; 745 goto start; 746 } 747 748 /* If the other end has shut down, throw anything we read away 749 * (even in 'peek' mode) */ 750 if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) { 751 rr->length = 0; 752 s->internal->rwstate = SSL_NOTHING; 753 return (0); 754 } 755 756 757 if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */ 758 { 759 /* make sure that we are not getting application data when we 760 * are doing a handshake for the first time */ 761 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && 762 (s->enc_read_ctx == NULL)) { 763 al = SSL_AD_UNEXPECTED_MESSAGE; 764 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); 765 goto f_err; 766 } 767 768 if (len <= 0) 769 return (len); 770 771 if ((unsigned int)len > rr->length) 772 n = rr->length; 773 else 774 n = (unsigned int)len; 775 776 memcpy(buf, &(rr->data[rr->off]), n); 777 if (!peek) { 778 rr->length -= n; 779 rr->off += n; 780 if (rr->length == 0) { 781 s->internal->rstate = SSL_ST_READ_HEADER; 782 rr->off = 0; 783 } 784 } 785 786 return (n); 787 } 788 789 790 /* If we get here, then type != rr->type; if we have a handshake 791 * message, then it was unexpected (Hello Request or Client Hello). */ 792 793 /* In case of record types for which we have 'fragment' storage, 794 * fill that so that we can process the data at a fixed place. 795 */ 796 { 797 unsigned int k, dest_maxlen = 0; 798 unsigned char *dest = NULL; 799 unsigned int *dest_len = NULL; 800 801 if (rr->type == SSL3_RT_HANDSHAKE) { 802 dest_maxlen = sizeof D1I(s)->handshake_fragment; 803 dest = D1I(s)->handshake_fragment; 804 dest_len = &D1I(s)->handshake_fragment_len; 805 } else if (rr->type == SSL3_RT_ALERT) { 806 dest_maxlen = sizeof(D1I(s)->alert_fragment); 807 dest = D1I(s)->alert_fragment; 808 dest_len = &D1I(s)->alert_fragment_len; 809 } 810 /* else it's a CCS message, or application data or wrong */ 811 else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) { 812 /* Application data while renegotiating 813 * is allowed. Try again reading. 814 */ 815 if (rr->type == SSL3_RT_APPLICATION_DATA) { 816 BIO *bio; 817 S3I(s)->in_read_app_data = 2; 818 bio = SSL_get_rbio(s); 819 s->internal->rwstate = SSL_READING; 820 BIO_clear_retry_flags(bio); 821 BIO_set_retry_read(bio); 822 return (-1); 823 } 824 825 /* Not certain if this is the right error handling */ 826 al = SSL_AD_UNEXPECTED_MESSAGE; 827 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); 828 goto f_err; 829 } 830 831 if (dest_maxlen > 0) { 832 /* XDTLS: In a pathalogical case, the Client Hello 833 * may be fragmented--don't always expect dest_maxlen bytes */ 834 if (rr->length < dest_maxlen) { 835 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE 836 /* 837 * for normal alerts rr->length is 2, while 838 * dest_maxlen is 7 if we were to handle this 839 * non-existing alert... 840 */ 841 FIX ME 842 #endif 843 s->internal->rstate = SSL_ST_READ_HEADER; 844 rr->length = 0; 845 goto start; 846 } 847 848 /* now move 'n' bytes: */ 849 for ( k = 0; k < dest_maxlen; k++) { 850 dest[k] = rr->data[rr->off++]; 851 rr->length--; 852 } 853 *dest_len = dest_maxlen; 854 } 855 } 856 857 /* D1I(s)->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; 858 * D1I(s)->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. 859 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ 860 861 /* If we are a client, check for an incoming 'Hello Request': */ 862 if ((!s->server) && 863 (D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && 864 (D1I(s)->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && 865 (s->session != NULL) && (s->session->cipher != NULL)) { 866 D1I(s)->handshake_fragment_len = 0; 867 868 if ((D1I(s)->handshake_fragment[1] != 0) || 869 (D1I(s)->handshake_fragment[2] != 0) || 870 (D1I(s)->handshake_fragment[3] != 0)) { 871 al = SSL_AD_DECODE_ERROR; 872 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST); 873 goto err; 874 } 875 876 /* no need to check sequence number on HELLO REQUEST messages */ 877 878 if (s->internal->msg_callback) 879 s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, 880 D1I(s)->handshake_fragment, 4, s, s->internal->msg_callback_arg); 881 882 if (SSL_is_init_finished(s) && 883 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && 884 !S3I(s)->renegotiate) { 885 D1I(s)->handshake_read_seq++; 886 s->internal->new_session = 1; 887 ssl3_renegotiate(s); 888 if (ssl3_renegotiate_check(s)) { 889 i = s->internal->handshake_func(s); 890 if (i < 0) 891 return (i); 892 if (i == 0) { 893 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); 894 return (-1); 895 } 896 897 if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) { 898 if (s->s3->rbuf.left == 0) /* no read-ahead left? */ 899 { 900 BIO *bio; 901 /* In the case where we try to read application data, 902 * but we trigger an SSL handshake, we return -1 with 903 * the retry option set. Otherwise renegotiation may 904 * cause nasty problems in the blocking world */ 905 s->internal->rwstate = SSL_READING; 906 bio = SSL_get_rbio(s); 907 BIO_clear_retry_flags(bio); 908 BIO_set_retry_read(bio); 909 return (-1); 910 } 911 } 912 } 913 } 914 /* we either finished a handshake or ignored the request, 915 * now try again to obtain the (application) data we were asked for */ 916 goto start; 917 } 918 919 if (D1I(s)->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { 920 int alert_level = D1I(s)->alert_fragment[0]; 921 int alert_descr = D1I(s)->alert_fragment[1]; 922 923 D1I(s)->alert_fragment_len = 0; 924 925 if (s->internal->msg_callback) 926 s->internal->msg_callback(0, s->version, SSL3_RT_ALERT, 927 D1I(s)->alert_fragment, 2, s, s->internal->msg_callback_arg); 928 929 if (s->internal->info_callback != NULL) 930 cb = s->internal->info_callback; 931 else if (s->ctx->internal->info_callback != NULL) 932 cb = s->ctx->internal->info_callback; 933 934 if (cb != NULL) { 935 j = (alert_level << 8) | alert_descr; 936 cb(s, SSL_CB_READ_ALERT, j); 937 } 938 939 if (alert_level == 1) /* warning */ 940 { 941 S3I(s)->warn_alert = alert_descr; 942 if (alert_descr == SSL_AD_CLOSE_NOTIFY) { 943 s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN; 944 return (0); 945 } 946 } else if (alert_level == 2) /* fatal */ 947 { 948 s->internal->rwstate = SSL_NOTHING; 949 S3I(s)->fatal_alert = alert_descr; 950 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); 951 ERR_asprintf_error_data("SSL alert number %d", 952 alert_descr); 953 s->internal->shutdown|=SSL_RECEIVED_SHUTDOWN; 954 SSL_CTX_remove_session(s->ctx, s->session); 955 return (0); 956 } else { 957 al = SSL_AD_ILLEGAL_PARAMETER; 958 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE); 959 goto f_err; 960 } 961 962 goto start; 963 } 964 965 if (s->internal->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */ 966 { 967 s->internal->rwstate = SSL_NOTHING; 968 rr->length = 0; 969 return (0); 970 } 971 972 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { 973 struct ccs_header_st ccs_hdr; 974 unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH; 975 976 dtls1_get_ccs_header(rr->data, &ccs_hdr); 977 978 /* 'Change Cipher Spec' is just a single byte, so we know 979 * exactly what the record payload has to look like */ 980 /* XDTLS: check that epoch is consistent */ 981 if ((rr->length != ccs_hdr_len) || 982 (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { 983 i = SSL_AD_ILLEGAL_PARAMETER; 984 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC); 985 goto err; 986 } 987 988 rr->length = 0; 989 990 if (s->internal->msg_callback) 991 s->internal->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, 992 rr->data, 1, s, s->internal->msg_callback_arg); 993 994 /* We can't process a CCS now, because previous handshake 995 * messages are still missing, so just drop it. 996 */ 997 if (!D1I(s)->change_cipher_spec_ok) { 998 goto start; 999 } 1000 1001 D1I(s)->change_cipher_spec_ok = 0; 1002 1003 S3I(s)->change_cipher_spec = 1; 1004 if (!ssl3_do_change_cipher_spec(s)) 1005 goto err; 1006 1007 /* do this whenever CCS is processed */ 1008 dtls1_reset_seq_numbers(s, SSL3_CC_READ); 1009 1010 goto start; 1011 } 1012 1013 /* Unexpected handshake message (Client Hello, or protocol violation) */ 1014 if ((D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && 1015 !s->internal->in_handshake) { 1016 struct hm_header_st msg_hdr; 1017 1018 /* this may just be a stale retransmit */ 1019 if (!dtls1_get_message_header(rr->data, &msg_hdr)) 1020 return -1; 1021 if (rr->epoch != D1I(s)->r_epoch) { 1022 rr->length = 0; 1023 goto start; 1024 } 1025 1026 /* If we are server, we may have a repeated FINISHED of the 1027 * client here, then retransmit our CCS and FINISHED. 1028 */ 1029 if (msg_hdr.type == SSL3_MT_FINISHED) { 1030 if (dtls1_check_timeout_num(s) < 0) 1031 return -1; 1032 1033 dtls1_retransmit_buffered_messages(s); 1034 rr->length = 0; 1035 goto start; 1036 } 1037 1038 if (((s->internal->state&SSL_ST_MASK) == SSL_ST_OK) && 1039 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { 1040 s->internal->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; 1041 s->internal->renegotiate = 1; 1042 s->internal->new_session = 1; 1043 } 1044 i = s->internal->handshake_func(s); 1045 if (i < 0) 1046 return (i); 1047 if (i == 0) { 1048 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); 1049 return (-1); 1050 } 1051 1052 if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) { 1053 if (s->s3->rbuf.left == 0) /* no read-ahead left? */ 1054 { 1055 BIO *bio; 1056 /* In the case where we try to read application data, 1057 * but we trigger an SSL handshake, we return -1 with 1058 * the retry option set. Otherwise renegotiation may 1059 * cause nasty problems in the blocking world */ 1060 s->internal->rwstate = SSL_READING; 1061 bio = SSL_get_rbio(s); 1062 BIO_clear_retry_flags(bio); 1063 BIO_set_retry_read(bio); 1064 return (-1); 1065 } 1066 } 1067 goto start; 1068 } 1069 1070 switch (rr->type) { 1071 default: 1072 /* TLS just ignores unknown message types */ 1073 if (s->version == TLS1_VERSION) { 1074 rr->length = 0; 1075 goto start; 1076 } 1077 al = SSL_AD_UNEXPECTED_MESSAGE; 1078 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); 1079 goto f_err; 1080 case SSL3_RT_CHANGE_CIPHER_SPEC: 1081 case SSL3_RT_ALERT: 1082 case SSL3_RT_HANDSHAKE: 1083 /* we already handled all of these, with the possible exception 1084 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that 1085 * should not happen when type != rr->type */ 1086 al = SSL_AD_UNEXPECTED_MESSAGE; 1087 SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); 1088 goto f_err; 1089 case SSL3_RT_APPLICATION_DATA: 1090 /* At this point, we were expecting handshake data, 1091 * but have application data. If the library was 1092 * running inside ssl3_read() (i.e. in_read_app_data 1093 * is set) and it makes sense to read application data 1094 * at this point (session renegotiation not yet started), 1095 * we will indulge it. 1096 */ 1097 if (S3I(s)->in_read_app_data && 1098 (S3I(s)->total_renegotiations != 0) && 1099 (((s->internal->state & SSL_ST_CONNECT) && 1100 (s->internal->state >= SSL3_ST_CW_CLNT_HELLO_A) && 1101 (s->internal->state <= SSL3_ST_CR_SRVR_HELLO_A)) || ( 1102 (s->internal->state & SSL_ST_ACCEPT) && 1103 (s->internal->state <= SSL3_ST_SW_HELLO_REQ_A) && 1104 (s->internal->state >= SSL3_ST_SR_CLNT_HELLO_A)))) { 1105 S3I(s)->in_read_app_data = 2; 1106 return (-1); 1107 } else { 1108 al = SSL_AD_UNEXPECTED_MESSAGE; 1109 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); 1110 goto f_err; 1111 } 1112 } 1113 /* not reached */ 1114 1115 f_err: 1116 ssl3_send_alert(s, SSL3_AL_FATAL, al); 1117 err: 1118 return (-1); 1119 } 1120 1121 int 1122 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len) 1123 { 1124 int i; 1125 1126 if (SSL_in_init(s) && !s->internal->in_handshake) 1127 { 1128 i = s->internal->handshake_func(s); 1129 if (i < 0) 1130 return (i); 1131 if (i == 0) { 1132 SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); 1133 return -1; 1134 } 1135 } 1136 1137 if (len > SSL3_RT_MAX_PLAIN_LENGTH) { 1138 SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES, SSL_R_DTLS_MESSAGE_TOO_BIG); 1139 return -1; 1140 } 1141 1142 i = dtls1_write_bytes(s, type, buf_, len); 1143 return i; 1144 } 1145 1146 1147 /* this only happens when a client hello is received and a handshake 1148 * is started. */ 1149 static int 1150 have_handshake_fragment(SSL *s, int type, unsigned char *buf, 1151 int len, int peek) 1152 { 1153 1154 if ((type == SSL3_RT_HANDSHAKE) && (D1I(s)->handshake_fragment_len > 0)) 1155 /* (partially) satisfy request from storage */ 1156 { 1157 unsigned char *src = D1I(s)->handshake_fragment; 1158 unsigned char *dst = buf; 1159 unsigned int k, n; 1160 1161 /* peek == 0 */ 1162 n = 0; 1163 while ((len > 0) && (D1I(s)->handshake_fragment_len > 0)) { 1164 *dst++ = *src++; 1165 len--; 1166 D1I(s)->handshake_fragment_len--; 1167 n++; 1168 } 1169 /* move any remaining fragment bytes: */ 1170 for (k = 0; k < D1I(s)->handshake_fragment_len; k++) 1171 D1I(s)->handshake_fragment[k] = *src++; 1172 return n; 1173 } 1174 1175 return 0; 1176 } 1177 1178 1179 /* Call this to write data in records of type 'type' 1180 * It will return <= 0 if not all data has been sent or non-blocking IO. 1181 */ 1182 int 1183 dtls1_write_bytes(SSL *s, int type, const void *buf, int len) 1184 { 1185 int i; 1186 1187 OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH); 1188 s->internal->rwstate = SSL_NOTHING; 1189 i = do_dtls1_write(s, type, buf, len); 1190 return i; 1191 } 1192 1193 int 1194 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len) 1195 { 1196 unsigned char *p, *pseq; 1197 int i, mac_size, clear = 0; 1198 int prefix_len = 0; 1199 SSL3_RECORD *wr; 1200 SSL3_BUFFER *wb; 1201 SSL_SESSION *sess; 1202 int bs; 1203 1204 /* first check if there is a SSL3_BUFFER still being written 1205 * out. This will happen with non blocking IO */ 1206 if (s->s3->wbuf.left != 0) { 1207 OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */ 1208 return (ssl3_write_pending(s, type, buf, len)); 1209 } 1210 1211 /* If we have an alert to send, lets send it */ 1212 if (s->s3->alert_dispatch) { 1213 i = s->method->ssl_dispatch_alert(s); 1214 if (i <= 0) 1215 return (i); 1216 /* if it went, fall through and send more stuff */ 1217 } 1218 1219 if (len == 0) 1220 return 0; 1221 1222 wr = &(S3I(s)->wrec); 1223 wb = &(s->s3->wbuf); 1224 sess = s->session; 1225 1226 if ((sess == NULL) || (s->internal->enc_write_ctx == NULL) || 1227 (EVP_MD_CTX_md(s->internal->write_hash) == NULL)) 1228 clear = 1; 1229 1230 if (clear) 1231 mac_size = 0; 1232 else { 1233 mac_size = EVP_MD_CTX_size(s->internal->write_hash); 1234 if (mac_size < 0) 1235 goto err; 1236 } 1237 1238 /* DTLS implements explicit IV, so no need for empty fragments. */ 1239 1240 p = wb->buf + prefix_len; 1241 1242 /* write the header */ 1243 1244 *(p++) = type&0xff; 1245 wr->type = type; 1246 1247 *(p++) = (s->version >> 8); 1248 *(p++) = s->version&0xff; 1249 1250 /* field where we are to write out packet epoch, seq num and len */ 1251 pseq = p; 1252 1253 p += 10; 1254 1255 /* lets setup the record stuff. */ 1256 1257 /* Make space for the explicit IV in case of CBC. 1258 * (this is a bit of a boundary violation, but what the heck). 1259 */ 1260 if (s->internal->enc_write_ctx && 1261 (EVP_CIPHER_mode(s->internal->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE)) 1262 bs = EVP_CIPHER_block_size(s->internal->enc_write_ctx->cipher); 1263 else 1264 bs = 0; 1265 1266 wr->data = p + bs; 1267 /* make room for IV in case of CBC */ 1268 wr->length = (int)len; 1269 wr->input = (unsigned char *)buf; 1270 1271 /* we now 'read' from wr->input, wr->length bytes into 1272 * wr->data */ 1273 1274 memcpy(wr->data, wr->input, wr->length); 1275 wr->input = wr->data; 1276 1277 /* we should still have the output to wr->data and the input 1278 * from wr->input. Length should be wr->length. 1279 * wr->data still points in the wb->buf */ 1280 1281 if (mac_size != 0) { 1282 if (s->method->internal->ssl3_enc->mac(s, &(p[wr->length + bs]), 1) < 0) 1283 goto err; 1284 wr->length += mac_size; 1285 } 1286 1287 /* this is true regardless of mac size */ 1288 wr->input = p; 1289 wr->data = p; 1290 1291 1292 /* ssl3_enc can only have an error on read */ 1293 if (bs) /* bs != 0 in case of CBC */ 1294 { 1295 arc4random_buf(p, bs); 1296 /* master IV and last CBC residue stand for 1297 * the rest of randomness */ 1298 wr->length += bs; 1299 } 1300 1301 s->method->internal->ssl3_enc->enc(s, 1); 1302 1303 /* record length after mac and block padding */ 1304 /* if (type == SSL3_RT_APPLICATION_DATA || 1305 (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */ 1306 1307 /* there's only one epoch between handshake and app data */ 1308 1309 s2n(D1I(s)->w_epoch, pseq); 1310 1311 /* XDTLS: ?? */ 1312 /* else 1313 s2n(D1I(s)->handshake_epoch, pseq); 1314 */ 1315 1316 memcpy(pseq, &(S3I(s)->write_sequence[2]), 6); 1317 pseq += 6; 1318 s2n(wr->length, pseq); 1319 1320 /* we should now have 1321 * wr->data pointing to the encrypted data, which is 1322 * wr->length long */ 1323 wr->type=type; /* not needed but helps for debugging */ 1324 wr->length += DTLS1_RT_HEADER_LENGTH; 1325 1326 tls1_record_sequence_increment(S3I(s)->write_sequence); 1327 1328 /* now let's set up wb */ 1329 wb->left = prefix_len + wr->length; 1330 wb->offset = 0; 1331 1332 /* memorize arguments so that ssl3_write_pending can detect bad write retries later */ 1333 S3I(s)->wpend_tot = len; 1334 S3I(s)->wpend_buf = buf; 1335 S3I(s)->wpend_type = type; 1336 S3I(s)->wpend_ret = len; 1337 1338 /* we now just need to write the buffer */ 1339 return ssl3_write_pending(s, type, buf, len); 1340 err: 1341 return -1; 1342 } 1343 1344 1345 1346 static int 1347 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) 1348 { 1349 int cmp; 1350 unsigned int shift; 1351 const unsigned char *seq = S3I(s)->read_sequence; 1352 1353 cmp = satsub64be(seq, bitmap->max_seq_num); 1354 if (cmp > 0) { 1355 memcpy (S3I(s)->rrec.seq_num, seq, 8); 1356 return 1; /* this record in new */ 1357 } 1358 shift = -cmp; 1359 if (shift >= sizeof(bitmap->map)*8) 1360 return 0; /* stale, outside the window */ 1361 else if (bitmap->map & (1UL << shift)) 1362 return 0; /* record previously received */ 1363 1364 memcpy(S3I(s)->rrec.seq_num, seq, 8); 1365 return 1; 1366 } 1367 1368 1369 static void 1370 dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) 1371 { 1372 int cmp; 1373 unsigned int shift; 1374 const unsigned char *seq = S3I(s)->read_sequence; 1375 1376 cmp = satsub64be(seq, bitmap->max_seq_num); 1377 if (cmp > 0) { 1378 shift = cmp; 1379 if (shift < sizeof(bitmap->map)*8) 1380 bitmap->map <<= shift, bitmap->map |= 1UL; 1381 else 1382 bitmap->map = 1UL; 1383 memcpy(bitmap->max_seq_num, seq, 8); 1384 } else { 1385 shift = -cmp; 1386 if (shift < sizeof(bitmap->map) * 8) 1387 bitmap->map |= 1UL << shift; 1388 } 1389 } 1390 1391 1392 int 1393 dtls1_dispatch_alert(SSL *s) 1394 { 1395 int i, j; 1396 void (*cb)(const SSL *ssl, int type, int val) = NULL; 1397 unsigned char buf[DTLS1_AL_HEADER_LENGTH]; 1398 unsigned char *ptr = &buf[0]; 1399 1400 s->s3->alert_dispatch = 0; 1401 1402 memset(buf, 0x00, sizeof(buf)); 1403 *ptr++ = s->s3->send_alert[0]; 1404 *ptr++ = s->s3->send_alert[1]; 1405 1406 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE 1407 if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { 1408 s2n(D1I(s)->handshake_read_seq, ptr); 1409 l2n3(D1I(s)->r_msg_hdr.frag_off, ptr); 1410 } 1411 #endif 1412 1413 i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf)); 1414 if (i <= 0) { 1415 s->s3->alert_dispatch = 1; 1416 /* fprintf( stderr, "not done with alert\n" ); */ 1417 } else { 1418 if (s->s3->send_alert[0] == SSL3_AL_FATAL 1419 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE 1420 || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE 1421 #endif 1422 ) 1423 (void)BIO_flush(s->wbio); 1424 1425 if (s->internal->msg_callback) 1426 s->internal->msg_callback(1, s->version, SSL3_RT_ALERT, 1427 s->s3->send_alert, 2, s, s->internal->msg_callback_arg); 1428 1429 if (s->internal->info_callback != NULL) 1430 cb = s->internal->info_callback; 1431 else if (s->ctx->internal->info_callback != NULL) 1432 cb = s->ctx->internal->info_callback; 1433 1434 if (cb != NULL) { 1435 j = (s->s3->send_alert[0]<<8)|s->s3->send_alert[1]; 1436 cb(s, SSL_CB_WRITE_ALERT, j); 1437 } 1438 } 1439 return (i); 1440 } 1441 1442 1443 static DTLS1_BITMAP * 1444 dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch) 1445 { 1446 1447 *is_next_epoch = 0; 1448 1449 /* In current epoch, accept HM, CCS, DATA, & ALERT */ 1450 if (rr->epoch == D1I(s)->r_epoch) 1451 return &D1I(s)->bitmap; 1452 1453 /* Only HM and ALERT messages can be from the next epoch */ 1454 else if (rr->epoch == (unsigned long)(D1I(s)->r_epoch + 1) && 1455 (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) { 1456 *is_next_epoch = 1; 1457 return &D1I(s)->next_bitmap; 1458 } 1459 1460 return NULL; 1461 } 1462 1463 void 1464 dtls1_reset_seq_numbers(SSL *s, int rw) 1465 { 1466 unsigned char *seq; 1467 unsigned int seq_bytes = sizeof(S3I(s)->read_sequence); 1468 1469 if (rw & SSL3_CC_READ) { 1470 seq = S3I(s)->read_sequence; 1471 D1I(s)->r_epoch++; 1472 memcpy(&(D1I(s)->bitmap), &(D1I(s)->next_bitmap), sizeof(DTLS1_BITMAP)); 1473 memset(&(D1I(s)->next_bitmap), 0x00, sizeof(DTLS1_BITMAP)); 1474 } else { 1475 seq = S3I(s)->write_sequence; 1476 memcpy(D1I(s)->last_write_sequence, seq, sizeof(S3I(s)->write_sequence)); 1477 D1I(s)->w_epoch++; 1478 } 1479 1480 memset(seq, 0x00, seq_bytes); 1481 } 1482