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