Coverage Report

Created: 2025-12-31 06:58

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