Coverage Report

Created: 2026-08-31 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/ssl/statem/statem_dtls.c
Line
Count
Source
1
/*
2
 * Copyright 2005-2026 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
0
#define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
21
22
#define RSMBLY_BITMASK_MARK(bitmask, start, end)                             \
23
0
    {                                                                        \
24
0
        if ((end) - (start) <= 8) {                                          \
25
0
            long ii;                                                         \
26
0
            for (ii = (start); ii < (end); ii++)                             \
27
0
                bitmask[((ii) >> 3)] |= (1 << ((ii) & 7));                   \
28
0
        } else {                                                             \
29
0
            long ii;                                                         \
30
0
            bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)];  \
31
0
            for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) \
32
0
                bitmask[ii] = 0xff;                                          \
33
0
            bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)];  \
34
0
        }                                                                    \
35
0
    }
36
37
#define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete)                   \
38
0
    {                                                                               \
39
0
        long ii;                                                                    \
40
0
        is_complete = 1;                                                            \
41
0
        if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) \
42
0
            is_complete = 0;                                                        \
43
0
        if (is_complete)                                                            \
44
0
            for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0; ii--)                    \
45
0
                if (bitmask[ii] != 0xff) {                                          \
46
0
                    is_complete = 0;                                                \
47
0
                    break;                                                          \
48
0
                }                                                                   \
49
0
    }
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 int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
59
    size_t *len);
60
61
/*
62
 * Check if CCS is expected in current state.
63
 *
64
 * RFC 6347 Section 4.1 states DTLS must handle message reordering since UDP
65
 * does not guarantee in-order delivery. This function determines when a
66
 * buffered CCS should be delivered to the state machine.
67
 *
68
 * Server states where CCS is expected:
69
 *   - TLS_ST_SR_KEY_EXCH: After key exchange (anonymous or no_cert_verify)
70
 *   - TLS_ST_SR_CERT_VRFY: After certificate verify
71
 *   - TLS_ST_SW_FINISHED: Session resumption (abbreviated handshake)
72
 *
73
 * Client states where CCS is expected:
74
 *   - TLS_ST_CR_SRVR_HELLO: Abbreviated handshake without ticket
75
 *   - TLS_ST_CW_FINISHED: After sending Finished, before server CCS
76
 *   - TLS_ST_CR_SESSION_TICKET: After receiving session ticket
77
 */
78
static int dtls_ccs_expected(SSL_CONNECTION *s)
79
0
{
80
0
    OSSL_HANDSHAKE_STATE st = s->statem.hand_state;
81
82
0
    if (s->server) {
83
0
        switch (st) {
84
0
        case TLS_ST_SR_KEY_EXCH:
85
            /* Anonymous or no client cert: CCS follows KeyExchange */
86
0
            if (s->session->peer == NULL && s->session->peer_rpk == NULL)
87
0
                return 1;
88
            /* Client cert but no verify message required */
89
0
            return s->statem.no_cert_verify;
90
0
        case TLS_ST_SR_CERT_VRFY:
91
0
            return 1;
92
0
        case TLS_ST_SW_FINISHED:
93
            /* Abbreviated handshake: server sends first, then receives CCS */
94
0
            return s->hit;
95
0
        default:
96
0
            return 0;
97
0
        }
98
0
    } else {
99
0
        switch (st) {
100
0
        case TLS_ST_CR_SRVR_HELLO:
101
            /* Abbreviated handshake without session ticket */
102
0
            return (s->hit && !s->ext.ticket_expected);
103
0
        case TLS_ST_CW_FINISHED:
104
            /* Full handshake: waiting for server CCS after sending Finished */
105
0
            return !s->ext.ticket_expected;
106
0
        case TLS_ST_CR_SESSION_TICKET:
107
0
            return 1;
108
0
        default:
109
0
            return 0;
110
0
        }
111
0
    }
112
0
}
113
114
static dtls_sent_msg *dtls1_sent_msg_new(size_t msg_len)
115
0
{
116
0
    dtls_sent_msg *msg = OPENSSL_malloc(sizeof(*msg) + msg_len);
117
118
0
    if (msg == NULL)
119
0
        return NULL;
120
121
0
    memset(msg, 0, sizeof(*msg));
122
123
    /* zero length msg gets msg->msg_buf == NULL */
124
0
    if (msg_len > 0)
125
0
        msg->msg_buf = (unsigned char *)(msg + 1);
126
127
0
    return msg;
128
0
}
129
130
void dtls1_sent_msg_free(dtls_sent_msg *msg)
131
0
{
132
0
    if (msg != NULL)
133
0
        ossl_list_record_number_elem_free(&msg->rec_nums);
134
135
0
    OPENSSL_free(msg);
136
0
}
137
138
static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)
139
0
{
140
0
    const size_t bitmask_len = (reassembly ? RSMBLY_BITMASK_SIZE(frag_len) : 0);
141
0
    hm_fragment *frag = OPENSSL_malloc(sizeof(*frag) + frag_len + bitmask_len);
142
143
0
    if (frag == NULL)
144
0
        return NULL;
145
146
0
    memset(frag, 0, sizeof(*frag));
147
148
    /* zero length fragment gets zero frag->fragment */
149
0
    if (frag_len > 0)
150
0
        frag->fragment = (unsigned char *)(frag + 1);
151
152
    /* Initialize reassembly bitmask if necessary */
153
0
    if (bitmask_len > 0) {
154
0
        if (frag->fragment == NULL)
155
0
            frag->reassembly = (unsigned char *)(frag + 1);
156
0
        else
157
0
            frag->reassembly = frag->fragment + frag_len;
158
159
0
        memset(frag->reassembly, 0, bitmask_len);
160
0
    }
161
162
0
    return frag;
163
0
}
164
165
void dtls1_hm_fragment_free(hm_fragment *frag)
166
0
{
167
0
    OPENSSL_free(frag);
168
0
}
169
170
static int dtls1_write_hm_header(unsigned char *msgheaderstart,
171
    unsigned char msg_type, size_t msg_len,
172
    unsigned short msg_seq, size_t fragoff,
173
    size_t fraglen)
174
0
{
175
0
    WPACKET msgheader;
176
0
    size_t msgheaderlen;
177
178
0
    if (!WPACKET_init_static_len(&msgheader, msgheaderstart,
179
0
            DTLS1_HM_HEADER_LENGTH, 0)
180
0
        || !WPACKET_put_bytes_u8(&msgheader, msg_type)
181
0
        || !WPACKET_put_bytes_u24(&msgheader, msg_len)
182
0
        || !WPACKET_put_bytes_u16(&msgheader, msg_seq)
183
0
        || !WPACKET_put_bytes_u24(&msgheader, fragoff)
184
0
        || !WPACKET_put_bytes_u24(&msgheader, fraglen)
185
0
        || !WPACKET_get_total_written(&msgheader, &msgheaderlen)
186
0
        || msgheaderlen != DTLS1_HM_HEADER_LENGTH
187
0
        || !WPACKET_finish(&msgheader))
188
0
        return 0;
189
190
0
    return 1;
191
0
}
192
193
/*
194
 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
195
 * SSL3_RT_CHANGE_CIPHER_SPEC)
196
 *
197
 * When sending a fragmented handshake message this function will re-use
198
 * s->init_buf->data but overwrite previously sent data to fill out the handshake
199
 * message header for the next fragment.
200
 *
201
 * E.g.
202
 * |-------------------------s->init_buf->data------------------------------|
203
 * |-- header1 --||-- fragment1 --|
204
 *                  |-- header2 --||-- fragment2 --|
205
 *                                   |-- header3 --||-- fragment3 --|
206
 *                                                                 .........
207
 */
