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 <stdio.h>
119 #include <string.h>
120 
121 #include <openssl/buf.h>
122 #include <openssl/err.h>
123 #include <openssl/evp.h>
124 #include <openssl/mem.h>
125 #include <openssl/obj.h>
126 #include <openssl/rand.h>
127 #include <openssl/x509.h>
128 
129 #include "internal.h"
130 
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 /* kMaxHandshakeBuffer is the maximum number of handshake messages ahead of the
145  * current one to buffer. */
146 static const unsigned int kHandshakeBufferSize = 10;
147 
dtls1_hm_fragment_new(size_t frag_len,int reassembly)148 static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly) {
149   hm_fragment *frag = OPENSSL_malloc(sizeof(hm_fragment));
150   if (frag == NULL) {
151     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
152     return NULL;
153   }
154   memset(frag, 0, sizeof(hm_fragment));
155 
156   /* If the handshake message is empty, |frag->fragment| and |frag->reassembly|
157    * are NULL. */
158   if (frag_len > 0) {
159     frag->fragment = OPENSSL_malloc(frag_len);
160     if (frag->fragment == NULL) {
161       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
162       goto err;
163     }
164 
165     if (reassembly) {
166       /* Initialize reassembly bitmask. */
167       if (frag_len + 7 < frag_len) {
168         OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
169         goto err;
170       }
171       size_t bitmask_len = (frag_len + 7) / 8;
172       frag->reassembly = OPENSSL_malloc(bitmask_len);
173       if (frag->reassembly == NULL) {
174         OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
175         goto err;
176       }
177       memset(frag->reassembly, 0, bitmask_len);
178     }
179   }
180 
181   return frag;
182 
183 err:
184   dtls1_hm_fragment_free(frag);
185   return NULL;
186 }
187 
dtls1_hm_fragment_free(hm_fragment * frag)188 void dtls1_hm_fragment_free(hm_fragment *frag) {
189   if (frag == NULL) {
190     return;
191   }
192   OPENSSL_free(frag->fragment);
193   OPENSSL_free(frag->reassembly);
194   OPENSSL_free(frag);
195 }
196 
197 #if !defined(inline)
198 #define inline __inline
199 #endif
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 inline 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 i;
214   size_t msg_len = frag->msg_header.msg_len;
215 
216   if (frag->reassembly == NULL || start > end || end > msg_len) {
217     assert(0);
218     return;
219   }
220   /* A zero-length message will never have a pending reassembly. */
221   assert(msg_len > 0);
222 
223   if ((start >> 3) == (end >> 3)) {
224     frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
225   } else {
226     frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
227     for (i = (start >> 3) + 1; i < (end >> 3); i++) {
228       frag->reassembly[i] = 0xff;
229     }
230     if ((end & 7) != 0) {
231       frag->reassembly[end >> 3] |= bit_range(0, end & 7);
232     }
233   }
234 
235   /* Check if the fragment is complete. */
236   for (i = 0; i < (msg_len >> 3); i++) {
237     if (frag->reassembly[i] != 0xff) {
238       return;
239     }
240   }
241   if ((msg_len & 7) != 0 &&
242       frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
243     return;
244   }
245 
246   OPENSSL_free(frag->reassembly);
247   frag->reassembly = NULL;
248 }
249 
dtls1_update_mtu(SSL * ssl)250 static void dtls1_update_mtu(SSL *ssl) {
251   /* TODO(davidben): What is this code doing and do we need it? */
252   if (ssl->d1->mtu < dtls1_min_mtu() &&
253       !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
254     long mtu = BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
255     if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
256       ssl->d1->mtu = (unsigned)mtu;
257     } else {
258       ssl->d1->mtu = kDefaultMTU;
259       BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
260     }
261   }
262 
263   /* The MTU should be above the minimum now. */
264   assert(ssl->d1->mtu >= dtls1_min_mtu());
265 }
266 
267 /* dtls1_max_record_size returns the maximum record body length that may be
268  * written without exceeding the MTU. It accounts for any buffering installed on
269  * the write BIO. If no record may be written, it returns zero. */
dtls1_max_record_size(SSL * ssl)270 static size_t dtls1_max_record_size(SSL *ssl) {
271   size_t ret = ssl->d1->mtu;
272 
273   size_t overhead = ssl_max_seal_overhead(ssl);
274   if (ret <= overhead) {
275     return 0;
276   }
277   ret -= overhead;
278 
279   size_t pending = BIO_wpending(SSL_get_wbio(ssl));
280   if (ret <= pending) {
281     return 0;
282   }
283   ret -= pending;
284 
285   return ret;
286 }
287 
dtls1_write_change_cipher_spec(SSL * ssl,enum dtls1_use_epoch_t use_epoch)288 static int dtls1_write_change_cipher_spec(SSL *ssl,
289                                           enum dtls1_use_epoch_t use_epoch) {
290   dtls1_update_mtu(ssl);
291 
292   /* During the handshake, wbio is buffered to pack messages together. Flush the
293    * buffer if the ChangeCipherSpec would not fit in a packet. */
294   if (dtls1_max_record_size(ssl) == 0) {
295     ssl->rwstate = SSL_WRITING;
296     int ret = BIO_flush(SSL_get_wbio(ssl));
297     if (ret <= 0) {
298       return ret;
299     }
300     ssl->rwstate = SSL_NOTHING;
301   }
302 
303   static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
304   int ret =
305       dtls1_write_bytes(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
306                         sizeof(kChangeCipherSpec), use_epoch);
307   if (ret <= 0) {
308     return ret;
309   }
310 
311   if (ssl->msg_callback != NULL) {
312     ssl->msg_callback(1 /* write */, ssl->version, SSL3_RT_CHANGE_CIPHER_SPEC,
313                       kChangeCipherSpec, sizeof(kChangeCipherSpec), ssl,
314                       ssl->msg_callback_arg);
315   }
316 
317   return 1;
318 }
319 
dtls1_do_handshake_write(SSL * ssl,enum dtls1_use_epoch_t use_epoch)320 int dtls1_do_handshake_write(SSL *ssl, enum dtls1_use_epoch_t use_epoch) {
321   dtls1_update_mtu(ssl);
322 
323   int ret = -1;
324   CBB cbb;
325   CBB_zero(&cbb);
326   /* Allocate a temporary buffer to hold the message fragments to avoid
327    * clobbering the message. */
328   uint8_t *buf = OPENSSL_malloc(ssl->d1->mtu);
329   if (buf == NULL) {
330     goto err;
331   }
332 
333   /* Consume the message header. Fragments will have different headers
334    * prepended. */
335   if (ssl->init_off == 0) {
336     ssl->init_off += DTLS1_HM_HEADER_LENGTH;
337     ssl->init_num -= DTLS1_HM_HEADER_LENGTH;
338   }
339   assert(ssl->init_off >= DTLS1_HM_HEADER_LENGTH);
340 
341   do {
342     /* During the handshake, wbio is buffered to pack messages together. Flush
343      * the buffer if there isn't enough room to make progress. */
344     if (dtls1_max_record_size(ssl) < DTLS1_HM_HEADER_LENGTH + 1) {
345       ssl->rwstate = SSL_WRITING;
346       int flush_ret = BIO_flush(SSL_get_wbio(ssl));
347       if (flush_ret <= 0) {
348         ret = flush_ret;
349         goto err;
350       }
351       ssl->rwstate = SSL_NOTHING;
352       assert(BIO_wpending(SSL_get_wbio(ssl)) == 0);
353     }
354 
355     size_t todo = dtls1_max_record_size(ssl);
356     if (todo < DTLS1_HM_HEADER_LENGTH + 1) {
357       /* To make forward progress, the MTU must, at minimum, fit the handshake
358        * header and one byte of handshake body. */
359       OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
360       goto err;
361     }
362     todo -= DTLS1_HM_HEADER_LENGTH;
363 
364     if (todo > (size_t)ssl->init_num) {
365       todo = ssl->init_num;
366     }
367     if (todo >= (1u << 24)) {
368       todo = (1u << 24) - 1;
369     }
370 
371     size_t len;
372     if (!CBB_init_fixed(&cbb, buf, ssl->d1->mtu) ||
373         !CBB_add_u8(&cbb, ssl->d1->w_msg_hdr.type) ||
374         !CBB_add_u24(&cbb, ssl->d1->w_msg_hdr.msg_len) ||
375         !CBB_add_u16(&cbb, ssl->d1->w_msg_hdr.seq) ||
376         !CBB_add_u24(&cbb, ssl->init_off - DTLS1_HM_HEADER_LENGTH) ||
377         !CBB_add_u24(&cbb, todo) ||
378         !CBB_add_bytes(
379             &cbb, (const uint8_t *)ssl->init_buf->data + ssl->init_off, todo) ||
380         !CBB_finish(&cbb, NULL, &len)) {
381       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
382       goto err;
383     }
384 
385     int write_ret = dtls1_write_bytes(ssl, SSL3_RT_HANDSHAKE, buf, len,
386                                       use_epoch);
387     if (write_ret <= 0) {
388       ret = write_ret;
389       goto err;
390     }
391     ssl->init_off += todo;
392     ssl->init_num -= todo;
393   } while (ssl->init_num > 0);
394 
395   if (ssl->msg_callback != NULL) {
396     ssl->msg_callback(
397         1 /* write */, ssl->version, SSL3_RT_HANDSHAKE, ssl->init_buf->data,
398         (size_t)(ssl->init_off + ssl->init_num), ssl, ssl->msg_callback_arg);
399   }
400 
401   ssl->init_off = 0;
402   ssl->init_num = 0;
403 
404   ret = 1;
405 
406 err:
407   CBB_cleanup(&cbb);
408   OPENSSL_free(buf);
409   return ret;
410 }
411 
412 /* dtls1_is_next_message_complete returns one if the next handshake message is
413  * complete and zero otherwise. */
dtls1_is_next_message_complete(SSL * ssl)414 static int dtls1_is_next_message_complete(SSL *ssl) {
415   pitem *item = pqueue_peek(ssl->d1->buffered_messages);
416   if (item == NULL) {
417     return 0;
418   }
419 
420   hm_fragment *frag = (hm_fragment *)item->data;
421   assert(ssl->d1->handshake_read_seq <= frag->msg_header.seq);
422 
423   return ssl->d1->handshake_read_seq == frag->msg_header.seq &&
424          frag->reassembly == NULL;
425 }
426 
427 /* dtls1_discard_fragment_body discards a handshake fragment body of length
428  * |frag_len|. It returns one on success and zero on error.
429  *
430  * TODO(davidben): This function will go away when ssl_read_bytes is gone from
431  * the DTLS side. */
dtls1_discard_fragment_body(SSL * ssl,size_t frag_len)432 static int dtls1_discard_fragment_body(SSL *ssl, size_t frag_len) {
433   uint8_t discard[256];
434   while (frag_len > 0) {
435     size_t chunk = frag_len < sizeof(discard) ? frag_len : sizeof(discard);
436     int ret = dtls1_read_bytes(ssl, SSL3_RT_HANDSHAKE, discard, chunk, 0);
437     if (ret != (int) chunk) {
438       return 0;
439     }
440     frag_len -= chunk;
441   }
442   return 1;
443 }
444 
445 /* dtls1_get_buffered_message returns the buffered message corresponding to
446  * |msg_hdr|. If none exists, it creates a new one and inserts it in the
447  * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
448  * returns NULL on failure. The caller does not take ownership of the result. */
dtls1_get_buffered_message(SSL * ssl,const struct hm_header_st * msg_hdr)449 static hm_fragment *dtls1_get_buffered_message(
450     SSL *ssl, const struct hm_header_st *msg_hdr) {
451   uint8_t seq64be[8];
452   memset(seq64be, 0, sizeof(seq64be));
453   seq64be[6] = (uint8_t)(msg_hdr->seq >> 8);
454   seq64be[7] = (uint8_t)msg_hdr->seq;
455   pitem *item = pqueue_find(ssl->d1->buffered_messages, seq64be);
456 
457   hm_fragment *frag;
458   if (item == NULL) {
459     /* This is the first fragment from this message. */
460     frag = dtls1_hm_fragment_new(msg_hdr->msg_len,
461                                  1 /* reassembly buffer needed */);
462     if (frag == NULL) {
463       return NULL;
464     }
465     memcpy(&frag->msg_header, msg_hdr, sizeof(*msg_hdr));
466     item = pitem_new(seq64be, frag);
467     if (item == NULL) {
468       dtls1_hm_fragment_free(frag);
469       return NULL;
470     }
471     item = pqueue_insert(ssl->d1->buffered_messages, item);
472     /* |pqueue_insert| fails iff a duplicate item is inserted, but |item| cannot
473      * be a duplicate. */
474     assert(item != NULL);
475   } else {
476     frag = item->data;
477     assert(frag->msg_header.seq == msg_hdr->seq);
478     if (frag->msg_header.type != msg_hdr->type ||
479         frag->msg_header.msg_len != msg_hdr->msg_len) {
480       /* The new fragment must be compatible with the previous fragments from
481        * this message. */
482       OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
483       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
484       return NULL;
485     }
486   }
487   return frag;
488 }
489 
490 /* dtls1_max_handshake_message_len returns the maximum number of bytes
491  * permitted in a DTLS handshake message for |ssl|. The minimum is 16KB, but may
492  * be greater if the maximum certificate list size requires it. */
dtls1_max_handshake_message_len(const SSL * ssl)493 static size_t dtls1_max_handshake_message_len(const SSL *ssl) {
494   size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
495   if (max_len < ssl->max_cert_list) {
496     return ssl->max_cert_list;
497   }
498   return max_len;
499 }
500 
501 /* dtls1_process_fragment reads a handshake fragment and processes it. It
502  * returns one if a fragment was successfully processed and 0 or -1 on error. */
dtls1_process_fragment(SSL * ssl)503 static int dtls1_process_fragment(SSL *ssl) {
504   /* Read handshake message header. */
505   uint8_t header[DTLS1_HM_HEADER_LENGTH];
506   int ret = dtls1_read_bytes(ssl, SSL3_RT_HANDSHAKE, header,
507                              DTLS1_HM_HEADER_LENGTH, 0);
508   if (ret <= 0) {
509     return ret;
510   }
511   if (ret != DTLS1_HM_HEADER_LENGTH) {
512     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
513     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
514     return -1;
515   }
516 
517   /* Parse the message fragment header. */
518   struct hm_header_st msg_hdr;
519   dtls1_get_message_header(header, &msg_hdr);
520 
521   /* TODO(davidben): dtls1_read_bytes is the wrong abstraction for DTLS. There
522    * should be no need to reach into |ssl->s3->rrec.length|. */
523   const size_t frag_off = msg_hdr.frag_off;
524   const size_t frag_len = msg_hdr.frag_len;
525   const size_t msg_len = msg_hdr.msg_len;
526   if (frag_off > msg_len || frag_off + frag_len < frag_off ||
527       frag_off + frag_len > msg_len ||
528       msg_len > dtls1_max_handshake_message_len(ssl) ||
529       frag_len > ssl->s3->rrec.length) {
530     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
531     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
532     return -1;
533   }
534 
535   if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
536       msg_hdr.seq > (unsigned)ssl->d1->handshake_read_seq +
537                     kHandshakeBufferSize) {
538     /* Ignore fragments from the past, or ones too far in the future. */
539     if (!dtls1_discard_fragment_body(ssl, frag_len)) {
540       return -1;
541     }
542     return 1;
543   }
544 
545   hm_fragment *frag = dtls1_get_buffered_message(ssl, &msg_hdr);
546   if (frag == NULL) {
547     return -1;
548   }
549   assert(frag->msg_header.msg_len == msg_len);
550 
551   if (frag->reassembly == NULL) {
552     /* The message is already assembled. */
553     if (!dtls1_discard_fragment_body(ssl, frag_len)) {
554       return -1;
555     }
556     return 1;
557   }
558   assert(msg_len > 0);
559 
560   /* Read the body of the fragment. */
561   ret = dtls1_read_bytes(ssl, SSL3_RT_HANDSHAKE, frag->fragment + frag_off,
562                          frag_len, 0);
563   if (ret != (int) frag_len) {
564     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
565     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
566     return -1;
567   }
568   dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
569 
570   return 1;
571 }
572 
573 /* dtls1_get_message reads a handshake message of message type |msg_type| (any
574  * if |msg_type| == -1), maximum acceptable body length |max|. Read an entire
575  * handshake message. Handshake messages arrive in fragments. */
dtls1_get_message(SSL * ssl,int st1,int stn,int msg_type,long max,enum ssl_hash_message_t hash_message,int * ok)576 long dtls1_get_message(SSL *ssl, int st1, int stn, int msg_type, long max,
577                        enum ssl_hash_message_t hash_message, int *ok) {
578   pitem *item = NULL;
579   hm_fragment *frag = NULL;
580   int al;
581 
582   /* s3->tmp is used to store messages that are unexpected, caused
583    * by the absence of an optional handshake message */
584   if (ssl->s3->tmp.reuse_message) {
585     /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
586      * ssl_dont_hash_message would have to have been applied to the previous
587      * call. */
588     assert(hash_message == ssl_hash_message);
589     ssl->s3->tmp.reuse_message = 0;
590     if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
591       al = SSL_AD_UNEXPECTED_MESSAGE;
592       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
593       goto f_err;
594     }
595     *ok = 1;
596     ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
597     ssl->init_num = (int)ssl->s3->tmp.message_size;
598     return ssl->init_num;
599   }
600 
601   /* Process fragments until one is found. */
602   while (!dtls1_is_next_message_complete(ssl)) {
603     int ret = dtls1_process_fragment(ssl);
604     if (ret <= 0) {
605       *ok = 0;
606       return ret;
607     }
608   }
609 
610   /* Read out the next complete handshake message. */
611   item = pqueue_pop(ssl->d1->buffered_messages);
612   assert(item != NULL);
613   frag = (hm_fragment *)item->data;
614   assert(ssl->d1->handshake_read_seq == frag->msg_header.seq);
615   assert(frag->reassembly == NULL);
616 
617   if (frag->msg_header.msg_len > (size_t)max) {
618     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
619     goto err;
620   }
621 
622   /* Reconstruct the assembled message. */
623   size_t len;
624   CBB cbb;
625   CBB_zero(&cbb);
626   if (!BUF_MEM_grow(ssl->init_buf, (size_t)frag->msg_header.msg_len +
627                                        DTLS1_HM_HEADER_LENGTH) ||
628       !CBB_init_fixed(&cbb, (uint8_t *)ssl->init_buf->data,
629                       ssl->init_buf->max) ||
630       !CBB_add_u8(&cbb, frag->msg_header.type) ||
631       !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
632       !CBB_add_u16(&cbb, frag->msg_header.seq) ||
633       !CBB_add_u24(&cbb, 0 /* frag_off */) ||
634       !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
635       !CBB_add_bytes(&cbb, frag->fragment, frag->msg_header.msg_len) ||
636       !CBB_finish(&cbb, NULL, &len)) {
637     CBB_cleanup(&cbb);
638     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
639     goto err;
640   }
641   assert(len == (size_t)frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
642 
643   ssl->d1->handshake_read_seq++;
644 
645   /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
646    * |ssl_get_message| API. */
647   ssl->s3->tmp.message_type = frag->msg_header.type;
648   ssl->s3->tmp.message_size = frag->msg_header.msg_len;
649   ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
650   ssl->init_num = frag->msg_header.msg_len;
651 
652   if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
653     al = SSL_AD_UNEXPECTED_MESSAGE;
654     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
655     goto f_err;
656   }
657   if (hash_message == ssl_hash_message && !ssl3_hash_current_message(ssl)) {
658     goto err;
659   }
660   if (ssl->msg_callback) {
661     ssl->msg_callback(0, ssl->version, SSL3_RT_HANDSHAKE, ssl->init_buf->data,
662                     ssl->init_num + DTLS1_HM_HEADER_LENGTH, ssl,
663                     ssl->msg_callback_arg);
664   }
665 
666   pitem_free(item);
667   dtls1_hm_fragment_free(frag);
668 
669   ssl->state = stn;
670   *ok = 1;
671   return ssl->init_num;
672 
673 f_err:
674   ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
675 err:
676   pitem_free(item);
677   dtls1_hm_fragment_free(frag);
678   *ok = 0;
679   return -1;
680 }
681 
dtls1_read_failed(SSL * ssl,int code)682 int dtls1_read_failed(SSL *ssl, int code) {
683   if (code > 0) {
684     assert(0);
685     return 1;
686   }
687 
688   if (!dtls1_is_timer_expired(ssl)) {
689     /* not a timeout, none of our business, let higher layers handle this. In
690      * fact, it's probably an error */
691     return code;
692   }
693 
694   if (!SSL_in_init(ssl)) {
695     /* done, no need to send a retransmit */
696     BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);
697     return code;
698   }
699 
700   return DTLSv1_handle_timeout(ssl);
701 }
702 
dtls1_get_queue_priority(uint16_t seq,int is_ccs)703 static uint16_t dtls1_get_queue_priority(uint16_t seq, int is_ccs) {
704   assert(seq * 2 >= seq);
705 
706   /* The index of the retransmission queue actually is the message sequence
707    * number, since the queue only contains messages of a single handshake.
708    * However, the ChangeCipherSpec has no message sequence number and so using
709    * only the sequence will result in the CCS and Finished having the same
710    * index. To prevent this, the sequence number is multiplied by 2. In case of
711    * a CCS 1 is subtracted. This does not only differ CSS and Finished, it also
712    * maintains the order of the index (important for priority queues) and fits
713    * in the unsigned short variable. */
714   return seq * 2 - is_ccs;
715 }
716 
dtls1_retransmit_message(SSL * ssl,hm_fragment * frag)717 static int dtls1_retransmit_message(SSL *ssl, hm_fragment *frag) {
718   /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
719    * (negotiated cipher) exist. */
720   assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
721   assert(frag->msg_header.epoch <= ssl->d1->w_epoch);
722   enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
723   if (ssl->d1->w_epoch == 1 && frag->msg_header.epoch == 0) {
724     use_epoch = dtls1_use_previous_epoch;
725   }
726 
727   /* TODO(davidben): This cannot handle non-blocking writes. */
728   int ret;
729   if (frag->msg_header.is_ccs) {
730     ret = dtls1_write_change_cipher_spec(ssl, use_epoch);
731   } else {
732     /* Restore the message body.
733      * TODO(davidben): Make this less stateful. */
734     memcpy(ssl->init_buf->data, frag->fragment,
735            frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
736     ssl->init_num = frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH;
737 
738     dtls1_set_message_header(ssl, frag->msg_header.type,
739                              frag->msg_header.msg_len, frag->msg_header.seq,
740                              0, frag->msg_header.frag_len);
741     ret = dtls1_do_handshake_write(ssl, use_epoch);
742   }
743 
744   /* TODO(davidben): Check return value? */
745   (void)BIO_flush(SSL_get_wbio(ssl));
746   return ret;
747 }
748 
749 
dtls1_retransmit_buffered_messages(SSL * ssl)750 int dtls1_retransmit_buffered_messages(SSL *ssl) {
751   pqueue sent = ssl->d1->sent_messages;
752   piterator iter = pqueue_iterator(sent);
753   pitem *item;
754 
755   for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
756     hm_fragment *frag = (hm_fragment *)item->data;
757     if (dtls1_retransmit_message(ssl, frag) <= 0) {
758       return -1;
759     }
760   }
761 
762   return 1;
763 }
764 
765 /* dtls1_buffer_change_cipher_spec adds a ChangeCipherSpec to the current
766  * handshake flight, ordered just before the handshake message numbered
767  * |seq|. */
dtls1_buffer_change_cipher_spec(SSL * ssl,uint16_t seq)768 static int dtls1_buffer_change_cipher_spec(SSL *ssl, uint16_t seq) {
769   hm_fragment *frag = dtls1_hm_fragment_new(0 /* frag_len */,
770                                             0 /* no reassembly */);
771   if (frag == NULL) {
772     return 0;
773   }
774   frag->msg_header.is_ccs = 1;
775   frag->msg_header.epoch = ssl->d1->w_epoch;
776 
777   uint16_t priority = dtls1_get_queue_priority(seq, 1 /* is_ccs */);
778   uint8_t seq64be[8];
779   memset(seq64be, 0, sizeof(seq64be));
780   seq64be[6] = (uint8_t)(priority >> 8);
781   seq64be[7] = (uint8_t)priority;
782 
783   pitem *item = pitem_new(seq64be, frag);
784   if (item == NULL) {
785     dtls1_hm_fragment_free(frag);
786     return 0;
787   }
788 
789   pqueue_insert(ssl->d1->sent_messages, item);
790   return 1;
791 }
792 
dtls1_buffer_message(SSL * ssl)793 int dtls1_buffer_message(SSL *ssl) {
794   /* this function is called immediately after a message has
795    * been serialized */
796   assert(ssl->init_off == 0);
797 
798   hm_fragment *frag = dtls1_hm_fragment_new(ssl->init_num, 0);
799   if (!frag) {
800     return 0;
801   }
802 
803   memcpy(frag->fragment, ssl->init_buf->data, ssl->init_num);
804 
805   assert(ssl->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH ==
806          (unsigned int)ssl->init_num);
807 
808   frag->msg_header.msg_len = ssl->d1->w_msg_hdr.msg_len;
809   frag->msg_header.seq = ssl->d1->w_msg_hdr.seq;
810   frag->msg_header.type = ssl->d1->w_msg_hdr.type;
811   frag->msg_header.frag_off = 0;
812   frag->msg_header.frag_len = ssl->d1->w_msg_hdr.msg_len;
813   frag->msg_header.is_ccs = 0;
814   frag->msg_header.epoch = ssl->d1->w_epoch;
815 
816   uint16_t priority = dtls1_get_queue_priority(frag->msg_header.seq,
817                                                0 /* handshake */);
818   uint8_t seq64be[8];
819   memset(seq64be, 0, sizeof(seq64be));
820   seq64be[6] = (uint8_t)(priority >> 8);
821   seq64be[7] = (uint8_t)priority;
822 
823   pitem *item = pitem_new(seq64be, frag);
824   if (item == NULL) {
825     dtls1_hm_fragment_free(frag);
826     return 0;
827   }
828 
829   pqueue_insert(ssl->d1->sent_messages, item);
830   return 1;
831 }
832 
dtls1_send_change_cipher_spec(SSL * ssl,int a,int b)833 int dtls1_send_change_cipher_spec(SSL *ssl, int a, int b) {
834   if (ssl->state == a) {
835     /* Buffer the message to handle retransmits. */
836     ssl->d1->handshake_write_seq = ssl->d1->next_handshake_write_seq;
837     dtls1_buffer_change_cipher_spec(ssl, ssl->d1->handshake_write_seq);
838     ssl->state = b;
839   }
840 
841   return dtls1_write_change_cipher_spec(ssl, dtls1_use_current_epoch);
842 }
843 
844 /* call this function when the buffered messages are no longer needed */
dtls1_clear_record_buffer(SSL * ssl)845 void dtls1_clear_record_buffer(SSL *ssl) {
846   pitem *item;
847 
848   for (item = pqueue_pop(ssl->d1->sent_messages); item != NULL;
849        item = pqueue_pop(ssl->d1->sent_messages)) {
850     dtls1_hm_fragment_free((hm_fragment *)item->data);
851     pitem_free(item);
852   }
853 }
854 
855 /* don't actually do the writing, wait till the MTU has been retrieved */
dtls1_set_message_header(SSL * ssl,uint8_t mt,unsigned long len,unsigned short seq_num,unsigned long frag_off,unsigned long frag_len)856 void dtls1_set_message_header(SSL *ssl, uint8_t mt, unsigned long len,
857                               unsigned short seq_num, unsigned long frag_off,
858                               unsigned long frag_len) {
859   struct hm_header_st *msg_hdr = &ssl->d1->w_msg_hdr;
860 
861   msg_hdr->type = mt;
862   msg_hdr->msg_len = len;
863   msg_hdr->seq = seq_num;
864   msg_hdr->frag_off = frag_off;
865   msg_hdr->frag_len = frag_len;
866 }
867 
dtls1_min_mtu(void)868 unsigned int dtls1_min_mtu(void) {
869   return kMinMTU;
870 }
871 
dtls1_get_message_header(uint8_t * data,struct hm_header_st * msg_hdr)872 void dtls1_get_message_header(uint8_t *data,
873                               struct hm_header_st *msg_hdr) {
874   memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
875   msg_hdr->type = *(data++);
876   n2l3(data, msg_hdr->msg_len);
877 
878   n2s(data, msg_hdr->seq);
879   n2l3(data, msg_hdr->frag_off);
880   n2l3(data, msg_hdr->frag_len);
881 }
882