GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: lib/libssl/d1_pkt.c Lines: 285 572 49.8 %
Date: 2017-11-07 Branches: 155 407 38.1 %

Line Branch Exec Source
1
/* $OpenBSD: d1_pkt.c,v 1.63 2017/05/07 04:22:24 beck Exp $ */
2
/*
3
 * DTLS implementation written by Nagendra Modadugu
4
 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
5
 */
6
/* ====================================================================
7
 * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
8
 *
9
 * Redistribution and use in source and binary forms, with or without
10
 * modification, are permitted provided that the following conditions
11
 * are met:
12
 *
13
 * 1. Redistributions of source code must retain the above copyright
14
 *    notice, this list of conditions and the following disclaimer.
15
 *
16
 * 2. Redistributions in binary form must reproduce the above copyright
17
 *    notice, this list of conditions and the following disclaimer in
18
 *    the documentation and/or other materials provided with the
19
 *    distribution.
20
 *
21
 * 3. All advertising materials mentioning features or use of this
22
 *    software must display the following acknowledgment:
23
 *    "This product includes software developed by the OpenSSL Project
24
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25
 *
26
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27
 *    endorse or promote products derived from this software without
28
 *    prior written permission. For written permission, please contact
29
 *    openssl-core@openssl.org.
30
 *
31
 * 5. Products derived from this software may not be called "OpenSSL"
32
 *    nor may "OpenSSL" appear in their names without prior written
33
 *    permission of the OpenSSL Project.
34
 *
35
 * 6. Redistributions of any form whatsoever must retain the following
36
 *    acknowledgment:
37
 *    "This product includes software developed by the OpenSSL Project
38
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39
 *
40
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51
 * OF THE POSSIBILITY OF SUCH DAMAGE.
52
 * ====================================================================
53
 *
54
 * This product includes cryptographic software written by Eric Young
55
 * (eay@cryptsoft.com).  This product includes software written by Tim
56
 * Hudson (tjh@cryptsoft.com).
57
 *
58
 */
59
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60
 * All rights reserved.
61
 *
62
 * This package is an SSL implementation written
63
 * by Eric Young (eay@cryptsoft.com).
64
 * The implementation was written so as to conform with Netscapes SSL.
65
 *
66
 * This library is free for commercial and non-commercial use as long as
67
 * the following conditions are aheared to.  The following conditions
68
 * apply to all code found in this distribution, be it the RC4, RSA,
69
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70
 * included with this distribution is covered by the same copyright terms
71
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72
 *
73
 * Copyright remains Eric Young's, and as such any Copyright notices in
74
 * the code are not to be removed.
75
 * If this package is used in a product, Eric Young should be given attribution
76
 * as the author of the parts of the library used.
77
 * This can be in the form of a textual message at program startup or
78
 * in documentation (online or textual) provided with the package.
79
 *
80
 * Redistribution and use in source and binary forms, with or without
81
 * modification, are permitted provided that the following conditions
82
 * are met:
83
 * 1. Redistributions of source code must retain the copyright
84
 *    notice, this list of conditions and the following disclaimer.
85
 * 2. Redistributions in binary form must reproduce the above copyright
86
 *    notice, this list of conditions and the following disclaimer in the
87
 *    documentation and/or other materials provided with the distribution.
88
 * 3. All advertising materials mentioning features or use of this software
89
 *    must display the following acknowledgement:
90
 *    "This product includes cryptographic software written by
91
 *     Eric Young (eay@cryptsoft.com)"
92
 *    The word 'cryptographic' can be left out if the rouines from the library
93
 *    being used are not cryptographic related :-).
94
 * 4. If you include any Windows specific code (or a derivative thereof) from
95
 *    the apps directory (application code) you must include an acknowledgement:
96
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97
 *
98
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108
 * SUCH DAMAGE.
109
 *
110
 * The licence and distribution terms for any publically available version or
111
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
112
 * copied and put under another distribution licence
113
 * [including the GNU Public Licence.]
114
 */
115
116
#include <machine/endian.h>
117
118
#include <errno.h>
119
#include <stdio.h>
120
121
#include "ssl_locl.h"
122
123
#include <openssl/buffer.h>
124
#include <openssl/evp.h>
125
126
#include "pqueue.h"
127
#include "bytestring.h"
128
129
static int	do_dtls1_write(SSL *s, int type, const unsigned char *buf,
130
		    unsigned int len);
131
132
133
/* mod 128 saturating subtract of two 64-bit values in big-endian order */
134
static int
135
satsub64be(const unsigned char *v1, const unsigned char *v2)
136
{
137
	int ret, sat, brw, i;
138
139
	if (sizeof(long) == 8)
140
		do {
141
			long l;
142
143
			if (BYTE_ORDER == LITTLE_ENDIAN)
144
				break;
145
			/* not reached on little-endians */
146
			/* following test is redundant, because input is
147
			 * always aligned, but I take no chances... */
148
			if (((size_t)v1 | (size_t)v2) & 0x7)
149
				break;
150
151
			l  = *((long *)v1);
152
			l -= *((long *)v2);
153
			if (l > 128)
154
				return 128;
155
			else if (l<-128)
156
				return -128;
157
			else
158
				return (int)l;
159
		} while (0);
160
161
2640
	ret = (int)v1[7] - (int)v2[7];
162
	sat = 0;
163
1320
	brw = ret >> 8;	/* brw is either 0 or -1 */
164
1320
	if (ret & 0x80) {
165
		for (i = 6; i >= 0; i--) {
166
			brw += (int)v1[i]-(int)v2[i];
167
			sat |= ~brw;
168
			brw >>= 8;
169
		}
170
	} else {
171
19800
		for (i = 6; i >= 0; i--) {
172
9240
			brw += (int)v1[i]-(int)v2[i];
173
9240
			sat |= brw;
174
9240
			brw >>= 8;
175
		}
176
	}
177
1320
	brw <<= 8;	/* brw is either 0 or -256 */
178
179
1320
	if (sat & 0xff)
180
		return brw | 0x80;
181
	else
182
1320
		return brw + (ret & 0xFF);
183
1320
}
184
185
static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
186
    int len, int peek);
187
static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
188
static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
189
static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
190
    unsigned int *is_next_epoch);
191
static int dtls1_buffer_record(SSL *s, record_pqueue *q,
192
    unsigned char *priority);