208
int dtls1_do_write(SSL_CONNECTION *s, uint8_t recordtype)
209
0
{
210
0
    int ret;
211
0
    size_t written;
212
0
    size_t curr_mtu;
213
0
    int retry = 1;
214
0
    size_t len, overhead, used_len;
215
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
216
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
217
0
    uint8_t saved_payload[DTLS1_HM_HEADER_LENGTH];
218
    /* msg_len, msg_seq, msg_type are only used for recordtype == SSL3_RT_HANDSHAKE */
219
0
    const size_t msg_len = s->d1->w_msg.msg_body_len;
220
0
    const unsigned short msg_seq = s->d1->w_msg.msg_seq;
221
0
    const unsigned char msg_type = s->d1->w_msg.msg_type;
222
223
0
    if (!dtls1_query_mtu(s))
224
0
        return -1;
225
226
0
    if (s->d1->mtu < dtls1_min_mtu(s))
227
        /* should have something reasonable now */
228
0
        return -1;
229
230
0
    if (s->init_off == 0 && recordtype == SSL3_RT_HANDSHAKE) {
231
0
        if (!ossl_assert(s->init_num == msg_len + DTLS1_HM_HEADER_LENGTH))
232
0
            return -1;
233
0
    }
234
235
0
    overhead = s->rlayer.wrlmethod->get_max_record_overhead(s->rlayer.wrl);
236
237
0
    s->rwstate = SSL_NOTHING;
238
239
    /* s->init_num shouldn't ever be < 0...but just in case */
240
0
    while (s->init_num > 0) {
241
0
        unsigned char *msgstart;
242
243
0
        if (recordtype == SSL3_RT_HANDSHAKE && s->init_off > 0) {
244
            /*
245
             * We must be writing a fragment other than the first one
246
             * and this is the first attempt at writing out this fragment
247
             */
248
0
            if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {
249
                /*
250
                 * Each fragment that was already sent must at least have
251
                 * contained the message header plus one other byte.
252
                 * Therefore |init_off| must have progressed by at least
253
                 * |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went
254
                 * wrong.
255
                 */
256
0
                return -1;
257
0
            }
258
259
            /*
260
             * Adjust |init_off| and |init_num| to allow room for a new
261
             * message header for this fragment.
262
             */
263
0
            s->init_off -= DTLS1_HM_HEADER_LENGTH;
264
0
            s->init_num += DTLS1_HM_HEADER_LENGTH;
265
0
        }
266
267
0
        used_len = BIO_wpending(s->wbio) + overhead;
268
0
        if (s->d1->mtu > used_len)
269
0
            curr_mtu = s->d1->mtu - used_len;
270
0
        else
271
0
            curr_mtu = 0;
272
273
0
        if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
274
            /*
275
             * grr.. we could get an error if MTU picked was wrong
276
             */
277
0
            ret = BIO_flush(s->wbio);
278
0
            if (ret <= 0) {
279
0
                s->rwstate = SSL_WRITING;
280
0
                return ret;
281
0
            }
282
0
            if (s->d1->mtu > overhead + DTLS1_HM_HEADER_LENGTH) {
283
0
                curr_mtu = s->d1->mtu - overhead;
284
0
            } else {
285
                /* Shouldn't happen */
286
0
                return -1;
287
0
            }
288
0
        }
289
290
0
        if (s->init_num > curr_mtu)
291
0
            len = curr_mtu;
292
0
        else
293
0
            len = s->init_num;
294
295
0
        if (len > ssl_get_max_send_fragment(s))
296
0
            len = ssl_get_max_send_fragment(s);
297
298
        /*
299
         * For DTLS1.3 and padding lets update the max fragment size
300
         * accordingly
301
         */
302
0
        if (SSL_CONNECTION_IS_DTLS13(s))
303
0
            s->rlayer.wrlmethod->set_curr_mtu(s->rlayer.wrl, curr_mtu);
304
305
0
        msgstart = (unsigned char *)&s->init_buf->data[s->init_off];
306
307
0
        if (recordtype == SSL3_RT_HANDSHAKE) {
308
0
            const size_t fragoff = s->init_off;
309
0
            const size_t fraglen = len - DTLS1_HM_HEADER_LENGTH;
310
311
            /*
312
             * Save the data that will be overwritten by
313
             * the following code so no corruption occurs when using
314
             * a msg callback.
315
             */
316
0
            if (s->msg_callback && s->init_off != 0)
317
0
                memcpy(saved_payload, msgstart, sizeof(saved_payload));
318
319
0
            if (len < DTLS1_HM_HEADER_LENGTH
320
0
                || !dtls1_write_hm_header(msgstart, msg_type, msg_len,
321
0
                    msg_seq, fragoff, fraglen))
322
                /*
323
                 * len is so small that we really can't do anything sensible
324
                 * so fail
325
                 */
326
0
                return -1;
327
0
        }
328
329
0
        ret = dtls1_write_bytes(s, recordtype, msgstart, len,
330
0
            &written);
331
332
0
        if (recordtype == SSL3_RT_HANDSHAKE && s->msg_callback && s->init_off != 0)
333
0
            memcpy(msgstart, saved_payload, sizeof(saved_payload));
334
335
0
        if (ret <= 0) {
336
            /*
337
             * might need to update MTU here, but we don't know which
338
             * previous packet caused the failure -- so can't really
339
             * retransmit anything.  continue as if everything is fine and
340
             * wait for an alert to handle the retransmit
341
             */
342
0
            if (retry && BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0
343
0
                && !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)
344
0
                && dtls1_query_mtu(s))
345
                /* Have one more go */
346
0
                retry = 0;
347
0
            else
348
0
                return -1;
349
0
        } else {
350
351
            /*
352
             * bad if this assert fails, only part of the handshake message
353
             * got sent.  but why would this happen?
354
             */
355
0
            if (!ossl_assert(len == written))
356
0
                return -1;
357
358
            /*
359
             * We should not exceed the MTU size. If compression is in use
360
             * then the max record overhead calculation is unreliable so we do
361
             * not check in that case. We use assert rather than ossl_assert
362
             * because in a production build, if this assert were ever to fail,
363
             * then the best thing to do is probably carry on regardless.
364
             */
365
0
            assert(s->s3.tmp.new_compression != NULL
366
0
                || BIO_wpending(s->wbio) <= (int)s->d1->mtu);
367
368
0
            if (recordtype == SSL3_RT_HANDSHAKE && !s->d1->retransmitting
369
0
                && s->init_off == 0) {
370
0
                size_t xlen = s->init_num;
371
372
0
                if (s->version == DTLS1_BAD_VER) {
373
0
                    msgstart += DTLS1_HM_HEADER_LENGTH;
374
0
                    xlen -= DTLS1_HM_HEADER_LENGTH;
375
0
                } else {
376
                    /*
377
                     * Now prepare to calculate the transcript hash. For
378
                     * versions prior to DTLSv1.3 this means:
379
                     *
380
                     * rfc6347: Hash calculations include entire handshake
381
                     *   messages, including DTLS-specific fields: message_seq,
382
                     *   fragment_offset, and fragment_length. However, the
383
                     *   Finished MAC MUST be computed as if each handshake
384
                     *   message had been sent as a single fragment.
385
                     *
386
                     * For DTLSv1.3 DTLS-specific fields: message_seq,
387
                     * fragment_offset, and fragment_length are not used in the
388
                     * calculation i.e. the MAC-calculation is the same as TLS
389
                     * even though DTLS handshake messages may be fragmented.
390
                     */
391
0
                    if (!dtls1_write_hm_header(msgstart, msg_type, msg_len,
392
0
                            msg_seq, 0, msg_len))
393
0
                        return -1;
394
0
                }
395
396
                /*
397
                 * should not be done for 'Hello Request's, but in that case we'll
398
                 * ignore the result anyway
399
                 * DTLS1.3 KeyUpdate and NewSessionTicket do not need to be added
400
                 */
401
0
                if (!SSL_CONNECTION_IS_DTLS13(s)
402
0
                    || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
403
0
                        && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
404
0
                        && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
405
0
                    if (!ssl3_finish_mac(s, msgstart, xlen))
406
0
                        return -1;
407
0
            }
408
0
            if (written == s->init_num) {
409
0
                if (s->msg_callback)
410
0
                    s->msg_callback(1, s->version, recordtype, s->init_buf->data,
411
0
                        s->init_off + s->init_num, ussl,
412
0
                        s->msg_callback_arg);
413
414
0
                s->init_off = 0; /* done writing this message */
415
0
                s->init_num = 0;
416
417
0
                return 1;
418
0
            }
419
0
            s->init_off += written;
420
0
            s->init_num -= written;
421
0
            written -= DTLS1_HM_HEADER_LENGTH;
422
0
        }
423
0
    }
