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