Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/ssl/statem/statem_dtls.c
Line
Count
Source
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
23.2k
    {                                                                        \
24
23.2k
        if ((end) - (start) <= 8) {                                          \
25
18.2k
            long ii;                                                         \
26
66.5k
            for (ii = (start); ii < (end); ii++)                             \
27
48.3k
                bitmask[((ii) >> 3)] |= (1 << ((ii) & 7));                   \
28
18.2k
        } else {                                                             \
29
5.01k
            long ii;                                                         \
30
5.01k
            bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)];  \
31
245k
            for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) \
32
240k
                bitmask[ii] = 0xff;                                          \
33
5.01k
            bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)];  \
34
5.01k
        }                                                                    \
35
23.2k
    }
36
37
#define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete)                   \
38
23.2k
    {                                                                               \
39
23.2k
        long ii;                                                                    \
40
23.2k
        is_complete = 1;                                                            \
41
23.2k
        if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) \
42
23.2k
            is_complete = 0;                                                        \
43
23.2k
        if (is_complete)                                                            \
44
224k
            for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0; ii--)                    \
45
223k
                if (bitmask[ii] != 0xff) {                                          \
46
1.96k
                    is_complete = 0;                                                \
47
1.96k
                    break;                                                          \
48
1.96k
                }                                                                   \
49
23.2k
    }
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
95.8k
{
72
95.8k
    hm_fragment *frag = NULL;
73
95.8k
    unsigned char *buf = NULL;
74
95.8k
    unsigned char *bitmask = NULL;
75
76
95.8k
    if ((frag = OPENSSL_zalloc(sizeof(*frag))) == NULL)
77
0
        return NULL;
78
79
95.8k
    if (frag_len) {
80
93.8k
        if ((buf = OPENSSL_malloc(frag_len)) == NULL) {
81
0
            OPENSSL_free(frag);
82
0
            return NULL;
83
0
        }
84
93.8k
    }
85
86
    /* zero length fragment gets zero frag->fragment */
87
95.8k
    frag->fragment = buf;
88
89
    /* Initialize reassembly bitmask if necessary */
90
95.8k
    if (reassembly) {
91
7.12k
        bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len));
92
7.12k
        if (bitmask == NULL) {
93
0
            OPENSSL_free(buf);
94
0
            OPENSSL_free(frag);
95
0
            return NULL;
96
0
        }
97
7.12k
    }
98
99
95.8k
    frag->reassembly = bitmask;
100
101
95.8k
    return frag;
102
95.8k
}
103
104
void dtls1_hm_fragment_free(hm_fragment *frag)
105
97.5k
{
106
97.5k
    if (!frag)
107
1.67k
        return;
108
109
95.8k
    OPENSSL_free(frag->fragment);
110
95.8k
    OPENSSL_free(frag->reassembly);
111
95.8k
    OPENSSL_free(frag);
112
95.8k
}
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
77.5k
{
120
77.5k
    int ret;
121
77.5k
    size_t written;
122
77.5k
    size_t curr_mtu;
123
77.5k
    int retry = 1;
124
77.5k
    size_t len, frag_off, overhead, used_len;
125
77.5k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
126
77.5k
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
127
77.5k
    uint8_t saved_payload[DTLS1_HM_HEADER_LENGTH];
128
129
77.5k
    if (!dtls1_query_mtu(s))
130
0
        return -1;
131
132
77.5k
    if (s->d1->mtu < dtls1_min_mtu(s))
133
        /* should have something reasonable now */
134
0
        return -1;
135
136
77.5k
    if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
137
74.7k
        if (!ossl_assert(s->init_num == s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH))
138
0
            return -1;
139
74.7k
    }
140
141
77.5k
    overhead = s->rlayer.wrlmethod->get_max_record_overhead(s->rlayer.wrl);
142
143
77.5k
    frag_off = 0;
144
77.5k
    s->rwstate = SSL_NOTHING;
145
146
    /* s->init_num shouldn't ever be < 0...but just in case */
147
152k
    while (s->init_num > 0) {
148
152k
        if (type == SSL3_RT_HANDSHAKE && s->init_off != 0) {
149
            /* We must be writing a fragment other than the first one */
150
151
74.7k
            if (frag_off > 0) {
152
                /* This is the first attempt at writing out this fragment */
153
154
74.7k
                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
0
                    return -1;
163
0
                }
164
165
                /*
166
                 * Adjust |init_off| and |init_num| to allow room for a new
167
                 * message header for this fragment.
168
                 */
169
74.7k
                s->init_off -= DTLS1_HM_HEADER_LENGTH;
170
74.7k
                s->init_num += DTLS1_HM_HEADER_LENGTH;
171
74.7k
            } 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
0
                frag_off = s->d1->w_msg_hdr.frag_off;
179
0
            }
180
74.7k
        }
181
182
152k
        used_len = BIO_wpending(s->wbio) + overhead;
183
152k
        if (s->d1->mtu > used_len)
184
76.7k
            curr_mtu = s->d1->mtu - used_len;