424
0
    return 0;
425
0
}
426
427
int dtls_get_message(SSL_CONNECTION *s, int *mt)
428
0
{
429
0
    unsigned char *rec_data;
430
0
    size_t tmplen;
431
0
    int errtype;
432
433
0
    s->d1->r_msg_seq = 0;
434
435
0
again:
436
0
    if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
437
0
        if (errtype == DTLS1_HM_BAD_FRAGMENT
438
0
            || errtype == DTLS1_HM_FRAGMENT_RETRY) {
439
            /* bad fragment received */
440
0
            goto again;
441
0
        }
442
0
        return 0;
443
0
    }
444
445
0
    *mt = s->s3.tmp.message_type;
446
447
0
    rec_data = (unsigned char *)s->init_buf->data;
448
449
    /*
450
     * If this isn't a real handshake message skip the processing below.
451
     */
452
0
    if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC || *mt == DTLS13_MT_ACK)
453
0
        return 1;
454
455
    /* reconstruct message header */
456
0
    dtls1_write_hm_header(rec_data, s->s3.tmp.message_type, s->s3.tmp.message_size,
457
0
        s->d1->r_msg_seq, 0, s->s3.tmp.message_size);
458
459
0
    s->d1->r_msg_seq = 0;
460
461
0
    s->d1->handshake_read_seq++;
462
463
0
    s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
464
465
0
    return 1;
466
0
}
467
468
/*
469
 * Actually we already have the message body - but this is an opportunity for
470
 * DTLS to do any further processing it wants at the same point that TLS would
471
 * be asked for the message body.
472
 */
473
int dtls_get_message_body(SSL_CONNECTION *s, size_t *len)
474
0
{
475
0
    unsigned char *msg = (unsigned char *)s->init_buf->data;
476
0
    size_t msg_len;
477
0
    int recordtype;
478
479
0
    switch (s->s3.tmp.message_type) {
480
0
    default:
481
0
        recordtype = SSL3_RT_HANDSHAKE;
482
0
        msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;
483
484
0
        break;
485
0
    case DTLS13_MT_ACK:
486
0
        recordtype = SSL3_RT_ACK;
487
0
        msg_len = s->init_num;
488
489
0
        goto end;
490
0
    case SSL3_MT_CHANGE_CIPHER_SPEC:
491
0
        recordtype = SSL3_RT_CHANGE_CIPHER_SPEC;
492
0
        msg_len = 1;
493
494
0
        goto end;
495
0
    }
496
497
    /*
498
     * If receiving Finished, record MAC of prior handshake messages for
499
     * Finished verification.
500
     */
501
0
    if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
502
        /* SSLfatal() already called */
503
0
        return 0;
504
0
    }
505
506
0
    if (!tls_common_finish_mac(s))
507
0
        return 0;
508
509
0
end:
510
0
    if (s->msg_callback)
511
0
        s->msg_callback(0, s->version, recordtype, msg, msg_len,
512
0
            SSL_CONNECTION_GET_USER_SSL(s), s->msg_callback_arg);
513
514
0
    *len = s->init_num;
515
0
    return 1;
516
0
}
517
518
/*
519
 * dtls1_max_handshake_message_len returns the maximum number of bytes
520
 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
521
 * may be greater if the maximum certificate list size requires it.
522
 */
523
static size_t dtls1_max_handshake_message_len(const SSL_CONNECTION *s)
524
0
{
525
0
    size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
526
0
    if (max_len < s->max_cert_list)
527
0
        return s->max_cert_list;
528
0
    return max_len;
529
0
}
530
531
static int dtls1_preprocess_fragment(SSL_CONNECTION *s,
532
    const struct hm_header_st *const msg_hdr)
533
0
{
534
0
    size_t frag_off, frag_len, msg_len;
535
536
0
    msg_len = msg_hdr->msg_len;
537
0
    frag_off = msg_hdr->frag_off;
538
0
    frag_len = msg_hdr->frag_len;
539
540
    /* sanity checking */
541
0
    if ((frag_off + frag_len) > msg_len
542
0
        || msg_len > dtls1_max_handshake_message_len(s)) {
543
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
544
0
        return 0;
545
0
    }
546
547
    /*
548
     * msg_len is limited to 2^24, but is effectively checked against
549
     * dtls_max_handshake_message_len(s) above
550
     */
551
0
    if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
552
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
553
0
        return 0;
554
0
    }
555
556
0
    s->s3.tmp.message_size = msg_len;
557
0
    s->s3.tmp.message_type = msg_hdr->type;
558
0
    s->d1->r_msg_seq = msg_hdr->seq;
559
560
0
    return 1;
561
0
}
562
563
static int add_record_to_ack_list(SSL_CONNECTION *sc)
564
0
{
565
0
    DTLS1_RECORD_NUMBER *recnum;
566
0
    uint64_t epoch = sc->s3.tmp.record_epoch;
567
0
    uint64_t sequence = sc->s3.tmp.record_seq_num;
568
569
0
    for (recnum = ossl_list_record_number_head(&sc->d1->ack_rec_num);
570
0
        recnum != NULL;
571
0
        recnum = ossl_list_record_number_next(recnum)) {
572
        /* Is the record number already in the list? */
573
0
        if (recnum->epoch == epoch && recnum->seqnum == sequence)
574
0
            return 1;
575
0
    }
576
577
0
    recnum = dtls1_record_number_new(epoch, sequence);
578
579
0
    if (recnum == NULL)
580
0
        return 0;
581
582
0
    ossl_list_record_number_insert_tail(&sc->d1->ack_rec_num, recnum);
583
584
0
    return 1;
585
0
}
586
587
/*
588
 * Returns 1 if there is a buffered fragment available, 0 if not, or -1 on a
589
 * fatal error.
590
 */