193
static int dtls1_process_record(SSL *s);
194
195
/* copy buffered record into SSL structure */
196
static int
197
dtls1_copy_record(SSL *s, pitem *item)
198
{
199
	DTLS1_RECORD_DATA *rdata;
200
201
	rdata = (DTLS1_RECORD_DATA *)item->data;
202
203
	free(s->s3->rbuf.buf);
204
205
	s->internal->packet = rdata->packet;
206
	s->internal->packet_length = rdata->packet_length;
207
	memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
208
	memcpy(&(S3I(s)->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
209
210
	/* Set proper sequence number for mac calculation */
211
	memcpy(&(S3I(s)->read_sequence[2]), &(rdata->packet[5]), 6);
212
213
	return (1);
214
}
215
216
217
static int
218
dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
219
{
220
	DTLS1_RECORD_DATA *rdata;
221
	pitem *item;
222
223
	/* Limit the size of the queue to prevent DOS attacks */
224
	if (pqueue_size(queue->q) >= 100)
225
		return 0;
226
227
	rdata = malloc(sizeof(DTLS1_RECORD_DATA));
228
	item = pitem_new(priority, rdata);
229
	if (rdata == NULL || item == NULL)
230
		goto init_err;
231
232
	rdata->packet = s->internal->packet;
233
	rdata->packet_length = s->internal->packet_length;
234
	memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
235
	memcpy(&(rdata->rrec), &(S3I(s)->rrec), sizeof(SSL3_RECORD));
236
237
	item->data = rdata;
238
239
240
	s->internal->packet = NULL;
241
	s->internal->packet_length = 0;
242
	memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
243
	memset(&(S3I(s)->rrec), 0, sizeof(SSL3_RECORD));
244
245
	if (!ssl3_setup_buffers(s))
246
		goto err;
247
248
	/* insert should not fail, since duplicates are dropped */
249
	if (pqueue_insert(queue->q, item) == NULL)
250
		goto err;
251
252
	return (1);
253
254
err:
255
	free(rdata->rbuf.buf);
256
257
init_err:
258
	SSLerror(s, ERR_R_INTERNAL_ERROR);
259
	free(rdata);
260
	pitem_free(item);
261
	return (-1);
262
}
263
264
265
static int
266
dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
267
{
268
	pitem *item;
269
270
1712
	item = pqueue_pop(queue->q);
271
856
	if (item) {
272
		dtls1_copy_record(s, item);
273
274
		free(item->data);
275
		pitem_free(item);
276
277
		return (1);
278
	}
279
280
856
	return (0);
281
856
}
282
283
284
/* retrieve a buffered record that belongs to the new epoch, i.e., not processed
285
 * yet */
286
#define dtls1_get_unprocessed_record(s) \
287
                   dtls1_retrieve_buffered_record((s), \
288
		       &((D1I(s))->unprocessed_rcds))
289
290
/* retrieve a buffered record that belongs to the current epoch, ie, processed */
291
#define dtls1_get_processed_record(s) \
292
                   dtls1_retrieve_buffered_record((s), \
293
		       &((D1I(s))->processed_rcds))
294
295
static int
296
dtls1_process_buffered_records(SSL *s)
297
{
298
	pitem *item;
299
300
1712
	item = pqueue_peek(D1I(s)->unprocessed_rcds.q);
301
856
	if (item) {
302
		/* Check if epoch is current. */
303
		if (D1I(s)->unprocessed_rcds.epoch != D1I(s)->r_epoch)
304
			return (1);
305
		/* Nothing to do. */
306
307
		/* Process all the records. */
308
		while (pqueue_peek(D1I(s)->unprocessed_rcds.q)) {
309
			dtls1_get_unprocessed_record(s);
310
			if (! dtls1_process_record(s))
311
				return (0);
312
			if (dtls1_buffer_record(s, &(D1I(s)->processed_rcds),
313
			    S3I(s)->rrec.seq_num) < 0)
314
				return (-1);
315
		}
316
	}
317
318
    /* sync epoch numbers once all the unprocessed records
319
     * have been processed */
320
856
	D1I(s)->processed_rcds.epoch = D1I(s)->r_epoch;
321
856
	D1I(s)->unprocessed_rcds.epoch = D1I(s)->r_epoch + 1;
322
323
856
	return (1);
324
856
}
325
326
static int
327
dtls1_process_record(SSL *s)
328
{
329
	int i, al;
330
	int enc_err;
331
	SSL_SESSION *sess;
332
	SSL3_RECORD *rr;
333
	unsigned int mac_size, orig_len;
334
1320
	unsigned char md[EVP_MAX_MD_SIZE];
335
336
660
	rr = &(S3I(s)->rrec);
337
660
	sess = s->session;
338
339
	/* At this point, s->internal->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
340
	 * and we have that many bytes in s->internal->packet
341
	 */
342
660
	rr->input = &(s->internal->packet[DTLS1_RT_HEADER_LENGTH]);
343
344
	/* ok, we can now read from 's->internal->packet' data into 'rr'
345
	 * rr->input points at rr->length bytes, which
346
	 * need to be copied into rr->data by either
347
	 * the decryption or by the decompression
348
	 * When the data is 'copied' into the rr->data buffer,
349
	 * rr->input will be pointed at the new buffer */
350
351
	/* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
352
	 * rr->length bytes of encrypted compressed stuff. */
353
354
	/* check is not needed I believe */
355
660
	if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
356
		al = SSL_AD_RECORD_OVERFLOW;
357
		SSLerror(s, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
358
		goto f_err;
359
	}
360
361
	/* decrypt in place in 'rr->input' */
362
660
	rr->data = rr->input;
363
364
660
	enc_err = s->method->internal->ssl3_enc->enc(s, 0);
365
	/* enc_err is:
366
	 *    0: (in non-constant time) if the record is publically invalid.
367
	 *    1: if the padding is valid
368
	 *    -1: if the padding is invalid */
369
660
	if (enc_err == 0) {
370
		/* For DTLS we simply ignore bad packets. */
371
		rr->length = 0;
372
		s->internal->packet_length = 0;
373
		goto err;
374
	}
375
376
377
	/* r->length is now the compressed data plus mac */
378

1464
	if ((sess != NULL) && (s->enc_read_ctx != NULL) &&
379
192
	    (EVP_MD_CTX_md(s->read_hash) != NULL)) {
380
		/* s->read_hash != NULL => mac_size != -1 */
381
		unsigned char *mac = NULL;
382
192
		unsigned char mac_tmp[EVP_MAX_MD_SIZE];
383
192
		mac_size = EVP_MD_CTX_size(s->read_hash);
384
192
		OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
385
386
		/* kludge: *_cbc_remove_padding passes padding length in rr->type */
387
192
		orig_len = rr->length + ((unsigned int)rr->type >> 8);
388
389
		/* orig_len is the length of the record before any padding was
390
		 * removed. This is public information, as is the MAC in use,
391
		 * therefore we can safely process the record in a different
392
		 * amount of time if it's too short to possibly contain a MAC.
393
		 */
394

352
		if (orig_len < mac_size ||
395
			/* CBC records must have a padding length byte too. */
396
192
		    (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
397
160
		    orig_len < mac_size + 1)) {
398
			al = SSL_AD_DECODE_ERROR;
399
			SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
400
			goto f_err;
401
		}
402
403
192
		if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
404
			/* We update the length so that the TLS header bytes
405
			 * can be constructed correctly but we need to extract
406
			 * the MAC in constant time from within the record,
407
			 * without leaking the contents of the padding bytes.
408
			 * */
409
160
			mac = mac_tmp;
410
160
			ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
411
160
			rr->length -= mac_size;
412
160
		} else {
413
			/* In this case there's no padding, so |orig_len|
414
			 * equals |rec->length| and we checked that there's
415
			 * enough bytes for |mac_size| above. */
416
32
			rr->length -= mac_size;
417
32
			mac = &rr->data[rr->length];
418
		}
419
420
192
		i = tls1_mac(s, md, 0 /* not send */);
421

384
		if (i < 0 || mac == NULL || timingsafe_memcmp(md, mac, (size_t)mac_size) != 0)
422
			enc_err = -1;
423
192
		if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
424
			enc_err = -1;
425
768
	}
426
427
660
	if (enc_err < 0) {
428
		/* decryption failed, silently discard message */
429
		rr->length = 0;
430
		s->internal->packet_length = 0;
431
		goto err;
432
	}
433
434
660
	if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
435
		al = SSL_AD_RECORD_OVERFLOW;
436
		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
437
		goto f_err;
438
	}
439
440
660
	rr->off = 0;
441
	/* So at this point the following is true
442
	 * ssl->s3->internal->rrec.type 	is the type of record
443
	 * ssl->s3->internal->rrec.length	== number of bytes in record
444
	 * ssl->s3->internal->rrec.off	== offset to first valid byte
445
	 * ssl->s3->internal->rrec.data	== where to take bytes from, increment
446
	 *			   after use :-).
447
	 */
448
449
	/* we have pulled in a full packet so zero things */
450
660
	s->internal->packet_length = 0;
451
660
	return (1);
452
453
f_err:
454
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
455
err:
456
	return (0);
457
660
}
458
459
460
/* Call this to get a new input record.
461
 * It will return <= 0 if more data is needed, normally due to an error
462
 * or non-blocking IO.
463
 * When it finishes, one packet has been decoded and can be found in
464
 * ssl->s3->internal->rrec.type    - is the type of record
465
 * ssl->s3->internal->rrec.data, 	 - data
466
 * ssl->s3->internal->rrec.length, - number of bytes
467
 */
