Update copyright year
[openssl.git] / ssl / statem / statem_dtls.c
1 /*
2  * Copyright 2005-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <limits.h>
11 #include <string.h>
12 #include <stdio.h>
13 #include "../ssl_local.h"
14 #include "statem_local.h"
15 #include "internal/cryptlib.h"
16 #include <openssl/buffer.h>
17 #include <openssl/objects.h>
18 #include <openssl/evp.h>
19 #include <openssl/x509.h>
20
21 #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
22
23 #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
24                         if ((end) - (start) <= 8) { \
25                                 long ii; \
26                                 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
27                         } else { \
28                                 long ii; \
29                                 bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
30                                 for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
31                                 bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
32                         } }
33
34 #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
35                         long ii; \
36                         is_complete = 1; \
37                         if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
38                         if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
39                                 if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
40
41 static unsigned char bitmask_start_values[] =
42     { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
43 static unsigned char bitmask_end_values[] =
44     { 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f };
45
46 static void dtls1_fix_message_header(SSL *s, size_t frag_off,
47                                      size_t frag_len);
48 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
49 static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
50                                          size_t len,
51                                          unsigned short seq_num,
52                                          size_t frag_off,
53                                          size_t frag_len);
54 static int dtls_get_reassembled_message(SSL *s, int *errtype, size_t *len);
55
56 static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)
57 {
58     hm_fragment *frag = NULL;
59     unsigned char *buf = NULL;
60     unsigned char *bitmask = NULL;
61
62     if ((frag = OPENSSL_malloc(sizeof(*frag))) == NULL) {
63         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
64         return NULL;
65     }
66
67     if (frag_len) {
68         if ((buf = OPENSSL_malloc(frag_len)) == NULL) {
69             ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
70             OPENSSL_free(frag);
71             return NULL;
72         }
73     }
74
75     /* zero length fragment gets zero frag->fragment */
76     frag->fragment = buf;
77
78     /* Initialize reassembly bitmask if necessary */
79     if (reassembly) {
80         bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len));
81         if (bitmask == NULL) {
82             ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
83             OPENSSL_free(buf);
84             OPENSSL_free(frag);
85             return NULL;
86         }
87     }
88
89     frag->reassembly = bitmask;
90
91     return frag;
92 }
93
94 void dtls1_hm_fragment_free(hm_fragment *frag)
95 {
96     if (!frag)
97         return;
98     if (frag->msg_header.is_ccs) {
99         EVP_CIPHER_CTX_free(frag->msg_header.
100                             saved_retransmit_state.enc_write_ctx);
101         EVP_MD_CTX_free(frag->msg_header.saved_retransmit_state.write_hash);
102     }
103     OPENSSL_free(frag->fragment);
104     OPENSSL_free(frag->reassembly);
105     OPENSSL_free(frag);
106 }
107
108 /*
109  * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
110  * SSL3_RT_CHANGE_CIPHER_SPEC)
111  */
112 int dtls1_do_write(SSL *s, int type)
113 {
114     int ret;
115     size_t written;
116     size_t curr_mtu;
117     int retry = 1;
118     size_t len, frag_off, mac_size, blocksize, used_len;
119
120     if (!dtls1_query_mtu(s))
121         return -1;
122
123     if (s->d1->mtu < dtls1_min_mtu(s))
124         /* should have something reasonable now */
125         return -1;
126
127     if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
128         if (!ossl_assert(s->init_num ==
129                          s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH))
130             return -1;
131     }
132
133     if (s->write_hash) {
134         if (s->enc_write_ctx
135             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx)) &
136                 EVP_CIPH_FLAG_AEAD_CIPHER) != 0)
137             mac_size = 0;
138         else
139             mac_size = EVP_MD_CTX_get_size(s->write_hash);
140     } else
141         mac_size = 0;
142
143     if (s->enc_write_ctx &&
144         (EVP_CIPHER_CTX_get_mode(s->enc_write_ctx) == EVP_CIPH_CBC_MODE))
145         blocksize = 2 * EVP_CIPHER_CTX_get_block_size(s->enc_write_ctx);
146     else
147         blocksize = 0;
148
149     frag_off = 0;
150     s->rwstate = SSL_NOTHING;
151
152     /* s->init_num shouldn't ever be < 0...but just in case */
153     while (s->init_num > 0) {
154         if (type == SSL3_RT_HANDSHAKE && s->init_off != 0) {
155             /* We must be writing a fragment other than the first one */
156
157             if (frag_off > 0) {
158                 /* This is the first attempt at writing out this fragment */
159
160                 if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {
161                     /*
162                      * Each fragment that was already sent must at least have
163                      * contained the message header plus one other byte.
164                      * Therefore |init_off| must have progressed by at least
165                      * |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went
166                      * wrong.
167                      */
168                     return -1;
169                 }
170
171                 /*
172                  * Adjust |init_off| and |init_num| to allow room for a new
173                  * message header for this fragment.
174                  */
175                 s->init_off -= DTLS1_HM_HEADER_LENGTH;
176                 s->init_num += DTLS1_HM_HEADER_LENGTH;
177             } else {
178                 /*
179                  * We must have been called again after a retry so use the
180                  * fragment offset from our last attempt. We do not need
181                  * to adjust |init_off| and |init_num| as above, because
182                  * that should already have been done before the retry.
183                  */
184                 frag_off = s->d1->w_msg_hdr.frag_off;
185             }
186         }
187
188         used_len = BIO_wpending(s->wbio) + DTLS1_RT_HEADER_LENGTH
189             + mac_size + blocksize;
190         if (s->d1->mtu > used_len)
191             curr_mtu = s->d1->mtu - used_len;
192         else
193             curr_mtu = 0;
194
195         if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
196             /*
197              * grr.. we could get an error if MTU picked was wrong
198              */
199             ret = BIO_flush(s->wbio);
200             if (ret <= 0) {
201                 s->rwstate = SSL_WRITING;
202                 return ret;
203             }
204             used_len = DTLS1_RT_HEADER_LENGTH + mac_size + blocksize;
205             if (s->d1->mtu > used_len + DTLS1_HM_HEADER_LENGTH) {
206                 curr_mtu = s->d1->mtu - used_len;
207             } else {
208                 /* Shouldn't happen */
209                 return -1;
210             }
211         }
212
213         /*
214          * We just checked that s->init_num > 0 so this cast should be safe
215          */
216         if (((unsigned int)s->init_num) > curr_mtu)
217             len = curr_mtu;
218         else
219             len = s->init_num;
220
221         if (len > ssl_get_max_send_fragment(s))
222             len = ssl_get_max_send_fragment(s);
223
224         /*
225          * XDTLS: this function is too long.  split out the CCS part
226          */
227         if (type == SSL3_RT_HANDSHAKE) {
228             if (len < DTLS1_HM_HEADER_LENGTH) {
229                 /*
230                  * len is so small that we really can't do anything sensible
231                  * so fail
232                  */
233                 return -1;
234             }
235             dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);
236
237             dtls1_write_message_header(s,
238                                        (unsigned char *)&s->init_buf->
239                                        data[s->init_off]);
240         }
241
242         ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,
243                                 &written);
244         if (ret <= 0) {
245             /*
246              * might need to update MTU here, but we don't know which
247              * previous packet caused the failure -- so can't really
248              * retransmit anything.  continue as if everything is fine and
249              * wait for an alert to handle the retransmit
250              */
251             if (retry && BIO_ctrl(SSL_get_wbio(s),
252                                   BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
253                 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
254                     if (!dtls1_query_mtu(s))
255                         return -1;
256                     /* Have one more go */
257                     retry = 0;
258                 } else
259                     return -1;
260             } else {
261                 return -1;
262             }
263         } else {
264
265             /*
266              * bad if this assert fails, only part of the handshake message
267              * got sent.  but why would this happen?
268              */
269             if (!ossl_assert(len == written))
270                 return -1;
271
272             if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
273                 /*
274                  * should not be done for 'Hello Request's, but in that case
275                  * we'll ignore the result anyway
276                  */
277                 unsigned char *p =
278                     (unsigned char *)&s->init_buf->data[s->init_off];
279                 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
280                 size_t xlen;
281
282                 if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
283                     /*
284                      * reconstruct message header is if it is being sent in
285                      * single fragment
286                      */
287                     *p++ = msg_hdr->type;
288                     l2n3(msg_hdr->msg_len, p);
289                     s2n(msg_hdr->seq, p);
290                     l2n3(0, p);
291                     l2n3(msg_hdr->msg_len, p);
292                     p -= DTLS1_HM_HEADER_LENGTH;
293                     xlen = written;
294                 } else {
295                     p += DTLS1_HM_HEADER_LENGTH;
296                     xlen = written - DTLS1_HM_HEADER_LENGTH;
297                 }
298
299                 if (!ssl3_finish_mac(s, p, xlen))
300                     return -1;
301             }
302
303             if (written == s->init_num) {
304                 if (s->msg_callback)
305                     s->msg_callback(1, s->version, type, s->init_buf->data,
306                                     (size_t)(s->init_off + s->init_num), s,
307                                     s->msg_callback_arg);
308
309                 s->init_off = 0; /* done writing this message */
310                 s->init_num = 0;
311
312                 return 1;
313             }
314             s->init_off += written;
315             s->init_num -= written;
316             written -= DTLS1_HM_HEADER_LENGTH;
317             frag_off += written;
318
319             /*
320              * We save the fragment offset for the next fragment so we have it
321              * available in case of an IO retry. We don't know the length of the
322              * next fragment yet so just set that to 0 for now. It will be
323              * updated again later.
324              */
325             dtls1_fix_message_header(s, frag_off, 0);
326         }
327     }
328     return 0;
329 }
330
331 int dtls_get_message(SSL *s, int *mt)
332 {
333     struct hm_header_st *msg_hdr;
334     unsigned char *p;
335     size_t msg_len;
336     size_t tmplen;
337     int errtype;
338
339     msg_hdr = &s->d1->r_msg_hdr;
340     memset(msg_hdr, 0, sizeof(*msg_hdr));
341
342  again:
343     if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
344         if (errtype == DTLS1_HM_BAD_FRAGMENT
345                 || errtype == DTLS1_HM_FRAGMENT_RETRY) {
346             /* bad fragment received */
347             goto again;
348         }
349         return 0;
350     }
351
352     *mt = s->s3.tmp.message_type;
353
354     p = (unsigned char *)s->init_buf->data;
355
356     if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
357         if (s->msg_callback) {
358             s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
359                             p, 1, s, s->msg_callback_arg);
360         }
361         /*
362          * This isn't a real handshake message so skip the processing below.
363          */
364         return 1;
365     }
366
367     msg_len = msg_hdr->msg_len;
368
369     /* reconstruct message header */
370     *(p++) = msg_hdr->type;
371     l2n3(msg_len, p);
372     s2n(msg_hdr->seq, p);
373     l2n3(0, p);
374     l2n3(msg_len, p);
375
376     memset(msg_hdr, 0, sizeof(*msg_hdr));
377
378     s->d1->handshake_read_seq++;
379
380     s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
381
382     return 1;
383 }
384
385 /*
386  * Actually we already have the message body - but this is an opportunity for
387  * DTLS to do any further processing it wants at the same point that TLS would
388  * be asked for the message body.
389  */
390 int dtls_get_message_body(SSL *s, size_t *len)
391 {
392     unsigned char *msg = (unsigned char *)s->init_buf->data;
393     size_t msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;
394
395     if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
396         /* Nothing to be done */
397         goto end;
398     }
399     /*
400      * If receiving Finished, record MAC of prior handshake messages for
401      * Finished verification.
402      */
403     if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
404         /* SSLfatal() already called */
405         return 0;
406     }
407
408     if (s->version == DTLS1_BAD_VER) {
409         msg += DTLS1_HM_HEADER_LENGTH;
410         msg_len -= DTLS1_HM_HEADER_LENGTH;
411     }
412
413     if (!ssl3_finish_mac(s, msg, msg_len))
414         return 0;
415
416     if (s->msg_callback)
417         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
418                         s->init_buf->data, s->init_num + DTLS1_HM_HEADER_LENGTH,
419                         s, s->msg_callback_arg);
420
421  end:
422     *len = s->init_num;
423     return 1;
424 }
425
426 /*
427  * dtls1_max_handshake_message_len returns the maximum number of bytes
428  * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
429  * may be greater if the maximum certificate list size requires it.
430  */
431 static size_t dtls1_max_handshake_message_len(const SSL *s)
432 {
433     size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
434     if (max_len < s->max_cert_list)
435         return s->max_cert_list;
436     return max_len;
437 }
438
439 static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr)
440 {
441     size_t frag_off, frag_len, msg_len;
442
443     msg_len = msg_hdr->msg_len;
444     frag_off = msg_hdr->frag_off;
445     frag_len = msg_hdr->frag_len;
446
447     /* sanity checking */
448     if ((frag_off + frag_len) > msg_len
449             || msg_len > dtls1_max_handshake_message_len(s)) {
450         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
451         return 0;
452     }
453
454     if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
455         /*
456          * msg_len is limited to 2^24, but is effectively checked against
457          * dtls_max_handshake_message_len(s) above
458          */
459         if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
460             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
461             return 0;
462         }
463
464         s->s3.tmp.message_size = msg_len;
465         s->d1->r_msg_hdr.msg_len = msg_len;
466         s->s3.tmp.message_type = msg_hdr->type;
467         s->d1->r_msg_hdr.type = msg_hdr->type;
468         s->d1->r_msg_hdr.seq = msg_hdr->seq;
469     } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
470         /*
471          * They must be playing with us! BTW, failure to enforce upper limit
472          * would open possibility for buffer overrun.
473          */
474         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
475         return 0;
476     }
477
478     return 1;
479 }
480
481 /*
482  * Returns 1 if there is a buffered fragment available, 0 if not, or -1 on a
483  * fatal error.
484  */
485 static int dtls1_retrieve_buffered_fragment(SSL *s, size_t *len)
486 {
487     /*-
488      * (0) check whether the desired fragment is available
489      * if so:
490      * (1) copy over the fragment to s->init_buf->data[]
491      * (2) update s->init_num
492      */
493     pitem *item;
494     hm_fragment *frag;
495     int ret;
496
497     do {
498         item = pqueue_peek(s->d1->buffered_messages);
499         if (item == NULL)
500             return 0;
501
502         frag = (hm_fragment *)item->data;
503
504         if (frag->msg_header.seq < s->d1->handshake_read_seq) {
505             /* This is a stale message that has been buffered so clear it */
506             pqueue_pop(s->d1->buffered_messages);
507             dtls1_hm_fragment_free(frag);
508             pitem_free(item);
509             item = NULL;
510             frag = NULL;
511         }
512     } while (item == NULL);
513
514     /* Don't return if reassembly still in progress */
515     if (frag->reassembly != NULL)
516         return 0;
517
518     if (s->d1->handshake_read_seq == frag->msg_header.seq) {
519         size_t frag_len = frag->msg_header.frag_len;
520         pqueue_pop(s->d1->buffered_messages);
521
522         /* Calls SSLfatal() as required */
523         ret = dtls1_preprocess_fragment(s, &frag->msg_header);
524
525         if (ret && frag->msg_header.frag_len > 0) {
526             unsigned char *p =
527                 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
528             memcpy(&p[frag->msg_header.frag_off], frag->fragment,
529                    frag->msg_header.frag_len);
530         }
531
532         dtls1_hm_fragment_free(frag);
533         pitem_free(item);
534
535         if (ret) {
536             *len = frag_len;
537             return 1;
538         }
539
540         /* Fatal error */
541         s->init_num = 0;
542         return -1;
543     } else {
544         return 0;
545     }
546 }
547
548 static int
549 dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr)
550 {
551     hm_fragment *frag = NULL;
552     pitem *item = NULL;
553     int i = -1, is_complete;
554     unsigned char seq64be[8];
555     size_t frag_len = msg_hdr->frag_len;
556     size_t readbytes;
557
558     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
559         msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
560         goto err;
561
562     if (frag_len == 0) {
563         return DTLS1_HM_FRAGMENT_RETRY;
564     }
565
566     /* Try to find item in queue */
567     memset(seq64be, 0, sizeof(seq64be));
568     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
569     seq64be[7] = (unsigned char)msg_hdr->seq;
570     item = pqueue_find(s->d1->buffered_messages, seq64be);
571
572     if (item == NULL) {
573         frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
574         if (frag == NULL)
575             goto err;
576         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
577         frag->msg_header.frag_len = frag->msg_header.msg_len;
578         frag->msg_header.frag_off = 0;
579     } else {
580         frag = (hm_fragment *)item->data;
581         if (frag->msg_header.msg_len != msg_hdr->msg_len) {
582             item = NULL;
583             frag = NULL;
584             goto err;
585         }
586     }
587
588     /*
589      * If message is already reassembled, this must be a retransmit and can
590      * be dropped. In this case item != NULL and so frag does not need to be
591      * freed.
592      */
593     if (frag->reassembly == NULL) {
594         unsigned char devnull[256];
595
596         while (frag_len) {
597             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
598                                           devnull,
599                                           frag_len >
600                                           sizeof(devnull) ? sizeof(devnull) :
601                                           frag_len, 0, &readbytes);
602             if (i <= 0)
603                 goto err;
604             frag_len -= readbytes;
605         }
606         return DTLS1_HM_FRAGMENT_RETRY;
607     }
608
609     /* read the body of the fragment (header has already been read */
610     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
611                                   frag->fragment + msg_hdr->frag_off,
612                                   frag_len, 0, &readbytes);
613     if (i <= 0 || readbytes != frag_len)
614         i = -1;
615     if (i <= 0)
616         goto err;
617
618     RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
619                         (long)(msg_hdr->frag_off + frag_len));
620
621     if (!ossl_assert(msg_hdr->msg_len > 0))
622         goto err;
623     RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
624                                is_complete);
625
626     if (is_complete) {
627         OPENSSL_free(frag->reassembly);
628         frag->reassembly = NULL;
629     }
630
631     if (item == NULL) {
632         item = pitem_new(seq64be, frag);
633         if (item == NULL) {
634             i = -1;
635             goto err;
636         }
637
638         item = pqueue_insert(s->d1->buffered_messages, item);
639         /*
640          * pqueue_insert fails iff a duplicate item is inserted. However,
641          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
642          * would have returned it and control would never have reached this
643          * branch.
644          */
645         if (!ossl_assert(item != NULL))
646             goto err;
647     }
648
649     return DTLS1_HM_FRAGMENT_RETRY;
650
651  err:
652     if (item == NULL)
653         dtls1_hm_fragment_free(frag);
654     return -1;
655 }
656
657 static int
658 dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr)
659 {
660     int i = -1;
661     hm_fragment *frag = NULL;
662     pitem *item = NULL;
663     unsigned char seq64be[8];
664     size_t frag_len = msg_hdr->frag_len;
665     size_t readbytes;
666
667     if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
668         goto err;
669
670     /* Try to find item in queue, to prevent duplicate entries */
671     memset(seq64be, 0, sizeof(seq64be));
672     seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
673     seq64be[7] = (unsigned char)msg_hdr->seq;
674     item = pqueue_find(s->d1->buffered_messages, seq64be);
675
676     /*
677      * If we already have an entry and this one is a fragment, don't discard
678      * it and rather try to reassemble it.
679      */
680     if (item != NULL && frag_len != msg_hdr->msg_len)
681         item = NULL;
682
683     /*
684      * Discard the message if sequence number was already there, is too far
685      * in the future, already in the queue or if we received a FINISHED
686      * before the SERVER_HELLO, which then must be a stale retransmit.
687      */
688     if (msg_hdr->seq <= s->d1->handshake_read_seq ||
689         msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
690         (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED)) {
691         unsigned char devnull[256];
692
693         while (frag_len) {
694             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
695                                           devnull,
696                                           frag_len >
697                                           sizeof(devnull) ? sizeof(devnull) :
698                                           frag_len, 0, &readbytes);
699             if (i <= 0)
700                 goto err;
701             frag_len -= readbytes;
702         }
703     } else {
704         if (frag_len != msg_hdr->msg_len) {
705             return dtls1_reassemble_fragment(s, msg_hdr);
706         }
707
708         if (frag_len > dtls1_max_handshake_message_len(s))
709             goto err;
710
711         frag = dtls1_hm_fragment_new(frag_len, 0);
712         if (frag == NULL)
713             goto err;
714
715         memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
716
717         if (frag_len) {
718             /*
719              * read the body of the fragment (header has already been read
720              */
721             i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
722                                           frag->fragment, frag_len, 0,
723                                           &readbytes);
724             if (i<=0 || readbytes != frag_len)
725                 i = -1;
726             if (i <= 0)
727                 goto err;
728         }
729
730         item = pitem_new(seq64be, frag);
731         if (item == NULL)
732             goto err;
733
734         item = pqueue_insert(s->d1->buffered_messages, item);
735         /*
736          * pqueue_insert fails iff a duplicate item is inserted. However,
737          * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
738          * would have returned it. Then, either |frag_len| !=
739          * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
740          * have been processed with |dtls1_reassemble_fragment|, above, or
741          * the record will have been discarded.
742          */
743         if (!ossl_assert(item != NULL))
744             goto err;
745     }
746
747     return DTLS1_HM_FRAGMENT_RETRY;
748
749  err:
750     if (item == NULL)
751         dtls1_hm_fragment_free(frag);
752     return 0;
753 }
754
755 static int dtls_get_reassembled_message(SSL *s, int *errtype, size_t *len)
756 {
757     unsigned char wire[DTLS1_HM_HEADER_LENGTH];
758     size_t mlen, frag_off, frag_len;
759     int i, ret, recvd_type;
760     struct hm_header_st msg_hdr;
761     size_t readbytes;
762
763     *errtype = 0;
764
765  redo:
766     /* see if we have the required fragment already */
767     ret = dtls1_retrieve_buffered_fragment(s, &frag_len);
768     if (ret < 0) {
769         /* SSLfatal() already called */
770         return 0;
771     }
772     if (ret > 0) {
773         s->init_num = frag_len;
774         *len = frag_len;
775         return 1;
776     }
777
778     /* read handshake message header */
779     i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type, wire,
780                                   DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
781     if (i <= 0) {               /* nbio, or an error */
782         s->rwstate = SSL_READING;
783         *len = 0;
784         return 0;
785     }
786     if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
787         if (wire[0] != SSL3_MT_CCS) {
788             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
789                      SSL_R_BAD_CHANGE_CIPHER_SPEC);
790             goto f_err;
791         }
792
793         memcpy(s->init_buf->data, wire, readbytes);
794         s->init_num = readbytes - 1;
795         s->init_msg = s->init_buf->data + 1;
796         s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
797         s->s3.tmp.message_size = readbytes - 1;
798         *len = readbytes - 1;
799         return 1;
800     }
801
802     /* Handshake fails if message header is incomplete */
803     if (readbytes != DTLS1_HM_HEADER_LENGTH) {
804         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
805         goto f_err;
806     }
807
808     /* parse the message fragment header */
809     dtls1_get_message_header(wire, &msg_hdr);
810
811     mlen = msg_hdr.msg_len;
812     frag_off = msg_hdr.frag_off;
813     frag_len = msg_hdr.frag_len;
814
815     /*
816      * We must have at least frag_len bytes left in the record to be read.
817      * Fragments must not span records.
818      */
819     if (frag_len > RECORD_LAYER_get_rrec_length(&s->rlayer)) {
820         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
821         goto f_err;
822     }
823
824     /*
825      * if this is a future (or stale) message it gets buffered
826      * (or dropped)--no further processing at this time
827      * While listening, we accept seq 1 (ClientHello with cookie)
828      * although we're still expecting seq 0 (ClientHello)
829      */
830     if (msg_hdr.seq != s->d1->handshake_read_seq) {
831         *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
832         return 0;
833     }
834
835     if (frag_len && frag_len < mlen) {
836         *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
837         return 0;
838     }
839
840     if (!s->server
841             && s->d1->r_msg_hdr.frag_off == 0
842             && s->statem.hand_state != TLS_ST_OK
843             && wire[0] == SSL3_MT_HELLO_REQUEST) {
844         /*
845          * The server may always send 'Hello Request' messages -- we are
846          * doing a handshake anyway now, so ignore them if their format is
847          * correct. Does not count for 'Finished' MAC.
848          */
849         if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
850             if (s->msg_callback)
851                 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
852                                 wire, DTLS1_HM_HEADER_LENGTH, s,
853                                 s->msg_callback_arg);
854
855             s->init_num = 0;
856             goto redo;
857         } else {                /* Incorrectly formatted Hello request */
858
859             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
860             goto f_err;
861         }
862     }
863
864     if (!dtls1_preprocess_fragment(s, &msg_hdr)) {
865         /* SSLfatal() already called */
866         goto f_err;
867     }
868
869     if (frag_len > 0) {
870         unsigned char *p =
871             (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
872
873         i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, NULL,
874                                       &p[frag_off], frag_len, 0, &readbytes);
875
876         /*
877          * This shouldn't ever fail due to NBIO because we already checked
878          * that we have enough data in the record
879          */
880         if (i <= 0) {
881             s->rwstate = SSL_READING;
882             *len = 0;
883             return 0;
884         }
885     } else {
886         readbytes = 0;
887     }
888
889     /*
890      * XDTLS: an incorrectly formatted fragment should cause the handshake
891      * to fail
892      */
893     if (readbytes != frag_len) {
894         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
895         goto f_err;
896     }
897
898     /*
899      * Note that s->init_num is *not* used as current offset in
900      * s->init_buf->data, but as a counter summing up fragments' lengths: as
901      * soon as they sum up to handshake packet length, we assume we have got
902      * all the fragments.
903      */
904     *len = s->init_num = frag_len;
905     return 1;
906
907  f_err:
908     s->init_num = 0;
909     *len = 0;
910     return 0;
911 }
912
913 /*-
914  * for these 2 messages, we need to
915  * ssl->enc_read_ctx                    re-init
916  * ssl->rlayer.read_sequence            zero
917  * ssl->s3.read_mac_secret             re-init
918  * ssl->session->read_sym_enc           assign
919  * ssl->session->read_compression       assign
920  * ssl->session->read_hash              assign
921  */
922 int dtls_construct_change_cipher_spec(SSL *s, WPACKET *pkt)
923 {
924     if (s->version == DTLS1_BAD_VER) {
925         s->d1->next_handshake_write_seq++;
926
927         if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {
928             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
929             return 0;
930         }
931     }
932
933     return 1;
934 }
935
936 #ifndef OPENSSL_NO_SCTP
937 /*
938  * Wait for a dry event. Should only be called at a point in the handshake
939  * where we are not expecting any data from the peer except an alert.
940  */
941 WORK_STATE dtls_wait_for_dry(SSL *s)
942 {
943     int ret, errtype;
944     size_t len;
945
946     /* read app data until dry event */
947     ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s));
948     if (ret < 0) {
949         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
950         return WORK_ERROR;
951     }
952
953     if (ret == 0) {
954         /*
955          * We're not expecting any more messages from the peer at this point -
956          * but we could get an alert. If an alert is waiting then we will never
957          * return successfully. Therefore we attempt to read a message. This
958          * should never succeed but will process any waiting alerts.
959          */
960         if (dtls_get_reassembled_message(s, &errtype, &len)) {
961             /* The call succeeded! This should never happen */
962             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
963             return WORK_ERROR;
964         }
965
966         s->s3.in_read_app_data = 2;
967         s->rwstate = SSL_READING;
968         BIO_clear_retry_flags(SSL_get_rbio(s));
969         BIO_set_retry_read(SSL_get_rbio(s));
970         return WORK_MORE_A;
971     }
972     return WORK_FINISHED_CONTINUE;
973 }
974 #endif
975
976 int dtls1_read_failed(SSL *s, int code)
977 {
978     if (code > 0) {
979         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
980         return 0;
981     }
982
983     if (!dtls1_is_timer_expired(s) || ossl_statem_in_error(s)) {
984         /*
985          * not a timeout, none of our business, let higher layers handle
986          * this.  in fact it's probably an error
987          */
988         return code;
989     }
990     /* done, no need to send a retransmit */
991     if (!SSL_in_init(s))
992     {
993         BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
994         return code;
995     }
996
997     return dtls1_handle_timeout(s);
998 }
999
1000 int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1001 {
1002     /*
1003      * The index of the retransmission queue actually is the message sequence
1004      * number, since the queue only contains messages of a single handshake.
1005      * However, the ChangeCipherSpec has no message sequence number and so
1006      * using only the sequence will result in the CCS and Finished having the
1007      * same index. To prevent this, the sequence number is multiplied by 2.
1008      * In case of a CCS 1 is subtracted. This does not only differ CSS and
1009      * Finished, it also maintains the order of the index (important for
1010      * priority queues) and fits in the unsigned short variable.
1011      */
1012     return seq * 2 - is_ccs;
1013 }
1014
1015 int dtls1_retransmit_buffered_messages(SSL *s)
1016 {
1017     pqueue *sent = s->d1->sent_messages;
1018     piterator iter;
1019     pitem *item;
1020     hm_fragment *frag;
1021     int found = 0;
1022
1023     iter = pqueue_iterator(sent);
1024
1025     for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1026         frag = (hm_fragment *)item->data;
1027         if (dtls1_retransmit_message(s, (unsigned short)
1028                                      dtls1_get_queue_priority
1029                                      (frag->msg_header.seq,
1030                                       frag->msg_header.is_ccs), &found) <= 0)
1031             return -1;
1032     }
1033
1034     return 1;
1035 }
1036
1037 int dtls1_buffer_message(SSL *s, int is_ccs)
1038 {
1039     pitem *item;
1040     hm_fragment *frag;
1041     unsigned char seq64be[8];
1042
1043     /*
1044      * this function is called immediately after a message has been
1045      * serialized
1046      */
1047     if (!ossl_assert(s->init_off == 0))
1048         return 0;
1049
1050     frag = dtls1_hm_fragment_new(s->init_num, 0);
1051     if (frag == NULL)
1052         return 0;
1053
1054     memcpy(frag->fragment, s->init_buf->data, s->init_num);
1055
1056     if (is_ccs) {
1057         /* For DTLS1_BAD_VER the header length is non-standard */
1058         if (!ossl_assert(s->d1->w_msg_hdr.msg_len +
1059                          ((s->version ==
1060                            DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH)
1061                          == (unsigned int)s->init_num)) {
1062             dtls1_hm_fragment_free(frag);
1063             return 0;
1064         }
1065     } else {
1066         if (!ossl_assert(s->d1->w_msg_hdr.msg_len +
1067                          DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num)) {
1068             dtls1_hm_fragment_free(frag);
1069             return 0;
1070         }
1071     }
1072
1073     frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1074     frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1075     frag->msg_header.type = s->d1->w_msg_hdr.type;
1076     frag->msg_header.frag_off = 0;
1077     frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1078     frag->msg_header.is_ccs = is_ccs;
1079
1080     /* save current state */
1081     frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1082     frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1083     frag->msg_header.saved_retransmit_state.compress = s->compress;
1084     frag->msg_header.saved_retransmit_state.session = s->session;
1085     frag->msg_header.saved_retransmit_state.epoch =
1086         DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer);
1087
1088     memset(seq64be, 0, sizeof(seq64be));
1089     seq64be[6] =
1090         (unsigned
1091          char)(dtls1_get_queue_priority(frag->msg_header.seq,
1092                                         frag->msg_header.is_ccs) >> 8);
1093     seq64be[7] =
1094         (unsigned
1095          char)(dtls1_get_queue_priority(frag->msg_header.seq,
1096                                         frag->msg_header.is_ccs));
1097
1098     item = pitem_new(seq64be, frag);
1099     if (item == NULL) {
1100         dtls1_hm_fragment_free(frag);
1101         return 0;
1102     }
1103
1104     pqueue_insert(s->d1->sent_messages, item);
1105     return 1;
1106 }
1107
1108 int dtls1_retransmit_message(SSL *s, unsigned short seq, int *found)
1109 {
1110     int ret;
1111     /* XDTLS: for now assuming that read/writes are blocking */
1112     pitem *item;
1113     hm_fragment *frag;
1114     unsigned long header_length;
1115     unsigned char seq64be[8];
1116     struct dtls1_retransmit_state saved_state;
1117
1118     /* XDTLS:  the requested message ought to be found, otherwise error */
1119     memset(seq64be, 0, sizeof(seq64be));
1120     seq64be[6] = (unsigned char)(seq >> 8);
1121     seq64be[7] = (unsigned char)seq;
1122
1123     item = pqueue_find(s->d1->sent_messages, seq64be);
1124     if (item == NULL) {
1125         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1126         *found = 0;
1127         return 0;
1128     }
1129
1130     *found = 1;
1131     frag = (hm_fragment *)item->data;
1132
1133     if (frag->msg_header.is_ccs)
1134         header_length = DTLS1_CCS_HEADER_LENGTH;
1135     else
1136         header_length = DTLS1_HM_HEADER_LENGTH;
1137
1138     memcpy(s->init_buf->data, frag->fragment,
1139            frag->msg_header.msg_len + header_length);
1140     s->init_num = frag->msg_header.msg_len + header_length;
1141
1142     dtls1_set_message_header_int(s, frag->msg_header.type,
1143                                  frag->msg_header.msg_len,
1144                                  frag->msg_header.seq, 0,
1145                                  frag->msg_header.frag_len);
1146
1147     /* save current state */
1148     saved_state.enc_write_ctx = s->enc_write_ctx;
1149     saved_state.write_hash = s->write_hash;
1150     saved_state.compress = s->compress;
1151     saved_state.session = s->session;
1152     saved_state.epoch = DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer);
1153
1154     s->d1->retransmitting = 1;
1155
1156     /* restore state in which the message was originally sent */
1157     s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1158     s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1159     s->compress = frag->msg_header.saved_retransmit_state.compress;
1160     s->session = frag->msg_header.saved_retransmit_state.session;
1161     DTLS_RECORD_LAYER_set_saved_w_epoch(&s->rlayer,
1162                                         frag->msg_header.
1163                                         saved_retransmit_state.epoch);
1164
1165     ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1166                          SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1167
1168     /* restore current state */
1169     s->enc_write_ctx = saved_state.enc_write_ctx;
1170     s->write_hash = saved_state.write_hash;
1171     s->compress = saved_state.compress;
1172     s->session = saved_state.session;
1173     DTLS_RECORD_LAYER_set_saved_w_epoch(&s->rlayer, saved_state.epoch);
1174
1175     s->d1->retransmitting = 0;
1176
1177     (void)BIO_flush(s->wbio);
1178     return ret;
1179 }
1180
1181 void dtls1_set_message_header(SSL *s,
1182                               unsigned char mt, size_t len,
1183                               size_t frag_off, size_t frag_len)
1184 {
1185     if (frag_off == 0) {
1186         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1187         s->d1->next_handshake_write_seq++;
1188     }
1189
1190     dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1191                                  frag_off, frag_len);
1192 }
1193
1194 /* don't actually do the writing, wait till the MTU has been retrieved */
1195 static void
1196 dtls1_set_message_header_int(SSL *s, unsigned char mt,
1197                              size_t len, unsigned short seq_num,
1198                              size_t frag_off, size_t frag_len)
1199 {
1200     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1201
1202     msg_hdr->type = mt;
1203     msg_hdr->msg_len = len;
1204     msg_hdr->seq = seq_num;
1205     msg_hdr->frag_off = frag_off;
1206     msg_hdr->frag_len = frag_len;
1207 }
1208
1209 static void
1210 dtls1_fix_message_header(SSL *s, size_t frag_off, size_t frag_len)
1211 {
1212     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1213
1214     msg_hdr->frag_off = frag_off;
1215     msg_hdr->frag_len = frag_len;
1216 }
1217
1218 static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p)
1219 {
1220     struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1221
1222     *p++ = msg_hdr->type;
1223     l2n3(msg_hdr->msg_len, p);
1224
1225     s2n(msg_hdr->seq, p);
1226     l2n3(msg_hdr->frag_off, p);
1227     l2n3(msg_hdr->frag_len, p);
1228
1229     return p;
1230 }
1231
1232 void dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
1233 {
1234     memset(msg_hdr, 0, sizeof(*msg_hdr));
1235     msg_hdr->type = *(data++);
1236     n2l3(data, msg_hdr->msg_len);
1237
1238     n2s(data, msg_hdr->seq);
1239     n2l3(data, msg_hdr->frag_off);
1240     n2l3(data, msg_hdr->frag_len);
1241 }
1242
1243 int dtls1_set_handshake_header(SSL *s, WPACKET *pkt, int htype)
1244 {
1245     unsigned char *header;
1246
1247     if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {
1248         s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1249         dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1250                                      s->d1->handshake_write_seq, 0, 0);
1251         if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))
1252             return 0;
1253     } else {
1254         dtls1_set_message_header(s, htype, 0, 0, 0);
1255         /*
1256          * We allocate space at the start for the message header. This gets
1257          * filled in later
1258          */
1259         if (!WPACKET_allocate_bytes(pkt, DTLS1_HM_HEADER_LENGTH, &header)
1260                 || !WPACKET_start_sub_packet(pkt))
1261             return 0;
1262     }
1263
1264     return 1;
1265 }
1266
1267 int dtls1_close_construct_packet(SSL *s, WPACKET *pkt, int htype)
1268 {
1269     size_t msglen;
1270
1271     if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
1272             || !WPACKET_get_length(pkt, &msglen)
1273             || msglen > INT_MAX)
1274         return 0;
1275
1276     if (htype != SSL3_MT_CHANGE_CIPHER_SPEC) {
1277         s->d1->w_msg_hdr.msg_len = msglen - DTLS1_HM_HEADER_LENGTH;
1278         s->d1->w_msg_hdr.frag_len = msglen - DTLS1_HM_HEADER_LENGTH;
1279     }
1280     s->init_num = (int)msglen;
1281     s->init_off = 0;
1282
1283     if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST) {
1284         /* Buffer the message to handle re-xmits */
1285         if (!dtls1_buffer_message(s, htype == SSL3_MT_CHANGE_CIPHER_SPEC
1286                                      ? 1 : 0))
1287             return 0;
1288     }
1289
1290     return 1;
1291 }