591
static int dtls1_retrieve_buffered_fragment(SSL_CONNECTION *s, size_t *len)
592
0
{
593
    /*-
594
     * (0) check whether the desired fragment is available
595
     * if so:
596
     * (1) copy over the fragment to s->init_buf->data[]
597
     * (2) update s->init_num
598
     */
599
0
    pitem *item;
600
0
    piterator iter;
601
0
    hm_fragment *frag;
602
0
    int ret;
603
0
    int chretran = 0;
604
0
    pqueue *rcvd_messages = &s->d1->rcvd_messages;
605
606
0
    iter = pqueue_iterator(rcvd_messages);
607
0
    do {
608
0
        item = pqueue_next(&iter);
609
0
        if (item == NULL)
610
0
            return 0;
611
612
0
        frag = (hm_fragment *)item->data;
613
614
0
        if (frag->msg_header.seq < s->d1->handshake_read_seq) {
615
0
            pitem *next;
616
0
            hm_fragment *nextfrag;
617
618
0
            if (!s->server
619
0
                || frag->msg_header.seq != 0
620
0
                || s->d1->handshake_read_seq != 1
621
0
                || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
622
                /*
623
                 * This is a stale message that has been buffered so clear it.
624
                 * It is safe to pop this message from the queue even though
625
                 * we have an active iterator
626
                 */
627
0
                pqueue_pop(rcvd_messages);
628
0
                dtls1_hm_fragment_free(frag);
629
0
                pitem_free(item);
630
0
                item = NULL;
631
0
                frag = NULL;
632
0
            } else {
633
                /*
634
                 * We have fragments for a ClientHello without a cookie,
635
                 * even though we have sent a HelloVerifyRequest. It is possible
636
                 * that the HelloVerifyRequest got lost and this is a
637
                 * retransmission of the original ClientHello
638
                 */
639
0
                next = pqueue_next(&iter);
640
0
                if (next != NULL) {
641
0
                    nextfrag = (hm_fragment *)next->data;
642
0
                    if (nextfrag->msg_header.seq == s->d1->handshake_read_seq) {
643
                        /*
644
                         * We have fragments for both a ClientHello without
645
                         * cookie and one with. Ditch the one without.
646
                         */
647
0
                        pqueue_pop(rcvd_messages);
648
0
                        dtls1_hm_fragment_free(frag);
649
0
                        pitem_free(item);
650
0
                        item = next;
651
0
                        frag = nextfrag;
652
0
                    } else {
653
0
                        chretran = 1;
654
0
                    }
655
0
                } else {
656
0
                    chretran = 1;
657
0
                }
658
0
            }
659
0
        }
660
0
    } while (item == NULL);
661
662
    /* Don't return if reassembly still in progress */
663
0
    if (frag->reassembly != NULL)
664
0
        return 0;
665
666
0
    if (s->d1->handshake_read_seq == frag->msg_header.seq || chretran) {
667
0
        size_t frag_len = frag->msg_header.frag_len;
668
669
0
        pqueue_pop(rcvd_messages);
670
671
        /* Calls SSLfatal() as required */
672
0
        ret = dtls1_preprocess_fragment(s, &frag->msg_header);
673
674
0
        if (ret && frag->msg_header.frag_len > 0) {
675
0
            unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
676
0
            memcpy(&p[frag->msg_header.frag_off], frag->fragment,
677
0
                frag->msg_header.frag_len);
678
0
        }
679
680
0
        dtls1_hm_fragment_free(frag);
681
0
        pitem_free(item);
682
683
0
        if (ret) {
684
0
            if (chretran) {
685
                /*
686
                 * We got a new ClientHello with a message sequence of 0.
687
                 * Reset the read/write sequences back to the beginning.
688
                 * We process it like this is the first time we've seen a
689
                 * ClientHello from the client.
690
                 */
691
0
                s->d1->handshake_read_seq = 0;
692
0
                s->d1->next_handshake_write_seq = 0;
693
0
            }
694
0
            *len = frag_len;
695
0
            return 1;
696
0
        }
697
698
        /* Fatal error */
699
0
        s->init_num = 0;
700
0
        return -1;
701
0
    } else {
702
0
        return 0;
703
0
    }
704
0
}
705
706
static int dtls1_reassemble_fragment(SSL_CONNECTION *s,
707
    const struct hm_header_st *msg_hdr)
708
0
{
709
0
    hm_fragment *frag = NULL;
710
0
    pitem *item = NULL;
711
0
    int i = -1, is_complete;
712
0
    size_t frag_len = msg_hdr->frag_len;
713
0
    size_t readbytes;
714
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
715
716
0
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len
717
0
        || msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
718
0
        goto err;
719
720
0
    if (frag_len == 0) {
721
0
        return DTLS1_HM_FRAGMENT_RETRY;
722
0
    }
723
724
    /* Try to find item in queue */
725
0
    item = pqueue_find_u64(&s->d1->rcvd_messages, msg_hdr->seq);
726
727
0
    if (item == NULL) {
728
0
        frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
729
0
        if (frag == NULL)
730
0
            goto err;
731
0
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
732
0
        frag->msg_header.frag_len = frag->msg_header.msg_len;
733
0
        frag->msg_header.frag_off = 0;
734
0
    } else {
735
0
        frag = (hm_fragment *)item->data;
736
0
        if (frag->msg_header.msg_len != msg_hdr->msg_len) {
737
0
            item = NULL;
738
0
            frag = NULL;
739
0
            goto err;
740
0
        }
741
0
    }
742
743
    /*
744
     * If message is already reassembled, this must be a retransmit and can
745
     * be dropped. In this case item != NULL and so frag does not need to be
746
     * freed.
747
     */
748
0
    if (frag->reassembly == NULL) {
749
0
        unsigned char devnull[256];
750
751
0
        while (frag_len) {
752
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
753
0
                devnull,
754
0
                frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);
755
0
            if (i <= 0)
756
0
                goto err;
757
0
            frag_len -= readbytes;
758
0
        }
759
0
        return DTLS1_HM_FRAGMENT_RETRY;
760
0
    }
761
762
    /* read the body of the fragment (header has already been read */
763
0
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
764
0
        frag->fragment + msg_hdr->frag_off,
765
0
        frag_len, 0, &readbytes);
766
0
    if (i <= 0 || readbytes != frag_len)
767
0
        goto err;
768
769
0
    RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
770
0
        (long)(msg_hdr->frag_off + frag_len));
771
772
0
    if (!ossl_assert(msg_hdr->msg_len > 0))
773
0
        goto err;
774
0
    RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
775
0
        is_complete);
776
777
0
    if (is_complete)
778
0
        frag->reassembly = NULL;
779
780
0
    if (item == NULL) {
781
0
        item = pitem_new_u64(msg_hdr->seq, frag);
782
0
        if (item == NULL)
783
0
            goto err;
784
785
0
        item = pqueue_insert(&s->d1->rcvd_messages, item);
786
        /*
787
         * pqueue_insert fails iff a duplicate item is inserted. However,
788
         * |item| cannot be a duplicate. If it were, |pqueue_find_u64|, above,
789
         * would have returned it and control would never have reached this
790
         * branch.
791
         */
792
0
        if (!ossl_assert(item != NULL))
793
0
            goto err;
794
0
    }
795
796
0
    if (dtls_msg_needs_ack(!s->server, msg_hdr->type)
797
0
        && !add_record_to_ack_list(s))
798
0
        goto err;
799
800
0
    return DTLS1_HM_FRAGMENT_RETRY;
801
802
0
err:
803
0
    if (item == NULL)
804
0
        dtls1_hm_fragment_free(frag);
805
0
    return -1;
806
0
}
807
808
static int dtls1_process_out_of_seq_message(SSL_CONNECTION *s,
809
    const struct hm_header_st *msg_hdr)