185
75.5k
        else
186
75.5k
            curr_mtu = 0;
187
188
152k
        if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
189
            /*
190
             * grr.. we could get an error if MTU picked was wrong
191
             */
192
76.4k
            ret = BIO_flush(s->wbio);
193
76.4k
            if (ret <= 0) {
194
0
                s->rwstate = SSL_WRITING;
195
0
                return ret;
196
0
            }
197
76.4k
            if (s->d1->mtu > overhead + DTLS1_HM_HEADER_LENGTH) {
198
76.4k
                curr_mtu = s->d1->mtu - overhead;
199
76.4k
            } else {
200
                /* Shouldn't happen */
201
0
                return -1;
202
0
            }
203
76.4k
        }
204
205
        /*
206
         * We just checked that s->init_num > 0 so this cast should be safe
207
         */
208
152k
        if (((unsigned int)s->init_num) > curr_mtu)
209
74.7k
            len = curr_mtu;
210
77.5k
        else
211
77.5k
            len = s->init_num;
212
213
152k
        if (len > ssl_get_max_send_fragment(s))
214
0
            len = ssl_get_max_send_fragment(s);
215
216
        /*
217
         * XDTLS: this function is too long.  split out the CCS part
218
         */
219
152k
        if (type == SSL3_RT_HANDSHAKE) {
220
149k
            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
0
                return -1;
226
0
            }
227
149k
            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
149k
            if (s->msg_callback && s->init_off != 0)
235
0
                memcpy(saved_payload, &s->init_buf->data[s->init_off],
236
0
                    sizeof(saved_payload));
237
238
149k
            dtls1_write_message_header(s,
239
149k
                (unsigned char *)&s->init_buf->data[s->init_off]);
240
149k
        }
241
242
152k
        ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,
243
152k
            &written);
244
245
152k
        if (type == SSL3_RT_HANDSHAKE && s->msg_callback && s->init_off != 0)
246
0
            memcpy(&s->init_buf->data[s->init_off], saved_payload,
247
0
                sizeof(saved_payload));
248
249
152k
        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
0
            if (retry && BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
257
0
                if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
258
0
                    if (!dtls1_query_mtu(s))
259
0
                        return -1;
260
                    /* Have one more go */
261
0
                    retry = 0;
262
0
                } else
263
0
                    return -1;
264
0
            } else {
265
0
                return -1;
266
0
            }
267
152k
        } 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
152k
            if (!ossl_assert(len == written))
274
0
                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
152k
            assert(s->s3.tmp.new_compression != NULL
284
152k
                || BIO_wpending(s->wbio) <= (int)s->d1->mtu);
285
286
152k
            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
149k
                unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
292
149k
                const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
293
149k
                size_t xlen;
294
295
149k
                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
74.5k
                    *p++ = msg_hdr->type;
301
74.5k
                    l2n3(msg_hdr->msg_len, p);
302
74.5k
                    s2n(msg_hdr->seq, p);
303
74.5k
                    l2n3(0, p);
304
74.5k
                    l2n3(msg_hdr->msg_len, p);
305
74.5k
                    p -= DTLS1_HM_HEADER_LENGTH;
306
74.5k
                    xlen = written;
307
74.9k
                } else {
308
74.9k
                    p += DTLS1_HM_HEADER_LENGTH;
309
74.9k
                    xlen = written - DTLS1_HM_HEADER_LENGTH;
310
74.9k
                }
311
312
149k
                if (!ssl3_finish_mac(s, p, xlen))
313
0
                    return -1;
314
149k
            }
315
316
152k
            if (written == s->init_num) {
317
77.5k
                if (s->msg_callback)
318
0
                    s->msg_callback(1, s->version, type, s->init_buf->data,
319
0
                        s->init_off + s->init_num, ussl,
320
0
                        s->msg_callback_arg);
321
322
77.5k
                s->init_off = 0; /* done writing this message */
323
77.5k
                s->init_num = 0;
324
325
77.5k
                return 1;
326
77.5k
            }
327
74.7k
            s->init_off += written;
328
74.7k
            s->init_num -= written;
329
74.7k
            written -= DTLS1_HM_HEADER_LENGTH;
330
74.7k
            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
74.7k
            dtls1_fix_message_header(s, frag_off, 0);
339
74.7k
        }
340
152k
    }
341
0
    return 0;
342
77.5k
}
343
344
int dtls_get_message(SSL_CONNECTION *s, int *mt)
345
99.9k
{
346
99.9k
    struct hm_header_st *msg_hdr;
347
99.9k
    unsigned char *p;
348
99.9k
    size_t msg_len;
349
99.9k
    size_t tmplen;
350
99.9k
    int errtype;
351
352
99.9k
    msg_hdr = &s->d1->r_msg_hdr;
353
99.9k
    memset(msg_hdr, 0, sizeof(*msg_hdr));
354
355
166k
again:
356
166k
    if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
357
93.3k
        if (errtype == DTLS1_HM_BAD_FRAGMENT
358
93.3k
            || errtype == DTLS1_HM_FRAGMENT_RETRY) {
359
            /* bad fragment received */
360
66.2k
            goto again;
361
66.2k
        }
362
27.1k
        return 0;
363
93.3k
    }