468
/* used only by dtls1_read_bytes */
469
int
470
dtls1_get_record(SSL *s)
471
{
472
	SSL3_RECORD *rr;
473
	unsigned char *p = NULL;
474
	DTLS1_BITMAP *bitmap;
475
1712
	unsigned int is_next_epoch;
476
	int n;
477
478
856
	rr = &(S3I(s)->rrec);
479
480
	/* The epoch may have changed.  If so, process all the
481
	 * pending records.  This is a non-blocking operation. */
482
856
	if (dtls1_process_buffered_records(s) < 0)
483
		return (-1);
484
485
	/* if we're renegotiating, then there may be buffered records */
486
856
	if (dtls1_get_processed_record(s))
487
		return 1;
488
489
	/* get something from the wire */
490
	if (0) {
491
again:
492
		/* dump this record on all retries */
493
4
		rr->length = 0;
494
4
		s->internal->packet_length = 0;
495
4
	}
496
497
	/* check if we have the header */
498

860
	if ((s->internal->rstate != SSL_ST_READ_BODY) ||
499
	    (s->internal->packet_length < DTLS1_RT_HEADER_LENGTH)) {
500
860
		CBS header, seq_no;
501
860
		uint16_t epoch, len, ssl_version;
502
860
		uint8_t type;
503
504
860
		n = ssl3_packet_read(s, DTLS1_RT_HEADER_LENGTH);
505
860
		if (n <= 0)
506
196
			return (n);
507
508
		/* If this packet contained a partial record, dump it. */
509
664
		if (n != DTLS1_RT_HEADER_LENGTH)
510
4
			goto again;
511
512
660
		s->internal->rstate = SSL_ST_READ_BODY;
513
514
660
		CBS_init(&header, s->internal->packet, s->internal->packet_length);
515
516
		/* Pull apart the header into the DTLS1_RECORD */
517
660
		if (!CBS_get_u8(&header, &type))
518
			goto again;
519
660
		if (!CBS_get_u16(&header, &ssl_version))
520
			goto again;
521
522
		/* sequence number is 64 bits, with top 2 bytes = epoch */
523

1320
		if (!CBS_get_u16(&header, &epoch) ||
524
660
		    !CBS_get_bytes(&header, &seq_no, 6))
525
			goto again;
526
527
660
		if (!CBS_write_bytes(&seq_no, &(S3I(s)->read_sequence[2]),
528
		    sizeof(S3I(s)->read_sequence) - 2, NULL))
529
			goto again;
530
660
		if (!CBS_get_u16(&header, &len))
531
			goto again;
532
533
660
		rr->type = type;
534
660
		rr->epoch = epoch;
535
660
		rr->length = len;
536
537
		/* unexpected version, silently discard */
538

1224
		if (!s->internal->first_packet && ssl_version != s->version)
539
			goto again;
540
541
		/* wrong version, silently discard record */
542
660
		if ((ssl_version & 0xff00) != (s->version & 0xff00))
543
			goto again;
544
545
		/* record too long, silently discard it */
546
660
		if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
547
			goto again;
548
549
		/* now s->internal->rstate == SSL_ST_READ_BODY */
550
660
		p = (unsigned char *)CBS_data(&header);
551
2180
	}
552
553
	/* s->internal->rstate == SSL_ST_READ_BODY, get and decode the data */
554
555
660
	n = ssl3_packet_extend(s, DTLS1_RT_HEADER_LENGTH + rr->length);
556
660
	if (n <= 0)
557
		return (n);
558
559
	/* If this packet contained a partial record, dump it. */
560
660
	if (n != DTLS1_RT_HEADER_LENGTH + rr->length)
561
		goto again;
562
563
660
	s->internal->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
564
565
	/* match epochs.  NULL means the packet is dropped on the floor */
566
660
	bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
567
660
	if (bitmap == NULL)
568
		goto again;
569
570
	/*
571
	 * Check whether this is a repeat, or aged record.
572
	 * Don't check if we're listening and this message is
573
	 * a ClientHello. They can look as if they're replayed,
574
	 * since they arrive from different connections and
575
	 * would be dropped unnecessarily.
576
	 */
577

1320
	if (!(D1I(s)->listen && rr->type == SSL3_RT_HANDSHAKE &&
578
	    p != NULL && *p == SSL3_MT_CLIENT_HELLO) &&
579
660
	    !dtls1_record_replay_check(s, bitmap))
580
		goto again;
581
582
	/* just read a 0 length packet */
583
660
	if (rr->length == 0)
584
		goto again;
585
586
	/* If this record is from the next epoch (either HM or ALERT),
587
	 * and a handshake is currently in progress, buffer it since it
588
	 * cannot be processed at this time. However, do not buffer
589
	 * anything while listening.
590
	 */
591
660
	if (is_next_epoch) {
592
		if ((SSL_in_init(s) || s->internal->in_handshake) && !D1I(s)->listen) {
593
			if (dtls1_buffer_record(s, &(D1I(s)->unprocessed_rcds),
594
			    rr->seq_num) < 0)
595
				return (-1);
596
			/* Mark receipt of record. */
597
			dtls1_record_bitmap_update(s, bitmap);
598
		}
599
		goto again;
600
	}
601
602
660
	if (!dtls1_process_record(s))
603
		goto again;
604
605
	/* Mark receipt of record. */
606
660
	dtls1_record_bitmap_update(s, bitmap);
607
608
660
	return (1);
609
856
}
610
611
/* Return up to 'len' payload bytes received in 'type' records.
612
 * 'type' is one of the following:
613
 *
614
 *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
615
 *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
616
 *   -  0 (during a shutdown, no data has to be returned)
617
 *
618
 * If we don't have stored data to work from, read a SSL/TLS record first
619
 * (possibly multiple records if we still don't have anything to return).
620
 *
621
 * This function must handle any surprises the peer may have for us, such as
622
 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
623
 * a surprise, but handled as if it were), or renegotiation requests.
624
 * Also if record payloads contain fragments too small to process, we store
625
 * them until there is enough for the respective protocol (the record protocol
626
 * may use arbitrary fragmentation and even interleaving):
627
 *     Change cipher spec protocol
628
 *             just 1 byte needed, no need for keeping anything stored
629
 *     Alert protocol
630
 *             2 bytes needed (AlertLevel, AlertDescription)
631
 *     Handshake protocol
632
 *             4 bytes needed (HandshakeType, uint24 length) -- we just have
633
 *             to detect unexpected Client Hello and Hello Request messages
634
 *             here, anything else is handled by higher layers
635
 *     Application data protocol
636
 *             none of our business
637
 */