810
0
{
811
0
    int i = -1;
812
0
    hm_fragment *frag = NULL;
813
0
    pitem *item = NULL;
814
0
    size_t frag_len = msg_hdr->frag_len;
815
0
    size_t readbytes;
816
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
817
818
0
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
819
0
        goto err;
820
821
    /* Try to find item in queue, to prevent duplicate entries */
822
0
    item = pqueue_find_u64(&s->d1->rcvd_messages, msg_hdr->seq);
823
824
    /*
825
     * If we already have an entry and this one is a fragment, don't discard
826
     * it and rather try to reassemble it.
827
     */
828
0
    if (item != NULL && frag_len != msg_hdr->msg_len)
829
0
        item = NULL;
830
831
    /*
832
     * Discard the message if sequence number was already there, is too far
833
     * in the future, already in the queue or if we received a FINISHED
834
     * before the SERVER_HELLO, which then must be a stale retransmit.
835
     */
836
0
    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)) {
837
0
        unsigned char devnull[256];
838
839
0
        while (frag_len) {
840
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
841
0
                devnull,
842
0
                frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);
843
0
            if (i <= 0)
844
0
                goto err;
845
0
            frag_len -= readbytes;
846
0
        }
847
0
    } else {
848
0
        if (frag_len != msg_hdr->msg_len) {
849
0
            return dtls1_reassemble_fragment(s, msg_hdr);
850
0
        }
851
852
0
        if (frag_len > dtls1_max_handshake_message_len(s))
853
0
            goto err;
854
855
0
        frag = dtls1_hm_fragment_new(frag_len, 0);
856
0
        if (frag == NULL)
857
0
            goto err;
858
859
0
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
860
861
0
        if (frag_len) {
862
            /*
863
             * read the body of the fragment (header has already been read
864
             */
865
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
866
0
                frag->fragment, frag_len, 0,
867
0
                &readbytes);
868
0
            if (i <= 0 || readbytes != frag_len)
869
0
                goto err;
870
0
        }
871
872
0
        item = pitem_new_u64(msg_hdr->seq, frag);
873
0
        if (item == NULL)
874
0
            goto err;
875
876
0
        if (dtls_msg_needs_ack(!s->server, msg_hdr->type)
877
0
            && !add_record_to_ack_list(s))
878
0
            goto err;
879
880
0
        item = pqueue_insert(&s->d1->rcvd_messages, item);
881
        /*
882
         * pqueue_insert fails iff a duplicate item is inserted. However,
883
         * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
884
         * would have returned it. Then, either |frag_len| !=
885
         * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
886
         * have been processed with |dtls1_reassemble_fragment|, above, or
887
         * the record will have been discarded.
888
         */
889
0
        if (!ossl_assert(item != NULL))
890
0
            goto err;
891
0
    }
892
893
0
    return DTLS1_HM_FRAGMENT_RETRY;
894
895
0
err:
896
0
    if (item == NULL)
897
0
        dtls1_hm_fragment_free(frag);
898
0
    return 0;
899
0
}
900
901
static int dtls1_read_hm_header(unsigned char *msgheaderstart,
902
    struct hm_header_st *msg_hdr)
903
0
{
904
0
    unsigned long msg_len, frag_off, frag_len;
905
0
    unsigned int msg_seq, msg_type;
906
0
    PACKET msgheader;
907
908
0
    if (!PACKET_buf_init(&msgheader, msgheaderstart, DTLS1_HM_HEADER_LENGTH)
909
0
        || !PACKET_get_1(&msgheader, &msg_type)
910
0
        || !PACKET_get_net_3(&msgheader, &msg_len)
911
0
        || !PACKET_get_net_2(&msgheader, &msg_seq)
912
0
        || !PACKET_get_net_3(&msgheader, &frag_off)
913
0
        || !PACKET_get_net_3(&msgheader, &frag_len)
914
0
        || PACKET_remaining(&msgheader) != 0) {
915
0
        return 0;
916
0
    }
917
918
    /* We just checked that values did not exceed max size so cast must be alright */
919
0
    msg_hdr->type = (unsigned char)msg_type;
920
0
    msg_hdr->msg_len = (size_t)msg_len;
921
0
    msg_hdr->seq = (unsigned short)msg_seq;
922
0
    msg_hdr->frag_off = (size_t)frag_off;
923
0
    msg_hdr->frag_len = (size_t)frag_len;
924
925
0
    return 1;
926
0
}
927
928
/*
929
 * DTLS 1.3 reserves handshake message type 0, so a HelloRequest must reach the
930
 * state machine and be rejected there whenever DTLS 1.3 is still possible.
931
 *
932
 * s->version is the negotiated, or maximum version: before ServerHello this is
933
 * the effective maximum, and after ServerHello or during renegotiation it is the
934
 * selected version.
935
 */
936
static int dtls_should_skip_hello_request(const SSL_CONNECTION *s)
937
0
{
938
0
    if (SSL_CONNECTION_IS_DTLS13(s))
939
0
        return 0;
940
941
0
    return s->version > 0
942
0
        && ssl_version_cmp(s, s->version, DTLS1_3_VERSION) < 0;
943
0
}
944
945
static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
946
    size_t *len)
947
0
{
948
0
    int i, ret;
949
0
    uint8_t recvd_type;
950
0
    struct hm_header_st msg_hdr;
951
0
    size_t readbytes;
952
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
953
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
954
0
    int chretran = 0;
955
0
    unsigned char *p;
956
957
0
    *errtype = 0;
958
959
0
    p = (unsigned char *)s->init_buf->data;
960
961
0
redo:
962
    /* Check for buffered CCS */
963
0
    if ((s->version == DTLS1_VERSION || s->version == DTLS1_2_VERSION
964
0
            || s->version == DTLS1_BAD_VER)
965
0
        && s->d1->has_change_cipher_spec && dtls_ccs_expected(s)) {
966
0
        size_t extra = (s->version == DTLS1_BAD_VER) ? 2 : 0;
967
968
0
        s->d1->has_change_cipher_spec = 0;
969
0
        p[0] = SSL3_MT_CCS;
970
        /*
971
         * The extra 2 bytes are never consumed, only checked for
972
         * length -- zero-fill to avoid old init_buf content.
973
         */
974
0
        if (extra > 0)
975
0
            memset(p + 1, 0, extra);
976
0
        s->init_num = extra;
977
0
        s->init_msg = p + 1;
978
0
        s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
979
0
        s->s3.tmp.message_size = extra;
980
0
        *len = extra;
981
0
        return 1;
982
0
    }
983
984
    /* see if we have the required fragment already */
985
0
    ret = dtls1_retrieve_buffered_fragment(s, &msg_hdr.frag_len);
986
0
    if (ret < 0) {
987
        /* SSLfatal() already called */
988
0
        return 0;
989
0
    }
990
0
    if (ret > 0) {
991
0
        s->init_num = msg_hdr.frag_len;
992
0
        *len = msg_hdr.frag_len;
993
0
        return 1;
994
0
    }
995
996
    /* read handshake message header */
997
0
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type, p,
998
0
        DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
999
0
    if (i <= 0) { /* nbio, or an error */
1000
0
        s->rwstate = SSL_READING;
1001
0
        *len = 0;
1002
0
        return 0;
1003
0
    }
1004
0
    if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1005
0
        if (p[0] != SSL3_MT_CCS) {
1006
0
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1007
0
                SSL_R_BAD_CHANGE_CIPHER_SPEC);
1008
0
            goto f_err;
1009
0
        }
1010
1011
        /* Buffer CCS for reorder tolerance */
1012
0
        if (s->version == DTLS1_VERSION || s->version == DTLS1_2_VERSION
1013
0
            || s->version == DTLS1_BAD_VER) {
1014
0
            size_t expected = (s->version == DTLS1_BAD_VER) ? 3 : 1;
1015
1016
0
            if (readbytes != expected) {
1017
0
                SSLfatal(s, SSL_AD_DECODE_ERROR,
1018
0
                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
1019
0
                goto f_err;
1020
0
            }
1021
0
            s->d1->has_change_cipher_spec = 1;
1022
0
            goto redo;
1023
0
        }
1024
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1025
0
            SSL_R_BAD_CHANGE_CIPHER_SPEC);