364
365
72.8k
    *mt = s->s3.tmp.message_type;
366
367
72.8k
    p = (unsigned char *)s->init_buf->data;
368
369
72.8k
    if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
370
8.14k
        if (s->msg_callback) {
371
0
            s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
372
0
                p, 1, SSL_CONNECTION_GET_USER_SSL(s),
373
0
                s->msg_callback_arg);
374
0
        }
375
        /*
376
         * This isn't a real handshake message so skip the processing below.
377
         */
378
8.14k
        return 1;
379
8.14k
    }
380
381
64.6k
    msg_len = msg_hdr->msg_len;
382
383
    /* reconstruct message header */
384
64.6k
    *(p++) = msg_hdr->type;
385
64.6k
    l2n3(msg_len, p);
386
64.6k
    s2n(msg_hdr->seq, p);
387
64.6k
    l2n3(0, p);
388
64.6k
    l2n3(msg_len, p);
389
390
64.6k
    memset(msg_hdr, 0, sizeof(*msg_hdr));
391
392
64.6k
    s->d1->handshake_read_seq++;
393
394
64.6k
    s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
395
396
64.6k
    return 1;
397
72.8k
}
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
72.0k
{
406
72.0k
    unsigned char *msg = (unsigned char *)s->init_buf->data;
407
72.0k
    size_t msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;
408
409
72.0k
    if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
410
        /* Nothing to be done */
411
8.09k
        goto end;
412
8.09k
    }
413
    /*
414
     * If receiving Finished, record MAC of prior handshake messages for
415
     * Finished verification.
416
     */
417
63.9k
    if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
418
        /* SSLfatal() already called */
419
0
        return 0;
420
0
    }
421
422
63.9k
    if (s->version == DTLS1_BAD_VER) {
423
1.69k
        msg += DTLS1_HM_HEADER_LENGTH;
424
1.69k
        msg_len -= DTLS1_HM_HEADER_LENGTH;
425
1.69k
    }
426
427
63.9k
    if (!ssl3_finish_mac(s, msg, msg_len))
428
7
        return 0;
429
430
63.8k
    if (s->msg_callback)
431
0
        s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
432
0
            s->init_buf->data, s->init_num + DTLS1_HM_HEADER_LENGTH,
433
0
            SSL_CONNECTION_GET_USER_SSL(s), s->msg_callback_arg);
434
435
71.9k
end:
436
71.9k
    *len = s->init_num;
437
71.9k
    return 1;
438
63.8k
}
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
102k
{
447
102k
    size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
448
102k
    if (max_len < s->max_cert_list)
449
102k
        return s->max_cert_list;
450
0
    return max_len;
451
102k
}
452
453
static int dtls1_preprocess_fragment(SSL_CONNECTION *s,
454
    struct hm_header_st *msg_hdr)
455
65.3k
{
456
65.3k
    size_t frag_off, frag_len, msg_len;
457
458
65.3k
    msg_len = msg_hdr->msg_len;
459
65.3k
    frag_off = msg_hdr->frag_off;
460
65.3k
    frag_len = msg_hdr->frag_len;
461
462
    /* sanity checking */
463
65.3k
    if ((frag_off + frag_len) > msg_len
464
65.0k
        || msg_len > dtls1_max_handshake_message_len(s)) {
465
722
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
466
722
        return 0;
467
722
    }
468
469
64.6k
    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
64.6k
        if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
475
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
476
0
            return 0;
477
0
        }
478
479
64.6k
        s->s3.tmp.message_size = msg_len;
480
64.6k
        s->d1->r_msg_hdr.msg_len = msg_len;
481
64.6k
        s->s3.tmp.message_type = msg_hdr->type;
482
64.6k
        s->d1->r_msg_hdr.type = msg_hdr->type;
483
64.6k
        s->d1->r_msg_hdr.seq = msg_hdr->seq;
484
64.6k
    } 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
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
490
0
        return 0;
491
0
    }
492
493
64.6k
    return 1;