638
int
639
dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
640
{
641
	int al, i, j, ret;
642
	unsigned int n;
643
	SSL3_RECORD *rr;
644
	void (*cb)(const SSL *ssl, int type2, int val) = NULL;
645
646
2456
	if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
647
48
		if (!ssl3_setup_buffers(s))
648
			return (-1);
649
650
3684
	if ((type &&
651
2456
	     type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
652
1228
	    (peek && (type != SSL3_RT_APPLICATION_DATA))) {
653
		SSLerror(s, ERR_R_INTERNAL_ERROR);
654
		return -1;
655
	}
656
657
	/* check whether there's a handshake message (client hello?) waiting */
658
1228
	if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
659
		return ret;
660
661
	/* Now D1I(s)->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
662
663

1420
	if (!s->internal->in_handshake && SSL_in_init(s))
664
	{
665
		/* type == SSL3_RT_APPLICATION_DATA */
666
96
		i = s->internal->handshake_func(s);
667
96
		if (i < 0)
668
48
			return (i);
669
48
		if (i == 0) {
670
			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
671
			return (-1);
672
		}
673
	}
674
675
start:
676
1276
	s->internal->rwstate = SSL_NOTHING;
677
678
	/* S3I(s)->rrec.type	    - is the type of record
679
	 * S3I(s)->rrec.data,    - data
680
	 * S3I(s)->rrec.off,     - offset into 'data' for next read
681
	 * S3I(s)->rrec.length,  - number of bytes. */
682
1276
	rr = &(S3I(s)->rrec);
683
684
	/* We are not handshaking and have no data yet,
685
	 * so process data buffered during the last handshake
686
	 * in advance, if any.
687
	 */
688

1420
	if (S3I(s)->hs.state == SSL_ST_OK && rr->length == 0) {
689
		pitem *item;
690
144
		item = pqueue_pop(D1I(s)->buffered_app_data.q);
691
144
		if (item) {
692
693
			dtls1_copy_record(s, item);
694
695
			free(item->data);
696
			pitem_free(item);
697
		}
698
144
	}
699
700
	/* Check for timeout */
701
1276
	if (dtls1_handle_timeout(s) > 0)
702
		goto start;
703
704
	/* get new packet if necessary */
705

1696
	if ((rr->length == 0) || (s->internal->rstate == SSL_ST_READ_BODY)) {
706
856
		ret = dtls1_get_record(s);
707
856
		if (ret <= 0) {
708
196
			ret = dtls1_read_failed(s, ret);
709
			/* anything other than a timeout is an error */
710
196
			if (ret <= 0)
711
196
				return (ret);
712
			else
713
				goto start;
714
		}
715
	}
716
717

1080
	if (D1I(s)->listen && rr->type != SSL3_RT_HANDSHAKE) {
718
		rr->length = 0;
719
		goto start;
720
	}
721
722
	/* we now have a packet which can be read and processed */
723
724
1272
	if (S3I(s)->change_cipher_spec /* set when we receive ChangeCipherSpec,
725
	                               * reset by ssl3_get_finished */
726
1272
	    && (rr->type != SSL3_RT_HANDSHAKE)) {
727
		/* We now have application data between CCS and Finished.
728
		 * Most likely the packets were reordered on their way, so
729
		 * buffer the application data for later processing rather
730
		 * than dropping the connection.
731
		 */
732
		if (dtls1_buffer_record(s, &(D1I(s)->buffered_app_data),
733
		    rr->seq_num) < 0) {
734
			SSLerror(s, ERR_R_INTERNAL_ERROR);
735
			return (-1);
736
		}
737
		rr->length = 0;
738
		goto start;
739
	}
740
741
	/* If the other end has shut down, throw anything we read away
742
	 * (even in 'peek' mode) */
743
1080
	if (s->internal->shutdown & SSL_RECEIVED_SHUTDOWN) {
744
		rr->length = 0;
745
		s->internal->rwstate = SSL_NOTHING;
746
		return (0);
747
	}
748
749
750
1080
	if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
751
	{
752
		/* make sure that we are not getting application data when we
753
		 * are doing a handshake for the first time */
754

984
		if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
755
			(s->enc_read_ctx == NULL)) {
756
			al = SSL_AD_UNEXPECTED_MESSAGE;
757
			SSLerror(s, SSL_R_APP_DATA_IN_HANDSHAKE);
758
			goto f_err;
759
		}
760
761
984
		if (len <= 0)
762
			return (len);
763
764
984
		if ((unsigned int)len > rr->length)
765
96
			n = rr->length;
766
		else
767
			n = (unsigned int)len;
768
769
984
		memcpy(buf, &(rr->data[rr->off]), n);
770
984
		if (!peek) {
771
984
			rr->length -= n;
772
984
			rr->off += n;
773
984
			if (rr->length == 0) {
774
564
				s->internal->rstate = SSL_ST_READ_HEADER;
775
564
				rr->off = 0;
776
564
			}
777
		}
778
779
984
		return (n);
780
	}
