tzdata: update to 2018g
[unleashed.git] / lib / libssl / d1_pkt.c
blobb3104d21e7dcc5770325372eb342a17e60e4afee
1 /* $OpenBSD: d1_pkt.c,v 1.64 2018/08/24 19:35:05 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.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
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.
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/)"
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.
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.
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/)"
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 * ====================================================================
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).
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60 * All rights reserved.
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.
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).
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.
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)"
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.
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.]
116 #include <machine/endian.h>
118 #include <errno.h>
119 #include <stdio.h>
121 #include "ssl_locl.h"
123 #include <openssl/buffer.h>
124 #include <openssl/evp.h>
126 #include "pqueue.h"
127 #include "bytestring.h"
129 static int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
130 unsigned int len);
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)
137 int ret, sat, brw, i;
139 if (sizeof(long) == 8)
140 do {
141 long l;
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;
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);
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;
170 } else {
171 for (i = 6; i >= 0; i--) {
172 brw += (int)v1[i]-(int)v2[i];
173 sat |= brw;
174 brw >>= 8;
177 brw <<= 8; /* brw is either 0 or -256 */
179 if (sat & 0xff)
180 return brw | 0x80;
181 else
182 return brw + (ret & 0xFF);
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);
195 /* copy buffered record into SSL structure */
196 static int
197 dtls1_copy_record(SSL *s, pitem *item)
199 DTLS1_RECORD_DATA *rdata;
201 rdata = (DTLS1_RECORD_DATA *)item->data;
203 free(s->s3->rbuf.buf);
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));
210 /* Set proper sequence number for mac calculation */
211 memcpy(&(S3I(s)->read_sequence[2]), &(rdata->packet[5]), 6);
213 return (1);
217 static int
218 dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
220 DTLS1_RECORD_DATA *rdata;
221 pitem *item;
223 /* Limit the size of the queue to prevent DOS attacks */
224 if (pqueue_size(queue->q) >= 100)
225 return 0;
227 rdata = malloc(sizeof(DTLS1_RECORD_DATA));
228 item = pitem_new(priority, rdata);
229 if (rdata == NULL || item == NULL)
230 goto init_err;
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));
237 item->data = rdata;
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));
245 if (!ssl3_setup_buffers(s))
246 goto err;
248 /* insert should not fail, since duplicates are dropped */
249 if (pqueue_insert(queue->q, item) == NULL)
250 goto err;
252 return (1);
254 err:
255 free(rdata->rbuf.buf);
257 init_err:
258 SSLerror(s, ERR_R_INTERNAL_ERROR);
259 free(rdata);
260 pitem_free(item);
261 return (-1);
265 static int
266 dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
268 pitem *item;
270 item = pqueue_pop(queue->q);
271 if (item) {
272 dtls1_copy_record(s, item);
274 free(item->data);
275 pitem_free(item);
277 return (1);
280 return (0);
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))
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))
295 static int
296 dtls1_process_buffered_records(SSL *s)
298 pitem *item;
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. */
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);
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;
323 return (1);
326 static int
327 dtls1_process_record(SSL *s)
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];
336 rr = &(S3I(s)->rrec);
337 sess = s->session;
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
342 rr->input = &(s->internal->packet[DTLS1_RT_HEADER_LENGTH]);
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 */
351 /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
352 * rr->length bytes of encrypted compressed stuff. */
354 /* check is not needed I believe */
355 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
356 al = SSL_AD_RECORD_OVERFLOW;
357 SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
358 goto f_err;
361 /* decrypt in place in 'rr->input' */
362 rr->data = rr->input;
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;
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);
386 /* kludge: *_cbc_remove_padding passes padding length in rr->type */
387 orig_len = rr->length + ((unsigned int)rr->type >> 8);
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.
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 SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
400 goto f_err;
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];
420 i = tls1_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;
427 if (enc_err < 0) {
428 /* decryption failed, silently discard message */
429 rr->length = 0;
430 s->internal->packet_length = 0;
431 goto err;
434 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
435 al = SSL_AD_RECORD_OVERFLOW;
436 SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
437 goto f_err;
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 :-).
449 /* we have pulled in a full packet so zero things */
450 s->internal->packet_length = 0;
451 return (1);
453 f_err:
454 ssl3_send_alert(s, SSL3_AL_FATAL, al);
455 err:
456 return (0);
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
468 /* used only by dtls1_read_bytes */
470 dtls1_get_record(SSL *s)
472 SSL3_RECORD *rr;
473 unsigned char *p = NULL;
474 DTLS1_BITMAP *bitmap;
475 unsigned int is_next_epoch;
476 int n;
478 rr = &(S3I(s)->rrec);
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);
485 /* if we're renegotiating, then there may be buffered records */
486 if (dtls1_get_processed_record(s))
487 return 1;
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;
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;
504 n = ssl3_packet_read(s, DTLS1_RT_HEADER_LENGTH);
505 if (n <= 0)
506 return (n);
508 /* If this packet contained a partial record, dump it. */
509 if (n != DTLS1_RT_HEADER_LENGTH)
510 goto again;
512 s->internal->rstate = SSL_ST_READ_BODY;
514 CBS_init(&header, s->internal->packet, s->internal->packet_length);
516 /* Pull apart the header into the DTLS1_RECORD */
517 if (!CBS_get_u8(&header, &type))
518 goto again;
519 if (!CBS_get_u16(&header, &ssl_version))
520 goto again;
522 /* sequence number is 64 bits, with top 2 bytes = epoch */
523 if (!CBS_get_u16(&header, &epoch) ||
524 !CBS_get_bytes(&header, &seq_no, 6))
525 goto again;
527 if (!CBS_write_bytes(&seq_no, &(S3I(s)->read_sequence[2]),
528 sizeof(S3I(s)->read_sequence) - 2, NULL))
529 goto again;
530 if (!CBS_get_u16(&header, &len))
531 goto again;
533 rr->type = type;
534 rr->epoch = epoch;
535 rr->length = len;
537 /* unexpected version, silently discard */
538 if (!s->internal->first_packet && ssl_version != s->version)
539 goto again;
541 /* wrong version, silently discard record */
542 if ((ssl_version & 0xff00) != (s->version & 0xff00))
543 goto again;
545 /* record too long, silently discard it */
546 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
547 goto again;
549 /* now s->internal->rstate == SSL_ST_READ_BODY */
550 p = (unsigned char *)CBS_data(&header);
553 /* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */
555 n = ssl3_packet_extend(s, DTLS1_RT_HEADER_LENGTH + rr->length);
556 if (n <= 0)
557 return (n);
559 /* If this packet contained a partial record, dump it. */
560 if (n != DTLS1_RT_HEADER_LENGTH + rr->length)
561 goto again;
563 s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
565 /* match epochs. NULL means the packet is dropped on the floor */
566 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
567 if (bitmap == NULL)
568 goto again;
571 * Check whether this is a repeat, or aged record.
572 * Don't check if we're listening and this message is
573 * a ClientHello. They can look as if they're replayed,
574 * since they arrive from different connections and
575 * would be dropped unnecessarily.
577 if (!(D1I(s)->listen && rr->type == SSL3_RT_HANDSHAKE &&
578 p != NULL && *p == SSL3_MT_CLIENT_HELLO) &&
579 !dtls1_record_replay_check(s, bitmap))
580 goto again;
582 /* just read a 0 length packet */
583 if (rr->length == 0)
584 goto again;
586 /* If this record is from the next epoch (either HM or ALERT),
587 * and a handshake is currently in progress, buffer it since it
588 * cannot be processed at this time. However, do not buffer
589 * anything while listening.
591 if (is_next_epoch) {
592 if ((SSL_in_init(s) || s->internal->in_handshake) && !D1I(s)->listen) {
593 if (dtls1_buffer_record(s, &(D1I(s)->unprocessed_rcds),
594 rr->seq_num) < 0)
595 return (-1);
596 /* Mark receipt of record. */
597 dtls1_record_bitmap_update(s, bitmap);
599 goto again;
602 if (!dtls1_process_record(s))
603 goto again;
605 /* Mark receipt of record. */
606 dtls1_record_bitmap_update(s, bitmap);
608 return (1);
611 /* Return up to 'len' payload bytes received in 'type' records.
612 * 'type' is one of the following:
614 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
615 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
616 * - 0 (during a shutdown, no data has to be returned)
618 * If we don't have stored data to work from, read a SSL/TLS record first
619 * (possibly multiple records if we still don't have anything to return).
621 * This function must handle any surprises the peer may have for us, such as
622 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
623 * a surprise, but handled as if it were), or renegotiation requests.
624 * Also if record payloads contain fragments too small to process, we store
625 * them until there is enough for the respective protocol (the record protocol
626 * may use arbitrary fragmentation and even interleaving):
627 * Change cipher spec protocol
628 * just 1 byte needed, no need for keeping anything stored
629 * Alert protocol
630 * 2 bytes needed (AlertLevel, AlertDescription)
631 * Handshake protocol
632 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
633 * to detect unexpected Client Hello and Hello Request messages
634 * here, anything else is handled by higher layers
635 * Application data protocol
636 * none of our business
639 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
641 int al, i, j, ret;
642 unsigned int n;
643 SSL3_RECORD *rr;
644 void (*cb)(const SSL *ssl, int type2, int val) = NULL;
646 if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
647 if (!ssl3_setup_buffers(s))
648 return (-1);
650 if ((type &&
651 type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
652 (peek && (type != SSL3_RT_APPLICATION_DATA))) {
653 SSLerror(s, ERR_R_INTERNAL_ERROR);
654 return -1;
657 /* check whether there's a handshake message (client hello?) waiting */
658 if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
659 return ret;
661 /* Now D1I(s)->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
663 if (!s->internal->in_handshake && SSL_in_init(s))
665 /* type == SSL3_RT_APPLICATION_DATA */
666 i = s->internal->handshake_func(s);
667 if (i < 0)
668 return (i);
669 if (i == 0) {
670 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
671 return (-1);
675 start:
676 s->internal->rwstate = SSL_NOTHING;
678 /* S3I(s)->rrec.type - is the type of record
679 * S3I(s)->rrec.data, - data
680 * S3I(s)->rrec.off, - offset into 'data' for next read
681 * S3I(s)->rrec.length, - number of bytes. */
682 rr = &(S3I(s)->rrec);
684 /* We are not handshaking and have no data yet,
685 * so process data buffered during the last handshake
686 * in advance, if any.
688 if (S3I(s)->hs.state == SSL_ST_OK && rr->length == 0) {
689 pitem *item;
690 item = pqueue_pop(D1I(s)->buffered_app_data.q);
691 if (item) {
693 dtls1_copy_record(s, item);
695 free(item->data);
696 pitem_free(item);
700 /* Check for timeout */
701 if (dtls1_handle_timeout(s) > 0)
702 goto start;
704 /* get new packet if necessary */
705 if ((rr->length == 0) || (s->internal->rstate == SSL_ST_READ_BODY)) {
706 ret = dtls1_get_record(s);
707 if (ret <= 0) {
708 ret = dtls1_read_failed(s, ret);
709 /* anything other than a timeout is an error */
710 if (ret <= 0)
711 return (ret);
712 else
713 goto start;
717 if (D1I(s)->listen && rr->type != SSL3_RT_HANDSHAKE) {
718 rr->length = 0;
719 goto start;
722 /* we now have a packet which can be read and processed */
724 if (S3I(s)->change_cipher_spec /* set when we receive ChangeCipherSpec,
725 * reset by ssl3_get_finished */
726 && (rr->type != SSL3_RT_HANDSHAKE)) {
727 /* We now have application data between CCS and Finished.
728 * Most likely the packets were reordered on their way, so
729 * buffer the application data for later processing rather
730 * than dropping the connection.
732 if (dtls1_buffer_record(s, &(D1I(s)->buffered_app_data),
733 rr->seq_num) < 0) {
734 SSLerror(s, ERR_R_INTERNAL_ERROR);
735 return (-1);
737 rr->length = 0;
738 goto start;
741 /* If the other end has shut down, throw anything we read away
742 * (even in 'peek' mode) */
743 if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
744 rr->length = 0;
745 s->internal->rwstate = SSL_NOTHING;
746 return (0);
750 if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
752 /* make sure that we are not getting application data when we
753 * are doing a handshake for the first time */
754 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
755 (s->enc_read_ctx == NULL)) {
756 al = SSL_AD_UNEXPECTED_MESSAGE;
757 SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
758 goto f_err;
761 if (len <= 0)
762 return (len);
764 if ((unsigned int)len > rr->length)
765 n = rr->length;
766 else
767 n = (unsigned int)len;
769 memcpy(buf, &(rr->data[rr->off]), n);
770 if (!peek) {
771 rr->length -= n;
772 rr->off += n;
773 if (rr->length == 0) {
774 s->internal->rstate = SSL_ST_READ_HEADER;
775 rr->off = 0;
779 return (n);
783 /* If we get here, then type != rr->type; if we have a handshake
784 * message, then it was unexpected (Hello Request or Client Hello). */
786 /* In case of record types for which we have 'fragment' storage,
787 * fill that so that we can process the data at a fixed place.
790 unsigned int k, dest_maxlen = 0;
791 unsigned char *dest = NULL;
792 unsigned int *dest_len = NULL;
794 if (rr->type == SSL3_RT_HANDSHAKE) {
795 dest_maxlen = sizeof D1I(s)->handshake_fragment;
796 dest = D1I(s)->handshake_fragment;
797 dest_len = &D1I(s)->handshake_fragment_len;
798 } else if (rr->type == SSL3_RT_ALERT) {
799 dest_maxlen = sizeof(D1I(s)->alert_fragment);
800 dest = D1I(s)->alert_fragment;
801 dest_len = &D1I(s)->alert_fragment_len;
803 /* else it's a CCS message, or application data or wrong */
804 else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
805 /* Application data while renegotiating
806 * is allowed. Try again reading.
808 if (rr->type == SSL3_RT_APPLICATION_DATA) {
809 BIO *bio;
810 S3I(s)->in_read_app_data = 2;
811 bio = SSL_get_rbio(s);
812 s->internal->rwstate = SSL_READING;
813 BIO_clear_retry_flags(bio);
814 BIO_set_retry_read(bio);
815 return (-1);
818 /* Not certain if this is the right error handling */
819 al = SSL_AD_UNEXPECTED_MESSAGE;
820 SSLerror(s, SSL_R_UNEXPECTED_RECORD);
821 goto f_err;
824 if (dest_maxlen > 0) {
825 /* XDTLS: In a pathalogical case, the Client Hello
826 * may be fragmented--don't always expect dest_maxlen bytes */
827 if (rr->length < dest_maxlen) {
828 s->internal->rstate = SSL_ST_READ_HEADER;
829 rr->length = 0;
830 goto start;
833 /* now move 'n' bytes: */
834 for ( k = 0; k < dest_maxlen; k++) {
835 dest[k] = rr->data[rr->off++];
836 rr->length--;
838 *dest_len = dest_maxlen;
842 /* D1I(s)->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
843 * D1I(s)->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
844 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
846 /* If we are a client, check for an incoming 'Hello Request': */
847 if ((!s->server) &&
848 (D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
849 (D1I(s)->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
850 (s->session != NULL) && (s->session->cipher != NULL)) {
851 D1I(s)->handshake_fragment_len = 0;
853 if ((D1I(s)->handshake_fragment[1] != 0) ||
854 (D1I(s)->handshake_fragment[2] != 0) ||
855 (D1I(s)->handshake_fragment[3] != 0)) {
856 al = SSL_AD_DECODE_ERROR;
857 SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
858 goto err;
861 /* no need to check sequence number on HELLO REQUEST messages */
863 if (s->internal->msg_callback)
864 s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
865 D1I(s)->handshake_fragment, 4, s, s->internal->msg_callback_arg);
867 if (SSL_is_init_finished(s) &&
868 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
869 !S3I(s)->renegotiate) {
870 D1I(s)->handshake_read_seq++;
871 s->internal->new_session = 1;
872 ssl3_renegotiate(s);
873 if (ssl3_renegotiate_check(s)) {
874 i = s->internal->handshake_func(s);
875 if (i < 0)
876 return (i);
877 if (i == 0) {
878 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
879 return (-1);
882 if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
883 if (s->s3->rbuf.left == 0) /* no read-ahead left? */
885 BIO *bio;
886 /* In the case where we try to read application data,
887 * but we trigger an SSL handshake, we return -1 with
888 * the retry option set. Otherwise renegotiation may
889 * cause nasty problems in the blocking world */
890 s->internal->rwstate = SSL_READING;
891 bio = SSL_get_rbio(s);
892 BIO_clear_retry_flags(bio);
893 BIO_set_retry_read(bio);
894 return (-1);
899 /* we either finished a handshake or ignored the request,
900 * now try again to obtain the (application) data we were asked for */
901 goto start;
904 if (D1I(s)->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
905 int alert_level = D1I(s)->alert_fragment[0];
906 int alert_descr = D1I(s)->alert_fragment[1];
908 D1I(s)->alert_fragment_len = 0;
910 if (s->internal->msg_callback)
911 s->internal->msg_callback(0, s->version, SSL3_RT_ALERT,
912 D1I(s)->alert_fragment, 2, s, s->internal->msg_callback_arg);
914 if (s->internal->info_callback != NULL)
915 cb = s->internal->info_callback;
916 else if (s->ctx->internal->info_callback != NULL)
917 cb = s->ctx->internal->info_callback;
919 if (cb != NULL) {
920 j = (alert_level << 8) | alert_descr;
921 cb(s, SSL_CB_READ_ALERT, j);
924 if (alert_level == 1) /* warning */
926 S3I(s)->warn_alert = alert_descr;
927 if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
928 s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
929 return (0);
931 } else if (alert_level == 2) /* fatal */
933 s->internal->rwstate = SSL_NOTHING;
934 S3I(s)->fatal_alert = alert_descr;
935 SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
936 ERR_asprintf_error_data("SSL alert number %d",
937 alert_descr);
938 s->internal->shutdown|=SSL_RECEIVED_SHUTDOWN;
939 SSL_CTX_remove_session(s->ctx, s->session);
940 return (0);
941 } else {
942 al = SSL_AD_ILLEGAL_PARAMETER;
943 SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
944 goto f_err;
947 goto start;
950 if (s->internal->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
952 s->internal->rwstate = SSL_NOTHING;
953 rr->length = 0;
954 return (0);
957 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
958 struct ccs_header_st ccs_hdr;
959 unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
961 dtls1_get_ccs_header(rr->data, &ccs_hdr);
963 /* 'Change Cipher Spec' is just a single byte, so we know
964 * exactly what the record payload has to look like */
965 /* XDTLS: check that epoch is consistent */
966 if ((rr->length != ccs_hdr_len) ||
967 (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
968 i = SSL_AD_ILLEGAL_PARAMETER;
969 SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
970 goto err;
973 rr->length = 0;
975 if (s->internal->msg_callback)
976 s->internal->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
977 rr->data, 1, s, s->internal->msg_callback_arg);
979 /* We can't process a CCS now, because previous handshake
980 * messages are still missing, so just drop it.
982 if (!D1I(s)->change_cipher_spec_ok) {
983 goto start;
986 D1I(s)->change_cipher_spec_ok = 0;
988 S3I(s)->change_cipher_spec = 1;
989 if (!ssl3_do_change_cipher_spec(s))
990 goto err;
992 /* do this whenever CCS is processed */
993 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
995 goto start;
998 /* Unexpected handshake message (Client Hello, or protocol violation) */
999 if ((D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
1000 !s->internal->in_handshake) {
1001 struct hm_header_st msg_hdr;
1003 /* this may just be a stale retransmit */
1004 if (!dtls1_get_message_header(rr->data, &msg_hdr))
1005 return -1;
1006 if (rr->epoch != D1I(s)->r_epoch) {
1007 rr->length = 0;
1008 goto start;
1011 /* If we are server, we may have a repeated FINISHED of the
1012 * client here, then retransmit our CCS and FINISHED.
1014 if (msg_hdr.type == SSL3_MT_FINISHED) {
1015 if (dtls1_check_timeout_num(s) < 0)
1016 return -1;
1018 dtls1_retransmit_buffered_messages(s);
1019 rr->length = 0;
1020 goto start;
1023 if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) &&
1024 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1025 S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1026 s->internal->renegotiate = 1;
1027 s->internal->new_session = 1;
1029 i = s->internal->handshake_func(s);
1030 if (i < 0)
1031 return (i);
1032 if (i == 0) {
1033 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1034 return (-1);
1037 if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
1038 if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1040 BIO *bio;
1041 /* In the case where we try to read application data,
1042 * but we trigger an SSL handshake, we return -1 with
1043 * the retry option set. Otherwise renegotiation may
1044 * cause nasty problems in the blocking world */
1045 s->internal->rwstate = SSL_READING;
1046 bio = SSL_get_rbio(s);
1047 BIO_clear_retry_flags(bio);
1048 BIO_set_retry_read(bio);
1049 return (-1);
1052 goto start;
1055 switch (rr->type) {
1056 default:
1057 /* TLS just ignores unknown message types */
1058 if (s->version == TLS1_VERSION) {
1059 rr->length = 0;
1060 goto start;
1062 al = SSL_AD_UNEXPECTED_MESSAGE;
1063 SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1064 goto f_err;
1065 case SSL3_RT_CHANGE_CIPHER_SPEC:
1066 case SSL3_RT_ALERT:
1067 case SSL3_RT_HANDSHAKE:
1068 /* we already handled all of these, with the possible exception
1069 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that
1070 * should not happen when type != rr->type */
1071 al = SSL_AD_UNEXPECTED_MESSAGE;
1072 SSLerror(s, ERR_R_INTERNAL_ERROR);
1073 goto f_err;
1074 case SSL3_RT_APPLICATION_DATA:
1075 /* At this point, we were expecting handshake data,
1076 * but have application data. If the library was
1077 * running inside ssl3_read() (i.e. in_read_app_data
1078 * is set) and it makes sense to read application data
1079 * at this point (session renegotiation not yet started),
1080 * we will indulge it.
1082 if (S3I(s)->in_read_app_data &&
1083 (S3I(s)->total_renegotiations != 0) &&
1084 (((S3I(s)->hs.state & SSL_ST_CONNECT) &&
1085 (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1086 (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
1087 (S3I(s)->hs.state & SSL_ST_ACCEPT) &&
1088 (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
1089 (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1090 S3I(s)->in_read_app_data = 2;
1091 return (-1);
1092 } else {
1093 al = SSL_AD_UNEXPECTED_MESSAGE;
1094 SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1095 goto f_err;
1098 /* not reached */
1100 f_err:
1101 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1102 err:
1103 return (-1);
1107 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
1109 int i;
1111 if (SSL_in_init(s) && !s->internal->in_handshake)
1113 i = s->internal->handshake_func(s);
1114 if (i < 0)
1115 return (i);
1116 if (i == 0) {
1117 SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1118 return -1;
1122 if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
1123 SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
1124 return -1;
1127 i = dtls1_write_bytes(s, type, buf_, len);
1128 return i;
1132 /* this only happens when a client hello is received and a handshake
1133 * is started. */
1134 static int
1135 have_handshake_fragment(SSL *s, int type, unsigned char *buf,
1136 int len, int peek)
1139 if ((type == SSL3_RT_HANDSHAKE) && (D1I(s)->handshake_fragment_len > 0))
1140 /* (partially) satisfy request from storage */
1142 unsigned char *src = D1I(s)->handshake_fragment;
1143 unsigned char *dst = buf;
1144 unsigned int k, n;
1146 /* peek == 0 */
1147 n = 0;
1148 while ((len > 0) && (D1I(s)->handshake_fragment_len > 0)) {
1149 *dst++ = *src++;
1150 len--;
1151 D1I(s)->handshake_fragment_len--;
1152 n++;
1154 /* move any remaining fragment bytes: */
1155 for (k = 0; k < D1I(s)->handshake_fragment_len; k++)
1156 D1I(s)->handshake_fragment[k] = *src++;
1157 return n;
1160 return 0;
1164 /* Call this to write data in records of type 'type'
1165 * It will return <= 0 if not all data has been sent or non-blocking IO.
1168 dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
1170 int i;
1172 OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
1173 s->internal->rwstate = SSL_NOTHING;
1174 i = do_dtls1_write(s, type, buf, len);
1175 return i;
1179 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
1181 unsigned char *p, *pseq;
1182 int i, mac_size, clear = 0;
1183 int prefix_len = 0;
1184 SSL3_RECORD *wr;
1185 SSL3_BUFFER *wb;
1186 SSL_SESSION *sess;
1187 int bs;
1189 /* first check if there is a SSL3_BUFFER still being written
1190 * out. This will happen with non blocking IO */
1191 if (s->s3->wbuf.left != 0) {
1192 OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
1193 return (ssl3_write_pending(s, type, buf, len));
1196 /* If we have an alert to send, lets send it */
1197 if (s->s3->alert_dispatch) {
1198 i = s->method->ssl_dispatch_alert(s);
1199 if (i <= 0)
1200 return (i);
1201 /* if it went, fall through and send more stuff */
1204 if (len == 0)
1205 return 0;
1207 wr = &(S3I(s)->wrec);
1208 wb = &(s->s3->wbuf);
1209 sess = s->session;
1211 if ((sess == NULL) || (s->internal->enc_write_ctx == NULL) ||
1212 (EVP_MD_CTX_md(s->internal->write_hash) == NULL))
1213 clear = 1;
1215 if (clear)
1216 mac_size = 0;
1217 else {
1218 mac_size = EVP_MD_CTX_size(s->internal->write_hash);
1219 if (mac_size < 0)
1220 goto err;
1223 /* DTLS implements explicit IV, so no need for empty fragments. */
1225 p = wb->buf + prefix_len;
1227 /* write the header */
1229 *(p++) = type&0xff;
1230 wr->type = type;
1232 *(p++) = (s->version >> 8);
1233 *(p++) = s->version&0xff;
1235 /* field where we are to write out packet epoch, seq num and len */
1236 pseq = p;
1238 p += 10;
1240 /* lets setup the record stuff. */
1242 /* Make space for the explicit IV in case of CBC.
1243 * (this is a bit of a boundary violation, but what the heck).
1245 if (s->internal->enc_write_ctx &&
1246 (EVP_CIPHER_mode(s->internal->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
1247 bs = EVP_CIPHER_block_size(s->internal->enc_write_ctx->cipher);
1248 else
1249 bs = 0;
1251 wr->data = p + bs;
1252 /* make room for IV in case of CBC */
1253 wr->length = (int)len;
1254 wr->input = (unsigned char *)buf;
1256 /* we now 'read' from wr->input, wr->length bytes into
1257 * wr->data */
1259 memcpy(wr->data, wr->input, wr->length);
1260 wr->input = wr->data;
1262 /* we should still have the output to wr->data and the input
1263 * from wr->input. Length should be wr->length.
1264 * wr->data still points in the wb->buf */
1266 if (mac_size != 0) {
1267 if (tls1_mac(s, &(p[wr->length + bs]), 1) < 0)
1268 goto err;
1269 wr->length += mac_size;
1272 /* this is true regardless of mac size */
1273 wr->input = p;
1274 wr->data = p;
1277 /* ssl3_enc can only have an error on read */
1278 if (bs) /* bs != 0 in case of CBC */
1280 arc4random_buf(p, bs);
1281 /* master IV and last CBC residue stand for
1282 * the rest of randomness */
1283 wr->length += bs;
1286 s->method->internal->ssl3_enc->enc(s, 1);
1288 /* record length after mac and block padding */
1289 /* if (type == SSL3_RT_APPLICATION_DATA ||
1290 (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
1292 /* there's only one epoch between handshake and app data */
1294 s2n(D1I(s)->w_epoch, pseq);
1296 /* XDTLS: ?? */
1297 /* else
1298 s2n(D1I(s)->handshake_epoch, pseq);
1301 memcpy(pseq, &(S3I(s)->write_sequence[2]), 6);
1302 pseq += 6;
1303 s2n(wr->length, pseq);
1305 /* we should now have
1306 * wr->data pointing to the encrypted data, which is
1307 * wr->length long */
1308 wr->type=type; /* not needed but helps for debugging */
1309 wr->length += DTLS1_RT_HEADER_LENGTH;
1311 tls1_record_sequence_increment(S3I(s)->write_sequence);
1313 /* now let's set up wb */
1314 wb->left = prefix_len + wr->length;
1315 wb->offset = 0;
1317 /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
1318 S3I(s)->wpend_tot = len;
1319 S3I(s)->wpend_buf = buf;
1320 S3I(s)->wpend_type = type;
1321 S3I(s)->wpend_ret = len;
1323 /* we now just need to write the buffer */
1324 return ssl3_write_pending(s, type, buf, len);
1325 err:
1326 return -1;
1331 static int
1332 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
1334 int cmp;
1335 unsigned int shift;
1336 const unsigned char *seq = S3I(s)->read_sequence;
1338 cmp = satsub64be(seq, bitmap->max_seq_num);
1339 if (cmp > 0) {
1340 memcpy (S3I(s)->rrec.seq_num, seq, 8);
1341 return 1; /* this record in new */
1343 shift = -cmp;
1344 if (shift >= sizeof(bitmap->map)*8)
1345 return 0; /* stale, outside the window */
1346 else if (bitmap->map & (1UL << shift))
1347 return 0; /* record previously received */
1349 memcpy(S3I(s)->rrec.seq_num, seq, 8);
1350 return 1;
1354 static void
1355 dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
1357 int cmp;
1358 unsigned int shift;
1359 const unsigned char *seq = S3I(s)->read_sequence;
1361 cmp = satsub64be(seq, bitmap->max_seq_num);
1362 if (cmp > 0) {
1363 shift = cmp;
1364 if (shift < sizeof(bitmap->map)*8)
1365 bitmap->map <<= shift, bitmap->map |= 1UL;
1366 else
1367 bitmap->map = 1UL;
1368 memcpy(bitmap->max_seq_num, seq, 8);
1369 } else {
1370 shift = -cmp;
1371 if (shift < sizeof(bitmap->map) * 8)
1372 bitmap->map |= 1UL << shift;
1378 dtls1_dispatch_alert(SSL *s)
1380 int i, j;
1381 void (*cb)(const SSL *ssl, int type, int val) = NULL;
1382 unsigned char buf[DTLS1_AL_HEADER_LENGTH];
1383 unsigned char *ptr = &buf[0];
1385 s->s3->alert_dispatch = 0;
1387 memset(buf, 0x00, sizeof(buf));
1388 *ptr++ = s->s3->send_alert[0];
1389 *ptr++ = s->s3->send_alert[1];
1391 i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
1392 if (i <= 0) {
1393 s->s3->alert_dispatch = 1;
1394 /* fprintf( stderr, "not done with alert\n" ); */
1395 } else {
1396 if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1397 (void)BIO_flush(s->wbio);
1399 if (s->internal->msg_callback)
1400 s->internal->msg_callback(1, s->version, SSL3_RT_ALERT,
1401 s->s3->send_alert, 2, s, s->internal->msg_callback_arg);
1403 if (s->internal->info_callback != NULL)
1404 cb = s->internal->info_callback;
1405 else if (s->ctx->internal->info_callback != NULL)
1406 cb = s->ctx->internal->info_callback;
1408 if (cb != NULL) {
1409 j = (s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1410 cb(s, SSL_CB_WRITE_ALERT, j);
1413 return (i);
1417 static DTLS1_BITMAP *
1418 dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
1421 *is_next_epoch = 0;
1423 /* In current epoch, accept HM, CCS, DATA, & ALERT */
1424 if (rr->epoch == D1I(s)->r_epoch)
1425 return &D1I(s)->bitmap;
1427 /* Only HM and ALERT messages can be from the next epoch */
1428 else if (rr->epoch == (unsigned long)(D1I(s)->r_epoch + 1) &&
1429 (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1430 *is_next_epoch = 1;
1431 return &D1I(s)->next_bitmap;
1434 return NULL;
1437 void
1438 dtls1_reset_seq_numbers(SSL *s, int rw)
1440 unsigned char *seq;
1441 unsigned int seq_bytes = sizeof(S3I(s)->read_sequence);
1443 if (rw & SSL3_CC_READ) {
1444 seq = S3I(s)->read_sequence;
1445 D1I(s)->r_epoch++;
1446 memcpy(&(D1I(s)->bitmap), &(D1I(s)->next_bitmap), sizeof(DTLS1_BITMAP));
1447 memset(&(D1I(s)->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
1448 } else {
1449 seq = S3I(s)->write_sequence;
1450 memcpy(D1I(s)->last_write_sequence, seq, sizeof(S3I(s)->write_sequence));
1451 D1I(s)->w_epoch++;
1454 memset(seq, 0x00, seq_bytes);