Coverage Report

Created: 2025-06-13 06:58

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