xref: /dragonfly/crypto/libressl/ssl/d1_pkt.c (revision 89656a4e)
1 /* $OpenBSD: d1_pkt.c,v 1.66 2018/12/03 17:16:12 tb Exp $ */
2 /*
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
5  */
6 /* ====================================================================
7  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@openssl.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  *
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  *
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  *
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  *
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  *
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115 
116 #include <machine/endian.h>
117 
118 #include <errno.h>
119 #include <stdio.h>
120 
121 #include "ssl_locl.h"
122 
123 #include <openssl/buffer.h>
124 #include <openssl/evp.h>
125 
126 #include "pqueue.h"
127 #include "bytestring.h"
128 
129 static int	do_dtls1_write(SSL *s, int type, const unsigned char *buf,
130 		    unsigned int len);
131 
132 
133 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
134 static int
135 satsub64be(const unsigned char *v1, const unsigned char *v2)
136 {
137 	int ret, sat, brw, i;
138 
139 	if (sizeof(long) == 8)
140 		do {
141 			long l;
142 
143 			if (BYTE_ORDER == LITTLE_ENDIAN)
144 				break;
145 			/* not reached on little-endians */
146 			/* following test is redundant, because input is
147 			 * always aligned, but I take no chances... */
148 			if (((size_t)v1 | (size_t)v2) & 0x7)
149 				break;
150 
151 			l  = *((long *)v1);
152 			l -= *((long *)v2);
153 			if (l > 128)
154 				return 128;
155 			else if (l<-128)
156 				return -128;
157 			else
158 				return (int)l;
159 		} while (0);
160 
161 	ret = (int)v1[7] - (int)v2[7];
162 	sat = 0;
163 	brw = ret >> 8;	/* brw is either 0 or -1 */
164 	if (ret & 0x80) {
165 		for (i = 6; i >= 0; i--) {
166 			brw += (int)v1[i]-(int)v2[i];
167 			sat |= ~brw;
168 			brw >>= 8;
169 		}
170 	} else {
171 		for (i = 6; i >= 0; i--) {
172 			brw += (int)v1[i]-(int)v2[i];
173 			sat |= brw;
174 			brw >>= 8;
175 		}
176 	}
177 	brw <<= 8;	/* brw is either 0 or -256 */
178 
179 	if (sat & 0xff)
180 		return brw | 0x80;
181 	else
182 		return brw + (ret & 0xFF);
183 }
184 
185 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
186     int len, int peek);
187 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
188 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(S3I(s)->rbuf.buf);
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));
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), &(S3I(s)->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(&(S3I(s)->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 	SSLerror(s, 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 		SSLerror(s, 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 			SSLerror(s, 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 = 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;
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 		SSLerror(s, 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 	SSL3_RECORD *rr;
473 	unsigned char *p = NULL;
474 	DTLS1_BITMAP *bitmap;
475 	unsigned int is_next_epoch;
476 	int n;
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_packet_read(s, DTLS1_RT_HEADER_LENGTH);
505 		if (n <= 0)
506 			return (n);
507 
508 		/* If this packet contained a partial record, dump it. */
509 		if (n != DTLS1_RT_HEADER_LENGTH)
510 			goto again;
511 
512 		s->internal->rstate = SSL_ST_READ_BODY;
513 
514 		CBS_init(&header, s->internal->packet, s->internal->packet_length);
515 
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;
521 
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;
526 
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;
532 
533 		rr->type = type;
534 		rr->epoch = epoch;
535 		rr->length = len;
536 
537 		/* unexpected version, silently discard */
538 		if (!s->internal->first_packet && ssl_version != s->version)
539 			goto again;
540 
541 		/* wrong version, silently discard record */
542 		if ((ssl_version & 0xff00) != (s->version & 0xff00))
543 			goto again;
544 
545 		/* record too long, silently discard it */
546 		if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
547 			goto again;
548 
549 		/* now s->internal->rstate == SSL_ST_READ_BODY */
550 		p = (unsigned char *)CBS_data(&header);
551 	}
552 
553 	/* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */
554 
555 	n = ssl3_packet_extend(s, DTLS1_RT_HEADER_LENGTH + rr->length);
556 	if (n <= 0)
557 		return (n);
558 
559 	/* If this packet contained a partial record, dump it. */
560 	if (n != DTLS1_RT_HEADER_LENGTH + rr->length)
561 		goto again;
562 
563 	s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
564 
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;
569 
570 	/*
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.
576 	 */
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;
581 
582 	/* just read a 0 length packet */
583 	if (rr->length == 0)
584 		goto again;
585 
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.
590 	 */
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);
598 		}
599 		goto again;
600 	}
601 
602 	if (!dtls1_process_record(s))
603 		goto again;
604 
605 	/* Mark receipt of record. */
606 	dtls1_record_bitmap_update(s, bitmap);
607 
608 	return (1);
609 }
610 
611 /* Return up to 'len' payload bytes received in 'type' records.
612  * 'type' is one of the following:
613  *
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)
617  *
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).
620  *
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
637  */
638 int
639 dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
640 {
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;
645 
646 	if (S3I(s)->rbuf.buf == NULL) /* Not initialized yet */
647 		if (!ssl3_setup_buffers(s))
648 			return (-1);
649 
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;
655 	}
656 
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;
660 
661 	/* Now D1I(s)->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
662 
663 	if (!s->internal->in_handshake && SSL_in_init(s))
664 	{
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);
672 		}
673 	}
674 
675  start:
676 	s->internal->rwstate = SSL_NOTHING;
677 
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);
683 
684 	/* We are not handshaking and have no data yet,
685 	 * so process data buffered during the last handshake
686 	 * in advance, if any.
687 	 */
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) {
692 
693 			dtls1_copy_record(s, item);
694 
695 			free(item->data);
696 			pitem_free(item);
697 		}
698 	}
699 
700 	/* Check for timeout */
701 	if (dtls1_handle_timeout(s) > 0)
702 		goto start;
703 
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;
714 		}
715 	}
716 
717 	if (D1I(s)->listen && rr->type != SSL3_RT_HANDSHAKE) {
718 		rr->length = 0;
719 		goto start;
720 	}
721 
722 	/* we now have a packet which can be read and processed */
723 
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.
731 		 */
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);
736 		}
737 		rr->length = 0;
738 		goto start;
739 	}
740 
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);
747 	}
748 
749 
750 	if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
751 	{
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;
759 		}
760 
761 		if (len <= 0)
762 			return (len);
763 
764 		if ((unsigned int)len > rr->length)
765 			n = rr->length;
766 		else
767 			n = (unsigned int)len;
768 
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;
776 			}
777 		}
778 
779 		return (n);
780 	}
781 
782 
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). */
785 
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.
788 	 */
789 	{
790 		unsigned int k, dest_maxlen = 0;
791 		unsigned char *dest = NULL;
792 		unsigned int *dest_len = NULL;
793 
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;
802 		}
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.
807 			 */
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);
816 			}
817 
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;
822 		}
823 
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;
831 			}
832 
833 			/* now move 'n' bytes: */
834 			for ( k = 0; k < dest_maxlen; k++) {
835 				dest[k] = rr->data[rr->off++];
836 				rr->length--;
837 			}
838 			*dest_len = dest_maxlen;
839 		}
840 	}
841 
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.) */
845 
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;
852 
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 f_err;
859 		}
860 
861 		/* no need to check sequence number on HELLO REQUEST messages */
862 
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);
866 
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);
880 				}
881 
882 				if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
883 					if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */
884 					{
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);
895 					}
896 				}
897 			}
898 		}
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;
902 	}
903 
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];
907 
908 		D1I(s)->alert_fragment_len = 0;
909 
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);
913 
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;
918 
919 		if (cb != NULL) {
920 			j = (alert_level << 8) | alert_descr;
921 			cb(s, SSL_CB_READ_ALERT, j);
922 		}
923 
924 		if (alert_level == 1) /* warning */
925 		{
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);
930 			}
931 		} else if (alert_level == 2) /* fatal */
932 		{
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;
945 		}
946 
947 		goto start;
948 	}
949 
950 	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
951 	{
952 		s->internal->rwstate = SSL_NOTHING;
953 		rr->length = 0;
954 		return (0);
955 	}
956 
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;
960 
961 		dtls1_get_ccs_header(rr->data, &ccs_hdr);
962 
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 			al = SSL_AD_DECODE_ERROR;
969 			SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
970 			goto f_err;
971 		}
972 
973 		rr->length = 0;
974 
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);
978 
979 		/* We can't process a CCS now, because previous handshake
980 		 * messages are still missing, so just drop it.
981 		 */
982 		if (!D1I(s)->change_cipher_spec_ok) {
983 			goto start;
984 		}
985 
986 		D1I(s)->change_cipher_spec_ok = 0;
987 
988 		S3I(s)->change_cipher_spec = 1;
989 		if (!ssl3_do_change_cipher_spec(s))
990 			goto err;
991 
992 		/* do this whenever CCS is processed */
993 		dtls1_reset_seq_numbers(s, SSL3_CC_READ);
994 
995 		goto start;
996 	}
997 
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;
1002 
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;
1009 		}
1010 
1011 		/* If we are server, we may have a repeated FINISHED of the
1012 		 * client here, then retransmit our CCS and FINISHED.
1013 		 */
1014 		if (msg_hdr.type == SSL3_MT_FINISHED) {
1015 			if (dtls1_check_timeout_num(s) < 0)
1016 				return -1;
1017 
1018 			dtls1_retransmit_buffered_messages(s);
1019 			rr->length = 0;
1020 			goto start;
1021 		}
1022 
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;
1028 		}
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);
1035 		}
1036 
1037 		if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
1038 			if (S3I(s)->rbuf.left == 0) /* no read-ahead left? */
1039 			{
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);
1050 			}
1051 		}
1052 		goto start;
1053 	}
1054 
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;
1061 		}
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.
1081 		 */
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;
1096 		}
1097 	}
1098 	/* not reached */
1099 
1100  f_err:
1101 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1102  err:
1103 	return (-1);
1104 }
1105 
1106 int
1107 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
1108 {
1109 	int i;
1110 
1111 	if (SSL_in_init(s) && !s->internal->in_handshake)
1112 	{
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;
1119 		}
1120 	}
1121 
1122 	if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
1123 		SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
1124 		return -1;
1125 	}
1126 
1127 	i = dtls1_write_bytes(s, type, buf_, len);
1128 	return i;
1129 }
1130 
1131 
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)
1137 {
1138 
1139 	if ((type == SSL3_RT_HANDSHAKE) && (D1I(s)->handshake_fragment_len > 0))
1140 		/* (partially) satisfy request from storage */
1141 	{
1142 		unsigned char *src = D1I(s)->handshake_fragment;
1143 		unsigned char *dst = buf;
1144 		unsigned int k, n;
1145 
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++;
1153 		}
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;
1158 	}
1159 
1160 	return 0;
1161 }
1162 
1163 
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.
1166  */
1167 int
1168 dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
1169 {
1170 	int i;
1171 
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;
1176 }
1177 
1178 int
1179 do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
1180 {
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;
1188 
1189 	/* first check if there is a SSL3_BUFFER still being written
1190 	 * out.  This will happen with non blocking IO */
1191 	if (S3I(s)->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));
1194 	}
1195 
1196 	/* If we have an alert to send, lets send it */
1197 	if (S3I(s)->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 */
1202 	}
1203 
1204 	if (len == 0)
1205 		return 0;
1206 
1207 	wr = &(S3I(s)->wrec);
1208 	wb = &(S3I(s)->wbuf);
1209 	sess = s->session;
1210 
1211 	if ((sess == NULL) || (s->internal->enc_write_ctx == NULL) ||
1212 	    (EVP_MD_CTX_md(s->internal->write_hash) == NULL))
1213 		clear = 1;
1214 
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;
1221 	}
1222 
1223 	/* DTLS implements explicit IV, so no need for empty fragments. */
1224 
1225 	p = wb->buf + prefix_len;
1226 
1227 	/* write the header */
1228 
1229 	*(p++) = type&0xff;
1230 	wr->type = type;
1231 
1232 	*(p++) = (s->version >> 8);
1233 	*(p++) = s->version&0xff;
1234 
1235 	/* field where we are to write out packet epoch, seq num and len */
1236 	pseq = p;
1237 
1238 	p += 10;
1239 
1240 	/* lets setup the record stuff. */
1241 
1242 	/* Make space for the explicit IV in case of CBC.
1243 	 * (this is a bit of a boundary violation, but what the heck).
1244 	 */
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;
1250 
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;
1255 
1256 	/* we now 'read' from wr->input, wr->length bytes into
1257 	 * wr->data */
1258 
1259 	memcpy(wr->data, wr->input, wr->length);
1260 	wr->input = wr->data;
1261 
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 */
1265 
1266 	if (mac_size != 0) {
1267 		if (tls1_mac(s, &(p[wr->length + bs]), 1) < 0)
1268 			goto err;
1269 		wr->length += mac_size;
1270 	}
1271 
1272 	/* this is true regardless of mac size */
1273 	wr->input = p;
1274 	wr->data = p;
1275 
1276 
1277 	/* ssl3_enc can only have an error on read */
1278 	if (bs)	/* bs != 0 in case of CBC */
1279 	{
1280 		arc4random_buf(p, bs);
1281 		/* master IV and last CBC residue stand for
1282 		 * the rest of randomness */
1283 		wr->length += bs;
1284 	}
1285 
1286 	s->method->internal->ssl3_enc->enc(s, 1);
1287 
1288 	/* record length after mac and block padding */
1289 /*	if (type == SSL3_RT_APPLICATION_DATA ||
1290 	(type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
1291 
1292 	/* there's only one epoch between handshake and app data */
1293 
1294 	s2n(D1I(s)->w_epoch, pseq);
1295 
1296 	/* XDTLS: ?? */
1297 /*	else
1298 	s2n(D1I(s)->handshake_epoch, pseq);
1299 */
1300 
1301 	memcpy(pseq, &(S3I(s)->write_sequence[2]), 6);
1302 	pseq += 6;
1303 	s2n(wr->length, pseq);
1304 
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;
1310 
1311 	tls1_record_sequence_increment(S3I(s)->write_sequence);
1312 
1313 	/* now let's set up wb */
1314 	wb->left = prefix_len + wr->length;
1315 	wb->offset = 0;
1316 
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;
1322 
1323 	/* we now just need to write the buffer */
1324 	return ssl3_write_pending(s, type, buf, len);
1325 err:
1326 	return -1;
1327 }
1328 
1329 
1330 
1331 static int
1332 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
1333 {
1334 	int cmp;
1335 	unsigned int shift;
1336 	const unsigned char *seq = S3I(s)->read_sequence;
1337 
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 */
1342 	}
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 */
1348 
1349 	memcpy(S3I(s)->rrec.seq_num, seq, 8);
1350 	return 1;
1351 }
1352 
1353 
1354 static void
1355 dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
1356 {
1357 	int cmp;
1358 	unsigned int shift;
1359 	const unsigned char *seq = S3I(s)->read_sequence;
1360 
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;
1373 	}
1374 }
1375 
1376 
1377 int
1378 dtls1_dispatch_alert(SSL *s)
1379 {
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];
1384 
1385 	S3I(s)->alert_dispatch = 0;
1386 
1387 	memset(buf, 0x00, sizeof(buf));
1388 	*ptr++ = S3I(s)->send_alert[0];
1389 	*ptr++ = S3I(s)->send_alert[1];
1390 
1391 	i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
1392 	if (i <= 0) {
1393 		S3I(s)->alert_dispatch = 1;
1394 		/* fprintf( stderr, "not done with alert\n" ); */
1395 	} else {
1396 		if (S3I(s)->send_alert[0] == SSL3_AL_FATAL)
1397 			(void)BIO_flush(s->wbio);
1398 
1399 		if (s->internal->msg_callback)
1400 			s->internal->msg_callback(1, s->version, SSL3_RT_ALERT,
1401 			    S3I(s)->send_alert, 2, s, s->internal->msg_callback_arg);
1402 
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;
1407 
1408 		if (cb != NULL) {
1409 			j = (S3I(s)->send_alert[0]<<8)|S3I(s)->send_alert[1];
1410 			cb(s, SSL_CB_WRITE_ALERT, j);
1411 		}
1412 	}
1413 	return (i);
1414 }
1415 
1416 
1417 static DTLS1_BITMAP *
1418 dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
1419 {
1420 
1421 	*is_next_epoch = 0;
1422 
1423 	/* In current epoch, accept HM, CCS, DATA, & ALERT */
1424 	if (rr->epoch == D1I(s)->r_epoch)
1425 		return &D1I(s)->bitmap;
1426 
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;
1432 	}
1433 
1434 	return NULL;
1435 }
1436 
1437 void
1438 dtls1_reset_seq_numbers(SSL *s, int rw)
1439 {
1440 	unsigned char *seq;
1441 	unsigned int seq_bytes = sizeof(S3I(s)->read_sequence);
1442 
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++;
1452 	}
1453 
1454 	memset(seq, 0x00, seq_bytes);
1455 }
1456