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