494
64.6k
}
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
178k
{
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
178k
    pitem *item;
509
178k
    piterator iter;
510
178k
    hm_fragment *frag;
511
178k
    int ret;
512
178k
    int chretran = 0;
513
514
178k
    iter = pqueue_iterator(s->d1->buffered_messages);
515
180k
    do {
516
180k
        item = pqueue_next(&iter);
517
180k
        if (item == NULL)
518
113k
            return 0;
519
520
67.6k
        frag = (hm_fragment *)item->data;
521
522
67.6k
        if (frag->msg_header.seq < s->d1->handshake_read_seq) {
523
2.05k
            pitem *next;
524
2.05k
            hm_fragment *nextfrag;
525
526
2.05k
            if (!s->server
527
1.95k
                || frag->msg_header.seq != 0
528
948
                || s->d1->handshake_read_seq != 1
529
2.05k
                || 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
2.05k
                pqueue_pop(s->d1->buffered_messages);
536
2.05k
                dtls1_hm_fragment_free(frag);
537
2.05k
                pitem_free(item);
538
2.05k
                item = NULL;
539
2.05k
                frag = NULL;
540
2.05k
            } 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
0
                next = pqueue_next(&iter);
548
0
                if (next != NULL) {
549
0
                    nextfrag = (hm_fragment *)next->data;
550
0
                    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
0
                        pqueue_pop(s->d1->buffered_messages);
556
0
                        dtls1_hm_fragment_free(frag);
557
0
                        pitem_free(item);
558
0
                        item = next;
559
0
                        frag = nextfrag;
560
0
                    } else {
561
0
                        chretran = 1;
562
0
                    }
563
0
                } else {
564
0
                    chretran = 1;
565
0
                }
566
0
            }
567
2.05k
        }
568
67.6k
    } while (item == NULL);
569
570
    /* Don't return if reassembly still in progress */
571
65.6k
    if (frag->reassembly != NULL)
572
33.9k
        return 0;
573
574
31.6k
    if (s->d1->handshake_read_seq == frag->msg_header.seq || chretran) {
575
10.4k
        size_t frag_len = frag->msg_header.frag_len;
576
10.4k
        pqueue_pop(s->d1->buffered_messages);
577
578
        /* Calls SSLfatal() as required */
579
10.4k
        ret = dtls1_preprocess_fragment(s, &frag->msg_header);
580
581
10.4k
        if (ret && frag->msg_header.frag_len > 0) {
582
9.97k
            unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
583
9.97k
            memcpy(&p[frag->msg_header.frag_off], frag->fragment,
584
9.97k
                frag->msg_header.frag_len);
585
9.97k
        }
586
587
10.4k
        dtls1_hm_fragment_free(frag);
588
10.4k
        pitem_free(item);
589
590
10.4k
        if (ret) {
591
10.4k
            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
0
                s->d1->handshake_read_seq = 0;
599
0
                s->d1->next_handshake_write_seq = 0;
600
0
            }
601
10.4k
            *len = frag_len;
602
10.4k
            return 1;
603
10.4k
        }
604
605
        /* Fatal error */
606
0
        s->init_num = 0;
607
0
        return -1;
608
21.1k
    } else {
609
21.1k
        return 0;
610
21.1k
    }
611
31.6k
}
612
613
static int dtls1_reassemble_fragment(SSL_CONNECTION *s,
614
    const struct hm_header_st *msg_hdr)
615
26.3k
{
616
26.3k
    hm_fragment *frag = NULL;
617
26.3k
    pitem *item = NULL;
618
26.3k
    int i = -1, is_complete;
619
26.3k
    unsigned char seq64be[8];
620
26.3k
    size_t frag_len = msg_hdr->frag_len;
621
26.3k
    size_t readbytes;
622
26.3k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
623
624
26.3k
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len || msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
625
866
        goto err;
626
627
25.4k
    if (frag_len == 0) {
628
1.19k
        return DTLS1_HM_FRAGMENT_RETRY;
629
1.19k
    }
630
631
    /* Try to find item in queue */
632
24.2k
    memset(seq64be, 0, sizeof(seq64be));
633
24.2k
    seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
634
24.2k
    seq64be[7] = (unsigned char)msg_hdr->seq;
635
24.2k
    item = pqueue_find(s->d1->buffered_messages, seq64be);
636
637
24.2k
    if (item == NULL) {
638
7.12k
        frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
639
7.12k
        if (frag == NULL)
640
0
            goto err;
641
7.12k
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
642
7.12k
        frag->msg_header.frag_len = frag->msg_header.msg_len;
643
7.12k
        frag->msg_header.frag_off = 0;
644
17.1k
    } else {
645
17.1k
        frag = (hm_fragment *)item->data;
646
17.1k
        if (frag->msg_header.msg_len != msg_hdr->msg_len) {
647
291
            item = NULL;
648
291
            frag = NULL;
649
291
            goto err;
650
291
        }
651
17.1k
    }
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
24.0k
    if (frag->reassembly == NULL) {
659
784
        unsigned char devnull[256];
660
661
1.62k
        while (frag_len) {
662
844
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
663
844
                devnull,
664
844
                frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);
665
844
            if (i <= 0)
666
0
                goto err;
667
844
            frag_len -= readbytes;
668
844
        }
669
784
        return DTLS1_HM_FRAGMENT_RETRY;
670
784
    }
671
672
    /* read the body of the fragment (header has already been read */
673
23.2k
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
674
23.2k
        frag->fragment + msg_hdr->frag_off,
675
23.2k
        frag_len, 0, &readbytes);
676
23.2k
    if (i <= 0 || readbytes != frag_len)
677
0
        i = -1;
678
23.2k
    if (i <= 0)
679
0
        goto err;
680
681
23.2k
    RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
682
23.2k
        (long)(msg_hdr->frag_off + frag_len));