1026
0
        goto f_err;
1027
0
    }
1028
0
    if (recvd_type == SSL3_RT_ACK) {
1029
0
        if (readbytes == DTLS1_HM_HEADER_LENGTH) {
1030
0
            const size_t first_readbytes = readbytes;
1031
1032
0
            p += DTLS1_HM_HEADER_LENGTH;
1033
1034
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL, p,
1035
0
                s->init_num - DTLS1_HM_HEADER_LENGTH,
1036
0
                0, &readbytes);
1037
0
            readbytes += first_readbytes;
1038
            /*
1039
             * This shouldn't ever fail due to NBIO because we already checked
1040
             * that we have enough data in the record
1041
             */
1042
0
            if (i <= 0) {
1043
0
                s->rwstate = SSL_READING;
1044
0
                *len = 0;
1045
0
                return 0;
1046
0
            }
1047
0
        }
1048
0
        s->init_num = readbytes;
1049
0
        s->init_msg = s->init_buf->data;
1050
0
        s->s3.tmp.message_type = DTLS13_MT_ACK;
1051
0
        s->s3.tmp.message_size = readbytes;
1052
0
        *len = readbytes;
1053
0
        return 1;
1054
0
    }
1055
1056
    /* Handshake fails if message header is incomplete */
1057
0
    if (readbytes != DTLS1_HM_HEADER_LENGTH) {
1058
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1059
0
        goto f_err;
1060
0
    }
1061
1062
    /* parse the message fragment header */
1063
0
    if (!dtls1_read_hm_header(p, &msg_hdr)) {
1064
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
1065
0
        goto f_err;
1066
0
    }
1067
1068
    /*
1069
     * We must have at least frag_len bytes left in the record to be read.
1070
     * Fragments must not span records.
1071
     */
1072
0
    if (msg_hdr.frag_len > s->rlayer.tlsrecs[s->rlayer.curr_rec].length) {
1073
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
1074
0
        goto f_err;
1075
0
    }
1076
1077
    /*
1078
     * if this is a future (or stale) message it gets buffered
1079
     * (or dropped)--no further processing at this time
1080
     * While listening, we accept seq 1 (ClientHello with cookie)
1081
     * although we're still expecting seq 0 (ClientHello)
1082
     */
1083
0
    if (msg_hdr.seq != s->d1->handshake_read_seq) {
1084
0
        if (!s->server
1085
0
            || msg_hdr.seq != 0
1086
0
            || s->d1->handshake_read_seq != 1
1087
0
            || msg_hdr.type != SSL3_MT_CLIENT_HELLO
1088
0
            || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
1089
0
            *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
1090
0
            return 0;
1091
0
        }
1092
        /*
1093
         * We received a ClientHello and sent back a HelloVerifyRequest. We
1094
         * now seem to have received a retransmitted initial ClientHello. That
1095
         * is allowed (possibly our HelloVerifyRequest got lost).
1096
         */
1097
0
        chretran = 1;
1098
0
    }
1099
1100
0
    if (msg_hdr.frag_len > 0 && msg_hdr.frag_len < msg_hdr.msg_len) {
1101
0
        *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
1102
0
        return 0;
1103
0
    }
1104
1105
0
    if (!s->server
1106
0
        && s->statem.hand_state != TLS_ST_OK
1107
0
        && msg_hdr.type == SSL3_MT_HELLO_REQUEST
1108
0
        && dtls_should_skip_hello_request(s)) {
1109
        /*
1110
         * The server may always send 'Hello Request' messages -- we are
1111
         * doing a handshake anyway now, so ignore them if their format is
1112
         * correct. Does not count for 'Finished' MAC.
1113
         */
1114
0
        if (msg_hdr.msg_len == 0) {
1115
0
            if (s->msg_callback)
1116
0
                s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1117
0
                    p, DTLS1_HM_HEADER_LENGTH, ussl,
1118
0
                    s->msg_callback_arg);
1119
1120
0
            s->init_num = 0;
1121
0
            goto redo;
1122
0
        } else {
1123
            /* Incorrectly formatted Hello request */
1124
0
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1125
0
            goto f_err;
1126
0
        }
1127
0
    }
1128
1129
0
    if (!dtls1_preprocess_fragment(s, &msg_hdr)) {
1130
        /* SSLfatal() already called */
1131
0
        goto f_err;
1132
0
    }
1133
1134
0
    if (msg_hdr.frag_len > 0) {
1135
        /* dtls1_preprocess_fragment() above could reallocate init_buf */
1136
0
        p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH + msg_hdr.frag_off;
1137
1138
0
        i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1139
0
            p, msg_hdr.frag_len, 0, &readbytes);
1140
1141
        /*
1142
         * This shouldn't ever fail due to NBIO because we already checked
1143
         * that we have enough data in the record
1144
         */
1145
0
        if (i <= 0) {
1146
0
            s->rwstate = SSL_READING;
1147
0
            *len = 0;
1148
0
            return 0;
1149
0
        }
1150
0
    } else {
1151
0
        readbytes = 0;
1152
0
    }
1153
1154
    /*
1155
     * XDTLS: an incorrectly formatted fragment should cause the handshake
1156
     * to fail
1157
     */
1158
0
    if (readbytes != msg_hdr.frag_len) {
1159
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
1160
0
        goto f_err;
1161
0
    }
1162
1163
0
    if (chretran) {
1164
        /*
1165
         * We got a new ClientHello with a message sequence of 0.
1166
         * Reset the read/write sequences back to the beginning.
1167
         * We process it like this is the first time we've seen a ClientHello
1168
         * from the client.
1169
         */
1170
0
        s->d1->handshake_read_seq = 0;
1171
0
        s->d1->next_handshake_write_seq = 0;
1172
0
    }
1173
1174
0
    if (dtls_msg_needs_ack(!s->server, msg_hdr.type)
1175
0
        && !add_record_to_ack_list(s)) {
1176
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1177
0
        goto f_err;
1178
0
    }
1179
1180
    /*
1181
     * Note that s->init_num is *not* used as current offset in
1182
     * s->init_buf->data, but as a counter summing up fragments' lengths: as
1183
     * soon as they sum up to handshake packet length, we assume we have got
1184
     * all the fragments.
1185
     */
1186
0
    *len = s->init_num = msg_hdr.frag_len;
1187
0
    return 1;
1188
1189
0
f_err:
1190
0
    s->init_num = 0;
1191
0
    *len = 0;
1192
0
    return 0;
1193
0
}
1194
1195
/*-
1196
 * for these 2 messages, we need to
1197
 * ssl->session->read_sym_enc           assign
1198
 * ssl->session->read_compression       assign
1199
 * ssl->session->read_hash              assign
1200
 */
1201
CON_FUNC_RETURN dtls_construct_change_cipher_spec(SSL_CONNECTION *s,
1202
    WPACKET *pkt)
