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