683
684
23.2k
    if (!ossl_assert(msg_hdr->msg_len > 0))
685
0
        goto err;
686
23.2k
    RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
687
23.2k
        is_complete);
688
689
23.2k
    if (is_complete) {
690
1.31k
        OPENSSL_free(frag->reassembly);
691
1.31k
        frag->reassembly = NULL;
692
1.31k
    }
693
694
23.2k
    if (item == NULL) {
695
7.12k
        item = pitem_new(seq64be, frag);
696
7.12k
        if (item == NULL) {
697
0
            i = -1;
698
0
            goto err;
699
0
        }
700
701
7.12k
        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
7.12k
        if (!ossl_assert(item != NULL))
709
0
            goto err;
710
7.12k
    }
711
712
23.2k
    return DTLS1_HM_FRAGMENT_RETRY;
713
714
1.15k
err:
715
1.15k
    if (item == NULL)
716
1.15k
        dtls1_hm_fragment_free(frag);
717
1.15k
    return -1;
718
23.2k
}
719
720
static int dtls1_process_out_of_seq_message(SSL_CONNECTION *s,
721
    const struct hm_header_st *msg_hdr)
722
60.4k
{
723
60.4k
    int i = -1;
724
60.4k
    hm_fragment *frag = NULL;
725
60.4k
    pitem *item = NULL;
726
60.4k
    unsigned char seq64be[8];
727
60.4k
    size_t frag_len = msg_hdr->frag_len;
728
60.4k
    size_t readbytes;
729
60.4k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
730
731
60.4k
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
732
515
        goto err;
733
734
    /* Try to find item in queue, to prevent duplicate entries */
735
59.9k
    memset(seq64be, 0, sizeof(seq64be));
736
59.9k
    seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
737
59.9k
    seq64be[7] = (unsigned char)msg_hdr->seq;
738
59.9k
    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
59.9k
    if (item != NULL && frag_len != msg_hdr->msg_len)
745
13.8k
        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
59.9k
    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
29.8k
        unsigned char devnull[256];
754
755
40.6k
        while (frag_len) {
756
10.8k
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
757
10.8k
                devnull,
758
10.8k
                frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);
759
10.8k
            if (i <= 0)
760
0
                goto err;
761
10.8k
            frag_len -= readbytes;
762
10.8k
        }
763
30.1k
    } else {
764
30.1k
        if (frag_len != msg_hdr->msg_len) {
765
18.9k
            return dtls1_reassemble_fragment(s, msg_hdr);
766
18.9k
        }
767
768
11.2k
        if (frag_len > dtls1_max_handshake_message_len(s))
769
0
            goto err;
770
771
11.2k
        frag = dtls1_hm_fragment_new(frag_len, 0);
772
11.2k
        if (frag == NULL)
773
0
            goto err;
774
775
11.2k
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
776
777
11.2k
        if (frag_len) {
778
            /*
779
             * read the body of the fragment (header has already been read
780
             */
781
9.20k
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
782
9.20k
                frag->fragment, frag_len, 0,
783
9.20k
                &readbytes);
784
9.20k
            if (i <= 0 || readbytes != frag_len)
785
0
                i = -1;
786
9.20k
            if (i <= 0)
787
0
                goto err;
788
9.20k
        }
789
790
11.2k
        item = pitem_new(seq64be, frag);
791
11.2k
        if (item == NULL)
792
0
            goto err;
793
794
11.2k
        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
11.2k
        if (!ossl_assert(item != NULL))
804
0
            goto err;
805
11.2k
    }
806
807
41.0k
    return DTLS1_HM_FRAGMENT_RETRY;
808
809
515
err:
810
515
    if (item == NULL)
811
515
        dtls1_hm_fragment_free(frag);
812
515
    return 0;
813
59.9k
}
814
815
static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
816
    size_t *len)
817
166k
{
818
166k
    size_t mlen, frag_off, frag_len;
819
166k
    int i, ret;
820
166k
    uint8_t recvd_type;
821
166k
    struct hm_header_st msg_hdr;
822
166k
    size_t readbytes;
823
166k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
824
166k
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
825
166k
    int chretran = 0;
826
166k
    unsigned char *p;
827
828
166k
    *errtype = 0;
829
830
166k
    p = (unsigned char *)s->init_buf->data;
831
832
178k
redo:
833
    /* see if we have the required fragment already */
834
178k
    ret = dtls1_retrieve_buffered_fragment(s, &frag_len);
835
178k
    if (ret < 0) {
836
        /* SSLfatal() already called */
837
0
        return 0;
838
0
    }
839
178k
    if (ret > 0) {
840
10.4k
        s->init_num = frag_len;
841
10.4k
        *len = frag_len;
842
10.4k
        return 1;
843
10.4k
    }
844
845
    /* read handshake message header */
846
168k
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type, p,
847
168k
        DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
848
168k
    if (i <= 0) { /* nbio, or an error */
849
19.8k
        s->rwstate = SSL_READING;
850
19.8k
        *len = 0;
851
19.8k
        return 0;
852
19.8k
    }
853
148k
    if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
854
8.22k
        if (p[0] != SSL3_MT_CCS) {
855
77
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
856
77
                SSL_R_BAD_CHANGE_CIPHER_SPEC);
857
77
            goto f_err;
858
77
        }