1203
0
{
1204
0
    if (s->version == DTLS1_BAD_VER) {
1205
0
        s->d1->next_handshake_write_seq++;
1206
1207
0
        if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {
1208
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1209
0
            return CON_FUNC_ERROR;
1210
0
        }
1211
0
    }
1212
1213
0
    return CON_FUNC_SUCCESS;
1214
0
}
1215
1216
CON_FUNC_RETURN dtls_construct_ack(SSL_CONNECTION *s, WPACKET *pkt)
1217
0
{
1218
0
    DTLS1_RECORD_NUMBER *recnum;
1219
0
    DTLS1_RECORD_NUMBER *recnumnext = ossl_list_record_number_head(&s->d1->ack_rec_num);
1220
1221
0
    if (!WPACKET_start_sub_packet_u16(pkt)) {
1222
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1223
0
        return CON_FUNC_ERROR;
1224
0
    }
1225
1226
0
    while ((recnum = recnumnext) != NULL) {
1227
        /*
1228
         * rfc9147: section 4.
1229
         *
1230
         * Record numbers are encoded as
1231
         *      struct {
1232
         *           uint64 epoch;
1233
         *           uint64 sequence_number;
1234
         *      } RecordNumber;
1235
         */
1236
1237
0
        recnumnext = ossl_list_record_number_next(recnum);
1238
1239
0
        if (recnum->epoch <= dtls1_get_epoch(s, SSL3_CC_WRITE)) {
1240
            /*
1241
             * rfc9147:
1242
             * During the handshake, ACK records MUST be sent with an epoch which
1243
             * is equal to or higher than the record which is being acknowledged
1244
             */
1245
0
            if (!WPACKET_put_bytes_u64(pkt, recnum->epoch)
1246
0
                || !WPACKET_put_bytes_u64(pkt, recnum->seqnum)) {
1247
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1248
0
                return CON_FUNC_ERROR;
1249
0
            }
1250
1251
0
            ossl_list_record_number_remove(&s->d1->ack_rec_num, recnum);
1252
0
            OPENSSL_free(recnum);
1253
0
        }
1254
0
    }
1255
1256
0
    if (!WPACKET_close(pkt)) {
1257
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1258
0
        return CON_FUNC_ERROR;
1259
0
    }
1260
1261
0
    return CON_FUNC_SUCCESS;
1262
0
}
1263
1264
MSG_PROCESS_RETURN dtls_process_ack(SSL_CONNECTION *s, PACKET *pkt)
1265
0
{
1266
0
    PACKET record_numbers;
1267
1268
0
    if (!PACKET_get_length_prefixed_2(pkt, &record_numbers)) {
1269
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_TOO_LONG);
1270
0
        return MSG_PROCESS_ERROR;
1271
0
    }
1272
1273
0
    while (PACKET_remaining(&record_numbers) > 0) {
1274
        /*
1275
         * rfc9147: section 4.
1276
         *
1277
         * Record numbers are encoded as
1278
         *      struct {
1279
         *           uint64 epoch;
1280
         *           uint64 sequence_number;
1281
         *      } RecordNumber;
1282
         */
1283
0
        pitem *item;
1284
0
        piterator iter;
1285
0
        uint64_t epoch;
1286
0
        uint64_t sequence_number;
1287
1288
0
        if (!PACKET_get_net_8(&record_numbers, &epoch)
1289
0
            || !PACKET_get_net_8(&record_numbers, &sequence_number)) {
1290
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1291
0
            return MSG_PROCESS_ERROR;
1292
0
        }
1293
1294
0
        iter = pqueue_iterator(&s->d1->sent_messages);
1295
1296
0
        while ((item = pqueue_next(&iter)) != NULL) {
1297
0
            dtls_sent_msg *msg = (dtls_sent_msg *)item->data;
1298
0
            DTLS1_RECORD_NUMBER *recnum;
1299
0
            DTLS1_RECORD_NUMBER *recnum_next = ossl_list_record_number_head(&msg->rec_nums);
1300
1301
0
            while ((recnum = recnum_next) != NULL) {
1302
0
                recnum_next = ossl_list_record_number_next(recnum_next);
1303
1304
0
                if (recnum->epoch == epoch && recnum->seqnum == sequence_number) {
1305
0
                    ossl_list_record_number_remove(&msg->rec_nums, recnum);
1306
0
                    OPENSSL_free(recnum);
1307
0
                }
1308
0
            }
1309
0
        }
1310
0
    }
1311
1312
0
    return MSG_PROCESS_FINISHED_READING;
1313
0
}
1314
1315
#ifndef OPENSSL_NO_SCTP
1316
/*
1317
 * Wait for a dry event. Should only be called at a point in the handshake
1318
 * where we are not expecting any data from the peer except an alert.
1319
 */
1320
WORK_STATE dtls_wait_for_dry(SSL_CONNECTION *s)
1321
{
1322
    int ret, errtype;
1323
    size_t len;
1324
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1325
1326
    /* read app data until dry event */
1327
    ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(ssl));
1328
    if (ret < 0) {
1329
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1330
        return WORK_ERROR;
1331
    }
1332
1333
    if (ret == 0) {
1334
        /*
1335
         * We're not expecting any more messages from the peer at this point -
1336
         * but we could get an alert. If an alert is waiting then we will never
1337
         * return successfully. Therefore we attempt to read a message. This
1338
         * should never succeed but will process any waiting alerts.
1339
         */
1340
        if (dtls_get_reassembled_message(s, &errtype, &len)) {
1341
            /* The call succeeded! This should never happen */
1342
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1343
            return WORK_ERROR;
1344
        }
1345
1346
        s->s3.in_read_app_data = 2;
1347
        s->rwstate = SSL_READING;
1348
        BIO_clear_retry_flags(SSL_get_rbio(ssl));
1349
        BIO_set_retry_read(SSL_get_rbio(ssl));
1350
        return WORK_MORE_A;
1351
    }
1352
    return WORK_FINISHED_CONTINUE;
1353
}
1354
#endif
1355
1356
int dtls1_read_failed(SSL_CONNECTION *s, int code)
1357
0
{
1358
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1359
1360
0
    if (code > 0) {
1361
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1362
0
        return 0;
1363
0
    }
1364
1365
0
    if (!dtls1_is_timer_expired(s) || ossl_statem_in_error(s)) {
1366
        /*
1367
         * not a timeout, none of our business, let higher layers handle
1368
         * this.  in fact it's probably an error
1369
         */
1370
0
        return code;
1371
0
    }
1372
    /* done, no need to send a retransmit */
1373
0
    if (!SSL_in_init(ssl)) {
1374
0
        BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);
1375
0
        return code;
1376
0
    }
1377
1378
0
    return dtls1_handle_timeout(s);
1379
0
}
1380
1381
void dtls1_get_queue_priority(unsigned char *prio64be, unsigned short seq,
1382
    int record_type)
1383
0
{
1384
    /*
1385
     * The index of the retransmission queue actually is the message sequence
1386
     * number, since the queue only contains messages of a single handshake.
1387
     * However, the ChangeCipherSpec has no message sequence number and so
1388
     * using only the sequence will result in the CCS and Finished having the
1389
     * same index. To prevent this, the sequence number is multiplied by 2.
1390
     * In case of a CCS 1 is subtracted. This does not only differ CSS and
1391
     * Finished, it also maintains the order of the index (important for
1392
     * priority queues) and fits in the unsigned short variable.
1393
     */
1394
0
    int lsb = (record_type == SSL3_RT_CHANGE_CIPHER_SPEC);
1395
0
    const uint16_t prio = seq * 2 - lsb;
1396
1397
0
    memset(prio64be, 0, 8);
1398
0
    prio64be[6] = (unsigned char)(prio >> 8);
1399
0
    prio64be[7] = (unsigned char)(prio);
1400
0
}
1401
1402
int dtls1_retransmit_sent_messages(SSL_CONNECTION *s)
1403
0
{
1404
0
    piterator iter = pqueue_iterator(&s->d1->sent_messages);
1405
0
    pitem *item;
1406
1407
0
    for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1408
0
        dtls_sent_msg *sent_msg = (dtls_sent_msg *)item->data;
1409
1410
0
        if (SSL_CONNECTION_IS_DTLS13(s)
1411
0
            && ossl_list_record_number_is_empty(&sent_msg->rec_nums))
1412
            /* rfc9147: Implementations must not retransmit acknowledged msgs */
1413
0
            continue;
1414
1415
0
        if (dtls1_retransmit_message(s, sent_msg) <= 0)
1416
0
            return -1;
1417
0
    }
