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