781
782
783
	/* If we get here, then type != rr->type; if we have a handshake
784
	 * message, then it was unexpected (Hello Request or Client Hello). */
785
786
	/* In case of record types for which we have 'fragment' storage,
787
	 * fill that so that we can process the data at a fixed place.
788
	 */
789
	{
790
		unsigned int k, dest_maxlen = 0;
791
		unsigned char *dest = NULL;
792
		unsigned int *dest_len = NULL;
793
794
96
		if (rr->type == SSL3_RT_HANDSHAKE) {
795
			dest_maxlen = sizeof D1I(s)->handshake_fragment;
796
			dest = D1I(s)->handshake_fragment;
797
			dest_len = &D1I(s)->handshake_fragment_len;
798
96
		} else if (rr->type == SSL3_RT_ALERT) {
799
			dest_maxlen = sizeof(D1I(s)->alert_fragment);
800
			dest = D1I(s)->alert_fragment;
801
			dest_len = &D1I(s)->alert_fragment_len;
802
		}
803
		/* else it's a CCS message, or application data or wrong */
804
96
		else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
805
			/* Application data while renegotiating
806
			 * is allowed. Try again reading.
807
			 */
808
			if (rr->type == SSL3_RT_APPLICATION_DATA) {
809
				BIO *bio;
810
				S3I(s)->in_read_app_data = 2;
811
				bio = SSL_get_rbio(s);
812
				s->internal->rwstate = SSL_READING;
813
				BIO_clear_retry_flags(bio);
814
				BIO_set_retry_read(bio);
815
				return (-1);
816
			}
817
818
			/* Not certain if this is the right error handling */
819
			al = SSL_AD_UNEXPECTED_MESSAGE;
820
			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
821
			goto f_err;
822
		}
823
824
96
		if (dest_maxlen > 0) {
825
            /* XDTLS:  In a pathalogical case, the Client Hello
826
             *  may be fragmented--don't always expect dest_maxlen bytes */
827
			if (rr->length < dest_maxlen) {
828
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
829
				/*
830
				 * for normal alerts rr->length is 2, while
831
				 * dest_maxlen is 7 if we were to handle this
832
				 * non-existing alert...
833
				 */
834
				FIX ME
835
#endif
836
				s->internal->rstate = SSL_ST_READ_HEADER;
837
				rr->length = 0;
838
				goto start;
839
			}
840
841
			/* now move 'n' bytes: */
842
			for ( k = 0; k < dest_maxlen; k++) {
843
				dest[k] = rr->data[rr->off++];
844
				rr->length--;
845
			}
846
			*dest_len = dest_maxlen;
847
		}
848

96
	}
849
850
	/* D1I(s)->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
851
	 * D1I(s)->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
852
	 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
853
854
	/* If we are a client, check for an incoming 'Hello Request': */
855

96
	if ((!s->server) &&
856
48
	    (D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
857
	    (D1I(s)->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
858
	    (s->session != NULL) && (s->session->cipher != NULL)) {
859
		D1I(s)->handshake_fragment_len = 0;
860
861
		if ((D1I(s)->handshake_fragment[1] != 0) ||
862
		    (D1I(s)->handshake_fragment[2] != 0) ||
863
		    (D1I(s)->handshake_fragment[3] != 0)) {
864
			al = SSL_AD_DECODE_ERROR;
865
			SSLerror(s, SSL_R_BAD_HELLO_REQUEST);
866
			goto err;
867
		}
868
869
		/* no need to check sequence number on HELLO REQUEST messages */
870
871
		if (s->internal->msg_callback)
872
			s->internal->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
873
		D1I(s)->handshake_fragment, 4, s, s->internal->msg_callback_arg);
874
875
		if (SSL_is_init_finished(s) &&
876
		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
877
		    !S3I(s)->renegotiate) {
878
			D1I(s)->handshake_read_seq++;
879
			s->internal->new_session = 1;
880
			ssl3_renegotiate(s);
881
			if (ssl3_renegotiate_check(s)) {
882
				i = s->internal->handshake_func(s);
883
				if (i < 0)
884
					return (i);
885
				if (i == 0) {
886
					SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
887
					return (-1);
888
				}
889
890
				if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
891
					if (s->s3->rbuf.left == 0) /* no read-ahead left? */
892
					{
893
						BIO *bio;
894
						/* In the case where we try to read application data,
895
						 * but we trigger an SSL handshake, we return -1 with
896
						 * the retry option set.  Otherwise renegotiation may
897
						 * cause nasty problems in the blocking world */
898
						s->internal->rwstate = SSL_READING;
899
						bio = SSL_get_rbio(s);
900
						BIO_clear_retry_flags(bio);
901
						BIO_set_retry_read(bio);
902
						return (-1);
903
					}
904
				}
905
			}
906
		}
907
		/* we either finished a handshake or ignored the request,
908
		 * now try again to obtain the (application) data we were asked for */
909
		goto start;
910
	}
911
912
96
	if (D1I(s)->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
913
		int alert_level = D1I(s)->alert_fragment[0];
914
		int alert_descr = D1I(s)->alert_fragment[1];
915
916
		D1I(s)->alert_fragment_len = 0;
917
918
		if (s->internal->msg_callback)
919
			s->internal->msg_callback(0, s->version, SSL3_RT_ALERT,
920
		D1I(s)->alert_fragment, 2, s, s->internal->msg_callback_arg);
921
922
		if (s->internal->info_callback != NULL)
923
			cb = s->internal->info_callback;
924
		else if (s->ctx->internal->info_callback != NULL)
925
			cb = s->ctx->internal->info_callback;
926
927
		if (cb != NULL) {
928
			j = (alert_level << 8) | alert_descr;
929
			cb(s, SSL_CB_READ_ALERT, j);
930
		}
931
932
		if (alert_level == 1) /* warning */
933
		{
934
			S3I(s)->warn_alert = alert_descr;
935
			if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
936
				s->internal->shutdown |= SSL_RECEIVED_SHUTDOWN;
937
				return (0);
938
			}
939
		} else if (alert_level == 2) /* fatal */