1418
1419
0
    return 1;
1420
0
}
1421
1422
int dtls1_buffer_sent_message(SSL_CONNECTION *s, int record_type)
1423
0
{
1424
0
    pitem *item;
1425
0
    dtls_sent_msg *sent_msg;
1426
0
    unsigned char seq64be[8];
1427
0
    size_t headerlen;
1428
1429
    /*
1430
     * this function is called immediately after a message has been
1431
     * serialized
1432
     */
1433
0
    if (!ossl_assert(s->init_off == 0))
1434
0
        return 0;
1435
1436
0
    sent_msg = dtls1_sent_msg_new(s->init_num);
1437
0
    if (sent_msg == NULL)
1438
0
        return 0;
1439
1440
0
    memcpy(sent_msg->msg_buf, s->init_buf->data, s->init_num);
1441
1442
0
    if (record_type == SSL3_RT_CHANGE_CIPHER_SPEC)
1443
        /* For DTLS1_BAD_VER the header length is non-standard */
1444
0
        headerlen = (s->version == DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH;
1445
0
    else
1446
0
        headerlen = DTLS1_HM_HEADER_LENGTH;
1447
1448
0
    if (!ossl_assert(s->d1->w_msg.msg_body_len + headerlen == s->init_num)) {
1449
0
        dtls1_sent_msg_free(sent_msg);
1450
0
        return 0;
1451
0
    }
1452
1453
0
    memcpy(&sent_msg->msg_info, &s->d1->w_msg, sizeof(s->d1->w_msg));
1454
1455
    /* save current state */
1456
0
    sent_msg->saved_retransmit_state.wrlmethod = s->rlayer.wrlmethod;
1457
0
    sent_msg->saved_retransmit_state.wrl = s->rlayer.wrl;
1458
1459
0
    dtls1_get_queue_priority(seq64be, sent_msg->msg_info.msg_seq, sent_msg->msg_info.record_type);
1460
1461
0
    item = pitem_new(seq64be, sent_msg);
1462
0
    if (item == NULL) {
1463
0
        dtls1_sent_msg_free(sent_msg);
1464
0
        return 0;
1465
0
    }
1466
1467
0
    if (pqueue_insert(&s->d1->sent_messages, item) == NULL) {
1468
0
        dtls1_sent_msg_free(sent_msg);
1469
0
        pitem_free(item);
1470
0
        return 0;
1471
0
    }
1472
0
    return 1;
1473
0
}
1474
1475
int dtls1_retransmit_message(SSL_CONNECTION *s, dtls_sent_msg *sent_msg)
1476
0
{
1477
0
    int ret;
1478
0
    unsigned long header_length;
1479
0
    struct dtls1_retransmit_state saved_state;
1480
1481
0
    if (sent_msg->msg_info.record_type == SSL3_RT_CHANGE_CIPHER_SPEC)
1482
0
        header_length = DTLS1_CCS_HEADER_LENGTH;
1483
0
    else
1484
0
        header_length = DTLS1_HM_HEADER_LENGTH;
1485
1486
    /* Clear the record number list to be acked for retransmitted messages */
1487
0
    ossl_list_record_number_elem_free(&sent_msg->rec_nums);
1488
1489
0
    memcpy(s->init_buf->data, sent_msg->msg_buf,
1490
0
        sent_msg->msg_info.msg_body_len + header_length);
1491
0
    s->init_num = sent_msg->msg_info.msg_body_len + header_length;
1492
1493
0
    memcpy(&s->d1->w_msg, &sent_msg->msg_info, sizeof(sent_msg->msg_info));
1494
1495
    /* save current state */
1496
0
    saved_state.wrlmethod = s->rlayer.wrlmethod;
1497
0
    saved_state.wrl = s->rlayer.wrl;
1498
1499
0
    s->d1->retransmitting = 1;
1500
1501
    /* restore state in which the message was originally sent */
1502
0
    s->rlayer.wrlmethod = sent_msg->saved_retransmit_state.wrlmethod;
1503
0
    s->rlayer.wrl = sent_msg->saved_retransmit_state.wrl;
1504
1505
    /*
1506
     * The old wrl may be still pointing at an old BIO. Update it to what we're
1507
     * using now.
1508
     */
1509
0
    s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
1510
1511
0
    ret = dtls1_do_write(s, sent_msg->msg_info.record_type);
1512
1513
    /* restore current state */
1514
0
    s->rlayer.wrlmethod = saved_state.wrlmethod;
1515
0
    s->rlayer.wrl = saved_state.wrl;
1516
1517
0
    s->d1->retransmitting = 0;
1518
1519
0
    (void)BIO_flush(s->wbio);
1520
0
    return ret;
1521
0
}
1522
1523
int dtls1_set_handshake_header(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1524
0
{
1525
0
    s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1526
0
    s->d1->w_msg.msg_seq = s->d1->handshake_write_seq;
1527
0
    s->d1->w_msg.msg_body_len = 0;
1528
1529
0
    if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {
1530
0
        s->d1->w_msg.record_type = SSL3_RT_CHANGE_CIPHER_SPEC;
1531
0
        s->d1->w_msg.msg_type = SSL3_MT_CCS;
1532
1533
0
        if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))
1534
0
            return 0;
1535
0
    } else if (htype == DTLS13_MT_ACK) {
1536
0
        s->d1->w_msg.record_type = SSL3_RT_ACK;
1537
0
        s->d1->w_msg.msg_type = 0;
1538
0
    } else {
1539
0
        size_t subpacket_offset = DTLS1_HM_HEADER_LENGTH - SSL3_HM_HEADER_LENGTH;
1540
1541
0
        s->d1->next_handshake_write_seq++;
1542
0
        s->d1->w_msg.record_type = SSL3_RT_HANDSHAKE;
1543
0
        s->d1->w_msg.msg_type = htype;
1544
1545
        /* Set the content type and 3 bytes for the message len */
1546
0
        if (!WPACKET_put_bytes_u8(pkt, htype)
1547
            /*
1548
             * We allocate space for DTLS specific fields.
1549
             * These gets filled later.
1550
             */
1551
0
            || !WPACKET_start_sub_packet_u24_at_offset(pkt, subpacket_offset))
1552
0
            return 0;
1553
0
    }
1554
1555
0
    return 1;
1556
0
}
1557
1558
int dtls1_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1559
0
{
1560
0
    size_t msglen;
1561
1562
0
    if ((s->d1->w_msg.record_type == SSL3_RT_HANDSHAKE && !WPACKET_close(pkt))
1563
0
        || !WPACKET_get_length(pkt, &msglen)
1564
0
        || msglen > INT_MAX)
1565
0
        return 0;
1566
1567
0
    if (s->d1->w_msg.record_type == SSL3_RT_HANDSHAKE)
1568
0
        s->d1->w_msg.msg_body_len = msglen - DTLS1_HM_HEADER_LENGTH;
1569
1570
0
    s->init_num = msglen;
1571
0
    s->init_off = 0;
1572
1573
0
    if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST
1574
0
        && s->d1->w_msg.record_type != SSL3_RT_ACK) {
1575
        /* Buffer the message to handle re-xmits */
1576
0
        if (!dtls1_buffer_sent_message(s, s->d1->w_msg.record_type))
1577
0
            return 0;
1578
0
    }
1579
1580
0
    return 1;
1581
0
}