859
860
8.14k
        s->init_num = readbytes - 1;
861
8.14k
        s->init_msg = s->init_buf->data + 1;
862
8.14k
        s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
863
8.14k
        s->s3.tmp.message_size = readbytes - 1;
864
8.14k
        *len = readbytes - 1;
865
8.14k
        return 1;
866
8.22k
    }
867
868
    /* Handshake fails if message header is incomplete */
869
140k
    if (readbytes != DTLS1_HM_HEADER_LENGTH) {
870
2.36k
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
871
2.36k
        goto f_err;
872
2.36k
    }
873
874
    /* parse the message fragment header */
875
137k
    dtls1_get_message_header(p, &msg_hdr);
876
877
137k
    mlen = msg_hdr.msg_len;
878
137k
    frag_off = msg_hdr.frag_off;
879
137k
    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
137k
    if (frag_len > s->rlayer.tlsrecs[s->rlayer.curr_rec].length) {
886
2.33k
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
887
2.33k
        goto f_err;
888
2.33k
    }
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
135k
    if (msg_hdr.seq != s->d1->handshake_read_seq) {
897
60.4k
        if (!s->server
898
26.1k
            || msg_hdr.seq != 0
899
12.5k
            || s->d1->handshake_read_seq != 1
900
8.01k
            || p[0] != SSL3_MT_CLIENT_HELLO
901
60.4k
            || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
902
60.4k
            *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
903
60.4k
            return 0;
904
60.4k
        }
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
0
        chretran = 1;
911
0
    }
912
913
74.9k
    if (frag_len && frag_len < mlen) {
914
7.43k
        *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
915
7.43k
        return 0;
916
7.43k
    }
917
918
67.4k
    if (!s->server
919
43.0k
        && s->d1->r_msg_hdr.frag_off == 0
920
43.0k
        && s->statem.hand_state != TLS_ST_OK
921
43.0k
        && 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
12.5k
        if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
928
12.4k
            if (s->msg_callback)
929
0
                s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
930
0
                    p, DTLS1_HM_HEADER_LENGTH, ussl,
931
0
                    s->msg_callback_arg);
932
933
12.4k
            s->init_num = 0;
934
12.4k
            goto redo;
935
12.4k
        } else { /* Incorrectly formatted Hello request */
936
937
107
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
938
107
            goto f_err;
939
107
        }
940
12.5k
    }
941
942
54.9k
    if (!dtls1_preprocess_fragment(s, &msg_hdr)) {
943
        /* SSLfatal() already called */
944
722
        goto f_err;
945
722
    }
946
947
54.2k
    if (frag_len > 0) {
948
        /* dtls1_preprocess_fragment() above could reallocate init_buf */
949
50.5k
        p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
950
951
50.5k
        i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
952
50.5k
            &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
50.5k
        if (i <= 0) {
959
0
            s->rwstate = SSL_READING;
960
0
            *len = 0;
961
0
            return 0;
962
0
        }
963
50.5k
    } else {
964
3.65k
        readbytes = 0;
965
3.65k
    }
966
967
    /*
968
     * XDTLS: an incorrectly formatted fragment should cause the handshake
969
     * to fail
970
     */
971
54.2k
    if (readbytes != frag_len) {
972
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
973
0
        goto f_err;
974
0
    }
975
976
54.2k
    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
0
        s->d1->handshake_read_seq = 0;
984
0
        s->d1->next_handshake_write_seq = 0;
985
0
    }
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
54.2k
    *len = s->init_num = frag_len;
994
54.2k
    return 1;
995
996
5.60k
f_err:
997
5.60k
    s->init_num = 0;
998
5.60k
    *len = 0;
999
5.60k
    return 0;
1000
54.2k
}
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
2.77k
{
1011
2.77k
    if (s->version == DTLS1_BAD_VER) {
1012
0
        s->d1->next_handshake_write_seq++;
1013
1014
0
        if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {
1015
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1016
0
            return CON_FUNC_ERROR;
1017
0
        }
1018
0
    }
1019
1020
2.77k
    return CON_FUNC_SUCCESS;
1021
2.77k
}
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
18.7k
{
1066
18.7k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1067
1068
18.7k
    if (code > 0) {
1069
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1070
0
        return 0;
1071
0
    }
1072
1073
18.7k
    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
18.7k
        return code;
1079
18.7k
    }
1080
    /* done, no need to send a retransmit */
1081
0
    if (!SSL_in_init(ssl)) {
1082
0
        BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);
1083
0
        return code;
1084
0
    }
1085
1086
0
    return dtls1_handle_timeout(s);
