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