blob: 451a3c24b2e2e7987634816a888b8b6f5fc4e939 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001/* DTLS implementation written by Nagendra Modadugu
2 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */
3/* ====================================================================
4 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
16 * distribution.
17 *
18 * 3. All advertising materials mentioning features or use of this
19 * software must display the following acknowledgment:
20 * "This product includes software developed by the OpenSSL Project
21 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
22 *
23 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
24 * endorse or promote products derived from this software without
25 * prior written permission. For written permission, please contact
26 * openssl-core@openssl.org.
27 *
28 * 5. Products derived from this software may not be called "OpenSSL"
29 * nor may "OpenSSL" appear in their names without prior written
30 * permission of the OpenSSL Project.
31 *
32 * 6. Redistributions of any form whatsoever must retain the following
33 * acknowledgment:
34 * "This product includes software developed by the OpenSSL Project
35 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
38 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
40 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
41 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
43 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
46 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
48 * OF THE POSSIBILITY OF SUCH DAMAGE.
49 * ====================================================================
50 *
51 * This product includes cryptographic software written by Eric Young
52 * (eay@cryptsoft.com). This product includes software written by Tim
53 * Hudson (tjh@cryptsoft.com).
54 *
55 */
56/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
57 * All rights reserved.
58 *
59 * This package is an SSL implementation written
60 * by Eric Young (eay@cryptsoft.com).
61 * The implementation was written so as to conform with Netscapes SSL.
62 *
63 * This library is free for commercial and non-commercial use as long as
64 * the following conditions are aheared to. The following conditions
65 * apply to all code found in this distribution, be it the RC4, RSA,
66 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
67 * included with this distribution is covered by the same copyright terms
68 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
69 *
70 * Copyright remains Eric Young's, and as such any Copyright notices in
71 * the code are not to be removed.
72 * If this package is used in a product, Eric Young should be given attribution
73 * as the author of the parts of the library used.
74 * This can be in the form of a textual message at program startup or
75 * in documentation (online or textual) provided with the package.
76 *
77 * Redistribution and use in source and binary forms, with or without
78 * modification, are permitted provided that the following conditions
79 * are met:
80 * 1. Redistributions of source code must retain the copyright
81 * notice, this list of conditions and the following disclaimer.
82 * 2. Redistributions in binary form must reproduce the above copyright
83 * notice, this list of conditions and the following disclaimer in the
84 * documentation and/or other materials provided with the distribution.
85 * 3. All advertising materials mentioning features or use of this software
86 * must display the following acknowledgement:
87 * "This product includes cryptographic software written by
88 * Eric Young (eay@cryptsoft.com)"
89 * The word 'cryptographic' can be left out if the rouines from the library
90 * being used are not cryptographic related :-).
91 * 4. If you include any Windows specific code (or a derivative thereof) from
92 * the apps directory (application code) you must include an acknowledgement:
93 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
94 *
95 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
96 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
97 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
98 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
99 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
100 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
101 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
102 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
103 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
104 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
105 * SUCH DAMAGE.
106 *
107 * The licence and distribution terms for any publically available version or
108 * derivative of this code cannot be changed. i.e. this code cannot simply be
109 * copied and put under another distribution licence
110 * [including the GNU Public Licence.] */
111
112#include <stdio.h>
113#include <errno.h>
114#include <assert.h>
115
116#include <openssl/buf.h>
117#include <openssl/mem.h>
118#include <openssl/evp.h>
119#include <openssl/err.h>
120#include <openssl/rand.h>
121
122#include "ssl_locl.h"
Adam Langley71d8a082014-12-13 16:28:18 -0800123
124
Adam Langley95c29f32014-06-20 12:00:00 -0700125/* mod 128 saturating subtract of two 64-bit values in big-endian order */
Adam Langley71d8a082014-12-13 16:28:18 -0800126static int satsub64be(const uint8_t *v1, const uint8_t *v2) {
127 int ret, sat, brw, i;
Adam Langley95c29f32014-06-20 12:00:00 -0700128
Adam Langley71d8a082014-12-13 16:28:18 -0800129 if (sizeof(long) == 8) {
130 do {
131 const union {
132 long one;
133 char little;
134 } is_endian = {1};
135 long l;
Adam Langley95c29f32014-06-20 12:00:00 -0700136
Adam Langley71d8a082014-12-13 16:28:18 -0800137 if (is_endian.little) {
138 break;
139 }
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 }
Adam Langley95c29f32014-06-20 12:00:00 -0700146
Adam Langley71d8a082014-12-13 16:28:18 -0800147 l = *((long *)v1);
148 l -= *((long *)v2);
149 if (l > 128) {
150 return 128;
151 } else if (l < -128) {
152 return -128;
153 } else {
154 return (int)l;
155 }
156 } while (0);
157 }
Adam Langley95c29f32014-06-20 12:00:00 -0700158
Adam Langley71d8a082014-12-13 16:28:18 -0800159 ret = (int)v1[7] - (int)v2[7];
160 sat = 0;
161 brw = ret >> 8; /* brw is either 0 or -1 */
162 if (ret & 0x80) {
163 for (i = 6; i >= 0; i--) {
164 brw += (int)v1[i] - (int)v2[i];
165 sat |= ~brw;
166 brw >>= 8;
167 }
168 } else {
169 for (i = 6; i >= 0; i--) {
170 brw += (int)v1[i] - (int)v2[i];
171 sat |= brw;
172 brw >>= 8;
173 }
174 }
175 brw <<= 8; /* brw is either 0 or -256 */
Adam Langley95c29f32014-06-20 12:00:00 -0700176
Adam Langley71d8a082014-12-13 16:28:18 -0800177 if (sat & 0xff) {
178 return brw | 0x80;
179 } else {
180 return brw + (ret & 0xFF);
181 }
Adam Langley95c29f32014-06-20 12:00:00 -0700182}
183
Adam Langley71d8a082014-12-13 16:28:18 -0800184static int have_handshake_fragment(SSL *s, int type, uint8_t *buf, int len,
185 int peek);
Adam Langley95c29f32014-06-20 12:00:00 -0700186static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
187static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
Adam Langley71d8a082014-12-13 16:28:18 -0800188static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
189 unsigned int *is_next_epoch);
Adam Langley95c29f32014-06-20 12:00:00 -0700190static int dtls1_buffer_record(SSL *s, record_pqueue *q,
Adam Langley71d8a082014-12-13 16:28:18 -0800191 uint8_t *priority);
Adam Langley95c29f32014-06-20 12:00:00 -0700192static int dtls1_process_record(SSL *s);
Adam Langley71d8a082014-12-13 16:28:18 -0800193static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
194 unsigned int len);
Adam Langley95c29f32014-06-20 12:00:00 -0700195
196/* copy buffered record into SSL structure */
Adam Langley71d8a082014-12-13 16:28:18 -0800197static int dtls1_copy_record(SSL *s, pitem *item) {
198 DTLS1_RECORD_DATA *rdata;
Adam Langley95c29f32014-06-20 12:00:00 -0700199
Adam Langley71d8a082014-12-13 16:28:18 -0800200 rdata = (DTLS1_RECORD_DATA *)item->data;
Adam Langley95c29f32014-06-20 12:00:00 -0700201
Adam Langley71d8a082014-12-13 16:28:18 -0800202 if (s->s3->rbuf.buf != NULL) {
203 OPENSSL_free(s->s3->rbuf.buf);
204 }
Adam Langley95c29f32014-06-20 12:00:00 -0700205
Adam Langley71d8a082014-12-13 16:28:18 -0800206 s->packet = rdata->packet;
207 s->packet_length = rdata->packet_length;
208 memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
209 memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
Adam Langley95c29f32014-06-20 12:00:00 -0700210
Adam Langley71d8a082014-12-13 16:28:18 -0800211 /* Set proper sequence number for mac calculation */
212 memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
Adam Langley95c29f32014-06-20 12:00:00 -0700213
Adam Langley71d8a082014-12-13 16:28:18 -0800214 return 1;
Adam Langley95c29f32014-06-20 12:00:00 -0700215}
216
Adam Langley71d8a082014-12-13 16:28:18 -0800217static int dtls1_buffer_record(SSL *s, record_pqueue *queue,
218 uint8_t *priority) {
219 DTLS1_RECORD_DATA *rdata;
220 pitem *item;
221
222 /* Limit the size of the queue to prevent DOS attacks */
223 if (pqueue_size(queue->q) >= 100) {
224 return 0;
225 }
226
227 rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
228 item = pitem_new(priority, rdata);
229 if (rdata == NULL || item == NULL) {
230 if (rdata != NULL) {
231 OPENSSL_free(rdata);
232 }
233 if (item != NULL) {
234 pitem_free(item);
235 }
236
237 OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
Adam Langley44e27092015-01-08 12:02:28 -0800238 return -1;
Adam Langley71d8a082014-12-13 16:28:18 -0800239 }
240
241 rdata->packet = s->packet;
242 rdata->packet_length = s->packet_length;
243 memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
244 memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
245
246 item->data = rdata;
247
248 s->packet = NULL;
249 s->packet_length = 0;
250 memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
251 memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
252
253 if (!ssl3_setup_buffers(s)) {
Adam Langley44e27092015-01-08 12:02:28 -0800254 goto internal_error;
Adam Langley71d8a082014-12-13 16:28:18 -0800255 }
256
257 /* insert should not fail, since duplicates are dropped */
258 if (pqueue_insert(queue->q, item) == NULL) {
Adam Langley44e27092015-01-08 12:02:28 -0800259 goto internal_error;
Adam Langley71d8a082014-12-13 16:28:18 -0800260 }
261
262 return 1;
Adam Langley44e27092015-01-08 12:02:28 -0800263
264internal_error:
265 OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
266 if (rdata->rbuf.buf != NULL) {
267 OPENSSL_free(rdata->rbuf.buf);
268 }
269 OPENSSL_free(rdata);
270 pitem_free(item);
271 return -1;
Adam Langley71d8a082014-12-13 16:28:18 -0800272}
273
274static int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue) {
275 pitem *item;
276
277 item = pqueue_pop(queue->q);
278 if (item) {
279 dtls1_copy_record(s, item);
280
281 OPENSSL_free(item->data);
282 pitem_free(item);
283
284 return 1;
285 }
286
287 return 0;
288}
289
290/* retrieve a buffered record that belongs to the new epoch, i.e., not
291 * processed yet */
292#define dtls1_get_unprocessed_record(s) \
293 dtls1_retrieve_buffered_record((s), &((s)->d1->unprocessed_rcds))
294
295/* retrieve a buffered record that belongs to the current epoch, i.e.,
296 * processed */
297#define dtls1_get_processed_record(s) \
298 dtls1_retrieve_buffered_record((s), &((s)->d1->processed_rcds))
299
300static int dtls1_process_buffered_records(SSL *s) {
301 pitem *item;
302
303 item = pqueue_peek(s->d1->unprocessed_rcds.q);
304 if (item) {
305 /* Check if epoch is current. */
306 if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) {
307 return 1; /* Nothing to do. */
308 }
309
310 /* Process all the records. */
311 while (pqueue_peek(s->d1->unprocessed_rcds.q)) {
312 dtls1_get_unprocessed_record(s);
313 if (!dtls1_process_record(s)) {
314 return 0;
315 }
Adam Langley44e27092015-01-08 12:02:28 -0800316 if (dtls1_buffer_record(s, &(s->d1->processed_rcds),
317 s->s3->rrec.seq_num) < 0) {
318 return -1;
319 }
Adam Langley71d8a082014-12-13 16:28:18 -0800320 }
321 }
322
323 /* sync epoch numbers once all the unprocessed records have been processed */
324 s->d1->processed_rcds.epoch = s->d1->r_epoch;
325 s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
326
327 return 1;
328}
329
330static int dtls1_process_record(SSL *s) {
David Benjaminb8a56f12014-12-23 11:41:02 -0500331 int al;
Adam Langley71d8a082014-12-13 16:28:18 -0800332 int enc_err;
Adam Langley71d8a082014-12-13 16:28:18 -0800333 SSL3_RECORD *rr;
Adam Langley71d8a082014-12-13 16:28:18 -0800334
335 rr = &(s->s3->rrec);
Adam Langley71d8a082014-12-13 16:28:18 -0800336
337 /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, and
338 * we have that many bytes in s->packet. */
339 rr->input = &(s->packet[DTLS1_RT_HEADER_LENGTH]);
340
341 /* ok, we can now read from 's->packet' data into 'rr' rr->input points at
342 * rr->length bytes, which need to be copied into rr->data by either the
343 * decryption or by the decompression When the data is 'copied' into the
344 * rr->data buffer, rr->input will be pointed at the new buffer */
345
346 /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length bytes
347 * of encrypted compressed stuff. */
348
349 /* check is not needed I believe */
350 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
351 al = SSL_AD_RECORD_OVERFLOW;
352 OPENSSL_PUT_ERROR(SSL, dtls1_process_record,
353 SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
354 goto f_err;
355 }
356
357 /* decrypt in place in 'rr->input' */
358 rr->data = rr->input;
359
360 enc_err = s->enc_method->enc(s, 0);
361 /* enc_err is:
362 * 0: (in non-constant time) if the record is publically invalid.
363 * 1: if the padding is valid
364 * -1: if the padding is invalid */
365 if (enc_err == 0) {
366 /* For DTLS we simply ignore bad packets. */
367 rr->length = 0;
368 s->packet_length = 0;
369 goto err;
370 }
Adam Langley71d8a082014-12-13 16:28:18 -0800371 if (enc_err < 0) {
372 /* decryption failed, silently discard message */
373 rr->length = 0;
374 s->packet_length = 0;
375 goto err;
376 }
377
378 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
379 al = SSL_AD_RECORD_OVERFLOW;
380 OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_DATA_LENGTH_TOO_LONG);
381 goto f_err;
382 }
383
384 rr->off = 0;
385 /* So at this point the following is true
386 * ssl->s3->rrec.type is the type of record
387 * ssl->s3->rrec.length == number of bytes in record
388 * ssl->s3->rrec.off == offset to first valid byte
389 * ssl->s3->rrec.data == where to take bytes from, increment
390 * after use :-). */
391
392 /* we have pulled in a full packet so zero things */
393 s->packet_length = 0;
Adam Langley71d8a082014-12-13 16:28:18 -0800394 return 1;
395
396f_err:
397 ssl3_send_alert(s, SSL3_AL_FATAL, al);
398
399err:
400 return 0;
401}
Adam Langley95c29f32014-06-20 12:00:00 -0700402
403/* Call this to get a new input record.
404 * It will return <= 0 if more data is needed, normally due to an error
405 * or non-blocking IO.
406 * When it finishes, one packet has been decoded and can be found in
407 * ssl->s3->rrec.type - is the type of record
Adam Langley71d8a082014-12-13 16:28:18 -0800408 * ssl->s3->rrec.data, - data
Adam Langley95c29f32014-06-20 12:00:00 -0700409 * ssl->s3->rrec.length, - number of bytes
Adam Langley71d8a082014-12-13 16:28:18 -0800410 *
411 * used only by dtls1_read_bytes */
412int dtls1_get_record(SSL *s) {
413 int ssl_major, ssl_minor;
414 int i, n;
415 SSL3_RECORD *rr;
416 unsigned char *p = NULL;
417 unsigned short version;
418 DTLS1_BITMAP *bitmap;
419 unsigned int is_next_epoch;
Adam Langley95c29f32014-06-20 12:00:00 -0700420
Adam Langley71d8a082014-12-13 16:28:18 -0800421 rr = &(s->s3->rrec);
Adam Langley95c29f32014-06-20 12:00:00 -0700422
Adam Langley71d8a082014-12-13 16:28:18 -0800423 /* The epoch may have changed. If so, process all the pending records. This
424 * is a non-blocking operation. */
Adam Langley44e27092015-01-08 12:02:28 -0800425 if (dtls1_process_buffered_records(s) < 0) {
426 return -1;
427 }
Adam Langley95c29f32014-06-20 12:00:00 -0700428
Adam Langley71d8a082014-12-13 16:28:18 -0800429 /* If we're renegotiating, then there may be buffered records. */
430 if (dtls1_get_processed_record(s)) {
431 return 1;
432 }
Adam Langley95c29f32014-06-20 12:00:00 -0700433
Adam Langley71d8a082014-12-13 16:28:18 -0800434 /* get something from the wire */
Adam Langley95c29f32014-06-20 12:00:00 -0700435again:
Adam Langley71d8a082014-12-13 16:28:18 -0800436 /* check if we have the header */
437 if ((s->rstate != SSL_ST_READ_BODY) ||
438 (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
439 n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
440 /* read timeout is handled by dtls1_read_bytes */
441 if (n <= 0) {
442 return n; /* error or non-blocking */
443 }
Adam Langley95c29f32014-06-20 12:00:00 -0700444
Adam Langley71d8a082014-12-13 16:28:18 -0800445 /* this packet contained a partial record, dump it */
446 if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
447 s->packet_length = 0;
448 goto again;
449 }
Adam Langley95c29f32014-06-20 12:00:00 -0700450
Adam Langley71d8a082014-12-13 16:28:18 -0800451 s->rstate = SSL_ST_READ_BODY;
Adam Langley95c29f32014-06-20 12:00:00 -0700452
Adam Langley71d8a082014-12-13 16:28:18 -0800453 p = s->packet;
Adam Langley95c29f32014-06-20 12:00:00 -0700454
Adam Langley71d8a082014-12-13 16:28:18 -0800455 if (s->msg_callback) {
456 s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s,
457 s->msg_callback_arg);
458 }
Adam Langley95c29f32014-06-20 12:00:00 -0700459
Adam Langley71d8a082014-12-13 16:28:18 -0800460 /* Pull apart the header into the DTLS1_RECORD */
461 rr->type = *(p++);
462 ssl_major = *(p++);
463 ssl_minor = *(p++);
464 version = (ssl_major << 8) | ssl_minor;
Adam Langley95c29f32014-06-20 12:00:00 -0700465
Adam Langley71d8a082014-12-13 16:28:18 -0800466 /* sequence number is 64 bits, with top 2 bytes = epoch */
467 n2s(p, rr->epoch);
Adam Langley95c29f32014-06-20 12:00:00 -0700468
Adam Langley71d8a082014-12-13 16:28:18 -0800469 memcpy(&(s->s3->read_sequence[2]), p, 6);
470 p += 6;
Adam Langley95c29f32014-06-20 12:00:00 -0700471
Adam Langley71d8a082014-12-13 16:28:18 -0800472 n2s(p, rr->length);
Adam Langley95c29f32014-06-20 12:00:00 -0700473
Adam Langley71d8a082014-12-13 16:28:18 -0800474 /* Lets check version */
475 if (s->s3->have_version) {
476 if (version != s->version) {
477 /* The record's version doesn't match, so silently drop it.
478 *
479 * TODO(davidben): This doesn't work. The DTLS record layer is not
480 * packet-based, so the remainder of the packet isn't dropped and we
481 * get a framing error. It's also unclear what it means to silently
482 * drop a record in a packet containing two records. */
483 rr->length = 0;
484 s->packet_length = 0;
485 goto again;
486 }
487 }
Adam Langley95c29f32014-06-20 12:00:00 -0700488
Adam Langley71d8a082014-12-13 16:28:18 -0800489 if ((version & 0xff00) != (s->version & 0xff00)) {
490 /* wrong version, silently discard record */
491 rr->length = 0;
492 s->packet_length = 0;
493 goto again;
494 }
Adam Langley95c29f32014-06-20 12:00:00 -0700495
Adam Langley71d8a082014-12-13 16:28:18 -0800496 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
497 /* record too long, silently discard it */
498 rr->length = 0;
499 s->packet_length = 0;
500 goto again;
501 }
Adam Langley95c29f32014-06-20 12:00:00 -0700502
Adam Langley71d8a082014-12-13 16:28:18 -0800503 /* now s->rstate == SSL_ST_READ_BODY */
504 }
Adam Langley95c29f32014-06-20 12:00:00 -0700505
Adam Langley71d8a082014-12-13 16:28:18 -0800506 /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
Adam Langley95c29f32014-06-20 12:00:00 -0700507
Adam Langley71d8a082014-12-13 16:28:18 -0800508 if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
509 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
510 i = rr->length;
511 n = ssl3_read_n(s, i, i, 1);
512 if (n <= 0) {
513 return n; /* error or non-blocking io */
514 }
Adam Langley95c29f32014-06-20 12:00:00 -0700515
Adam Langley71d8a082014-12-13 16:28:18 -0800516 /* this packet contained a partial record, dump it */
517 if (n != i) {
518 rr->length = 0;
519 s->packet_length = 0;
520 goto again;
521 }
Adam Langley95c29f32014-06-20 12:00:00 -0700522
Adam Langley71d8a082014-12-13 16:28:18 -0800523 /* now n == rr->length,
524 * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
525 }
526 s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
Adam Langley95c29f32014-06-20 12:00:00 -0700527
Adam Langley71d8a082014-12-13 16:28:18 -0800528 /* match epochs. NULL means the packet is dropped on the floor */
529 bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
530 if (bitmap == NULL) {
531 rr->length = 0;
532 s->packet_length = 0; /* dump this record */
533 goto again; /* get another record */
534 }
Adam Langley95c29f32014-06-20 12:00:00 -0700535
Adam Langley71d8a082014-12-13 16:28:18 -0800536 /* Check whether this is a repeat, or aged record. */
537 if (!dtls1_record_replay_check(s, bitmap)) {
538 rr->length = 0;
539 s->packet_length = 0; /* dump this record */
540 goto again; /* get another record */
541 }
Adam Langley95c29f32014-06-20 12:00:00 -0700542
Adam Langley71d8a082014-12-13 16:28:18 -0800543 /* just read a 0 length packet */
544 if (rr->length == 0) {
545 goto again;
546 }
Adam Langley95c29f32014-06-20 12:00:00 -0700547
Adam Langley71d8a082014-12-13 16:28:18 -0800548 /* If this record is from the next epoch (either HM or ALERT),
549 * and a handshake is currently in progress, buffer it since it
550 * cannot be processed at this time.
551 */
552 if (is_next_epoch) {
553 if (SSL_in_init(s) || s->in_handshake) {
Adam Langley44e27092015-01-08 12:02:28 -0800554 if (dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0) {
555 return -1;
556 }
557 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
Adam Langley71d8a082014-12-13 16:28:18 -0800558 }
559 rr->length = 0;
560 s->packet_length = 0;
561 goto again;
562 }
Adam Langley95c29f32014-06-20 12:00:00 -0700563
Adam Langley71d8a082014-12-13 16:28:18 -0800564 if (!dtls1_process_record(s)) {
565 rr->length = 0;
566 s->packet_length = 0; /* dump this record */
567 goto again; /* get another record */
568 }
Adam Langley44e27092015-01-08 12:02:28 -0800569 dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
Adam Langley95c29f32014-06-20 12:00:00 -0700570
Adam Langley71d8a082014-12-13 16:28:18 -0800571 return 1;
572}
Adam Langley95c29f32014-06-20 12:00:00 -0700573
574/* Return up to 'len' payload bytes received in 'type' records.
575 * 'type' is one of the following:
576 *
577 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
578 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
579 * - 0 (during a shutdown, no data has to be returned)
580 *
581 * If we don't have stored data to work from, read a SSL/TLS record first
582 * (possibly multiple records if we still don't have anything to return).
583 *
584 * This function must handle any surprises the peer may have for us, such as
585 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
586 * a surprise, but handled as if it were), or renegotiation requests.
587 * Also if record payloads contain fragments too small to process, we store
588 * them until there is enough for the respective protocol (the record protocol
589 * may use arbitrary fragmentation and even interleaving):
590 * Change cipher spec protocol
591 * just 1 byte needed, no need for keeping anything stored
592 * Alert protocol
593 * 2 bytes needed (AlertLevel, AlertDescription)
594 * Handshake protocol
595 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
596 * to detect unexpected Client Hello and Hello Request messages
597 * here, anything else is handled by higher layers
598 * Application data protocol
599 * none of our business
600 */
Adam Langley71d8a082014-12-13 16:28:18 -0800601int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) {
602 int al, i, j, ret;
603 unsigned int n;
604 SSL3_RECORD *rr;
605 void (*cb)(const SSL *ssl, int type2, int val) = NULL;
Adam Langley95c29f32014-06-20 12:00:00 -0700606
Adam Langley71d8a082014-12-13 16:28:18 -0800607 if (s->s3->rbuf.buf == NULL && !ssl3_setup_buffers(s)) {
608 return -1;
609 }
Adam Langley95c29f32014-06-20 12:00:00 -0700610
Adam Langley71d8a082014-12-13 16:28:18 -0800611 /* XXX: check what the second '&& type' is about */
612 if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
613 (type != SSL3_RT_HANDSHAKE) && type) ||
614 (peek && (type != SSL3_RT_APPLICATION_DATA))) {
615 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
616 return -1;
617 }
Adam Langley95c29f32014-06-20 12:00:00 -0700618
Adam Langley71d8a082014-12-13 16:28:18 -0800619 /* check whether there's a handshake message (client hello?) waiting */
620 ret = have_handshake_fragment(s, type, buf, len, peek);
621 if (ret) {
622 return ret;
623 }
Adam Langley95c29f32014-06-20 12:00:00 -0700624
Adam Langley71d8a082014-12-13 16:28:18 -0800625 /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
Adam Langley95c29f32014-06-20 12:00:00 -0700626
Adam Langley71d8a082014-12-13 16:28:18 -0800627 if (!s->in_handshake && SSL_in_init(s)) {
628 /* type == SSL3_RT_APPLICATION_DATA */
629 i = s->handshake_func(s);
630 if (i < 0) {
631 return i;
632 }
633 if (i == 0) {
634 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
635 return -1;
636 }
637 }
Adam Langley95c29f32014-06-20 12:00:00 -0700638
639start:
Adam Langley71d8a082014-12-13 16:28:18 -0800640 s->rwstate = SSL_NOTHING;
Adam Langley95c29f32014-06-20 12:00:00 -0700641
Adam Langley71d8a082014-12-13 16:28:18 -0800642 /* s->s3->rrec.type - is the type of record
643 * s->s3->rrec.data - data
644 * s->s3->rrec.off - offset into 'data' for next read
645 * s->s3->rrec.length - number of bytes. */
646 rr = &s->s3->rrec;
Adam Langley95c29f32014-06-20 12:00:00 -0700647
Adam Langley71d8a082014-12-13 16:28:18 -0800648 /* We are not handshaking and have no data yet,
649 * so process data buffered during the last handshake
650 * in advance, if any.
651 */
652 if (s->state == SSL_ST_OK && rr->length == 0) {
653 pitem *item;
654 item = pqueue_pop(s->d1->buffered_app_data.q);
655 if (item) {
656 dtls1_copy_record(s, item);
Adam Langley95c29f32014-06-20 12:00:00 -0700657
Adam Langley71d8a082014-12-13 16:28:18 -0800658 OPENSSL_free(item->data);
659 pitem_free(item);
660 }
661 }
Adam Langley95c29f32014-06-20 12:00:00 -0700662
Adam Langley71d8a082014-12-13 16:28:18 -0800663 /* Check for timeout */
664 if (dtls1_handle_timeout(s) > 0) {
665 goto start;
666 }
Adam Langley95c29f32014-06-20 12:00:00 -0700667
Adam Langley71d8a082014-12-13 16:28:18 -0800668 /* get new packet if necessary */
669 if (rr->length == 0 || s->rstate == SSL_ST_READ_BODY) {
670 ret = dtls1_get_record(s);
671 if (ret <= 0) {
672 ret = dtls1_read_failed(s, ret);
673 /* anything other than a timeout is an error */
674 if (ret <= 0) {
675 return ret;
676 } else {
677 goto start;
678 }
679 }
680 }
Adam Langley95c29f32014-06-20 12:00:00 -0700681
Adam Langley71d8a082014-12-13 16:28:18 -0800682 /* we now have a packet which can be read and processed */
Adam Langley95c29f32014-06-20 12:00:00 -0700683
Adam Langley71d8a082014-12-13 16:28:18 -0800684 /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
685 * ssl3_get_finished. */
686 if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE) {
687 /* We now have application data between CCS and Finished. Most likely the
688 * packets were reordered on their way, so buffer the application data for
689 * later processing rather than dropping the connection. */
Adam Langley44e27092015-01-08 12:02:28 -0800690 if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) < 0) {
691 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
692 return -1;
693 }
Adam Langley71d8a082014-12-13 16:28:18 -0800694 rr->length = 0;
695 goto start;
696 }
Adam Langley95c29f32014-06-20 12:00:00 -0700697
Adam Langley71d8a082014-12-13 16:28:18 -0800698 /* If the other end has shut down, throw anything we read away (even in
699 * 'peek' mode) */
700 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
701 rr->length = 0;
702 s->rwstate = SSL_NOTHING;
703 return 0;
704 }
Adam Langley95c29f32014-06-20 12:00:00 -0700705
706
Adam Langley71d8a082014-12-13 16:28:18 -0800707 if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
708 /* make sure that we are not getting application data when we
709 * are doing a handshake for the first time */
710 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
David Benjaminb8a56f12014-12-23 11:41:02 -0500711 (s->aead_read_ctx == NULL)) {
712 /* TODO(davidben): Is this check redundant with the handshake_func
713 * check? */
Adam Langley71d8a082014-12-13 16:28:18 -0800714 al = SSL_AD_UNEXPECTED_MESSAGE;
715 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
716 goto f_err;
Adam Langley95c29f32014-06-20 12:00:00 -0700717 }
718
Adam Langley71d8a082014-12-13 16:28:18 -0800719 if (len <= 0) {
720 return len;
721 }
Adam Langley95c29f32014-06-20 12:00:00 -0700722
Adam Langley71d8a082014-12-13 16:28:18 -0800723 if ((unsigned int)len > rr->length) {
724 n = rr->length;
725 } else {
726 n = (unsigned int)len;
727 }
Adam Langley95c29f32014-06-20 12:00:00 -0700728
Adam Langley71d8a082014-12-13 16:28:18 -0800729 memcpy(buf, &(rr->data[rr->off]), n);
730 if (!peek) {
731 rr->length -= n;
732 rr->off += n;
733 if (rr->length == 0) {
734 s->rstate = SSL_ST_READ_HEADER;
735 rr->off = 0;
736 }
737 }
Adam Langley95c29f32014-06-20 12:00:00 -0700738
Adam Langley71d8a082014-12-13 16:28:18 -0800739 return n;
740 }
Adam Langley95c29f32014-06-20 12:00:00 -0700741
Adam Langley71d8a082014-12-13 16:28:18 -0800742 /* If we get here, then type != rr->type; if we have a handshake message,
743 * then it was unexpected (Hello Request or Client Hello). */
Adam Langley95c29f32014-06-20 12:00:00 -0700744
Adam Langley71d8a082014-12-13 16:28:18 -0800745 /* In case of record types for which we have 'fragment' storage, fill that so
746 * that we can process the data at a fixed place. */
747 {
748 unsigned int k, dest_maxlen = 0;
749 uint8_t *dest = NULL;
750 unsigned int *dest_len = NULL;
Adam Langley95c29f32014-06-20 12:00:00 -0700751
Adam Langley71d8a082014-12-13 16:28:18 -0800752 if (rr->type == SSL3_RT_HANDSHAKE) {
753 dest_maxlen = sizeof s->d1->handshake_fragment;
754 dest = s->d1->handshake_fragment;
755 dest_len = &s->d1->handshake_fragment_len;
756 } else if (rr->type == SSL3_RT_ALERT) {
757 dest_maxlen = sizeof(s->d1->alert_fragment);
758 dest = s->d1->alert_fragment;
759 dest_len = &s->d1->alert_fragment_len;
760 }
761 /* else it's a CCS message, or application data or wrong */
762 else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
763 /* Application data while renegotiating is allowed. Try again reading. */
764 if (rr->type == SSL3_RT_APPLICATION_DATA) {
765 BIO *bio;
766 s->s3->in_read_app_data = 2;
767 bio = SSL_get_rbio(s);
768 s->rwstate = SSL_READING;
769 BIO_clear_retry_flags(bio);
770 BIO_set_retry_read(bio);
771 return -1;
772 }
Adam Langley95c29f32014-06-20 12:00:00 -0700773
Adam Langley71d8a082014-12-13 16:28:18 -0800774 /* Not certain if this is the right error handling */
775 al = SSL_AD_UNEXPECTED_MESSAGE;
776 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
777 goto f_err;
778 }
779
780 if (dest_maxlen > 0) {
781 /* XDTLS: In a pathalogical case, the Client Hello
782 * may be fragmented--don't always expect dest_maxlen bytes */
783 if (rr->length < dest_maxlen) {
784 s->rstate = SSL_ST_READ_HEADER;
785 rr->length = 0;
786 goto start;
787 }
788
789 /* now move 'n' bytes: */
790 for (k = 0; k < dest_maxlen; k++) {
791 dest[k] = rr->data[rr->off++];
792 rr->length--;
793 }
794 *dest_len = dest_maxlen;
795 }
796 }
797
798 /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
799 * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
800 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
801
802 /* If we are a client, check for an incoming 'Hello Request': */
803 if (!s->server && s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH &&
804 s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST &&
805 s->session != NULL && s->session->cipher != NULL) {
806 s->d1->handshake_fragment_len = 0;
807
808 if ((s->d1->handshake_fragment[1] != 0) ||
809 (s->d1->handshake_fragment[2] != 0) ||
810 (s->d1->handshake_fragment[3] != 0)) {
811 al = SSL_AD_DECODE_ERROR;
812 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_HELLO_REQUEST);
813 goto f_err;
814 }
815
816 /* no need to check sequence number on HELLO REQUEST messages */
817
818 if (s->msg_callback) {
819 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
820 s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
821 }
822
823 if (SSL_is_init_finished(s) && !s->s3->renegotiate) {
824 s->d1->handshake_read_seq++;
825 s->new_session = 1;
826 ssl3_renegotiate(s);
827 if (ssl3_renegotiate_check(s)) {
828 i = s->handshake_func(s);
829 if (i < 0) {
830 return i;
831 }
832 if (i == 0) {
833 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
834 return -1;
835 }
836 }
837 }
838
839 /* we either finished a handshake or ignored the request, now try again to
840 * obtain the (application) data we were asked for */
841 goto start;
842 }
843
844 if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
845 int alert_level = s->d1->alert_fragment[0];
846 int alert_descr = s->d1->alert_fragment[1];
847
848 s->d1->alert_fragment_len = 0;
849
850 if (s->msg_callback) {
851 s->msg_callback(0, s->version, SSL3_RT_ALERT, s->d1->alert_fragment, 2, s,
852 s->msg_callback_arg);
853 }
854
855 if (s->info_callback != NULL) {
856 cb = s->info_callback;
857 } else if (s->ctx->info_callback != NULL) {
858 cb = s->ctx->info_callback;
859 }
860
861 if (cb != NULL) {
862 j = (alert_level << 8) | alert_descr;
863 cb(s, SSL_CB_READ_ALERT, j);
864 }
865
866 if (alert_level == 1) { /* warning */
867 s->s3->warn_alert = alert_descr;
868 if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
869 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
870 return 0;
871 }
872 } else if (alert_level == 2) { /* fatal */
873 char tmp[16];
874
875 s->rwstate = SSL_NOTHING;
876 s->s3->fatal_alert = alert_descr;
877 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes,
878 SSL_AD_REASON_OFFSET + alert_descr);
879 BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
880 ERR_add_error_data(2, "SSL alert number ", tmp);
881 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
882 SSL_CTX_remove_session(s->ctx, s->session);
883 return 0;
884 } else {
885 al = SSL_AD_ILLEGAL_PARAMETER;
886 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
887 goto f_err;
888 }
889
890 goto start;
891 }
892
893 if (s->shutdown & SSL_SENT_SHUTDOWN) {
894 /* but we have not received a shutdown */
895 s->rwstate = SSL_NOTHING;
896 rr->length = 0;
897 return 0;
898 }
899
900 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
901 struct ccs_header_st ccs_hdr;
902 unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
903
904 dtls1_get_ccs_header(rr->data, &ccs_hdr);
905
906 /* 'Change Cipher Spec' is just a single byte, so we know
907 * exactly what the record payload has to look like */
908 /* XDTLS: check that epoch is consistent */
909 if ((rr->length != ccs_hdr_len) || (rr->off != 0) ||
910 (rr->data[0] != SSL3_MT_CCS)) {
911 al = SSL_AD_ILLEGAL_PARAMETER;
912 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
913 goto f_err;
914 }
915
916 rr->length = 0;
917
918 if (s->msg_callback) {
919 s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
920 s->msg_callback_arg);
921 }
922
923 /* We can't process a CCS now, because previous handshake
924 * messages are still missing, so just drop it.
925 */
926 if (!s->d1->change_cipher_spec_ok) {
927 goto start;
928 }
929
930 s->d1->change_cipher_spec_ok = 0;
931
932 s->s3->change_cipher_spec = 1;
933 if (!ssl3_do_change_cipher_spec(s)) {
934 goto err;
935 }
936
937 /* do this whenever CCS is processed */
938 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
939
940 goto start;
941 }
942
943 /* Unexpected handshake message (Client Hello, or protocol violation) */
944 if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
945 !s->in_handshake) {
946 struct hm_header_st msg_hdr;
947
948 /* this may just be a stale retransmit */
949 dtls1_get_message_header(rr->data, &msg_hdr);
950 if (rr->epoch != s->d1->r_epoch) {
951 rr->length = 0;
952 goto start;
953 }
954
955 /* If we are server, we may have a repeated FINISHED of the client here,
956 * then retransmit our CCS and FINISHED. */
957 if (msg_hdr.type == SSL3_MT_FINISHED) {
958 if (dtls1_check_timeout_num(s) < 0) {
959 return -1;
960 }
961
962 dtls1_retransmit_buffered_messages(s);
963 rr->length = 0;
964 goto start;
965 }
966
967 if ((s->state & SSL_ST_MASK) == SSL_ST_OK) {
968 s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
969 s->renegotiate = 1;
970 s->new_session = 1;
971 }
972 i = s->handshake_func(s);
973 if (i < 0) {
974 return i;
975 }
976 if (i == 0) {
977 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
978 return -1;
979 }
980
981 goto start;
982 }
983
984 switch (rr->type) {
985 default:
986 /* TLS just ignores unknown message types */
987 if (s->version == TLS1_VERSION) {
988 rr->length = 0;
989 goto start;
990 }
991 al = SSL_AD_UNEXPECTED_MESSAGE;
992 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
993 goto f_err;
994
995 case SSL3_RT_CHANGE_CIPHER_SPEC:
996 case SSL3_RT_ALERT:
997 case SSL3_RT_HANDSHAKE:
998 /* we already handled all of these, with the possible exception of
999 * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
1000 * happen when type != rr->type */
1001 al = SSL_AD_UNEXPECTED_MESSAGE;
1002 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
1003 goto f_err;
1004
1005 case SSL3_RT_APPLICATION_DATA:
1006 /* At this point, we were expecting handshake data, but have application
1007 * data. If the library was running inside ssl3_read() (i.e.
1008 * in_read_app_data is set) and it makes sense to read application data
1009 * at this point (session renegotiation not yet started), we will indulge
1010 * it. */
1011 if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) &&
1012 (((s->state & SSL_ST_CONNECT) &&
1013 (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1014 (s->state <= SSL3_ST_CR_SRVR_HELLO_A)) ||
1015 ((s->state & SSL_ST_ACCEPT) &&
1016 (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1017 (s->state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1018 s->s3->in_read_app_data = 2;
1019 return -1;
1020 } else {
1021 al = SSL_AD_UNEXPECTED_MESSAGE;
1022 OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
1023 goto f_err;
1024 }
1025 }
1026
1027 /* not reached */
1028
1029f_err:
1030 ssl3_send_alert(s, SSL3_AL_FATAL, al);
1031err:
1032 return -1;
1033}
1034
1035int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len) {
1036 int i;
1037
1038 if (SSL_in_init(s) && !s->in_handshake) {
1039 i = s->handshake_func(s);
1040 if (i < 0) {
1041 return i;
1042 }
1043 if (i == 0) {
1044 OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes,
1045 SSL_R_SSL_HANDSHAKE_FAILURE);
1046 return -1;
1047 }
1048 }
1049
1050 if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
1051 OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes,
1052 SSL_R_DTLS_MESSAGE_TOO_BIG);
1053 return -1;
1054 }
1055
1056 i = dtls1_write_bytes(s, type, buf_, len);
1057 return i;
1058}
1059
1060
1061/* this only happens when a client hello is received and a handshake is
1062 * started. */
1063static int have_handshake_fragment(SSL *s, int type, uint8_t *buf,
1064 int len, int peek) {
1065 if (type == SSL3_RT_HANDSHAKE && s->d1->handshake_fragment_len > 0) {
1066 /* (partially) satisfy request from storage */
1067 uint8_t *src = s->d1->handshake_fragment;
1068 uint8_t *dst = buf;
1069 unsigned int k, n;
1070
1071 /* peek == 0 */
1072 n = 0;
1073 while (len > 0 && s->d1->handshake_fragment_len > 0) {
1074 *dst++ = *src++;
1075 len--;
1076 s->d1->handshake_fragment_len--;
1077 n++;
1078 }
1079 /* move any remaining fragment bytes: */
1080 for (k = 0; k < s->d1->handshake_fragment_len; k++) {
1081 s->d1->handshake_fragment[k] = *src++;
1082 }
1083 return n;
1084 }
1085
1086 return 0;
1087}
1088
1089/* Call this to write data in records of type 'type' It will return <= 0 if not
1090 * all data has been sent or non-blocking IO. */
1091int dtls1_write_bytes(SSL *s, int type, const void *buf, int len) {
1092 int i;
1093
1094 assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
1095 s->rwstate = SSL_NOTHING;
1096 i = do_dtls1_write(s, type, buf, len);
1097 return i;
1098}
1099
1100static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
1101 unsigned int len) {
1102 uint8_t *p, *pseq;
David Benjaminb8a56f12014-12-23 11:41:02 -05001103 int i;
Adam Langley71d8a082014-12-13 16:28:18 -08001104 int prefix_len = 0;
1105 int eivlen = 0;
1106 SSL3_RECORD *wr;
1107 SSL3_BUFFER *wb;
Adam Langley71d8a082014-12-13 16:28:18 -08001108
1109 /* first check if there is a SSL3_BUFFER still being written
1110 * out. This will happen with non blocking IO */
1111 if (s->s3->wbuf.left != 0) {
1112 assert(0); /* XDTLS: want to see if we ever get here */
1113 return ssl3_write_pending(s, type, buf, len);
1114 }
1115
1116 /* If we have an alert to send, lets send it */
1117 if (s->s3->alert_dispatch) {
1118 i = s->method->ssl_dispatch_alert(s);
1119 if (i <= 0) {
1120 return i;
1121 }
1122 /* if it went, fall through and send more stuff */
1123 }
1124
1125 if (len == 0) {
1126 return 0;
1127 }
1128
1129 wr = &(s->s3->wrec);
1130 wb = &(s->s3->wbuf);
Adam Langley71d8a082014-12-13 16:28:18 -08001131
1132 p = wb->buf + prefix_len;
1133
1134 /* write the header */
1135
1136 *(p++) = type & 0xff;
1137 wr->type = type;
1138 /* Special case: for hello verify request, client version 1.0 and
1139 * we haven't decided which version to use yet send back using
1140 * version 1.0 header: otherwise some clients will ignore it.
1141 */
1142 if (!s->s3->have_version) {
1143 *(p++) = DTLS1_VERSION >> 8;
1144 *(p++) = DTLS1_VERSION & 0xff;
1145 } else {
1146 *(p++) = s->version >> 8;
1147 *(p++) = s->version & 0xff;
1148 }
1149
1150 /* field where we are to write out packet epoch, seq num and len */
1151 pseq = p;
1152 p += 10;
1153
David Benjaminb8a56f12014-12-23 11:41:02 -05001154 /* Leave room for the variable nonce for AEADs which specify it explicitly. */
1155 if (s->aead_write_ctx != NULL &&
1156 s->aead_write_ctx->variable_nonce_included_in_record) {
David Benjamine95d20d2014-12-23 11:16:01 -05001157 eivlen = s->aead_write_ctx->variable_nonce_len;
Adam Langley71d8a082014-12-13 16:28:18 -08001158 }
1159
1160 /* lets setup the record stuff. */
1161 wr->data = p + eivlen; /* make room for IV in case of CBC */
1162 wr->length = (int)len;
1163 wr->input = (unsigned char *)buf;
1164
1165 /* we now 'read' from wr->input, wr->length bytes into wr->data */
1166 memcpy(wr->data, wr->input, wr->length);
1167 wr->input = wr->data;
1168
Adam Langley71d8a082014-12-13 16:28:18 -08001169 /* this is true regardless of mac size */
1170 wr->input = p;
1171 wr->data = p;
1172 wr->length += eivlen;
1173
1174 if (s->enc_method->enc(s, 1) < 1) {
1175 goto err;
1176 }
1177
1178 /* there's only one epoch between handshake and app data */
1179 s2n(s->d1->w_epoch, pseq);
1180
1181 memcpy(pseq, &(s->s3->write_sequence[2]), 6);
1182 pseq += 6;
1183 s2n(wr->length, pseq);
1184
1185 if (s->msg_callback) {
1186 s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
1187 DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
1188 }
1189
1190 /* we should now have wr->data pointing to the encrypted data, which is
1191 * wr->length long */
1192 wr->type = type; /* not needed but helps for debugging */
1193 wr->length += DTLS1_RT_HEADER_LENGTH;
1194
1195 ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
1196
1197 /* now let's set up wb */
1198 wb->left = prefix_len + wr->length;
1199 wb->offset = 0;
1200
1201 /* memorize arguments so that ssl3_write_pending can detect bad write retries
1202 * later */
1203 s->s3->wpend_tot = len;
1204 s->s3->wpend_buf = buf;
1205 s->s3->wpend_type = type;
1206 s->s3->wpend_ret = len;
1207
1208 /* we now just need to write the buffer */
1209 return ssl3_write_pending(s, type, buf, len);
1210
1211err:
1212 return -1;
1213}
1214
1215static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) {
1216 int cmp;
1217 unsigned int shift;
1218 const uint8_t *seq = s->s3->read_sequence;
1219
1220 cmp = satsub64be(seq, bitmap->max_seq_num);
1221 if (cmp > 0) {
1222 memcpy(s->s3->rrec.seq_num, seq, 8);
1223 return 1; /* this record in new */
1224 }
1225 shift = -cmp;
1226 if (shift >= sizeof(bitmap->map) * 8) {
1227 return 0; /* stale, outside the window */
1228 } else if (bitmap->map & (((uint64_t)1) << shift)) {
1229 return 0; /* record previously received */
1230 }
1231
1232 memcpy(s->s3->rrec.seq_num, seq, 8);
1233 return 1;
1234}
1235
1236static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) {
1237 int cmp;
1238 unsigned int shift;
1239 const uint8_t *seq = s->s3->read_sequence;
1240
1241 cmp = satsub64be(seq, bitmap->max_seq_num);
1242 if (cmp > 0) {
1243 shift = cmp;
1244 if (shift < sizeof(bitmap->map) * 8) {
1245 bitmap->map <<= shift, bitmap->map |= 1UL;
1246 } else {
1247 bitmap->map = 1UL;
1248 }
1249 memcpy(bitmap->max_seq_num, seq, 8);
1250 } else {
1251 shift = -cmp;
1252 if (shift < sizeof(bitmap->map) * 8) {
1253 bitmap->map |= ((uint64_t)1) << shift;
1254 }
1255 }
1256}
1257
1258int dtls1_dispatch_alert(SSL *s) {
1259 int i, j;
1260 void (*cb)(const SSL *ssl, int type, int val) = NULL;
1261 uint8_t buf[DTLS1_AL_HEADER_LENGTH];
1262 uint8_t *ptr = &buf[0];
1263
1264 s->s3->alert_dispatch = 0;
1265
1266 memset(buf, 0x00, sizeof(buf));
1267 *ptr++ = s->s3->send_alert[0];
1268 *ptr++ = s->s3->send_alert[1];
1269
1270 i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
1271 if (i <= 0) {
1272 s->s3->alert_dispatch = 1;
1273 } else {
1274 if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
1275 (void)BIO_flush(s->wbio);
1276 }
1277
1278 if (s->msg_callback) {
1279 s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
1280 s->msg_callback_arg);
1281 }
1282
1283 if (s->info_callback != NULL) {
1284 cb = s->info_callback;
1285 } else if (s->ctx->info_callback != NULL) {
1286 cb = s->ctx->info_callback;
1287 }
1288
1289 if (cb != NULL) {
1290 j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
1291 cb(s, SSL_CB_WRITE_ALERT, j);
1292 }
1293 }
1294
1295 return i;
1296}
1297
1298static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
1299 unsigned int *is_next_epoch) {
1300 *is_next_epoch = 0;
1301
1302 /* In current epoch, accept HM, CCS, DATA, & ALERT */
1303 if (rr->epoch == s->d1->r_epoch) {
1304 return &s->d1->bitmap;
1305 } else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
1306 (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1307 /* Only HM and ALERT messages can be from the next epoch */
1308 *is_next_epoch = 1;
1309 return &s->d1->next_bitmap;
1310 }
1311
1312 return NULL;
1313}
1314
1315void dtls1_reset_seq_numbers(SSL *s, int rw) {
1316 uint8_t *seq;
1317 unsigned int seq_bytes = sizeof(s->s3->read_sequence);
1318
1319 if (rw & SSL3_CC_READ) {
1320 seq = s->s3->read_sequence;
1321 s->d1->r_epoch++;
1322 memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
1323 memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
1324 } else {
1325 seq = s->s3->write_sequence;
1326 memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
1327 s->d1->w_epoch++;
1328 }
1329
1330 memset(seq, 0x00, seq_bytes);
1331}