1 /*
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
114 #include <openssl/ssl.h>
115
116 #include <assert.h>
117 #include <limits.h>
118 #include <string.h>
119
120 #include <openssl/buf.h>
121 #include <openssl/err.h>
122 #include <openssl/evp.h>
123 #include <openssl/mem.h>
124 #include <openssl/rand.h>
125
126 #include "../crypto/internal.h"
127 #include "internal.h"
128
129
130 BSSL_NAMESPACE_BEGIN
131
132 // TODO(davidben): 28 comes from the size of IP + UDP header. Is this reasonable
133 // for these values? Notably, why is kMinMTU a function of the transport
134 // protocol's overhead rather than, say, what's needed to hold a minimally-sized
135 // handshake fragment plus protocol overhead.
136
137 // kMinMTU is the minimum acceptable MTU value.
138 static const unsigned int kMinMTU = 256 - 28;
139
140 // kDefaultMTU is the default MTU value to use if neither the user nor
141 // the underlying BIO supplies one.
142 static const unsigned int kDefaultMTU = 1500 - 28;
143
144
145 // Receiving handshake messages.
146
~hm_fragment()147 hm_fragment::~hm_fragment() {
148 OPENSSL_free(data);
149 OPENSSL_free(reassembly);
150 }
151
dtls1_hm_fragment_new(const struct hm_header_st * msg_hdr)152 static UniquePtr<hm_fragment> dtls1_hm_fragment_new(
153 const struct hm_header_st *msg_hdr) {
154 ScopedCBB cbb;
155 UniquePtr<hm_fragment> frag = MakeUnique<hm_fragment>();
156 if (!frag) {
157 return nullptr;
158 }
159 frag->type = msg_hdr->type;
160 frag->seq = msg_hdr->seq;
161 frag->msg_len = msg_hdr->msg_len;
162
163 // Allocate space for the reassembled message and fill in the header.
164 frag->data =
165 (uint8_t *)OPENSSL_malloc(DTLS1_HM_HEADER_LENGTH + msg_hdr->msg_len);
166 if (frag->data == NULL) {
167 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
168 return nullptr;
169 }
170
171 if (!CBB_init_fixed(cbb.get(), frag->data, DTLS1_HM_HEADER_LENGTH) ||
172 !CBB_add_u8(cbb.get(), msg_hdr->type) ||
173 !CBB_add_u24(cbb.get(), msg_hdr->msg_len) ||
174 !CBB_add_u16(cbb.get(), msg_hdr->seq) ||
175 !CBB_add_u24(cbb.get(), 0 /* frag_off */) ||
176 !CBB_add_u24(cbb.get(), msg_hdr->msg_len) ||
177 !CBB_finish(cbb.get(), NULL, NULL)) {
178 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
179 return nullptr;
180 }
181
182 // If the handshake message is empty, |frag->reassembly| is NULL.
183 if (msg_hdr->msg_len > 0) {
184 // Initialize reassembly bitmask.
185 if (msg_hdr->msg_len + 7 < msg_hdr->msg_len) {
186 OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
187 return nullptr;
188 }
189 size_t bitmask_len = (msg_hdr->msg_len + 7) / 8;
190 frag->reassembly = (uint8_t *)OPENSSL_malloc(bitmask_len);
191 if (frag->reassembly == NULL) {
192 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
193 return nullptr;
194 }
195 OPENSSL_memset(frag->reassembly, 0, bitmask_len);
196 }
197
198 return frag;
199 }
200
201 // bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
202 // exclusive, set.
bit_range(size_t start,size_t end)203 static uint8_t bit_range(size_t start, size_t end) {
204 return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
205 }
206
207 // dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
208 // as received in |frag|. If |frag| becomes complete, it clears
209 // |frag->reassembly|. The range must be within the bounds of |frag|'s message
210 // and |frag->reassembly| must not be NULL.
dtls1_hm_fragment_mark(hm_fragment * frag,size_t start,size_t end)211 static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
212 size_t end) {
213 size_t msg_len = frag->msg_len;
214
215 if (frag->reassembly == NULL || start > end || end > msg_len) {
216 assert(0);
217 return;
218 }
219 // A zero-length message will never have a pending reassembly.
220 assert(msg_len > 0);
221
222 if (start == end) {
223 return;
224 }
225
226 if ((start >> 3) == (end >> 3)) {
227 frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
228 } else {
229 frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
230 for (size_t i = (start >> 3) + 1; i < (end >> 3); i++) {
231 frag->reassembly[i] = 0xff;
232 }
233 if ((end & 7) != 0) {
234 frag->reassembly[end >> 3] |= bit_range(0, end & 7);
235 }
236 }
237
238 // Check if the fragment is complete.
239 for (size_t i = 0; i < (msg_len >> 3); i++) {
240 if (frag->reassembly[i] != 0xff) {
241 return;
242 }
243 }
244 if ((msg_len & 7) != 0 &&
245 frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
246 return;
247 }
248
249 OPENSSL_free(frag->reassembly);
250 frag->reassembly = NULL;
251 }
252
253 // dtls1_is_current_message_complete returns whether the current handshake
254 // message is complete.
dtls1_is_current_message_complete(const SSL * ssl)255 static bool dtls1_is_current_message_complete(const SSL *ssl) {
256 size_t idx = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
257 hm_fragment *frag = ssl->d1->incoming_messages[idx].get();
258 return frag != NULL && frag->reassembly == NULL;
259 }
260
261 // dtls1_get_incoming_message returns the incoming message corresponding to
262 // |msg_hdr|. If none exists, it creates a new one and inserts it in the
263 // queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
264 // returns NULL on failure. The caller does not take ownership of the result.
dtls1_get_incoming_message(SSL * ssl,uint8_t * out_alert,const struct hm_header_st * msg_hdr)265 static hm_fragment *dtls1_get_incoming_message(
266 SSL *ssl, uint8_t *out_alert, const struct hm_header_st *msg_hdr) {
267 if (msg_hdr->seq < ssl->d1->handshake_read_seq ||
268 msg_hdr->seq - ssl->d1->handshake_read_seq >= SSL_MAX_HANDSHAKE_FLIGHT) {
269 *out_alert = SSL_AD_INTERNAL_ERROR;
270 return NULL;
271 }
272
273 size_t idx = msg_hdr->seq % SSL_MAX_HANDSHAKE_FLIGHT;
274 hm_fragment *frag = ssl->d1->incoming_messages[idx].get();
275 if (frag != NULL) {
276 assert(frag->seq == msg_hdr->seq);
277 // The new fragment must be compatible with the previous fragments from this
278 // message.
279 if (frag->type != msg_hdr->type ||
280 frag->msg_len != msg_hdr->msg_len) {
281 OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
282 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
283 return NULL;
284 }
285 return frag;
286 }
287
288 // This is the first fragment from this message.
289 ssl->d1->incoming_messages[idx] = dtls1_hm_fragment_new(msg_hdr);
290 if (!ssl->d1->incoming_messages[idx]) {
291 *out_alert = SSL_AD_INTERNAL_ERROR;
292 return NULL;
293 }
294 return ssl->d1->incoming_messages[idx].get();
295 }
296
dtls1_open_handshake(SSL * ssl,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)297 ssl_open_record_t dtls1_open_handshake(SSL *ssl, size_t *out_consumed,
298 uint8_t *out_alert, Span<uint8_t> in) {
299 uint8_t type;
300 Span<uint8_t> record;
301 auto ret = dtls_open_record(ssl, &type, &record, out_consumed, out_alert, in);
302 if (ret != ssl_open_record_success) {
303 return ret;
304 }
305
306 switch (type) {
307 case SSL3_RT_APPLICATION_DATA:
308 // Unencrypted application data records are always illegal.
309 if (ssl->s3->aead_read_ctx->is_null_cipher()) {
310 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
311 *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
312 return ssl_open_record_error;
313 }
314
315 // Out-of-order application data may be received between ChangeCipherSpec
316 // and finished. Discard it.
317 return ssl_open_record_discard;
318
319 case SSL3_RT_CHANGE_CIPHER_SPEC:
320 // We do not support renegotiation, so encrypted ChangeCipherSpec records
321 // are illegal.
322 if (!ssl->s3->aead_read_ctx->is_null_cipher()) {
323 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
324 *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
325 return ssl_open_record_error;
326 }
327
328 if (record.size() != 1u || record[0] != SSL3_MT_CCS) {
329 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
330 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
331 return ssl_open_record_error;
332 }
333
334 // Flag the ChangeCipherSpec for later.
335 ssl->d1->has_change_cipher_spec = true;
336 ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_CHANGE_CIPHER_SPEC,
337 record);
338 return ssl_open_record_success;
339
340 case SSL3_RT_HANDSHAKE:
341 // Break out to main processing.
342 break;
343
344 default:
345 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
346 *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
347 return ssl_open_record_error;
348 }
349
350 CBS cbs;
351 CBS_init(&cbs, record.data(), record.size());
352 while (CBS_len(&cbs) > 0) {
353 // Read a handshake fragment.
354 struct hm_header_st msg_hdr;
355 CBS body;
356 if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
357 OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
358 *out_alert = SSL_AD_DECODE_ERROR;
359 return ssl_open_record_error;
360 }
361
362 const size_t frag_off = msg_hdr.frag_off;
363 const size_t frag_len = msg_hdr.frag_len;
364 const size_t msg_len = msg_hdr.msg_len;
365 if (frag_off > msg_len || frag_off + frag_len < frag_off ||
366 frag_off + frag_len > msg_len ||
367 msg_len > ssl_max_handshake_message_len(ssl)) {
368 OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
369 *out_alert = SSL_AD_ILLEGAL_PARAMETER;
370 return ssl_open_record_error;
371 }
372
373 // The encrypted epoch in DTLS has only one handshake message.
374 if (ssl->d1->r_epoch == 1 && msg_hdr.seq != ssl->d1->handshake_read_seq) {
375 OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
376 *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
377 return ssl_open_record_error;
378 }
379
380 if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
381 msg_hdr.seq >
382 (unsigned)ssl->d1->handshake_read_seq + SSL_MAX_HANDSHAKE_FLIGHT) {
383 // Ignore fragments from the past, or ones too far in the future.
384 continue;
385 }
386
387 hm_fragment *frag = dtls1_get_incoming_message(ssl, out_alert, &msg_hdr);
388 if (frag == NULL) {
389 return ssl_open_record_error;
390 }
391 assert(frag->msg_len == msg_len);
392
393 if (frag->reassembly == NULL) {
394 // The message is already assembled.
395 continue;
396 }
397 assert(msg_len > 0);
398
399 // Copy the body into the fragment.
400 OPENSSL_memcpy(frag->data + DTLS1_HM_HEADER_LENGTH + frag_off,
401 CBS_data(&body), CBS_len(&body));
402 dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
403 }
404
405 return ssl_open_record_success;
406 }
407
dtls1_get_message(SSL * ssl,SSLMessage * out)408 bool dtls1_get_message(SSL *ssl, SSLMessage *out) {
409 if (!dtls1_is_current_message_complete(ssl)) {
410 return false;
411 }
412
413 size_t idx = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
414 hm_fragment *frag = ssl->d1->incoming_messages[idx].get();
415 out->type = frag->type;
416 CBS_init(&out->body, frag->data + DTLS1_HM_HEADER_LENGTH, frag->msg_len);
417 CBS_init(&out->raw, frag->data, DTLS1_HM_HEADER_LENGTH + frag->msg_len);
418 out->is_v2_hello = false;
419 if (!ssl->s3->has_message) {
420 ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HANDSHAKE, out->raw);
421 ssl->s3->has_message = true;
422 }
423 return true;
424 }
425
dtls1_next_message(SSL * ssl)426 void dtls1_next_message(SSL *ssl) {
427 assert(ssl->s3->has_message);
428 assert(dtls1_is_current_message_complete(ssl));
429 size_t index = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
430 ssl->d1->incoming_messages[index].reset();
431 ssl->d1->handshake_read_seq++;
432 ssl->s3->has_message = false;
433 // If we previously sent a flight, mark it as having a reply, so
434 // |on_handshake_complete| can manage post-handshake retransmission.
435 if (ssl->d1->outgoing_messages_complete) {
436 ssl->d1->flight_has_reply = true;
437 }
438 }
439
dtls_has_unprocessed_handshake_data(const SSL * ssl)440 bool dtls_has_unprocessed_handshake_data(const SSL *ssl) {
441 if (ssl->d1->has_change_cipher_spec) {
442 return true;
443 }
444
445 size_t current = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
446 for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
447 // Skip the current message.
448 if (ssl->s3->has_message && i == current) {
449 assert(dtls1_is_current_message_complete(ssl));
450 continue;
451 }
452 if (ssl->d1->incoming_messages[i] != nullptr) {
453 return true;
454 }
455 }
456 return false;
457 }
458
dtls1_parse_fragment(CBS * cbs,struct hm_header_st * out_hdr,CBS * out_body)459 bool dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
460 CBS *out_body) {
461 OPENSSL_memset(out_hdr, 0x00, sizeof(struct hm_header_st));
462
463 if (!CBS_get_u8(cbs, &out_hdr->type) ||
464 !CBS_get_u24(cbs, &out_hdr->msg_len) ||
465 !CBS_get_u16(cbs, &out_hdr->seq) ||
466 !CBS_get_u24(cbs, &out_hdr->frag_off) ||
467 !CBS_get_u24(cbs, &out_hdr->frag_len) ||
468 !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
469 return false;
470 }
471
472 return true;
473 }
474
dtls1_open_change_cipher_spec(SSL * ssl,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)475 ssl_open_record_t dtls1_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
476 uint8_t *out_alert,
477 Span<uint8_t> in) {
478 if (!ssl->d1->has_change_cipher_spec) {
479 // dtls1_open_handshake processes both handshake and ChangeCipherSpec.
480 auto ret = dtls1_open_handshake(ssl, out_consumed, out_alert, in);
481 if (ret != ssl_open_record_success) {
482 return ret;
483 }
484 }
485 if (ssl->d1->has_change_cipher_spec) {
486 ssl->d1->has_change_cipher_spec = false;
487 return ssl_open_record_success;
488 }
489 return ssl_open_record_discard;
490 }
491
492
493 // Sending handshake messages.
494
Clear()495 void DTLS_OUTGOING_MESSAGE::Clear() {
496 OPENSSL_free(data);
497 data = nullptr;
498 }
499
dtls_clear_outgoing_messages(SSL * ssl)500 void dtls_clear_outgoing_messages(SSL *ssl) {
501 for (size_t i = 0; i < ssl->d1->outgoing_messages_len; i++) {
502 ssl->d1->outgoing_messages[i].Clear();
503 }
504 ssl->d1->outgoing_messages_len = 0;
505 ssl->d1->outgoing_written = 0;
506 ssl->d1->outgoing_offset = 0;
507 ssl->d1->outgoing_messages_complete = false;
508 ssl->d1->flight_has_reply = false;
509 }
510
dtls1_init_message(SSL * ssl,CBB * cbb,CBB * body,uint8_t type)511 bool dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
512 // Pick a modest size hint to save most of the |realloc| calls.
513 if (!CBB_init(cbb, 64) ||
514 !CBB_add_u8(cbb, type) ||
515 !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||
516 !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||
517 !CBB_add_u24(cbb, 0 /* offset */) ||
518 !CBB_add_u24_length_prefixed(cbb, body)) {
519 return false;
520 }
521
522 return true;
523 }
524
dtls1_finish_message(SSL * ssl,CBB * cbb,Array<uint8_t> * out_msg)525 bool dtls1_finish_message(SSL *ssl, CBB *cbb, Array<uint8_t> *out_msg) {
526 if (!CBBFinishArray(cbb, out_msg) ||
527 out_msg->size() < DTLS1_HM_HEADER_LENGTH) {
528 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
529 return false;
530 }
531
532 // Fix up the header. Copy the fragment length into the total message
533 // length.
534 OPENSSL_memcpy(out_msg->data() + 1,
535 out_msg->data() + DTLS1_HM_HEADER_LENGTH - 3, 3);
536 return true;
537 }
538
539 // ssl_size_t_greater_than_32_bits returns whether |v| exceeds the bounds of a
540 // 32-bit value. The obvious thing doesn't work because, in some 32-bit build
541 // configurations, the compiler warns that the test is always false and breaks
542 // the build.
ssl_size_t_greater_than_32_bits(size_t v)543 static bool ssl_size_t_greater_than_32_bits(size_t v) {
544 #if defined(OPENSSL_64_BIT)
545 return v > 0xffffffff;
546 #elif defined(OPENSSL_32_BIT)
547 return false;
548 #else
549 #error "Building for neither 32- nor 64-bits."
550 #endif
551 }
552
553 // add_outgoing adds a new handshake message or ChangeCipherSpec to the current
554 // outgoing flight. It returns true on success and false on error.
add_outgoing(SSL * ssl,bool is_ccs,Array<uint8_t> data)555 static bool add_outgoing(SSL *ssl, bool is_ccs, Array<uint8_t> data) {
556 if (ssl->d1->outgoing_messages_complete) {
557 // If we've begun writing a new flight, we received the peer flight. Discard
558 // the timer and the our flight.
559 dtls1_stop_timer(ssl);
560 dtls_clear_outgoing_messages(ssl);
561 }
562
563 static_assert(SSL_MAX_HANDSHAKE_FLIGHT <
564 (1 << 8 * sizeof(ssl->d1->outgoing_messages_len)),
565 "outgoing_messages_len is too small");
566 if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT ||
567 ssl_size_t_greater_than_32_bits(data.size())) {
568 assert(false);
569 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
570 return false;
571 }
572
573 if (!is_ccs) {
574 // TODO(svaldez): Move this up a layer to fix abstraction for SSLTranscript
575 // on hs.
576 if (ssl->s3->hs != NULL &&
577 !ssl->s3->hs->transcript.Update(data)) {
578 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
579 return false;
580 }
581 ssl->d1->handshake_write_seq++;
582 }
583
584 DTLS_OUTGOING_MESSAGE *msg =
585 &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
586 size_t len;
587 data.Release(&msg->data, &len);
588 msg->len = len;
589 msg->epoch = ssl->d1->w_epoch;
590 msg->is_ccs = is_ccs;
591
592 ssl->d1->outgoing_messages_len++;
593 return true;
594 }
595
dtls1_add_message(SSL * ssl,Array<uint8_t> data)596 bool dtls1_add_message(SSL *ssl, Array<uint8_t> data) {
597 return add_outgoing(ssl, false /* handshake */, std::move(data));
598 }
599
dtls1_add_change_cipher_spec(SSL * ssl)600 bool dtls1_add_change_cipher_spec(SSL *ssl) {
601 return add_outgoing(ssl, true /* ChangeCipherSpec */, Array<uint8_t>());
602 }
603
604 // dtls1_update_mtu updates the current MTU from the BIO, ensuring it is above
605 // the minimum.
dtls1_update_mtu(SSL * ssl)606 static void dtls1_update_mtu(SSL *ssl) {
607 // TODO(davidben): No consumer implements |BIO_CTRL_DGRAM_SET_MTU| and the
608 // only |BIO_CTRL_DGRAM_QUERY_MTU| implementation could use
609 // |SSL_set_mtu|. Does this need to be so complex?
610 if (ssl->d1->mtu < dtls1_min_mtu() &&
611 !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
612 long mtu = BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
613 if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
614 ssl->d1->mtu = (unsigned)mtu;
615 } else {
616 ssl->d1->mtu = kDefaultMTU;
617 BIO_ctrl(ssl->wbio.get(), BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
618 }
619 }
620
621 // The MTU should be above the minimum now.
622 assert(ssl->d1->mtu >= dtls1_min_mtu());
623 }
624
625 enum seal_result_t {
626 seal_error,
627 seal_no_progress,
628 seal_partial,
629 seal_success,
630 };
631
632 // seal_next_message seals |msg|, which must be the next message, to |out|. If
633 // progress was made, it returns |seal_partial| or |seal_success| and sets
634 // |*out_len| to the number of bytes written.
seal_next_message(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,const DTLS_OUTGOING_MESSAGE * msg)635 static enum seal_result_t seal_next_message(SSL *ssl, uint8_t *out,
636 size_t *out_len, size_t max_out,
637 const DTLS_OUTGOING_MESSAGE *msg) {
638 assert(ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len);
639 assert(msg == &ssl->d1->outgoing_messages[ssl->d1->outgoing_written]);
640
641 enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
642 if (ssl->d1->w_epoch >= 1 && msg->epoch == ssl->d1->w_epoch - 1) {
643 use_epoch = dtls1_use_previous_epoch;
644 } else if (msg->epoch != ssl->d1->w_epoch) {
645 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
646 return seal_error;
647 }
648
649 size_t overhead = dtls_max_seal_overhead(ssl, use_epoch);
650 size_t prefix = dtls_seal_prefix_len(ssl, use_epoch);
651
652 if (msg->is_ccs) {
653 // Check there is room for the ChangeCipherSpec.
654 static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
655 if (max_out < sizeof(kChangeCipherSpec) + overhead) {
656 return seal_no_progress;
657 }
658
659 if (!dtls_seal_record(ssl, out, out_len, max_out,
660 SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
661 sizeof(kChangeCipherSpec), use_epoch)) {
662 return seal_error;
663 }
664
665 ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_CHANGE_CIPHER_SPEC,
666 kChangeCipherSpec);
667 return seal_success;
668 }
669
670 // DTLS messages are serialized as a single fragment in |msg|.
671 CBS cbs, body;
672 struct hm_header_st hdr;
673 CBS_init(&cbs, msg->data, msg->len);
674 if (!dtls1_parse_fragment(&cbs, &hdr, &body) ||
675 hdr.frag_off != 0 ||
676 hdr.frag_len != CBS_len(&body) ||
677 hdr.msg_len != CBS_len(&body) ||
678 !CBS_skip(&body, ssl->d1->outgoing_offset) ||
679 CBS_len(&cbs) != 0) {
680 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
681 return seal_error;
682 }
683
684 // Determine how much progress can be made.
685 if (max_out < DTLS1_HM_HEADER_LENGTH + 1 + overhead || max_out < prefix) {
686 return seal_no_progress;
687 }
688 size_t todo = CBS_len(&body);
689 if (todo > max_out - DTLS1_HM_HEADER_LENGTH - overhead) {
690 todo = max_out - DTLS1_HM_HEADER_LENGTH - overhead;
691 }
692
693 // Assemble a fragment, to be sealed in-place.
694 ScopedCBB cbb;
695 uint8_t *frag = out + prefix;
696 size_t max_frag = max_out - prefix, frag_len;
697 if (!CBB_init_fixed(cbb.get(), frag, max_frag) ||
698 !CBB_add_u8(cbb.get(), hdr.type) ||
699 !CBB_add_u24(cbb.get(), hdr.msg_len) ||
700 !CBB_add_u16(cbb.get(), hdr.seq) ||
701 !CBB_add_u24(cbb.get(), ssl->d1->outgoing_offset) ||
702 !CBB_add_u24(cbb.get(), todo) ||
703 !CBB_add_bytes(cbb.get(), CBS_data(&body), todo) ||
704 !CBB_finish(cbb.get(), NULL, &frag_len)) {
705 OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
706 return seal_error;
707 }
708
709 ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HANDSHAKE,
710 MakeSpan(frag, frag_len));
711
712 if (!dtls_seal_record(ssl, out, out_len, max_out, SSL3_RT_HANDSHAKE,
713 out + prefix, frag_len, use_epoch)) {
714 return seal_error;
715 }
716
717 if (todo == CBS_len(&body)) {
718 // The next message is complete.
719 ssl->d1->outgoing_offset = 0;
720 return seal_success;
721 }
722
723 ssl->d1->outgoing_offset += todo;
724 return seal_partial;
725 }
726
727 // seal_next_packet writes as much of the next flight as possible to |out| and
728 // advances |ssl->d1->outgoing_written| and |ssl->d1->outgoing_offset| as
729 // appropriate.
seal_next_packet(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out)730 static bool seal_next_packet(SSL *ssl, uint8_t *out, size_t *out_len,
731 size_t max_out) {
732 bool made_progress = false;
733 size_t total = 0;
734 assert(ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len);
735 for (; ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len;
736 ssl->d1->outgoing_written++) {
737 const DTLS_OUTGOING_MESSAGE *msg =
738 &ssl->d1->outgoing_messages[ssl->d1->outgoing_written];
739 size_t len;
740 enum seal_result_t ret = seal_next_message(ssl, out, &len, max_out, msg);
741 switch (ret) {
742 case seal_error:
743 return false;
744
745 case seal_no_progress:
746 goto packet_full;
747
748 case seal_partial:
749 case seal_success:
750 out += len;
751 max_out -= len;
752 total += len;
753 made_progress = true;
754
755 if (ret == seal_partial) {
756 goto packet_full;
757 }
758 break;
759 }
760 }
761
762 packet_full:
763 // The MTU was too small to make any progress.
764 if (!made_progress) {
765 OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
766 return false;
767 }
768
769 *out_len = total;
770 return true;
771 }
772
send_flight(SSL * ssl)773 static int send_flight(SSL *ssl) {
774 if (ssl->s3->write_shutdown != ssl_shutdown_none) {
775 OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
776 return -1;
777 }
778
779 dtls1_update_mtu(ssl);
780
781 int ret = -1;
782 uint8_t *packet = (uint8_t *)OPENSSL_malloc(ssl->d1->mtu);
783 if (packet == NULL) {
784 OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
785 goto err;
786 }
787
788 while (ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len) {
789 uint8_t old_written = ssl->d1->outgoing_written;
790 uint32_t old_offset = ssl->d1->outgoing_offset;
791
792 size_t packet_len;
793 if (!seal_next_packet(ssl, packet, &packet_len, ssl->d1->mtu)) {
794 goto err;
795 }
796
797 int bio_ret = BIO_write(ssl->wbio.get(), packet, packet_len);
798 if (bio_ret <= 0) {
799 // Retry this packet the next time around.
800 ssl->d1->outgoing_written = old_written;
801 ssl->d1->outgoing_offset = old_offset;
802 ssl->s3->rwstate = SSL_WRITING;
803 ret = bio_ret;
804 goto err;
805 }
806 }
807
808 if (BIO_flush(ssl->wbio.get()) <= 0) {
809 ssl->s3->rwstate = SSL_WRITING;
810 goto err;
811 }
812
813 ret = 1;
814
815 err:
816 OPENSSL_free(packet);
817 return ret;
818 }
819
dtls1_flush_flight(SSL * ssl)820 int dtls1_flush_flight(SSL *ssl) {
821 ssl->d1->outgoing_messages_complete = true;
822 // Start the retransmission timer for the next flight (if any).
823 dtls1_start_timer(ssl);
824 return send_flight(ssl);
825 }
826
dtls1_retransmit_outgoing_messages(SSL * ssl)827 int dtls1_retransmit_outgoing_messages(SSL *ssl) {
828 // Rewind to the start of the flight and write it again.
829 //
830 // TODO(davidben): This does not allow retransmits to be resumed on
831 // non-blocking write.
832 ssl->d1->outgoing_written = 0;
833 ssl->d1->outgoing_offset = 0;
834
835 return send_flight(ssl);
836 }
837
dtls1_min_mtu(void)838 unsigned int dtls1_min_mtu(void) {
839 return kMinMTU;
840 }
841
842 BSSL_NAMESPACE_END
843