blob: 2ad8fddda14377de98819168e9b00fe60ad2458d [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001/*
2 * DTLS implementation written by Nagendra Modadugu
3 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
4 */
5/* ====================================================================
6 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this
21 * software must display the following acknowledgment:
22 * "This product includes software developed by the OpenSSL Project
23 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
24 *
25 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26 * endorse or promote products derived from this software without
27 * prior written permission. For written permission, please contact
28 * openssl-core@openssl.org.
29 *
30 * 5. Products derived from this software may not be called "OpenSSL"
31 * nor may "OpenSSL" appear in their names without prior written
32 * permission of the OpenSSL Project.
33 *
34 * 6. Redistributions of any form whatsoever must retain the following
35 * acknowledgment:
36 * "This product includes software developed by the OpenSSL Project
37 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
43 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50 * OF THE POSSIBILITY OF SUCH DAMAGE.
51 * ====================================================================
52 *
53 * This product includes cryptographic software written by Eric Young
54 * (eay@cryptsoft.com). This product includes software written by Tim
55 * Hudson (tjh@cryptsoft.com).
56 *
57 */
58/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
59 * All rights reserved.
60 *
61 * This package is an SSL implementation written
62 * by Eric Young (eay@cryptsoft.com).
63 * The implementation was written so as to conform with Netscapes SSL.
64 *
65 * This library is free for commercial and non-commercial use as long as
66 * the following conditions are aheared to. The following conditions
67 * apply to all code found in this distribution, be it the RC4, RSA,
68 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
69 * included with this distribution is covered by the same copyright terms
70 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
71 *
72 * Copyright remains Eric Young's, and as such any Copyright notices in
73 * the code are not to be removed.
74 * If this package is used in a product, Eric Young should be given attribution
75 * as the author of the parts of the library used.
76 * This can be in the form of a textual message at program startup or
77 * in documentation (online or textual) provided with the package.
78 *
79 * Redistribution and use in source and binary forms, with or without
80 * modification, are permitted provided that the following conditions
81 * are met:
82 * 1. Redistributions of source code must retain the copyright
83 * notice, this list of conditions and the following disclaimer.
84 * 2. Redistributions in binary form must reproduce the above copyright
85 * notice, this list of conditions and the following disclaimer in the
86 * documentation and/or other materials provided with the distribution.
87 * 3. All advertising materials mentioning features or use of this software
88 * must display the following acknowledgement:
89 * "This product includes cryptographic software written by
90 * Eric Young (eay@cryptsoft.com)"
91 * The word 'cryptographic' can be left out if the rouines from the library
92 * being used are not cryptographic related :-).
93 * 4. If you include any Windows specific code (or a derivative thereof) from
94 * the apps directory (application code) you must include an acknowledgement:
95 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
96 *
97 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
98 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
99 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
100 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
101 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
102 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
103 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
104 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
105 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
106 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
107 * SUCH DAMAGE.
108 *
109 * The licence and distribution terms for any publically available version or
110 * derivative of this code cannot be changed. i.e. this code cannot simply be
111 * copied and put under another distribution licence
112 * [including the GNU Public Licence.] */
113
David Benjamin9e4e01e2015-09-15 01:48:04 -0400114#include <openssl/ssl.h>
115
Adam Langley95c29f32014-06-20 12:00:00 -0700116#include <assert.h>
117#include <limits.h>
Adam Langley95c29f32014-06-20 12:00:00 -0700118#include <string.h>
119
120#include <openssl/buf.h>
121#include <openssl/err.h>
122#include <openssl/evp.h>
123#include <openssl/mem.h>
Adam Langley95c29f32014-06-20 12:00:00 -0700124#include <openssl/rand.h>
125#include <openssl/x509.h>
126
David Benjamin2ee94aa2015-04-07 22:38:30 -0400127#include "internal.h"
Adam Langley95c29f32014-06-20 12:00:00 -0700128
Adam Langley95c29f32014-06-20 12:00:00 -0700129
David Benjamina18b6712015-01-11 19:31:22 -0500130/* TODO(davidben): 28 comes from the size of IP + UDP header. Is this reasonable
131 * for these values? Notably, why is kMinMTU a function of the transport
132 * protocol's overhead rather than, say, what's needed to hold a minimally-sized
133 * handshake fragment plus protocol overhead. */
Adam Langley95c29f32014-06-20 12:00:00 -0700134
David Benjamina18b6712015-01-11 19:31:22 -0500135/* kMinMTU is the minimum acceptable MTU value. */
136static const unsigned int kMinMTU = 256 - 28;
137
138/* kDefaultMTU is the default MTU value to use if neither the user nor
139 * the underlying BIO supplies one. */
140static const unsigned int kDefaultMTU = 1500 - 28;
141
David Benjamin9d632f42016-06-23 17:57:19 -0400142
143/* Receiving handshake messages. */
144
David Benjaminec847ce2016-06-17 19:30:47 -0400145static void dtls1_hm_fragment_free(hm_fragment *frag) {
146 if (frag == NULL) {
147 return;
148 }
149 OPENSSL_free(frag->fragment);
150 OPENSSL_free(frag->reassembly);
151 OPENSSL_free(frag);
152}
153
David Benjamin29a83c52016-06-17 19:12:54 -0400154static hm_fragment *dtls1_hm_fragment_new(size_t frag_len) {
David Benjaminc99807d2015-09-12 18:21:35 -0400155 hm_fragment *frag = OPENSSL_malloc(sizeof(hm_fragment));
Adam Langley71d8a082014-12-13 16:28:18 -0800156 if (frag == NULL) {
David Benjamin3570d732015-06-29 00:28:17 -0400157 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
Adam Langley71d8a082014-12-13 16:28:18 -0800158 return NULL;
159 }
David Benjaminc99807d2015-09-12 18:21:35 -0400160 memset(frag, 0, sizeof(hm_fragment));
Adam Langley95c29f32014-06-20 12:00:00 -0700161
David Benjaminc99807d2015-09-12 18:21:35 -0400162 /* If the handshake message is empty, |frag->fragment| and |frag->reassembly|
163 * are NULL. */
164 if (frag_len > 0) {
165 frag->fragment = OPENSSL_malloc(frag_len);
166 if (frag->fragment == NULL) {
David Benjamin3570d732015-06-29 00:28:17 -0400167 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
David Benjaminc99807d2015-09-12 18:21:35 -0400168 goto err;
Adam Langley71d8a082014-12-13 16:28:18 -0800169 }
Adam Langley95c29f32014-06-20 12:00:00 -0700170
David Benjamin29a83c52016-06-17 19:12:54 -0400171 /* Initialize reassembly bitmask. */
172 if (frag_len + 7 < frag_len) {
173 OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
174 goto err;
Adam Langley71d8a082014-12-13 16:28:18 -0800175 }
David Benjamin29a83c52016-06-17 19:12:54 -0400176 size_t bitmask_len = (frag_len + 7) / 8;
177 frag->reassembly = OPENSSL_malloc(bitmask_len);
178 if (frag->reassembly == NULL) {
179 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
180 goto err;
181 }
182 memset(frag->reassembly, 0, bitmask_len);
Adam Langley71d8a082014-12-13 16:28:18 -0800183 }
Adam Langley95c29f32014-06-20 12:00:00 -0700184
Adam Langley71d8a082014-12-13 16:28:18 -0800185 return frag;
David Benjaminc99807d2015-09-12 18:21:35 -0400186
187err:
188 dtls1_hm_fragment_free(frag);
189 return NULL;
Adam Langley71d8a082014-12-13 16:28:18 -0800190}
Adam Langley95c29f32014-06-20 12:00:00 -0700191
David Benjaminee562b92015-03-02 20:52:52 -0500192/* bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
193 * exclusive, set. */
David Benjamindca125e2016-06-23 17:52:47 -0400194static uint8_t bit_range(size_t start, size_t end) {
David Benjaminee562b92015-03-02 20:52:52 -0500195 return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
196}
197
198/* dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
199 * as received in |frag|. If |frag| becomes complete, it clears
200 * |frag->reassembly|. The range must be within the bounds of |frag|'s message
201 * and |frag->reassembly| must not be NULL. */
202static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
203 size_t end) {
204 size_t i;
205 size_t msg_len = frag->msg_header.msg_len;
206
207 if (frag->reassembly == NULL || start > end || end > msg_len) {
208 assert(0);
209 return;
210 }
211 /* A zero-length message will never have a pending reassembly. */
212 assert(msg_len > 0);
213
214 if ((start >> 3) == (end >> 3)) {
215 frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
216 } else {
217 frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
218 for (i = (start >> 3) + 1; i < (end >> 3); i++) {
219 frag->reassembly[i] = 0xff;
220 }
221 if ((end & 7) != 0) {
222 frag->reassembly[end >> 3] |= bit_range(0, end & 7);
223 }
224 }
225
226 /* Check if the fragment is complete. */
227 for (i = 0; i < (msg_len >> 3); i++) {
228 if (frag->reassembly[i] != 0xff) {
229 return;
230 }
231 }
232 if ((msg_len & 7) != 0 &&
233 frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
234 return;
235 }
236
237 OPENSSL_free(frag->reassembly);
238 frag->reassembly = NULL;
239}
240
David Benjamin9d632f42016-06-23 17:57:19 -0400241/* dtls1_is_next_message_complete returns one if the next handshake message is
242 * complete and zero otherwise. */
243static int dtls1_is_next_message_complete(SSL *ssl) {
244 hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
245 SSL_MAX_HANDSHAKE_FLIGHT];
246 return frag != NULL && frag->reassembly == NULL;
247}
248
249/* dtls1_get_incoming_message returns the incoming message corresponding to
250 * |msg_hdr|. If none exists, it creates a new one and inserts it in the
251 * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
252 * returns NULL on failure. The caller does not take ownership of the result. */
253static hm_fragment *dtls1_get_incoming_message(
254 SSL *ssl, const struct hm_header_st *msg_hdr) {
255 if (msg_hdr->seq < ssl->d1->handshake_read_seq ||
256 msg_hdr->seq - ssl->d1->handshake_read_seq >= SSL_MAX_HANDSHAKE_FLIGHT) {
257 return NULL;
258 }
259
260 size_t idx = msg_hdr->seq % SSL_MAX_HANDSHAKE_FLIGHT;
261 hm_fragment *frag = ssl->d1->incoming_messages[idx];
262 if (frag != NULL) {
263 assert(frag->msg_header.seq == msg_hdr->seq);
264 /* The new fragment must be compatible with the previous fragments from this
265 * message. */
266 if (frag->msg_header.type != msg_hdr->type ||
267 frag->msg_header.msg_len != msg_hdr->msg_len) {
268 OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
269 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
270 return NULL;
271 }
272 return frag;
273 }
274
275 /* This is the first fragment from this message. */
276 frag = dtls1_hm_fragment_new(msg_hdr->msg_len);
277 if (frag == NULL) {
278 return NULL;
279 }
280 memcpy(&frag->msg_header, msg_hdr, sizeof(*msg_hdr));
281 ssl->d1->incoming_messages[idx] = frag;
282 return frag;
283}
284
285/* dtls1_process_handshake_record reads a handshake record and processes it. It
286 * returns one if the record was successfully processed and 0 or -1 on error. */
287static int dtls1_process_handshake_record(SSL *ssl) {
288 SSL3_RECORD *rr = &ssl->s3->rrec;
289
290start:
291 if (rr->length == 0) {
292 int ret = dtls1_get_record(ssl);
293 if (ret <= 0) {
294 return ret;
295 }
296 }
297
298 /* Cross-epoch records are discarded, but we may receive out-of-order
299 * application data between ChangeCipherSpec and Finished or a ChangeCipherSpec
300 * before the appropriate point in the handshake. Those must be silently
301 * discarded.
302 *
303 * However, only allow the out-of-order records in the correct epoch.
304 * Application data must come in the encrypted epoch, and ChangeCipherSpec in
305 * the unencrypted epoch (we never renegotiate). Other cases fall through and
306 * fail with a fatal error. */
307 if ((rr->type == SSL3_RT_APPLICATION_DATA &&
308 ssl->s3->aead_read_ctx != NULL) ||
309 (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC &&
310 ssl->s3->aead_read_ctx == NULL)) {
311 rr->length = 0;
312 goto start;
313 }
314
315 if (rr->type != SSL3_RT_HANDSHAKE) {
316 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
317 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
318 return -1;
319 }
320
321 CBS cbs;
322 CBS_init(&cbs, rr->data, rr->length);
323
324 while (CBS_len(&cbs) > 0) {
325 /* Read a handshake fragment. */
326 struct hm_header_st msg_hdr;
327 CBS body;
328 if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
329 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
330 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
331 return -1;
332 }
333
334 const size_t frag_off = msg_hdr.frag_off;
335 const size_t frag_len = msg_hdr.frag_len;
336 const size_t msg_len = msg_hdr.msg_len;
337 if (frag_off > msg_len || frag_off + frag_len < frag_off ||
338 frag_off + frag_len > msg_len ||
339 msg_len > ssl_max_handshake_message_len(ssl)) {
340 OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
341 ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
342 return -1;
343 }
344
345 if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
346 msg_hdr.seq >
347 (unsigned)ssl->d1->handshake_read_seq + SSL_MAX_HANDSHAKE_FLIGHT) {
348 /* Ignore fragments from the past, or ones too far in the future. */
349 continue;
350 }
351
352 hm_fragment *frag = dtls1_get_incoming_message(ssl, &msg_hdr);
353 if (frag == NULL) {
354 return -1;
355 }
356 assert(frag->msg_header.msg_len == msg_len);
357
358 if (frag->reassembly == NULL) {
359 /* The message is already assembled. */
360 continue;
361 }
362 assert(msg_len > 0);
363
364 /* Copy the body into the fragment. */
365 memcpy(frag->fragment + frag_off, CBS_data(&body), CBS_len(&body));
366 dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
367 }
368
369 rr->length = 0;
370 ssl_read_buffer_discard(ssl);
371 return 1;
372}
373
374/* dtls1_get_message reads a handshake message of message type |msg_type| (any
375 * if |msg_type| == -1). Read an entire handshake message. Handshake messages
376 * arrive in fragments. */
377long dtls1_get_message(SSL *ssl, int msg_type,
378 enum ssl_hash_message_t hash_message, int *ok) {
379 hm_fragment *frag = NULL;
380 int al;
381
382 /* s3->tmp is used to store messages that are unexpected, caused
383 * by the absence of an optional handshake message */
384 if (ssl->s3->tmp.reuse_message) {
385 /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
386 * ssl_dont_hash_message would have to have been applied to the previous
387 * call. */
388 assert(hash_message == ssl_hash_message);
389 ssl->s3->tmp.reuse_message = 0;
390 if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
391 al = SSL_AD_UNEXPECTED_MESSAGE;
392 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
393 goto f_err;
394 }
395 *ok = 1;
396 assert(ssl->init_buf->length >= DTLS1_HM_HEADER_LENGTH);
397 ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
398 ssl->init_num = (int)ssl->init_buf->length - DTLS1_HM_HEADER_LENGTH;
399 return ssl->init_num;
400 }
401
402 /* Process handshake records until the next message is ready. */
403 while (!dtls1_is_next_message_complete(ssl)) {
404 int ret = dtls1_process_handshake_record(ssl);
405 if (ret <= 0) {
406 *ok = 0;
407 return ret;
408 }
409 }
410
411 /* Pop an entry from the ring buffer. */
412 frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
413 SSL_MAX_HANDSHAKE_FLIGHT];
414 ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
415 SSL_MAX_HANDSHAKE_FLIGHT] = NULL;
416
417 assert(frag != NULL);
418 assert(frag->reassembly == NULL);
419 assert(ssl->d1->handshake_read_seq == frag->msg_header.seq);
420
421 ssl->d1->handshake_read_seq++;
422
423 /* Reconstruct the assembled message. */
424 CBB cbb;
425 CBB_zero(&cbb);
426 if (!BUF_MEM_reserve(ssl->init_buf, (size_t)frag->msg_header.msg_len +
427 DTLS1_HM_HEADER_LENGTH) ||
428 !CBB_init_fixed(&cbb, (uint8_t *)ssl->init_buf->data,
429 ssl->init_buf->max) ||
430 !CBB_add_u8(&cbb, frag->msg_header.type) ||
431 !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
432 !CBB_add_u16(&cbb, frag->msg_header.seq) ||
433 !CBB_add_u24(&cbb, 0 /* frag_off */) ||
434 !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
435 !CBB_add_bytes(&cbb, frag->fragment, frag->msg_header.msg_len) ||
436 !CBB_finish(&cbb, NULL, &ssl->init_buf->length)) {
437 CBB_cleanup(&cbb);
438 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
439 goto err;
440 }
441 assert(ssl->init_buf->length ==
442 (size_t)frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
443
444 /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
445 * |ssl_get_message| API. */
446 ssl->s3->tmp.message_type = frag->msg_header.type;
447 ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
448 ssl->init_num = frag->msg_header.msg_len;
449
450 if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
451 al = SSL_AD_UNEXPECTED_MESSAGE;
452 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
453 goto f_err;
454 }
455 if (hash_message == ssl_hash_message && !ssl3_hash_current_message(ssl)) {
456 goto err;
457 }
458
459 ssl_do_msg_callback(ssl, 0 /* read */, ssl->version, SSL3_RT_HANDSHAKE,
460 ssl->init_buf->data,
461 ssl->init_num + DTLS1_HM_HEADER_LENGTH);
462
463 dtls1_hm_fragment_free(frag);
464
465 *ok = 1;
466 return ssl->init_num;
467
468f_err:
469 ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
470err:
471 dtls1_hm_fragment_free(frag);
472 *ok = 0;
473 return -1;
474}
475
476void dtls_clear_incoming_messages(SSL *ssl) {
477 size_t i;
478 for (i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
479 dtls1_hm_fragment_free(ssl->d1->incoming_messages[i]);
480 ssl->d1->incoming_messages[i] = NULL;
481 }
482}
483
484int dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
485 CBS *out_body) {
486 memset(out_hdr, 0x00, sizeof(struct hm_header_st));
487
488 if (!CBS_get_u8(cbs, &out_hdr->type) ||
489 !CBS_get_u24(cbs, &out_hdr->msg_len) ||
490 !CBS_get_u16(cbs, &out_hdr->seq) ||
491 !CBS_get_u24(cbs, &out_hdr->frag_off) ||
492 !CBS_get_u24(cbs, &out_hdr->frag_len) ||
493 !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
494 return 0;
495 }
496
497 return 1;
498}
499
500
501/* Sending handshake messages. */
502
David Benjamina97b7372015-11-03 14:54:39 -0500503static void dtls1_update_mtu(SSL *ssl) {
504 /* TODO(davidben): What is this code doing and do we need it? */
505 if (ssl->d1->mtu < dtls1_min_mtu() &&
506 !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
David Benjamin2f871122016-05-20 14:27:17 -0400507 long mtu = BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
David Benjamina97b7372015-11-03 14:54:39 -0500508 if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
509 ssl->d1->mtu = (unsigned)mtu;
510 } else {
511 ssl->d1->mtu = kDefaultMTU;
David Benjamin2f871122016-05-20 14:27:17 -0400512 BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
David Benjamina97b7372015-11-03 14:54:39 -0500513 }
514 }
515
516 /* The MTU should be above the minimum now. */
517 assert(ssl->d1->mtu >= dtls1_min_mtu());
518}
519
David Benjamin16285ea2015-11-03 15:39:45 -0500520/* dtls1_max_record_size returns the maximum record body length that may be
521 * written without exceeding the MTU. It accounts for any buffering installed on
522 * the write BIO. If no record may be written, it returns zero. */
523static size_t dtls1_max_record_size(SSL *ssl) {
524 size_t ret = ssl->d1->mtu;
525
526 size_t overhead = ssl_max_seal_overhead(ssl);
527 if (ret <= overhead) {
528 return 0;
529 }
530 ret -= overhead;
531
David Benjamin2f871122016-05-20 14:27:17 -0400532 size_t pending = BIO_wpending(ssl->wbio);
David Benjamin16285ea2015-11-03 15:39:45 -0500533 if (ret <= pending) {
534 return 0;
535 }
536 ret -= pending;
537
538 return ret;
539}
540
David Benjamina97b7372015-11-03 14:54:39 -0500541static int dtls1_write_change_cipher_spec(SSL *ssl,
542 enum dtls1_use_epoch_t use_epoch) {
543 dtls1_update_mtu(ssl);
544
545 /* During the handshake, wbio is buffered to pack messages together. Flush the
546 * buffer if the ChangeCipherSpec would not fit in a packet. */
David Benjamin16285ea2015-11-03 15:39:45 -0500547 if (dtls1_max_record_size(ssl) == 0) {
David Benjamin2f871122016-05-20 14:27:17 -0400548 int ret = BIO_flush(ssl->wbio);
David Benjamina97b7372015-11-03 14:54:39 -0500549 if (ret <= 0) {
David Benjamin4c5ddb82016-03-11 22:56:19 -0500550 ssl->rwstate = SSL_WRITING;
David Benjamina97b7372015-11-03 14:54:39 -0500551 return ret;
552 }
David Benjamina97b7372015-11-03 14:54:39 -0500553 }
554
555 static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
David Benjamin0d56f882015-12-19 17:05:56 -0500556 int ret =
David Benjamin45d45c12016-06-07 15:20:49 -0400557 dtls1_write_record(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
558 sizeof(kChangeCipherSpec), use_epoch);
David Benjamina97b7372015-11-03 14:54:39 -0500559 if (ret <= 0) {
560 return ret;
561 }
562
David Benjamin4e9cc712016-06-01 20:16:03 -0400563 ssl_do_msg_callback(ssl, 1 /* write */, ssl->version,
564 SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
565 sizeof(kChangeCipherSpec));
David Benjamina97b7372015-11-03 14:54:39 -0500566 return 1;
567}
568
David Benjamin75836432016-06-17 18:48:29 -0400569/* dtls1_do_handshake_write writes handshake message |in| using the given epoch,
570 * starting |offset| bytes into the message body. It returns one on success. On
571 * error, it returns <= 0 and sets |*out_offset| to the number of bytes of body
572 * that were successfully written. This may be used to retry the write
573 * later. |in| must be a reassembled handshake message with the full DTLS
574 * handshake header. */
575static int dtls1_do_handshake_write(SSL *ssl, size_t *out_offset,
576 const uint8_t *in, size_t offset,
577 size_t len,
578 enum dtls1_use_epoch_t use_epoch) {
David Benjamin16285ea2015-11-03 15:39:45 -0500579 dtls1_update_mtu(ssl);
Adam Langley95c29f32014-06-20 12:00:00 -0700580
David Benjamin16285ea2015-11-03 15:39:45 -0500581 int ret = -1;
582 CBB cbb;
583 CBB_zero(&cbb);
584 /* Allocate a temporary buffer to hold the message fragments to avoid
585 * clobbering the message. */
586 uint8_t *buf = OPENSSL_malloc(ssl->d1->mtu);
587 if (buf == NULL) {
588 goto err;
Adam Langley71d8a082014-12-13 16:28:18 -0800589 }
Adam Langley95c29f32014-06-20 12:00:00 -0700590
David Benjaminb5eb1952016-06-17 18:44:38 -0400591 /* Although it may be sent as multiple fragments, a DTLS message must be sent
592 * serialized as a single fragment for purposes of |ssl_do_msg_callback| and
593 * the handshake hash. */
594 CBS cbs, body;
595 struct hm_header_st hdr;
596 CBS_init(&cbs, in, len);
597 if (!dtls1_parse_fragment(&cbs, &hdr, &body) ||
598 hdr.frag_off != 0 ||
599 hdr.frag_len != CBS_len(&body) ||
600 hdr.msg_len != CBS_len(&body) ||
601 !CBS_skip(&body, offset) ||
602 CBS_len(&cbs) != 0) {
603 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
604 goto err;
David Benjamin16285ea2015-11-03 15:39:45 -0500605 }
Adam Langley95c29f32014-06-20 12:00:00 -0700606
David Benjamin16285ea2015-11-03 15:39:45 -0500607 do {
608 /* During the handshake, wbio is buffered to pack messages together. Flush
609 * the buffer if there isn't enough room to make progress. */
610 if (dtls1_max_record_size(ssl) < DTLS1_HM_HEADER_LENGTH + 1) {
David Benjamin2f871122016-05-20 14:27:17 -0400611 int flush_ret = BIO_flush(ssl->wbio);
David Benjamin16285ea2015-11-03 15:39:45 -0500612 if (flush_ret <= 0) {
David Benjamin4c5ddb82016-03-11 22:56:19 -0500613 ssl->rwstate = SSL_WRITING;
David Benjamin16285ea2015-11-03 15:39:45 -0500614 ret = flush_ret;
615 goto err;
Adam Langley71d8a082014-12-13 16:28:18 -0800616 }
David Benjamin2f871122016-05-20 14:27:17 -0400617 assert(BIO_wpending(ssl->wbio) == 0);
Adam Langley71d8a082014-12-13 16:28:18 -0800618 }
Adam Langley95c29f32014-06-20 12:00:00 -0700619
David Benjamin16285ea2015-11-03 15:39:45 -0500620 size_t todo = dtls1_max_record_size(ssl);
621 if (todo < DTLS1_HM_HEADER_LENGTH + 1) {
David Benjamina97b7372015-11-03 14:54:39 -0500622 /* To make forward progress, the MTU must, at minimum, fit the handshake
623 * header and one byte of handshake body. */
624 OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
David Benjamin16285ea2015-11-03 15:39:45 -0500625 goto err;
626 }
627 todo -= DTLS1_HM_HEADER_LENGTH;
628
David Benjaminb5eb1952016-06-17 18:44:38 -0400629 if (todo > CBS_len(&body)) {
630 todo = CBS_len(&body);
David Benjamin16285ea2015-11-03 15:39:45 -0500631 }
632 if (todo >= (1u << 24)) {
633 todo = (1u << 24) - 1;
David Benjamina97b7372015-11-03 14:54:39 -0500634 }
635
David Benjaminb5eb1952016-06-17 18:44:38 -0400636 size_t buf_len;
David Benjamin16285ea2015-11-03 15:39:45 -0500637 if (!CBB_init_fixed(&cbb, buf, ssl->d1->mtu) ||
David Benjaminb5eb1952016-06-17 18:44:38 -0400638 !CBB_add_u8(&cbb, hdr.type) ||
639 !CBB_add_u24(&cbb, hdr.msg_len) ||
640 !CBB_add_u16(&cbb, hdr.seq) ||
641 !CBB_add_u24(&cbb, offset) ||
David Benjamin16285ea2015-11-03 15:39:45 -0500642 !CBB_add_u24(&cbb, todo) ||
David Benjaminb5eb1952016-06-17 18:44:38 -0400643 !CBB_add_bytes(&cbb, CBS_data(&body), todo) ||
644 !CBB_finish(&cbb, NULL, &buf_len)) {
David Benjamin16285ea2015-11-03 15:39:45 -0500645 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
646 goto err;
Adam Langley71d8a082014-12-13 16:28:18 -0800647 }
David Benjamin5a3cc032015-01-11 19:25:32 -0500648
David Benjamin45d45c12016-06-07 15:20:49 -0400649 int write_ret =
David Benjaminb5eb1952016-06-17 18:44:38 -0400650 dtls1_write_record(ssl, SSL3_RT_HANDSHAKE, buf, buf_len, use_epoch);
David Benjamin16285ea2015-11-03 15:39:45 -0500651 if (write_ret <= 0) {
652 ret = write_ret;
653 goto err;
David Benjamin5a3cc032015-01-11 19:25:32 -0500654 }
David Benjamin16285ea2015-11-03 15:39:45 -0500655
David Benjaminb5eb1952016-06-17 18:44:38 -0400656 if (!CBS_skip(&body, todo)) {
657 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
658 goto err;
659 }
660 offset += todo;
661 } while (CBS_len(&body) != 0);
Adam Langley71d8a082014-12-13 16:28:18 -0800662
David Benjaminb5eb1952016-06-17 18:44:38 -0400663 ssl_do_msg_callback(ssl, 1 /* write */, ssl->version, SSL3_RT_HANDSHAKE, in,
664 len);
David Benjamin16285ea2015-11-03 15:39:45 -0500665
666 ret = 1;
667
668err:
David Benjaminb5eb1952016-06-17 18:44:38 -0400669 *out_offset = offset;
David Benjamin16285ea2015-11-03 15:39:45 -0500670 CBB_cleanup(&cbb);
671 OPENSSL_free(buf);
672 return ret;
Adam Langley71d8a082014-12-13 16:28:18 -0800673}
Adam Langley95c29f32014-06-20 12:00:00 -0700674
David Benjamin75836432016-06-17 18:48:29 -0400675void dtls_clear_outgoing_messages(SSL *ssl) {
676 size_t i;
677 for (i = 0; i < ssl->d1->outgoing_messages_len; i++) {
678 OPENSSL_free(ssl->d1->outgoing_messages[i].data);
679 ssl->d1->outgoing_messages[i].data = NULL;
680 }
681 ssl->d1->outgoing_messages_len = 0;
682}
683
David Benjaminaad50db2016-06-23 17:49:12 -0400684/* dtls1_add_change_cipher_spec adds a ChangeCipherSpec to the current
David Benjamin75836432016-06-17 18:48:29 -0400685 * handshake flight. */
David Benjaminaad50db2016-06-23 17:49:12 -0400686static int dtls1_add_change_cipher_spec(SSL *ssl) {
David Benjamin75836432016-06-17 18:48:29 -0400687 if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
688 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
689 return 0;
690 }
691
692 DTLS_OUTGOING_MESSAGE *msg =
693 &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
694 msg->data = NULL;
695 msg->len = 0;
696 msg->epoch = ssl->d1->w_epoch;
697 msg->is_ccs = 1;
698
699 ssl->d1->outgoing_messages_len++;
700 return 1;
701}
702
David Benjaminaad50db2016-06-23 17:49:12 -0400703static int dtls1_add_message(SSL *ssl, uint8_t *data, size_t len) {
David Benjamin75836432016-06-17 18:48:29 -0400704 if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
705 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
706 OPENSSL_free(data);
707 return 0;
708 }
709
710 DTLS_OUTGOING_MESSAGE *msg =
711 &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
712 msg->data = data;
713 msg->len = len;
714 msg->epoch = ssl->d1->w_epoch;
715 msg->is_ccs = 0;
716
717 ssl->d1->outgoing_messages_len++;
718 return 1;
719}
720
721int dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
722 /* Pick a modest size hint to save most of the |realloc| calls. */
723 if (!CBB_init(cbb, 64) ||
724 !CBB_add_u8(cbb, type) ||
725 !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||
726 !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||
727 !CBB_add_u24(cbb, 0 /* offset */) ||
728 !CBB_add_u24_length_prefixed(cbb, body)) {
729 return 0;
730 }
731
732 return 1;
733}
734
735int dtls1_finish_message(SSL *ssl, CBB *cbb) {
736 uint8_t *msg = NULL;
737 size_t len;
738 if (!CBB_finish(cbb, &msg, &len) ||
739 len > 0xffffffffu ||
740 len < DTLS1_HM_HEADER_LENGTH) {
741 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
742 OPENSSL_free(msg);
743 return 0;
744 }
745
746 /* Fix up the header. Copy the fragment length into the total message
747 * length. */
748 memcpy(msg + 1, msg + DTLS1_HM_HEADER_LENGTH - 3, 3);
749
750 ssl3_update_handshake_hash(ssl, msg, len);
751
752 ssl->d1->handshake_write_seq++;
753 ssl->init_off = 0;
David Benjaminaad50db2016-06-23 17:49:12 -0400754 return dtls1_add_message(ssl, msg, len);
David Benjamin75836432016-06-17 18:48:29 -0400755}
756
757int dtls1_write_message(SSL *ssl) {
758 if (ssl->d1->outgoing_messages_len == 0) {
759 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
760 return -1;
761 }
762
763 const DTLS_OUTGOING_MESSAGE *msg =
764 &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len - 1];
765 if (msg->is_ccs) {
766 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
767 return -1;
768 }
769
770 size_t offset = ssl->init_off;
771 int ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
772 dtls1_use_current_epoch);
773 ssl->init_off = offset;
774 return ret;
775}
776
David Benjamin29a83c52016-06-17 19:12:54 -0400777static int dtls1_retransmit_message(SSL *ssl,
778 const DTLS_OUTGOING_MESSAGE *msg) {
David Benjaminafbc63f2015-02-01 02:33:59 -0500779 /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
780 * (negotiated cipher) exist. */
David Benjamin0d56f882015-12-19 17:05:56 -0500781 assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
David Benjamin29a83c52016-06-17 19:12:54 -0400782 assert(msg->epoch <= ssl->d1->w_epoch);
David Benjamin3e3090d2015-04-05 12:48:30 -0400783 enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
David Benjamin29a83c52016-06-17 19:12:54 -0400784 if (ssl->d1->w_epoch == 1 && msg->epoch == 0) {
David Benjamin3e3090d2015-04-05 12:48:30 -0400785 use_epoch = dtls1_use_previous_epoch;
Adam Langley71d8a082014-12-13 16:28:18 -0800786 }
787
David Benjamina97b7372015-11-03 14:54:39 -0500788 /* TODO(davidben): This cannot handle non-blocking writes. */
789 int ret;
David Benjamin29a83c52016-06-17 19:12:54 -0400790 if (msg->is_ccs) {
David Benjamin0d56f882015-12-19 17:05:56 -0500791 ret = dtls1_write_change_cipher_spec(ssl, use_epoch);
David Benjamina97b7372015-11-03 14:54:39 -0500792 } else {
David Benjaminb5eb1952016-06-17 18:44:38 -0400793 size_t offset = 0;
David Benjamin29a83c52016-06-17 19:12:54 -0400794 ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
795 use_epoch);
David Benjamina97b7372015-11-03 14:54:39 -0500796 }
797
Adam Langley71d8a082014-12-13 16:28:18 -0800798 return ret;
799}
Adam Langley95c29f32014-06-20 12:00:00 -0700800
David Benjaminaad50db2016-06-23 17:49:12 -0400801int dtls1_retransmit_outgoing_messages(SSL *ssl) {
David Benjamin30152fd2016-05-05 20:45:48 -0400802 /* Ensure we are packing handshake messages. */
803 const int was_buffered = ssl_is_wbio_buffered(ssl);
804 assert(was_buffered == SSL_in_init(ssl));
David Benjaminb095f0f2016-05-05 21:50:24 -0400805 if (!was_buffered && !ssl_init_wbio_buffer(ssl)) {
David Benjamin30152fd2016-05-05 20:45:48 -0400806 return -1;
807 }
808 assert(ssl_is_wbio_buffered(ssl));
Adam Langleybcc4e232015-02-19 15:51:58 -0800809
David Benjamin30152fd2016-05-05 20:45:48 -0400810 int ret = -1;
David Benjamin29a83c52016-06-17 19:12:54 -0400811 size_t i;
812 for (i = 0; i < ssl->d1->outgoing_messages_len; i++) {
813 if (dtls1_retransmit_message(ssl, &ssl->d1->outgoing_messages[i]) <= 0) {
David Benjamin30152fd2016-05-05 20:45:48 -0400814 goto err;
Adam Langleybcc4e232015-02-19 15:51:58 -0800815 }
816 }
817
David Benjamin2f871122016-05-20 14:27:17 -0400818 ret = BIO_flush(ssl->wbio);
David Benjamin27309552016-05-05 21:17:53 -0400819 if (ret <= 0) {
820 ssl->rwstate = SSL_WRITING;
821 goto err;
822 }
David Benjamin30152fd2016-05-05 20:45:48 -0400823
824err:
825 if (!was_buffered) {
826 ssl_free_wbio_buffer(ssl);
827 }
828 return ret;
Adam Langleybcc4e232015-02-19 15:51:58 -0800829}
830
David Benjamin0d56f882015-12-19 17:05:56 -0500831int dtls1_send_change_cipher_spec(SSL *ssl, int a, int b) {
832 if (ssl->state == a) {
David Benjaminaad50db2016-06-23 17:49:12 -0400833 dtls1_add_change_cipher_spec(ssl);
David Benjamin0d56f882015-12-19 17:05:56 -0500834 ssl->state = b;
David Benjamina97b7372015-11-03 14:54:39 -0500835 }
836
David Benjamin0d56f882015-12-19 17:05:56 -0500837 return dtls1_write_change_cipher_spec(ssl, dtls1_use_current_epoch);
David Benjamina97b7372015-11-03 14:54:39 -0500838}
839
Adam Langley71d8a082014-12-13 16:28:18 -0800840unsigned int dtls1_min_mtu(void) {
David Benjamina18b6712015-01-11 19:31:22 -0500841 return kMinMTU;
Adam Langley71d8a082014-12-13 16:28:18 -0800842}