940
		{
941
			s->internal->rwstate = SSL_NOTHING;
942
			S3I(s)->fatal_alert = alert_descr;
943
			SSLerror(s, SSL_AD_REASON_OFFSET + alert_descr);
944
			ERR_asprintf_error_data("SSL alert number %d",
945
			    alert_descr);
946
			s->internal->shutdown|=SSL_RECEIVED_SHUTDOWN;
947
			SSL_CTX_remove_session(s->ctx, s->session);
948
			return (0);
949
		} else {
950
			al = SSL_AD_ILLEGAL_PARAMETER;
951
			SSLerror(s, SSL_R_UNKNOWN_ALERT_TYPE);
952
			goto f_err;
953
		}
954
955
		goto start;
956
	}
957
958
96
	if (s->internal->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
959
	{
960
		s->internal->rwstate = SSL_NOTHING;
961
		rr->length = 0;
962
		return (0);
963
	}
964
965
96
	if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
966
96
		struct ccs_header_st ccs_hdr;
967
		unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
968
969
96
		dtls1_get_ccs_header(rr->data, &ccs_hdr);
970
971
		/* 'Change Cipher Spec' is just a single byte, so we know
972
		 * exactly what the record payload has to look like */
973
		/* XDTLS: check that epoch is consistent */
974

192
		if ((rr->length != ccs_hdr_len) ||
975
192
		    (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
976
			i = SSL_AD_ILLEGAL_PARAMETER;
977
			SSLerror(s, SSL_R_BAD_CHANGE_CIPHER_SPEC);
978
			goto err;
979
		}
980
981
96
		rr->length = 0;
982
983
96
		if (s->internal->msg_callback)
984
			s->internal->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
985
		rr->data, 1, s, s->internal->msg_callback_arg);
986
987
		/* We can't process a CCS now, because previous handshake
988
		 * messages are still missing, so just drop it.
989
		 */
990
96
		if (!D1I(s)->change_cipher_spec_ok) {
991
			goto start;
992
		}
993
994
96
		D1I(s)->change_cipher_spec_ok = 0;
995
996
96
		S3I(s)->change_cipher_spec = 1;
997
96
		if (!ssl3_do_change_cipher_spec(s))
998
			goto err;
999
1000
		/* do this whenever CCS is processed */
1001
96
		dtls1_reset_seq_numbers(s, SSL3_CC_READ);
1002
1003
96
		goto start;
1004
912
	}
1005
1006
	/* Unexpected handshake message (Client Hello, or protocol violation) */