1087
0
}
1088
1089
int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1090
155k
{
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
155k
    return seq * 2 - is_ccs;
1102
155k
}
1103
1104
int dtls1_retransmit_buffered_messages(SSL_CONNECTION *s)
1105
0
{
1106
0
    pqueue *sent = s->d1->sent_messages;
1107
0
    piterator iter;
1108
0
    pitem *item;
1109
0
    hm_fragment *frag;
1110
0
    int found = 0;
1111
1112
0
    iter = pqueue_iterator(sent);
1113
1114
0
    for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1115
0
        frag = (hm_fragment *)item->data;
1116
0
        if (dtls1_retransmit_message(s, (unsigned short)dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs), &found) <= 0)
1117
0
            return -1;
1118
0
    }
1119
1120
0
    return 1;
1121
0
}
1122
1123
int dtls1_buffer_message(SSL_CONNECTION *s, int is_ccs)
1124
77.5k
{
1125
77.5k
    pitem *item;
1126
77.5k
    hm_fragment *frag;
1127
77.5k
    unsigned char seq64be[8];
1128
1129
    /*
1130
     * this function is called immediately after a message has been
1131
     * serialized
1132
     */
1133
77.5k
    if (!ossl_assert(s->init_off == 0))
1134
0
        return 0;
1135
1136
77.5k
    frag = dtls1_hm_fragment_new(s->init_num, 0);
1137
77.5k
    if (frag == NULL)
1138
0
        return 0;
1139
1140
77.5k
    memcpy(frag->fragment, s->init_buf->data, s->init_num);
1141
1142
77.5k
    if (is_ccs) {
1143
        /* For DTLS1_BAD_VER the header length is non-standard */
1144
2.77k
        if (!ossl_assert(s->d1->w_msg_hdr.msg_len + ((s->version == DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH)
1145
2.77k
                == (unsigned int)s->init_num)) {
1146
0
            dtls1_hm_fragment_free(frag);
1147
0
            return 0;
1148
0
        }
1149
74.7k
    } else {
1150
74.7k
        if (!ossl_assert(s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num)) {
1151
0
            dtls1_hm_fragment_free(frag);
1152
0
            return 0;
1153
0
        }
1154
74.7k
    }
1155
1156
77.5k
    frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1157
77.5k
    frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1158
77.5k
    frag->msg_header.type = s->d1->w_msg_hdr.type;
1159
77.5k
    frag->msg_header.frag_off = 0;
1160
77.5k
    frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1161
77.5k
    frag->msg_header.is_ccs = is_ccs;
1162
1163
    /* save current state */
1164
77.5k
    frag->msg_header.saved_retransmit_state.wrlmethod = s->rlayer.wrlmethod;
1165
77.5k
    frag->msg_header.saved_retransmit_state.wrl = s->rlayer.wrl;
1166
1167
77.5k
    memset(seq64be, 0, sizeof(seq64be));
1168
77.5k
    seq64be[6] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
1169
77.5k
                                     frag->msg_header.is_ccs)
1170
77.5k
        >> 8);
1171
77.5k
    seq64be[7] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
1172
77.5k
        frag->msg_header.is_ccs));
1173
1174
77.5k
    item = pitem_new(seq64be, frag);
1175
77.5k
    if (item == NULL) {
1176
0
        dtls1_hm_fragment_free(frag);
1177
0
        return 0;
1178
0
    }
1179
1180
77.5k
    pqueue_insert(s->d1->sent_messages, item);
1181
77.5k
    return 1;
