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