1007
	if ((D1I(s)->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
1008
	    !s->internal->in_handshake) {
1009
		struct hm_header_st msg_hdr;
1010
1011
		/* this may just be a stale retransmit */
1012
		if (!dtls1_get_message_header(rr->data, &msg_hdr))
1013
			return -1;
1014
		if (rr->epoch != D1I(s)->r_epoch) {
1015
			rr->length = 0;
1016
			goto start;
1017
		}
1018
1019
		/* If we are server, we may have a repeated FINISHED of the
1020
		 * client here, then retransmit our CCS and FINISHED.
1021
		 */
1022
		if (msg_hdr.type == SSL3_MT_FINISHED) {
1023
			if (dtls1_check_timeout_num(s) < 0)
1024
				return -1;
1025
1026
			dtls1_retransmit_buffered_messages(s);
1027
			rr->length = 0;
1028
			goto start;
1029
		}
1030
1031
		if (((S3I(s)->hs.state&SSL_ST_MASK) == SSL_ST_OK) &&
1032
		    !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1033
			S3I(s)->hs.state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1034
			s->internal->renegotiate = 1;
1035
			s->internal->new_session = 1;
1036
		}
1037
		i = s->internal->handshake_func(s);
1038
		if (i < 0)
1039
			return (i);
1040
		if (i == 0) {
1041
			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1042
			return (-1);
1043
		}
1044
1045
		if (!(s->internal->mode & SSL_MODE_AUTO_RETRY)) {
1046
			if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1047
			{
1048
				BIO *bio;
1049
				/* In the case where we try to read application data,
1050
				 * but we trigger an SSL handshake, we return -1 with
1051
				 * the retry option set.  Otherwise renegotiation may
1052
				 * cause nasty problems in the blocking world */
1053
				s->internal->rwstate = SSL_READING;
1054
				bio = SSL_get_rbio(s);
1055
				BIO_clear_retry_flags(bio);
1056
				BIO_set_retry_read(bio);
1057
				return (-1);
1058
			}
1059
		}
1060
		goto start;
1061
	}
1062
1063
	switch (rr->type) {
1064
	default:
1065
		/* TLS just ignores unknown message types */
1066
		if (s->version == TLS1_VERSION) {
1067
			rr->length = 0;
1068
			goto start;
1069
		}
1070
		al = SSL_AD_UNEXPECTED_MESSAGE;
1071
		SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1072
		goto f_err;
1073
	case SSL3_RT_CHANGE_CIPHER_SPEC:
1074
	case SSL3_RT_ALERT:
1075
	case SSL3_RT_HANDSHAKE:
1076
		/* we already handled all of these, with the possible exception
1077
		 * of SSL3_RT_HANDSHAKE when s->internal->in_handshake is set, but that
1078
		 * should not happen when type != rr->type */
1079
		al = SSL_AD_UNEXPECTED_MESSAGE;
1080
		SSLerror(s, ERR_R_INTERNAL_ERROR);
1081
		goto f_err;
1082
	case SSL3_RT_APPLICATION_DATA:
1083
		/* At this point, we were expecting handshake data,
1084
		 * but have application data.  If the library was
1085
		 * running inside ssl3_read() (i.e. in_read_app_data
1086
		 * is set) and it makes sense to read application data
1087
		 * at this point (session renegotiation not yet started),
1088
		 * we will indulge it.
1089
		 */
1090
		if (S3I(s)->in_read_app_data &&
1091
		    (S3I(s)->total_renegotiations != 0) &&
1092
		    (((S3I(s)->hs.state & SSL_ST_CONNECT) &&
1093
		    (S3I(s)->hs.state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1094
		    (S3I(s)->hs.state <= SSL3_ST_CR_SRVR_HELLO_A)) || (
1095
		    (S3I(s)->hs.state & SSL_ST_ACCEPT) &&
1096
		    (S3I(s)->hs.state <= SSL3_ST_SW_HELLO_REQ_A) &&
1097
		    (S3I(s)->hs.state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1098
			S3I(s)->in_read_app_data = 2;
1099
			return (-1);
1100
		} else {
1101
			al = SSL_AD_UNEXPECTED_MESSAGE;
1102
			SSLerror(s, SSL_R_UNEXPECTED_RECORD);
1103
			goto f_err;
1104
		}
1105
	}
1106
	/* not reached */
1107
1108
f_err:
1109
	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1110
err:
1111
	return (-1);
1112
1228
}
1113
1114
int
1115
dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
1116
{
1117
	int i;
1118
1119

528
	if (SSL_in_init(s) && !s->internal->in_handshake)
1120
	{
1121
144
		i = s->internal->handshake_func(s);
1122
144
		if (i < 0)
1123
96
			return (i);
1124
48
		if (i == 0) {
1125
			SSLerror(s, SSL_R_SSL_HANDSHAKE_FAILURE);
1126
			return -1;
1127
		}
1128
	}
1129
1130
96
	if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
1131
		SSLerror(s, SSL_R_DTLS_MESSAGE_TOO_BIG);
1132
		return -1;
1133
	}
1134
1135
96
	i = dtls1_write_bytes(s, type, buf_, len);
1136
96
	return i;
1137
192
}
1138
1139
1140
	/* this only happens when a client hello is received and a handshake
1141
	 * is started. */
1142
static int
1143
have_handshake_fragment(SSL *s, int type, unsigned char *buf,
1144
    int len, int peek)
1145
{
1146
1147

3492
	if ((type == SSL3_RT_HANDSHAKE) && (D1I(s)->handshake_fragment_len > 0))
1148
		/* (partially) satisfy request from storage */
1149
	{
1150
		unsigned char *src = D1I(s)->handshake_fragment;
1151
		unsigned char *dst = buf;
1152
		unsigned int k, n;
1153
1154
		/* peek == 0 */
1155
		n = 0;
1156
		while ((len > 0) && (D1I(s)->handshake_fragment_len > 0)) {
1157
			*dst++ = *src++;
1158
			len--;
1159
			D1I(s)->handshake_fragment_len--;
1160
			n++;
1161
		}
1162
		/* move any remaining fragment bytes: */
1163
		for (k = 0; k < D1I(s)->handshake_fragment_len; k++)
1164
			D1I(s)->handshake_fragment[k] = *src++;
1165
		return n;
1166
	}
1167
1168
1228
	return 0;
1169
1228
}
1170
1171
1172
/* Call this to write data in records of type 'type'
1173
 * It will return <= 0 if not all data has been sent or non-blocking IO.
1174
 */
1175
int
1176
dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
1177
{
1178
	int i;
1179
1180
1328
	OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
1181
664
	s->internal->rwstate = SSL_NOTHING;
1182
664
	i = do_dtls1_write(s, type, buf, len);
1183
664
	return i;
1184
}
1185
1186
int
1187
do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len)
1188
{
1189
	unsigned char *p, *pseq;
1190
	int i, mac_size, clear = 0;
1191
	int prefix_len = 0;
1192
	SSL3_RECORD *wr;
1193
	SSL3_BUFFER *wb;
1194
	SSL_SESSION *sess;
1195
	int bs;
1196
1197
	/* first check if there is a SSL3_BUFFER still being written
1198
	 * out.  This will happen with non blocking IO */
1199
1520
	if (s->s3->wbuf.left != 0) {
1200
		OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
1201
		return (ssl3_write_pending(s, type, buf, len));
1202
	}
1203
1204
	/* If we have an alert to send, lets send it */
1205
760
	if (s->s3->alert_dispatch) {
1206
		i = s->method->ssl_dispatch_alert(s);
1207
		if (i <= 0)
1208
			return (i);
1209
		/* if it went, fall through and send more stuff */
1210
	}
1211
1212
760
	if (len == 0)
1213
		return 0;
1214
1215
760
	wr = &(S3I(s)->wrec);
1216
760
	wb = &(s->s3->wbuf);
1217
760
	sess = s->session;
1218
1219

1808
	if ((sess == NULL) || (s->internal->enc_write_ctx == NULL) ||
1220
288
	    (EVP_MD_CTX_md(s->internal->write_hash) == NULL))
1221
472
		clear = 1;
1222
1223
760
	if (clear)
1224
472
		mac_size = 0;
1225
	else {
1226
288
		mac_size = EVP_MD_CTX_size(s->internal->write_hash);
1227
288
		if (mac_size < 0)
1228
			goto err;
1229
	}
1230
1231
	/* DTLS implements explicit IV, so no need for empty fragments. */
1232
1233
760
	p = wb->buf + prefix_len;
1234
1235
	/* write the header */
1236
1237
760
	*(p++) = type&0xff;
1238
760
	wr->type = type;
1239
1240
760
	*(p++) = (s->version >> 8);
1241
760
	*(p++) = s->version&0xff;
1242
1243
	/* field where we are to write out packet epoch, seq num and len */
1244
	pseq = p;
1245
1246
760
	p += 10;
1247
1248
	/* lets setup the record stuff. */
1249
1250
	/* Make space for the explicit IV in case of CBC.
1251
	 * (this is a bit of a boundary violation, but what the heck).
1252
	 */
1253

1048
	if (s->internal->enc_write_ctx &&
1254
288
	    (EVP_CIPHER_mode(s->internal->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
1255
240
		bs = EVP_CIPHER_block_size(s->internal->enc_write_ctx->cipher);
1256
	else
1257
		bs = 0;
1258
1259
760
	wr->data = p + bs;
1260
	/* make room for IV in case of CBC */
1261
760
	wr->length = (int)len;
1262
760
	wr->input = (unsigned char *)buf;
1263
1264
	/* we now 'read' from wr->input, wr->length bytes into
1265
	 * wr->data */
1266
1267
760
	memcpy(wr->data, wr->input, wr->length);
1268
760
	wr->input = wr->data;
1269
1270
	/* we should still have the output to wr->data and the input
1271
	 * from wr->input.  Length should be wr->length.
1272
	 * wr->data still points in the wb->buf */
1273
1274
760
	if (mac_size != 0) {
1275
288
		if (tls1_mac(s, &(p[wr->length + bs]), 1) < 0)
1276
			goto err;
1277
288
		wr->length += mac_size;
1278
288
	}
1279
1280
	/* this is true regardless of mac size */
1281
760
	wr->input = p;
1282
760
	wr->data = p;
1283
1284
1285
	/* ssl3_enc can only have an error on read */
1286
760
	if (bs)	/* bs != 0 in case of CBC */
1287
	{
1288
240
		arc4random_buf(p, bs);
1289
		/* master IV and last CBC residue stand for
1290
		 * the rest of randomness */
1291
240
		wr->length += bs;
1292
240
	}
1293
1294
760
	s->method->internal->ssl3_enc->enc(s, 1);
1295
1296
	/* record length after mac and block padding */
1297
/*	if (type == SSL3_RT_APPLICATION_DATA ||
1298
	(type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
1299
1300
	/* there's only one epoch between handshake and app data */
1301
1302
760
	s2n(D1I(s)->w_epoch, pseq);
1303
1304
	/* XDTLS: ?? */
1305
/*	else
1306
	s2n(D1I(s)->handshake_epoch, pseq);
1307
*/
1308
1309
760
	memcpy(pseq, &(S3I(s)->write_sequence[2]), 6);
1310
760
	pseq += 6;
1311
760
	s2n(wr->length, pseq);
1312
1313
	/* we should now have
1314
	 * wr->data pointing to the encrypted data, which is
1315
	 * wr->length long */
1316
760
	wr->type=type; /* not needed but helps for debugging */
1317
760
	wr->length += DTLS1_RT_HEADER_LENGTH;
1318
1319
760
	tls1_record_sequence_increment(S3I(s)->write_sequence);
1320
1321
	/* now let's set up wb */
1322
760
	wb->left = prefix_len + wr->length;
1323
760
	wb->offset = 0;
1324
1325
	/* memorize arguments so that ssl3_write_pending can detect bad write retries later */
1326
760
	S3I(s)->wpend_tot = len;
1327
760
	S3I(s)->wpend_buf = buf;
1328
760
	S3I(s)->wpend_type = type;
1329
760
	S3I(s)->wpend_ret = len;
1330
1331
	/* we now just need to write the buffer */
1332
760
	return ssl3_write_pending(s, type, buf, len);
1333
err:
1334
	return -1;
1335
760
}
1336
1337
1338
1339
static int
1340
dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
1341
{
1342
	int cmp;
1343
	unsigned int shift;
1344
1320
	const unsigned char *seq = S3I(s)->read_sequence;
1345
1346
660
	cmp = satsub64be(seq, bitmap->max_seq_num);
1347
660
	if (cmp > 0) {
1348
468
		memcpy (S3I(s)->rrec.seq_num, seq, 8);
1349
468
		return 1; /* this record in new */
1350
	}
1351
192
	shift = -cmp;
1352
192
	if (shift >= sizeof(bitmap->map)*8)
1353
		return 0; /* stale, outside the window */
1354
192
	else if (bitmap->map & (1UL << shift))
1355
		return 0; /* record previously received */
1356
1357
192
	memcpy(S3I(s)->rrec.seq_num, seq, 8);
1358
192
	return 1;
1359
660
}
1360
1361
1362
static void
1363
dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
1364
{
1365
	int cmp;
1366
	unsigned int shift;
1367
1320
	const unsigned char *seq = S3I(s)->read_sequence;
1368
1369
660
	cmp = satsub64be(seq, bitmap->max_seq_num);
1370
660
	if (cmp > 0) {
1371
		shift = cmp;
1372
468
		if (shift < sizeof(bitmap->map)*8)
1373
468
			bitmap->map <<= shift, bitmap->map |= 1UL;
1374
		else
1375
			bitmap->map = 1UL;
1376
468
		memcpy(bitmap->max_seq_num, seq, 8);
1377
468
	} else {
1378
192
		shift = -cmp;
1379
192
		if (shift < sizeof(bitmap->map) * 8)
1380
192
			bitmap->map |= 1UL << shift;
1381
	}
1382
660
}
1383
1384
1385
int
1386
dtls1_dispatch_alert(SSL *s)
1387
{
1388
	int i, j;
1389
	void (*cb)(const SSL *ssl, int type, int val) = NULL;
1390
192
	unsigned char buf[DTLS1_AL_HEADER_LENGTH];
1391
96
	unsigned char *ptr = &buf[0];
1392
1393
96
	s->s3->alert_dispatch = 0;
1394
1395
96
	memset(buf, 0x00, sizeof(buf));
1396
96
	*ptr++ = s->s3->send_alert[0];
1397
96
	*ptr++ = s->s3->send_alert[1];
1398
1399
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1400
	if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
1401
		s2n(D1I(s)->handshake_read_seq, ptr);
1402
		l2n3(D1I(s)->r_msg_hdr.frag_off, ptr);
1403
	}
1404
#endif
1405
1406
96
	i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
1407
96
	if (i <= 0) {
1408
96
		s->s3->alert_dispatch = 1;
1409
		/* fprintf( stderr, "not done with alert\n" ); */
1410
96
	} else {
1411
		if (s->s3->send_alert[0] == SSL3_AL_FATAL
1412
#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1413
		|| s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1414
#endif
1415
		)
1416
			(void)BIO_flush(s->wbio);
1417
1418
		if (s->internal->msg_callback)
1419
			s->internal->msg_callback(1, s->version, SSL3_RT_ALERT,
1420
			    s->s3->send_alert, 2, s, s->internal->msg_callback_arg);
1421
1422
		if (s->internal->info_callback != NULL)
1423
			cb = s->internal->info_callback;
1424
		else if (s->ctx->internal->info_callback != NULL)
1425
			cb = s->ctx->internal->info_callback;
1426
1427
		if (cb != NULL) {
1428
			j = (s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1429
			cb(s, SSL_CB_WRITE_ALERT, j);
1430
		}
1431
	}
1432
96
	return (i);
1433
96
}
1434
1435
1436
static DTLS1_BITMAP *
1437
dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
1438
{
1439
1440
1320
	*is_next_epoch = 0;
1441
1442
	/* In current epoch, accept HM, CCS, DATA, & ALERT */
1443
660
	if (rr->epoch == D1I(s)->r_epoch)
1444
660
		return &D1I(s)->bitmap;
1445
1446
	/* Only HM and ALERT messages can be from the next epoch */
1447
	else if (rr->epoch == (unsigned long)(D1I(s)->r_epoch + 1) &&
1448
		(rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1449
		*is_next_epoch = 1;
1450
		return &D1I(s)->next_bitmap;
1451
	}
1452
1453
	return NULL;
1454
660
}
1455
1456
void
1457
dtls1_reset_seq_numbers(SSL *s, int rw)
1458
{
1459
	unsigned char *seq;
1460
	unsigned int seq_bytes = sizeof(S3I(s)->read_sequence);
1461
1462
384
	if (rw & SSL3_CC_READ) {
1463
96
		seq = S3I(s)->read_sequence;
1464
96
		D1I(s)->r_epoch++;
1465
96
		memcpy(&(D1I(s)->bitmap), &(D1I(s)->next_bitmap), sizeof(DTLS1_BITMAP));
1466
96
		memset(&(D1I(s)->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
1467
96
	} else {
1468
96
		seq = S3I(s)->write_sequence;
1469
96
		memcpy(D1I(s)->last_write_sequence, seq, sizeof(S3I(s)->write_sequence));
1470
96
		D1I(s)->w_epoch++;
1471
	}
1472
1473
192
	memset(seq, 0x00, seq_bytes);
1474
192
}