1182
77.5k
}
1183
1184
int dtls1_retransmit_message(SSL_CONNECTION *s, unsigned short seq, int *found)
1185
0
{
1186
0
    int ret;
1187
    /* XDTLS: for now assuming that read/writes are blocking */
1188
0
    pitem *item;
1189
0
    hm_fragment *frag;
1190
0
    unsigned long header_length;
1191
0
    unsigned char seq64be[8];
1192
0
    struct dtls1_retransmit_state saved_state;
1193
1194
    /* XDTLS:  the requested message ought to be found, otherwise error */
1195
0
    memset(seq64be, 0, sizeof(seq64be));
1196
0
    seq64be[6] = (unsigned char)(seq >> 8);
1197
0
    seq64be[7] = (unsigned char)seq;
1198
1199
0
    item = pqueue_find(s->d1->sent_messages, seq64be);
1200
0
    if (item == NULL) {
1201
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1202
0
        *found = 0;
1203
0
        return 0;
1204
0
    }
1205
1206
0
    *found = 1;
1207
0
    frag = (hm_fragment *)item->data;
1208
1209
0
    if (frag->msg_header.is_ccs)
1210
0
        header_length = DTLS1_CCS_HEADER_LENGTH;
1211
0
    else
1212
0
        header_length = DTLS1_HM_HEADER_LENGTH;
1213
1214
0
    memcpy(s->init_buf->data, frag->fragment,
1215
0
        frag->msg_header.msg_len + header_length);
1216
0
    s->init_num = frag->msg_header.msg_len + header_length;
1217
1218
0
    dtls1_set_message_header_int(s, frag->msg_header.type,
1219
0
        frag->msg_header.msg_len,
1220
0
        frag->msg_header.seq, 0,
1221
0
        frag->msg_header.frag_len);
1222
1223
    /* save current state */
1224
0
    saved_state.wrlmethod = s->rlayer.wrlmethod;
1225
0
    saved_state.wrl = s->rlayer.wrl;
1226
1227
0
    s->d1->retransmitting = 1;
1228
1229
    /* restore state in which the message was originally sent */
1230
0
    s->rlayer.wrlmethod = frag->msg_header.saved_retransmit_state.wrlmethod;
1231
0
    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
0
    s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
1238
1239
0
    ret = dtls1_do_write(s, frag->msg_header.is_ccs ? SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1240
1241
    /* restore current state */
1242
0
    s->rlayer.wrlmethod = saved_state.wrlmethod;
1243
0
    s->rlayer.wrl = saved_state.wrl;
1244
1245
0
    s->d1->retransmitting = 0;
1246
1247
0
    (void)BIO_flush(s->wbio);
1248
0
    return ret;
1249
0
}
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
75.3k
{
1255
75.3k
    if (frag_off == 0) {
1256
75.3k
        s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1257
75.3k
        s->d1->next_handshake_write_seq++;
1258
75.3k
    }
1259
1260
75.3k
    dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1261
75.3k
        frag_off, frag_len);
1262
75.3k
}
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
78.1k
{
1270
78.1k
    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1271
1272
78.1k
    msg_hdr->type = mt;
1273
78.1k
    msg_hdr->msg_len = len;
1274
78.1k
    msg_hdr->seq = seq_num;
1275
78.1k
    msg_hdr->frag_off = frag_off;
1276
78.1k
    msg_hdr->frag_len = frag_len;
1277
78.1k
}
1278
1279
static void
1280
dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off, size_t frag_len)
1281
224k
{
1282
224k
    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1283
1284
224k
    msg_hdr->frag_off = frag_off;
1285
224k
    msg_hdr->frag_len = frag_len;
1286
224k
}
1287
1288
static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,
1289
    unsigned char *p)
1290
149k
{
1291
149k
    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1292
1293
149k
    *p++ = msg_hdr->type;
1294
149k
    l2n3(msg_hdr->msg_len, p);
1295
1296
149k
    s2n(msg_hdr->seq, p);
1297
149k
    l2n3(msg_hdr->frag_off, p);
1298
149k
    l2n3(msg_hdr->frag_len, p);
1299
1300
149k
    return p;
1301
149k
}
1302
1303
void dtls1_get_message_header(const unsigned char *data, struct hm_header_st *msg_hdr)
1304
137k
{
1305
137k
    memset(msg_hdr, 0, sizeof(*msg_hdr));
1306
137k
    msg_hdr->type = *(data++);
1307
137k
    n2l3(data, msg_hdr->msg_len);
1308
1309
137k
    n2s(data, msg_hdr->seq);
1310
137k
    n2l3(data, msg_hdr->frag_off);
1311
137k
    n2l3(data, msg_hdr->frag_len);
1312
137k
}
1313
1314
int dtls1_set_handshake_header(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1315
78.1k
{
1316
78.1k
    unsigned char *header;
1317
1318
78.1k
    if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {
1319
2.77k
        s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1320
2.77k
        dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1321
2.77k
            s->d1->handshake_write_seq, 0, 0);
1322
2.77k
        if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))
1323
0
            return 0;
1324
75.3k
    } else {
1325
75.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
75.3k
        if (!WPACKET_allocate_bytes(pkt, DTLS1_HM_HEADER_LENGTH, &header)
1331
75.3k
            || !WPACKET_start_sub_packet(pkt))
1332
0
            return 0;
1333
75.3k
    }
1334
1335
78.1k
    return 1;
1336
78.1k
}
1337
1338
int dtls1_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1339
77.5k
{
1340
77.5k
    size_t msglen;
1341
1342
77.5k
    if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
1343
77.5k
        || !WPACKET_get_length(pkt, &msglen)
1344
77.5k
        || msglen > INT_MAX)
1345
0
        return 0;
1346
1347
77.5k
    if (htype != SSL3_MT_CHANGE_CIPHER_SPEC) {
1348
74.7k
        s->d1->w_msg_hdr.msg_len = msglen - DTLS1_HM_HEADER_LENGTH;
1349
74.7k
        s->d1->w_msg_hdr.frag_len = msglen - DTLS1_HM_HEADER_LENGTH;
1350
74.7k
    }
1351
77.5k
    s->init_num = (int)msglen;
1352
77.5k
    s->init_off = 0;
1353
1354
77.5k
    if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST) {
1355
        /* Buffer the message to handle re-xmits */
1356
77.5k
        if (!dtls1_buffer_message(s, htype == SSL3_MT_CHANGE_CIPHER_SPEC ? 1 : 0))
1357
0
            return 0;
1358
77.5k
    }
1359
1360
77.5k
    return 1;
1361
77.5k
}