Coverage Report

Created: 2026-11-16 07:12

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, size_t body_len,
115
    int track_coverage)
116
0
{
117
0
    const size_t bitmask_len = (track_coverage && body_len > 0 ? RSMBLY_BITMASK_SIZE(body_len) : 0);
118
0
    dtls_sent_msg *msg = OPENSSL_malloc(sizeof(*msg) + msg_len + bitmask_len);
119
120
0
    if (msg == NULL)
121
0
        return NULL;
122
123
0
    memset(msg, 0, sizeof(*msg));
124
125
    /* zero length msg gets msg->msg_buf == NULL */
126
0
    if (msg_len > 0)
127
0
        msg->msg_buf = (unsigned char *)(msg + 1);
128
129
    /*
130
     * body_len > 0 implies msg_len > 0 (msg_len == body_len + headerlen, and
131
     * headerlen is never 0), so msg->msg_buf is already set here. Coverage
132
     * tracking only means anything for DTLS 1.3, the only version that ever
133
     * processes an ACK; older versions never read msg->covered, so don't pay
134
     * for the allocation on their behalf.
135
     */
136
0
    if (track_coverage && body_len > 0) {
137
0
        msg->covered = msg->msg_buf + msg_len;
138
0
        memset(msg->covered, 0, bitmask_len);
139
0
    }
140
141
0
    return msg;
142
0
}
143
144
void dtls1_sent_msg_free(dtls_sent_msg *msg)
145
0
{
146
0
    if (msg != NULL)
147
0
        ossl_list_record_number_elem_free(&msg->rec_nums);
148
149
0
    OPENSSL_free(msg);
150
0
}
151
152
static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)
153
0
{
154
0
    const size_t bitmask_len = (reassembly ? RSMBLY_BITMASK_SIZE(frag_len) : 0);
155
0
    hm_fragment *frag = OPENSSL_malloc(sizeof(*frag) + frag_len + bitmask_len);
156
157
0
    if (frag == NULL)
158
0
        return NULL;
159
160
0
    memset(frag, 0, sizeof(*frag));
161
162
    /* zero length fragment gets zero frag->fragment */
163
0
    if (frag_len > 0)
164
0
        frag->fragment = (unsigned char *)(frag + 1);
165
166
    /* Initialize reassembly bitmask if necessary */
167
0
    if (bitmask_len > 0) {
168
0
        if (frag->fragment == NULL)
169
0
            frag->reassembly = (unsigned char *)(frag + 1);
170
0
        else
171
0
            frag->reassembly = frag->fragment + frag_len;
172
173
0
        memset(frag->reassembly, 0, bitmask_len);
174
0
    }
175
176
0
    return frag;
177
0
}
178
179
void dtls1_hm_fragment_free(hm_fragment *frag)
180
0
{
181
0
    OPENSSL_free(frag);
182
0
}
183
184
static int dtls1_write_hm_header(unsigned char *msgheaderstart,
185
    unsigned char msg_type, size_t msg_len,
186
    unsigned short msg_seq, size_t fragoff,
187
    size_t fraglen)
188
0
{
189
0
    WPACKET msgheader;
190
0
    size_t msgheaderlen;
191
192
0
    if (!WPACKET_init_static_len(&msgheader, msgheaderstart,
193
0
            DTLS1_HM_HEADER_LENGTH, 0)
194
0
        || !WPACKET_put_bytes_u8(&msgheader, msg_type)
195
0
        || !WPACKET_put_bytes_u24(&msgheader, msg_len)
196
0
        || !WPACKET_put_bytes_u16(&msgheader, msg_seq)
197
0
        || !WPACKET_put_bytes_u24(&msgheader, fragoff)
198
0
        || !WPACKET_put_bytes_u24(&msgheader, fraglen)
199
0
        || !WPACKET_get_total_written(&msgheader, &msgheaderlen)
200
0
        || msgheaderlen != DTLS1_HM_HEADER_LENGTH
201
0
        || !WPACKET_finish(&msgheader)) {
202
0
        WPACKET_cleanup(&msgheader);
203
0
        return 0;
204
0
    }
205
206
0
    return 1;
207
0
}
208
209
/*
210
 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE,
211
 * SSL3_RT_CHANGE_CIPHER_SPEC or SSL3_RT_ACK)
212
 *
213
 * When sending a fragmented handshake message this function will re-use
214
 * s->init_buf->data but overwrite previously sent data to fill out the handshake
215
 * message header for the next fragment.
216
 *
217
 * E.g.
218
 * |-------------------------s->init_buf->data------------------------------|
219
 * |-- header1 --||-- fragment1 --|
220
 *                  |-- header2 --||-- fragment2 --|
221
 *                                   |-- header3 --||-- fragment3 --|
222
 *                                                                 .........
223
 */
224
int dtls1_do_write(SSL_CONNECTION *s, uint8_t recordtype)
225
0
{
226
0
    int ret;
227
0
    size_t written;
228
0
    size_t curr_mtu;
229
0
    int retry = 1;
230
0
    size_t len, overhead, used_len;
231
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
232
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
233
0
    uint8_t saved_payload[DTLS1_HM_HEADER_LENGTH];
234
    /* msg_len, msg_seq, msg_type are only used for recordtype == SSL3_RT_HANDSHAKE */
235
0
    const size_t msg_len = s->d1->w_msg.msg_body_len;
236
0
    const unsigned short msg_seq = s->d1->w_msg.msg_seq;
237
0
    const unsigned char msg_type = s->d1->w_msg.msg_type;
238
0
    const size_t min_len = recordtype == SSL3_RT_ACK
239
0
        ? DTLS13_ACK_MIN_NONEMPTY_LEN
240
0
        : DTLS1_HM_HEADER_LENGTH + 1;
241
242
0
    if (!dtls1_query_mtu(s))
243
0
        return -1;
244
245
0
    if (s->d1->mtu < dtls1_min_mtu(s))
246
        /* should have something reasonable now */
247
0
        return -1;
248
249
0
    if (s->init_off == 0 && recordtype == SSL3_RT_HANDSHAKE) {
250
0
        if (!ossl_assert(s->init_num == msg_len + DTLS1_HM_HEADER_LENGTH))
251
0
            return -1;
252
0
    }
253
254
0
    overhead = s->rlayer.wrlmethod->get_max_record_overhead(s->rlayer.wrl);
255
256
0
    s->rwstate = SSL_NOTHING;
257
258
    /* s->init_num shouldn't ever be < 0...but just in case */
259
0
    while (s->init_num > 0) {
260
0
        unsigned char *msgstart;
261
262
0
        if (recordtype == SSL3_RT_HANDSHAKE && s->init_off > 0) {
263
            /*
264
             * We must be writing a fragment other than the first one
265
             * and this is the first attempt at writing out this fragment
266
             */
267
0
            if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {
268
                /*
269
                 * Each fragment that was already sent must at least have
270
                 * contained the message header plus one other byte.
271
                 * Therefore |init_off| must have progressed by at least
272
                 * |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went
273
                 * wrong.
274
                 */
275
0
                return -1;
276
0
            }
277
278
            /*
279
             * Adjust |init_off| and |init_num| to allow room for a new
280
             * message header for this fragment.
281
             */
282
0
            s->init_off -= DTLS1_HM_HEADER_LENGTH;
283
0
            s->init_num += DTLS1_HM_HEADER_LENGTH;
284
0
        }
285
286
0
        used_len = BIO_wpending(s->wbio) + overhead;
287
0
        if (s->d1->mtu > used_len)
288
0
            curr_mtu = s->d1->mtu - used_len;
289
0
        else
290
0
            curr_mtu = 0;
291
292
0
        if (curr_mtu < min_len) {
293
            /*
294
             * grr.. we could get an error if MTU picked was wrong
295
             */
296
0
            ret = BIO_flush(s->wbio);
297
0
            if (ret <= 0) {
298
0
                s->rwstate = SSL_WRITING;
299
0
                return ret;
300
0
            }
301
0
            if (s->d1->mtu >= overhead + min_len) {
302
0
                curr_mtu = s->d1->mtu - overhead;
303
0
            } else {
304
                /* Shouldn't happen */
305
0
                return -1;
306
0
            }
307
0
        }
308
309
0
        if (s->init_num > curr_mtu)
310
0
            len = curr_mtu;
311
0
        else
312
0
            len = s->init_num;
313
314
0
        if (len > ssl_get_max_send_fragment(s))
315
0
            len = ssl_get_max_send_fragment(s);
316
317
        /*
318
         * For DTLS1.3 and padding lets update the max fragment size
319
         * accordingly
320
         */
321
0
        if (SSL_CONNECTION_IS_DTLS13(s))
322
0
            s->rlayer.wrlmethod->set_curr_mtu(s->rlayer.wrl, curr_mtu);
323
324
0
        msgstart = (unsigned char *)&s->init_buf->data[s->init_off];
325
326
0
        if (recordtype == SSL3_RT_ACK) {
327
            /* Each record needs a complete vector of record numbers. */
328
0
            if (!ossl_assert(len >= DTLS13_ACK_HEADER_LEN))
329
0
                return -1;
330
0
            len = DTLS13_ACK_HEADER_LEN
331
0
                + ((len - DTLS13_ACK_HEADER_LEN) / DTLS13_RECORD_NUMBER_LEN)
332
0
                    * DTLS13_RECORD_NUMBER_LEN;
333
0
            msgstart[0] = (unsigned char)((len - DTLS13_ACK_HEADER_LEN) >> 8);
334
0
            msgstart[1] = (unsigned char)(len - DTLS13_ACK_HEADER_LEN);
335
0
        }
336
337
0
        if (recordtype == SSL3_RT_HANDSHAKE) {
338
0
            const size_t fragoff = s->init_off;
339
0
            const size_t fraglen = len - DTLS1_HM_HEADER_LENGTH;
340
341
            /*
342
             * Save the data that will be overwritten by
343
             * the following code so no corruption occurs when using
344
             * a msg callback.
345
             */
346
0
            if (s->msg_callback && s->init_off != 0)
347
0
                memcpy(saved_payload, msgstart, sizeof(saved_payload));
348
349
0
            if (len < DTLS1_HM_HEADER_LENGTH
350
0
                || !dtls1_write_hm_header(msgstart, msg_type, msg_len,
351
0
                    msg_seq, fragoff, fraglen))
352
                /*
353
                 * len is so small that we really can't do anything sensible
354
                 * so fail
355
                 */
356
0
                return -1;
357
358
            /*
359
             * Recorded so do_dtls1_write() (rec_layer_d1.c) can tag this
360
             * fragment's record number with the byte range it covers.
361
             */
362
0
            s->d1->w_frag_off = fragoff;
363
0
            s->d1->w_frag_len = fraglen;
364
0
        }
365
366
0
        ret = dtls1_write_bytes(s, recordtype, msgstart, len,
367
0
            &written);
368
369
0
        if (recordtype == SSL3_RT_HANDSHAKE && s->msg_callback && s->init_off != 0)
370
0
            memcpy(msgstart, saved_payload, sizeof(saved_payload));
371
372
0
        if (ret <= 0) {
373
            /*
374
             * might need to update MTU here, but we don't know which
375
             * previous packet caused the failure -- so can't really
376
             * retransmit anything.  continue as if everything is fine and
377
             * wait for an alert to handle the retransmit
378
             */
379
0
            if (retry && BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0
380
0
                && !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
381
0
                size_t old_mtu = s->d1->mtu;
382
383
0
                if (!dtls1_query_mtu(s))
384
0
                    return -1;
385
                /* If MTU didn't change, retry is meaningless */
386
0
                if (s->d1->mtu == old_mtu)
387
0
                    return -1;
388
                /* Have one more go */
389
0
                retry = 0;
390
0
            } else {
391
0
                return -1;
392
0
            }
393
0
        } else {
394
395
            /*
396
             * bad if this assert fails, only part of the handshake message
397
             * got sent.  but why would this happen?
398
             */
399
0
            if (!ossl_assert(len == written))
400
0
                return -1;
401
402
            /*
403
             * We should not exceed the MTU size. If compression is in use
404
             * then the max record overhead calculation is unreliable so we do
405
             * not check in that case. We use assert rather than ossl_assert
406
             * because in a production build, if this assert were ever to fail,
407
             * then the best thing to do is probably carry on regardless.
408
             */
409
0
            assert(s->s3.tmp.new_compression != NULL
410
0
                || BIO_wpending(s->wbio) <= (int)s->d1->mtu);
411
412
0
            if (recordtype == SSL3_RT_HANDSHAKE && !s->d1->retransmitting
413
0
                && s->init_off == 0) {
414
0
                size_t xlen = s->init_num;
415
416
0
                if (s->version == DTLS1_BAD_VER) {
417
0
                    msgstart += DTLS1_HM_HEADER_LENGTH;
418
0
                    xlen -= DTLS1_HM_HEADER_LENGTH;
419
0
                } else {
420
                    /*
421
                     * Now prepare to calculate the transcript hash. For
422
                     * versions prior to DTLSv1.3 this means:
423
                     *
424
                     * rfc6347: Hash calculations include entire handshake
425
                     *   messages, including DTLS-specific fields: message_seq,
426
                     *   fragment_offset, and fragment_length. However, the
427
                     *   Finished MAC MUST be computed as if each handshake
428
                     *   message had been sent as a single fragment.
429
                     *
430
                     * For DTLSv1.3 DTLS-specific fields: message_seq,
431
                     * fragment_offset, and fragment_length are not used in the
432
                     * calculation i.e. the MAC-calculation is the same as TLS
433
                     * even though DTLS handshake messages may be fragmented.
434
                     */
435
0
                    if (!dtls1_write_hm_header(msgstart, msg_type, msg_len,
436
0
                            msg_seq, 0, msg_len))
437
0
                        return -1;
438
0
                }
439
440
                /*
441
                 * should not be done for 'Hello Request's, but in that case we'll
442
                 * ignore the result anyway
443
                 * DTLS1.3 KeyUpdate and NewSessionTicket do not need to be added
444
                 */
445
0
                if (!SSL_CONNECTION_IS_DTLS13(s)
446
0
                    || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
447
0
                        && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
448
0
                        && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
449
0
                    if (!ssl3_finish_mac(s, msgstart, xlen))
450
0
                        return -1;
451
0
            }
452
0
            if (recordtype == SSL3_RT_ACK && s->msg_callback != NULL)
453
0
                s->msg_callback(1, s->version, recordtype, msgstart, written,
454
0
                    ussl, s->msg_callback_arg);
455
456
0
            if (written == s->init_num) {
457
0
                if (s->msg_callback && recordtype != SSL3_RT_ACK)
458
0
                    s->msg_callback(1, s->version, recordtype, s->init_buf->data,
459
0
                        s->init_off + s->init_num, ussl,
460
0
                        s->msg_callback_arg);
461
462
0
                s->init_off = 0; /* done writing this message */
463
0
                s->init_num = 0;
464
465
0
                return 1;
466
0
            }
467
            /* Reuse the last two sent bytes for the next ACK vector length. */
468
0
            if (recordtype == SSL3_RT_ACK)
469
0
                written -= DTLS13_ACK_HEADER_LEN;
470
0
            s->init_off += written;
471
0
            s->init_num -= written;
472
0
        }
473
0
    }
474
0
    return 0;
475
0
}
476
477
int dtls_get_message(SSL_CONNECTION *s, int *mt)
478
0
{
479
0
    unsigned char *rec_data;
480
0
    size_t tmplen;
481
0
    int errtype;
482
483
0
    s->d1->r_msg_seq = 0;
484
485
0
again:
486
0
    if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
487
0
        if (s->statem.ack_for_retransmit)
488
0
            return 0;
489
0
        if (errtype == DTLS1_HM_BAD_FRAGMENT
490
0
            || errtype == DTLS1_HM_FRAGMENT_RETRY) {
491
            /* bad fragment received */
492
0
            goto again;
493
0
        }
494
0
        return 0;
495
0
    }
496
497
0
    *mt = s->s3.tmp.message_type;
498
499
0
    rec_data = (unsigned char *)s->init_buf->data;
500
501
    /*
502
     * If this isn't a real handshake message skip the processing below.
503
     */
504
0
    if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC || *mt == DTLS13_MT_ACK)
505
0
        return 1;
506
507
    /* reconstruct message header */
508
0
    if (!dtls1_write_hm_header(rec_data, s->s3.tmp.message_type, s->s3.tmp.message_size,
509
0
            s->d1->r_msg_seq, 0, s->s3.tmp.message_size)) {
510
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
511
0
        return 0;
512
0
    }
513
514
0
    s->d1->r_msg_seq = 0;
515
516
0
    s->d1->handshake_read_seq++;
517
518
0
    s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
519
520
0
    return 1;
521
0
}
522
523
/*
524
 * Actually we already have the message body - but this is an opportunity for
525
 * DTLS to do any further processing it wants at the same point that TLS would
526
 * be asked for the message body.
527
 */
528
int dtls_get_message_body(SSL_CONNECTION *s, size_t *len)
529
0
{
530
0
    unsigned char *msg = (unsigned char *)s->init_buf->data;
531
0
    size_t msg_len;
532
0
    int recordtype;
533
534
0
    switch (s->s3.tmp.message_type) {
535
0
    default:
536
0
        recordtype = SSL3_RT_HANDSHAKE;
537
0
        msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;
538
539
0
        break;
540
0
    case DTLS13_MT_ACK:
541
0
        recordtype = SSL3_RT_ACK;
542
0
        msg_len = s->init_num;
543
544
0
        goto end;
545
0
    case SSL3_MT_CHANGE_CIPHER_SPEC:
546
0
        recordtype = SSL3_RT_CHANGE_CIPHER_SPEC;
547
0
        msg_len = 1;
548
549
0
        goto end;
550
0
    }
551
552
    /*
553
     * If receiving Finished, record MAC of prior handshake messages for
554
     * Finished verification.
555
     */
556
0
    if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
557
        /* SSLfatal() already called */
558
0
        return 0;
559
0
    }
560
561
0
    if (!tls_common_finish_mac(s))
562
0
        return 0;
563
564
0
end:
565
0
    if (s->msg_callback)
566
0
        s->msg_callback(0, s->version, recordtype, msg, msg_len,
567
0
            SSL_CONNECTION_GET_USER_SSL(s), s->msg_callback_arg);
568
569
0
    *len = s->init_num;
570
0
    return 1;
571
0
}
572
573
/*
574
 * dtls1_max_handshake_message_len returns the maximum number of bytes
575
 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
576
 * may be greater if the maximum certificate list size requires it.
577
 */
578
static size_t dtls1_max_handshake_message_len(const SSL_CONNECTION *s)
579
0
{
580
0
    size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
581
0
    if (max_len < s->max_cert_list)
582
0
        return s->max_cert_list;
583
0
    return max_len;
584
0
}
585
586
static int dtls1_preprocess_fragment(SSL_CONNECTION *s,
587
    const struct hm_header_st *const msg_hdr)
588
0
{
589
0
    size_t frag_off, frag_len, msg_len;
590
591
0
    msg_len = msg_hdr->msg_len;
592
0
    frag_off = msg_hdr->frag_off;
593
0
    frag_len = msg_hdr->frag_len;
594
595
    /* sanity checking */
596
0
    if ((frag_off + frag_len) > msg_len
597
0
        || msg_len > dtls1_max_handshake_message_len(s)) {
598
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
599
0
        return 0;
600
0
    }
601
602
    /*
603
     * msg_len is limited to 2^24, but is effectively checked against
604
     * dtls_max_handshake_message_len(s) above
605
     */
606
0
    if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
607
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
608
0
        return 0;
609
0
    }
610
611
0
    s->s3.tmp.message_size = msg_len;
612
0
    s->s3.tmp.message_type = msg_hdr->type;
613
0
    s->d1->r_msg_seq = msg_hdr->seq;
614
615
0
    return 1;
616
0
}
617
618
static int add_record_to_ack_list(SSL_CONNECTION *sc)
619
0
{
620
0
    DTLS1_RECORD_NUMBER *recnum;
621
0
    uint64_t epoch = sc->s3.tmp.record_epoch;
622
0
    uint64_t sequence = sc->s3.tmp.record_seq_num;
623
624
    /*
625
     * Retain at most one maximum-sized ACK record's worth of record numbers.
626
     * Check before the duplicate scan to bound the work once the list is full.
627
     * Excess records may be omitted from ACKs (RFC 9147, section 7.1).
628
     */
629
0
    if (ossl_list_record_number_num(&sc->d1->ack_rec_num)
630
0
        >= (SSL3_RT_MAX_PLAIN_LENGTH - DTLS13_ACK_HEADER_LEN) / DTLS13_RECORD_NUMBER_LEN)
631
0
        return 1;
632
633
0
    for (recnum = ossl_list_record_number_head(&sc->d1->ack_rec_num);
634
0
        recnum != NULL;
635
0
        recnum = ossl_list_record_number_next(recnum)) {
636
        /* Is the record number already in the list? */
637
0
        if (recnum->epoch == epoch && recnum->seqnum == sequence)
638
0
            return 1;
639
0
    }
640
641
0
    recnum = dtls1_record_number_new(epoch, sequence, 0, 0);
642
643
0
    if (recnum == NULL)
644
0
        return 0;
645
646
0
    ossl_list_record_number_insert_tail(&sc->d1->ack_rec_num, recnum);
647
648
0
    return 1;
649
0
}
650
651
/*
652
 * Returns 1 if there is a buffered fragment available, 0 if not, or -1 on a
653
 * fatal error.
654
 */
655
static int dtls1_retrieve_buffered_fragment(SSL_CONNECTION *s, size_t *len)
656
0
{
657
    /*-
658
     * (0) check whether the desired fragment is available
659
     * if so:
660
     * (1) copy over the fragment to s->init_buf->data[]
661
     * (2) update s->init_num
662
     */
663
0
    pitem *item;
664
0
    piterator iter;
665
0
    hm_fragment *frag;
666
0
    int ret;
667
0
    int chretran = 0;
668
0
    pqueue *rcvd_messages = &s->d1->rcvd_messages;
669
670
0
    iter = pqueue_iterator(rcvd_messages);
671
0
    do {
672
0
        item = pqueue_next(&iter);
673
0
        if (item == NULL)
674
0
            return 0;
675
676
0
        frag = (hm_fragment *)item->data;
677
678
0
        if (frag->msg_header.seq < s->d1->handshake_read_seq) {
679
0
            pitem *next;
680
0
            hm_fragment *nextfrag;
681
682
0
            if (!s->server
683
0
                || frag->msg_header.seq != 0
684
0
                || s->d1->handshake_read_seq != 1
685
0
                || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
686
                /*
687
                 * This is a stale message that has been buffered so clear it.
688
                 * It is safe to pop this message from the queue even though
689
                 * we have an active iterator
690
                 */
691
0
                pqueue_pop(rcvd_messages);
692
0
                dtls1_hm_fragment_free(frag);
693
0
                pitem_free(item);
694
0
                item = NULL;
695
0
                frag = NULL;
696
0
            } else {
697
                /*
698
                 * We have fragments for a ClientHello without a cookie,
699
                 * even though we have sent a HelloVerifyRequest. It is possible
700
                 * that the HelloVerifyRequest got lost and this is a
701
                 * retransmission of the original ClientHello
702
                 */
703
0
                next = pqueue_next(&iter);
704
0
                if (next != NULL) {
705
0
                    nextfrag = (hm_fragment *)next->data;
706
0
                    if (nextfrag->msg_header.seq == s->d1->handshake_read_seq) {
707
                        /*
708
                         * We have fragments for both a ClientHello without
709
                         * cookie and one with. Ditch the one without.
710
                         */
711
0
                        pqueue_pop(rcvd_messages);
712
0
                        dtls1_hm_fragment_free(frag);
713
0
                        pitem_free(item);
714
0
                        item = next;
715
0
                        frag = nextfrag;
716
0
                    } else {
717
0
                        chretran = 1;
718
0
                    }
719
0
                } else {
720
0
                    chretran = 1;
721
0
                }
722
0
            }
723
0
        }
724
0
    } while (item == NULL);
725
726
    /* Don't return if reassembly still in progress */
727
0
    if (frag->reassembly != NULL)
728
0
        return 0;
729
730
0
    if (s->d1->handshake_read_seq == frag->msg_header.seq || chretran) {
731
0
        size_t frag_len = frag->msg_header.frag_len;
732
733
0
        pqueue_pop(rcvd_messages);
734
735
        /* Calls SSLfatal() as required */
736
0
        ret = dtls1_preprocess_fragment(s, &frag->msg_header);
737
738
0
        if (ret && frag->msg_header.frag_len > 0) {
739
0
            unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
740
0
            memcpy(&p[frag->msg_header.frag_off], frag->fragment,
741
0
                frag->msg_header.frag_len);
742
0
        }
743
744
0
        dtls1_hm_fragment_free(frag);
745
0
        pitem_free(item);
746
747
0
        if (ret) {
748
0
            if (chretran) {
749
                /*
750
                 * We got a new ClientHello with a message sequence of 0.
751
                 * Reset the read/write sequences back to the beginning.
752
                 * We process it like this is the first time we've seen a
753
                 * ClientHello from the client.
754
                 */
755
0
                s->d1->handshake_read_seq = 0;
756
0
                s->d1->next_handshake_write_seq = 0;
757
0
            }
758
0
            *len = frag_len;
759
0
            return 1;
760
0
        }
761
762
        /* Fatal error */
763
0
        s->init_num = 0;
764
0
        return -1;
765
0
    } else {
766
0
        return 0;
767
0
    }
768
0
}
769
770
/*
771
 * Whether a fully-received message is already sitting in the reassembly
772
 * buffer for the next sequence number we expect, independently of any new
773
 * record having just arrived on the wire. dtls1_retrieve_buffered_fragment()
774
 * checks this unconditionally on every entry into the read state machine,
775
 * but that entry only ever happens as a side effect of a *new*
776
 * SSL3_RT_HANDSHAKE/SSL3_RT_ACK record arriving (see dtls1_read_bytes()'s
777
 * trampoline) or of a message we just processed ourselves bringing us back
778
 * here. Callers use this to decide whether to keep looping instead of
779
 * going idle, so a message that arrived out of order and was buffered
780
 * ahead of something still missing is not left stranded once that
781
 * something finally arrives and is processed in the same call.
782
 */
783
int dtls1_has_buffered_ready_message(SSL_CONNECTION *s)
784
0
{
785
0
    pitem *item = pqueue_find_u64(&s->d1->rcvd_messages, s->d1->handshake_read_seq);
786
0
    hm_fragment *frag;
787
788
0
    if (item == NULL)
789
0
        return 0;
790
0
    frag = (hm_fragment *)item->data;
791
0
    return frag->reassembly == NULL;
792
0
}
793
794
static int dtls1_reassemble_fragment(SSL_CONNECTION *s,
795
    const struct hm_header_st *msg_hdr)
796
0
{
797
0
    hm_fragment *frag = NULL;
798
0
    pitem *item = NULL;
799
0
    int i = -1, is_complete;
800
0
    size_t frag_len = msg_hdr->frag_len;
801
0
    size_t readbytes;
802
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
803
804
0
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len
805
0
        || msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
806
0
        goto err;
807
808
0
    if (frag_len == 0) {
809
0
        return DTLS1_HM_FRAGMENT_RETRY;
810
0
    }
811
812
    /* Try to find item in queue */
813
0
    item = pqueue_find_u64(&s->d1->rcvd_messages, msg_hdr->seq);
814
815
0
    if (item == NULL) {
816
0
        frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
817
0
        if (frag == NULL)
818
0
            goto err;
819
0
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
820
0
        frag->msg_header.frag_len = frag->msg_header.msg_len;
821
0
        frag->msg_header.frag_off = 0;
822
0
    } else {
823
0
        frag = (hm_fragment *)item->data;
824
0
        if (frag->msg_header.msg_len != msg_hdr->msg_len) {
825
0
            item = NULL;
826
0
            frag = NULL;
827
0
            goto err;
828
0
        }
829
0
    }
830
831
    /*
832
     * If message is already reassembled, this must be a retransmit and can
833
     * be dropped. In this case item != NULL and so frag does not need to be
834
     * freed.
835
     */
836
0
    if (frag->reassembly == NULL) {
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
        return DTLS1_HM_FRAGMENT_RETRY;
848
0
    }
849
850
    /* read the body of the fragment (header has already been read */
851
0
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
852
0
        frag->fragment + msg_hdr->frag_off,
853
0
        frag_len, 0, &readbytes);
854
0
    if (i <= 0 || readbytes != frag_len)
855
0
        goto err;
856
857
0
    RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
858
0
        (long)(msg_hdr->frag_off + frag_len));
859
860
0
    if (!ossl_assert(msg_hdr->msg_len > 0))
861
0
        goto err;
862
0
    RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
863
0
        is_complete);
864
865
0
    if (is_complete)
866
0
        frag->reassembly = NULL;
867
868
0
    if (item == NULL) {
869
0
        item = pitem_new_u64(msg_hdr->seq, frag);
870
0
        if (item == NULL)
871
0
            goto err;
872
873
0
        item = pqueue_insert(&s->d1->rcvd_messages, item);
874
        /*
875
         * pqueue_insert fails iff a duplicate item is inserted. However,
876
         * |item| cannot be a duplicate. If it were, |pqueue_find_u64|, above,
877
         * would have returned it and control would never have reached this
878
         * branch.
879
         */
880
0
        if (!ossl_assert(item != NULL))
881
0
            goto err;
882
0
    }
883
884
0
    if (dtls_msg_needs_ack(!s->server, msg_hdr->type)
885
0
        && !add_record_to_ack_list(s))
886
0
        goto err;
887
888
0
    return DTLS1_HM_FRAGMENT_RETRY;
889
890
0
err:
891
0
    if (item == NULL)
892
0
        dtls1_hm_fragment_free(frag);
893
0
    return -1;
894
0
}
895
896
/*
897
 * True if the message currently being processed only authenticated because
898
 * the read record layer retained a previous epoch's keys for retransmission
899
 * recovery -- i.e. it did not actually arrive at the currently active
900
 * read epoch. Such a message must never be treated as new content: it may
901
 * only, at most, trigger a replacement ACK for something already fully
902
 * processed.
903
 */
904
int dtls_record_from_retained_epoch(SSL_CONNECTION *s)
905
0
{
906
0
    return SSL_CONNECTION_IS_DTLS13(s)
907
0
        && s->s3.tmp.record_epoch != dtls1_get_epoch(s, SSL3_CC_READ);
908
0
}
909
910
/*
911
 * Server read states where an ACK must not finish the client's flight.
912
 * The certificate states are also used during post-handshake authentication.
913
 * Callers admitting ACKs must exclude a pending HelloRetryRequest.
914
 */
915
int dtls13_server_waiting_for_client_flight(OSSL_HANDSHAKE_STATE state)
916
0
{
917
0
    return state == TLS_ST_EARLY_DATA
918
0
        || state == TLS_ST_SR_CERT
919
0
        || state == TLS_ST_SR_COMP_CERT
920
0
        || state == TLS_ST_SR_CERT_VRFY;
921
0
}
922
923
int dtls1_process_out_of_seq_message(SSL_CONNECTION *s,
924
    const struct hm_header_st *msg_hdr)
925
0
{
926
0
    int i = -1;
927
0
    hm_fragment *frag = NULL;
928
0
    pitem *item = NULL;
929
0
    size_t frag_len = msg_hdr->frag_len;
930
0
    size_t readbytes;
931
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
932
933
0
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
934
0
        goto err;
935
936
    /* Try to find item in queue, to prevent duplicate entries */
937
0
    item = pqueue_find_u64(&s->d1->rcvd_messages, msg_hdr->seq);
938
939
    /*
940
     * If we already have an entry and this one is a fragment, don't discard
941
     * it and rather try to reassemble it.
942
     */
943
0
    if (item != NULL && frag_len != msg_hdr->msg_len)
944
0
        item = NULL;
945
946
    /*
947
     * Discard the message if sequence number was already there, is too far
948
     * in the future, already in the queue, if we received a FINISHED
949
     * before the SERVER_HELLO (which then must be a stale retransmit), or
950
     * if it only authenticated via a retained previous epoch: such a
951
     * message must never be buffered for future reassembly and eventually
952
     * processed as new content, no matter what sequence number it claims.
953
     */
954
0
    if (msg_hdr->seq <= s->d1->handshake_read_seq
955
0
        || msg_hdr->seq > s->d1->handshake_read_seq + 10
956
0
        || item != NULL
957
0
        || (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED)
958
0
        || dtls_record_from_retained_epoch(s)) {
959
0
        unsigned char devnull[256];
960
961
0
        while (frag_len) {
962
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
963
0
                devnull,
964
0
                frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);
965
0
            if (i <= 0)
966
0
                goto err;
967
0
            frag_len -= readbytes;
968
0
        }
969
        /*
970
         * A lost ACK can cause an already processed message to be
971
         * retransmitted in a new record. ACK it without processing it
972
         * again. Epoch 2 is included alongside the post-handshake epochs
973
         * (3+) so that a client's Finished, retransmitted after the server
974
         * has already moved on to epoch 3, still gets ACKed instead of
975
         * silently dropped (see dtls_get_more_records()'s retained
976
         * prev_epoch_rl handling, which is what let this record
977
         * authenticate at all).
978
         */
979
0
        if (SSL_CONNECTION_IS_DTLS13(s)
980
0
            && s->s3.tmp.record_epoch >= 2
981
0
            && msg_hdr->seq < s->d1->handshake_read_seq
982
0
            && dtls_msg_needs_ack(!s->server, msg_hdr->type)) {
983
0
            if (!add_record_to_ack_list(s))
984
0
                goto err;
985
0
            s->statem.ack_for_retransmit = 1;
986
0
        }
987
0
    } else {
988
0
        if (frag_len != msg_hdr->msg_len) {
989
0
            return dtls1_reassemble_fragment(s, msg_hdr);
990
0
        }
991
992
0
        if (frag_len > dtls1_max_handshake_message_len(s))
993
0
            goto err;
994
995
0
        frag = dtls1_hm_fragment_new(frag_len, 0);
996
0
        if (frag == NULL)
997
0
            goto err;
998
999
0
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
1000
1001
0
        if (frag_len) {
1002
            /*
1003
             * read the body of the fragment (header has already been read
1004
             */
1005
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1006
0
                frag->fragment, frag_len, 0,
1007
0
                &readbytes);
1008
0
            if (i <= 0 || readbytes != frag_len)
1009
0
                goto err;
1010
0
        }
1011
1012
0
        item = pitem_new_u64(msg_hdr->seq, frag);
1013
0
        if (item == NULL)
1014
0
            goto err;
1015
1016
0
        if (dtls_msg_needs_ack(!s->server, msg_hdr->type)
1017
0
            && !add_record_to_ack_list(s)) {
1018
0
            pitem_free(item);
1019
0
            item = NULL;
1020
0
            goto err;
1021
0
        }
1022
1023
0
        item = pqueue_insert(&s->d1->rcvd_messages, item);
1024
        /*
1025
         * pqueue_insert fails iff a duplicate item is inserted. However,
1026
         * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
1027
         * would have returned it. Then, either |frag_len| !=
1028
         * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
1029
         * have been processed with |dtls1_reassemble_fragment|, above, or
1030
         * the record will have been discarded.
1031
         */
1032
0
        if (!ossl_assert(item != NULL))
1033
0
            goto err;
1034
0
    }
1035
1036
0
    return DTLS1_HM_FRAGMENT_RETRY;
1037
1038
0
err:
1039
0
    if (item == NULL)
1040
0
        dtls1_hm_fragment_free(frag);
1041
0
    return 0;
1042
0
}
1043
1044
static int dtls1_read_hm_header(unsigned char *msgheaderstart,
1045
    struct hm_header_st *msg_hdr)
1046
0
{
1047
0
    unsigned long msg_len, frag_off, frag_len;
1048
0
    unsigned int msg_seq, msg_type;
1049
0
    PACKET msgheader;
1050
1051
0
    if (!PACKET_buf_init(&msgheader, msgheaderstart, DTLS1_HM_HEADER_LENGTH)
1052
0
        || !PACKET_get_1(&msgheader, &msg_type)
1053
0
        || !PACKET_get_net_3(&msgheader, &msg_len)
1054
0
        || !PACKET_get_net_2(&msgheader, &msg_seq)
1055
0
        || !PACKET_get_net_3(&msgheader, &frag_off)
1056
0
        || !PACKET_get_net_3(&msgheader, &frag_len)
1057
0
        || PACKET_remaining(&msgheader) != 0) {
1058
0
        return 0;
1059
0
    }
1060
1061
    /* We just checked that values did not exceed max size so cast must be alright */
1062
0
    msg_hdr->type = (unsigned char)msg_type;
1063
0
    msg_hdr->msg_len = (size_t)msg_len;
1064
0
    msg_hdr->seq = (unsigned short)msg_seq;
1065
0
    msg_hdr->frag_off = (size_t)frag_off;
1066
0
    msg_hdr->frag_len = (size_t)frag_len;
1067
1068
0
    return 1;
1069
0
}
1070
1071
/*
1072
 * DTLS 1.3 reserves handshake message type 0, so a HelloRequest must reach the
1073
 * state machine and be rejected there whenever DTLS 1.3 is still possible.
1074
 *
1075
 * s->version is the negotiated, or maximum version: before ServerHello this is
1076
 * the effective maximum, and after ServerHello or during renegotiation it is the
1077
 * selected version.
1078
 */
1079
static int dtls_should_skip_hello_request(const SSL_CONNECTION *s)
1080
0
{
1081
0
    if (SSL_CONNECTION_IS_DTLS13(s))
1082
0
        return 0;
1083
1084
0
    return s->version > 0
1085
0
        && ssl_version_cmp(s, s->version, DTLS1_3_VERSION) < 0;
1086
0
}
1087
1088
static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
1089
    size_t *len)
1090
0
{
1091
0
    int i, ret;
1092
0
    uint8_t recvd_type;
1093
0
    struct hm_header_st msg_hdr;
1094
0
    size_t readbytes;
1095
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1096
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1097
0
    int chretran = 0;
1098
0
    unsigned char *p;
1099
1100
0
    *errtype = 0;
1101
1102
0
    p = (unsigned char *)s->init_buf->data;
1103
1104
0
redo:
1105
    /* Check for buffered CCS */
1106
0
    if ((s->version == DTLS1_VERSION || s->version == DTLS1_2_VERSION
1107
0
            || s->version == DTLS1_BAD_VER)
1108
0
        && s->d1->has_change_cipher_spec && dtls_ccs_expected(s)) {
1109
0
        size_t extra = (s->version == DTLS1_BAD_VER) ? 2 : 0;
1110
1111
0
        s->d1->has_change_cipher_spec = 0;
1112
0
        p[0] = SSL3_MT_CCS;
1113
        /*
1114
         * The extra 2 bytes are never consumed, only checked for
1115
         * length -- zero-fill to avoid old init_buf content.
1116
         */
1117
0
        if (extra > 0)
1118
0
            memset(p + 1, 0, extra);
1119
0
        s->init_num = extra;
1120
0
        s->init_msg = p + 1;
1121
0
        s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
1122
0
        s->s3.tmp.message_size = extra;
1123
0
        *len = extra;
1124
0
        return 1;
1125
0
    }
1126
1127
    /* see if we have the required fragment already */
1128
0
    ret = dtls1_retrieve_buffered_fragment(s, &msg_hdr.frag_len);
1129
0
    if (ret < 0) {
1130
        /* SSLfatal() already called */
1131
0
        return 0;
1132
0
    }
1133
0
    if (ret > 0) {
1134
0
        s->init_num = msg_hdr.frag_len;
1135
0
        *len = msg_hdr.frag_len;
1136
0
        return 1;
1137
0
    }
1138
1139
    /* read handshake message header */
1140
0
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type, p,
1141
0
        DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
1142
0
    if (i <= 0) { /* nbio, or an error */
1143
0
        s->rwstate = SSL_READING;
1144
0
        *len = 0;
1145
0
        return 0;
1146
0
    }
1147
0
    if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1148
0
        if (p[0] != SSL3_MT_CCS) {
1149
0
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1150
0
                SSL_R_BAD_CHANGE_CIPHER_SPEC);
1151
0
            goto f_err;
1152
0
        }
1153
1154
        /* Buffer CCS for reorder tolerance */
1155
0
        if (s->version == DTLS1_VERSION || s->version == DTLS1_2_VERSION
1156
0
            || s->version == DTLS1_BAD_VER) {
1157
0
            size_t expected = (s->version == DTLS1_BAD_VER) ? 3 : 1;
1158
1159
0
            if (readbytes != expected) {
1160
0
                SSLfatal(s, SSL_AD_DECODE_ERROR,
1161
0
                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
1162
0
                goto f_err;
1163
0
            }
1164
0
            s->d1->has_change_cipher_spec = 1;
1165
0
            goto redo;
1166
0
        }
1167
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1168
0
            SSL_R_BAD_CHANGE_CIPHER_SPEC);
1169
0
        goto f_err;
1170
0
    }
1171
0
    if (recvd_type == SSL3_RT_ACK) {
1172
        /*
1173
         * An ACK has no handshake message header: the bytes already read
1174
         * are body, and an ACK never spans records (RFC 9147 section 4),
1175
         * so the rest of the body - if any - is whatever is left in the
1176
         * current record. Take it directly to avoid re-entering the
1177
         * timeout path while assembling the ACK.
1178
         */
1179
0
        if (readbytes == DTLS1_HM_HEADER_LENGTH
1180
0
            && s->rlayer.curr_rec < s->rlayer.num_recs) {
1181
0
            TLS_RECORD *rr = &s->rlayer.tlsrecs[s->rlayer.curr_rec];
1182
1183
            /*
1184
             * DTLS currently processes one record at a time, so an exhausted
1185
             * record is excluded above. Keep these checks to avoid consuming
1186
             * a following record if pipelining is added.
1187
             */
1188
0
            if (rr->off > 0 && rr->length > 0) {
1189
                /*
1190
                 * init_buf has capacity for a full plaintext record, whose size
1191
                 * has already been checked by the record layer.
1192
                 */
1193
0
                memcpy(p + DTLS1_HM_HEADER_LENGTH, rr->data + rr->off,
1194
0
                    rr->length);
1195
0
                readbytes += rr->length;
1196
0
                if (!ssl_release_record(s, rr, rr->length)) {
1197
                    /* SSLfatal() already called */
1198
0
                    goto f_err;
1199
0
                }
1200
0
            }
1201
0
        }
1202
0
        s->init_num = readbytes;
1203
0
        s->init_msg = s->init_buf->data;
1204
0
        s->s3.tmp.message_type = DTLS13_MT_ACK;
1205
0
        s->s3.tmp.message_size = readbytes;
1206
0
        *len = readbytes;
1207
0
        return 1;
1208
0
    }
1209
1210
    /* Handshake fails if message header is incomplete */
1211
0
    if (readbytes != DTLS1_HM_HEADER_LENGTH) {
1212
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1213
0
        goto f_err;
1214
0
    }
1215
1216
    /* parse the message fragment header */
1217
0
    if (!dtls1_read_hm_header(p, &msg_hdr)) {
1218
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
1219
0
        goto f_err;
1220
0
    }
1221
1222
    /*
1223
     * We must have at least frag_len bytes left in the record to be read.
1224
     * Fragments must not span records.
1225
     */
1226
0
    if (msg_hdr.frag_len > s->rlayer.tlsrecs[s->rlayer.curr_rec].length) {
1227
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
1228
0
        goto f_err;
1229
0
    }
1230
1231
    /*
1232
     * if this is a future (or stale) message it gets buffered
1233
     * (or dropped)--no further processing at this time
1234
     * While listening, we accept seq 1 (ClientHello with cookie)
1235
     * although we're still expecting seq 0 (ClientHello)
1236
     *
1237
     * A message that only authenticated via a retained previous epoch must
1238
     * always be routed to dtls1_process_out_of_seq_message(), even when its
1239
     * claimed sequence number happens to match the next expected one: that
1240
     * match does not mean this content is actually new.
1241
     */
1242
0
    if (msg_hdr.seq != s->d1->handshake_read_seq
1243
0
        || dtls_record_from_retained_epoch(s)) {
1244
0
        if (!s->server
1245
0
            || msg_hdr.seq != 0
1246
0
            || s->d1->handshake_read_seq != 1
1247
0
            || msg_hdr.type != SSL3_MT_CLIENT_HELLO
1248
0
            || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
1249
0
            *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
1250
0
            return 0;
1251
0
        }
1252
        /*
1253
         * We received a ClientHello and sent back a HelloVerifyRequest. We
1254
         * now seem to have received a retransmitted initial ClientHello. That
1255
         * is allowed (possibly our HelloVerifyRequest got lost).
1256
         */
1257
0
        chretran = 1;
1258
0
    }
1259
1260
0
    if (msg_hdr.frag_len > 0 && msg_hdr.frag_len < msg_hdr.msg_len) {
1261
0
        *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
1262
0
        return 0;
1263
0
    }
1264
1265
0
    if (!s->server
1266
0
        && s->statem.hand_state != TLS_ST_OK
1267
0
        && msg_hdr.type == SSL3_MT_HELLO_REQUEST
1268
0
        && dtls_should_skip_hello_request(s)) {
1269
        /*
1270
         * The server may always send 'Hello Request' messages -- we are
1271
         * doing a handshake anyway now, so ignore them if their format is
1272
         * correct. Does not count for 'Finished' MAC.
1273
         */
1274
0
        if (msg_hdr.msg_len == 0) {
1275
0
            if (s->msg_callback)
1276
0
                s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1277
0
                    p, DTLS1_HM_HEADER_LENGTH, ussl,
1278
0
                    s->msg_callback_arg);
1279
1280
0
            s->init_num = 0;
1281
0
            goto redo;
1282
0
        } else {
1283
            /* Incorrectly formatted Hello request */
1284
0
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1285
0
            goto f_err;
1286
0
        }
1287
0
    }
1288
1289
0
    if (!dtls1_preprocess_fragment(s, &msg_hdr)) {
1290
        /* SSLfatal() already called */
1291
0
        goto f_err;
1292
0
    }
1293
1294
0
    if (msg_hdr.frag_len > 0) {
1295
        /* dtls1_preprocess_fragment() above could reallocate init_buf */
1296
0
        p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH + msg_hdr.frag_off;
1297
1298
0
        i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1299
0
            p, msg_hdr.frag_len, 0, &readbytes);
1300
1301
        /*
1302
         * This shouldn't ever fail due to NBIO because we already checked
1303
         * that we have enough data in the record
1304
         */
1305
0
        if (i <= 0) {
1306
0
            s->rwstate = SSL_READING;
1307
0
            *len = 0;
1308
0
            return 0;
1309
0
        }
1310
0
    } else {
1311
0
        readbytes = 0;
1312
0
    }
1313
1314
    /*
1315
     * XDTLS: an incorrectly formatted fragment should cause the handshake
1316
     * to fail
1317
     */
1318
0
    if (readbytes != msg_hdr.frag_len) {
1319
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
1320
0
        goto f_err;
1321
0
    }
1322
1323
0
    if (chretran) {
1324
        /*
1325
         * We got a new ClientHello with a message sequence of 0.
1326
         * Reset the read/write sequences back to the beginning.
1327
         * We process it like this is the first time we've seen a ClientHello
1328
         * from the client.
1329
         */
1330
0
        s->d1->handshake_read_seq = 0;
1331
0
        s->d1->next_handshake_write_seq = 0;
1332
0
    }
1333
1334
0
    if (dtls_msg_needs_ack(!s->server, msg_hdr.type)
1335
0
        && !add_record_to_ack_list(s)) {
1336
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1337
0
        goto f_err;
1338
0
    }
1339
1340
    /*
1341
     * Note that s->init_num is *not* used as current offset in
1342
     * s->init_buf->data, but as a counter summing up fragments' lengths: as
1343
     * soon as they sum up to handshake packet length, we assume we have got
1344
     * all the fragments.
1345
     */
1346
0
    *len = s->init_num = msg_hdr.frag_len;
1347
0
    return 1;
1348
1349
0
f_err:
1350
0
    s->init_num = 0;
1351
0
    *len = 0;
1352
0
    return 0;
1353
0
}
1354
1355
/*-
1356
 * for these 2 messages, we need to
1357
 * ssl->session->read_sym_enc           assign
1358
 * ssl->session->read_compression       assign
1359
 * ssl->session->read_hash              assign
1360
 */
1361
CON_FUNC_RETURN dtls_construct_change_cipher_spec(SSL_CONNECTION *s,
1362
    WPACKET *pkt)
1363
0
{
1364
0
    if (s->version == DTLS1_BAD_VER) {
1365
0
        s->d1->next_handshake_write_seq++;
1366
1367
0
        if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {
1368
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1369
0
            return CON_FUNC_ERROR;
1370
0
        }
1371
0
    }
1372
1373
0
    return CON_FUNC_SUCCESS;
1374
0
}
1375
1376
CON_FUNC_RETURN dtls_construct_ack(SSL_CONNECTION *s, WPACKET *pkt)
1377
0
{
1378
0
    DTLS1_RECORD_NUMBER *recnum;
1379
0
    DTLS1_RECORD_NUMBER *recnumnext = ossl_list_record_number_head(&s->d1->ack_rec_num);
1380
1381
0
    if (!WPACKET_start_sub_packet_u16(pkt)) {
1382
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1383
0
        return CON_FUNC_ERROR;
1384
0
    }
1385
1386
0
    while ((recnum = recnumnext) != NULL) {
1387
        /*
1388
         * rfc9147: section 4.
1389
         *
1390
         * Record numbers are encoded as
1391
         *      struct {
1392
         *           uint64 epoch;
1393
         *           uint64 sequence_number;
1394
         *      } RecordNumber;
1395
         */
1396
1397
0
        recnumnext = ossl_list_record_number_next(recnum);
1398
1399
0
        if (!SSL_IS_FIRST_HANDSHAKE(s)
1400
0
            || recnum->epoch <= dtls1_get_epoch(s, SSL3_CC_WRITE)) {
1401
            /*
1402
             * rfc9147:
1403
             * During the handshake, ACK records MUST be sent with an epoch which
1404
             * is equal to or higher than the record which is being acknowledged.
1405
             * After the handshake, the sending and receiving epochs can differ.
1406
             */
1407
0
            if (!WPACKET_put_bytes_u64(pkt, recnum->epoch)
1408
0
                || !WPACKET_put_bytes_u64(pkt, recnum->seqnum)) {
1409
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1410
0
                return CON_FUNC_ERROR;
1411
0
            }
1412
1413
0
            ossl_list_record_number_remove(&s->d1->ack_rec_num, recnum);
1414
0
            OPENSSL_free(recnum);
1415
0
        }
1416
0
    }
1417
1418
0
    if (!WPACKET_close(pkt)) {
1419
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1420
0
        return CON_FUNC_ERROR;
1421
0
    }
1422
1423
0
    return CON_FUNC_SUCCESS;
1424
0
}
1425
1426
/*
1427
 * If our own KeyUpdate is still awaiting installation of its new write
1428
 * keys, check whether it -- and everything sent before it -- is now
1429
 * acknowledged, and install the deferred write key if so. A peer can ACK a
1430
 * buffered message before it has actually processed the messages that
1431
 * precede it (rfc9147 section 7), so an ACK of the KeyUpdate itself does
1432
 * not establish that the peer has processed everything sent before it and
1433
 * installed the corresponding read keys. Erratum 8047 therefore requires
1434
 * waiting for every preceding message to be acknowledged too, not just the
1435
 * KeyUpdate -- a message sent *after* the KeyUpdate (e.g. a ticket) is
1436
 * unaffected and may remain outstanding.
1437
 *
1438
 * This deliberately does not search sent_messages for the KeyUpdate's own
1439
 * entry: key_update_acked, latched by dtls_process_ack() the instant
1440
 * coverage of that message completes, already captures whether it is
1441
 * acknowledged, and key_update_msg_seq -- the handshake message sequence
1442
 * number captured when it was sent -- identifies which other queued
1443
 * entries precede it, without depending on its own entry still being in
1444
 * the queue to do so. That matters because this is called from more than
1445
 * one place: not just from dtls_process_ack() when an ACK record arrives,
1446
 * but also from dtls1_stop_timer_for_read_flight(), since a preceding
1447
 * CertificateRequest can instead be retired implicitly (rfc9147 7.2) by
1448
 * the next flight, with no ACK record of its own ever involved.
1449
 *
1450
 * Returns 0 only on a fatal error installing the key (SSLfatal() already
1451
 * called); 1 otherwise, including when there was nothing to do.
1452
 */
1453
int dtls1_check_deferred_write_key(SSL_CONNECTION *s)
1454
0
{
1455
0
    pitem *item;
1456
0
    piterator iter;
1457
0
    int preceding_unacked = 0;
1458
1459
0
    if (!s->d1->key_update_write_pending || !s->d1->key_update_acked)
1460
0
        return 1;
1461
1462
0
    iter = pqueue_iterator(&s->d1->sent_messages);
1463
0
    while ((item = pqueue_next(&iter)) != NULL) {
1464
0
        dtls_sent_msg *msg = (dtls_sent_msg *)item->data;
1465
1466
0
        if (msg->msg_info.msg_seq < s->d1->key_update_msg_seq
1467
0
            && !ossl_list_record_number_is_empty(&msg->rec_nums)) {
1468
0
            preceding_unacked = 1;
1469
0
            break;
1470
0
        }
1471
0
    }
1472
1473
0
    if (!preceding_unacked) {
1474
0
        s->d1->key_update_write_pending = 0;
1475
0
        s->d1->key_update_acked = 0;
1476
0
        if (!tls13_update_key(s, 1)) {
1477
            /* SSLfatal() already called */
1478
0
            return 0;
1479
0
        }
1480
0
    }
1481
1482
0
    return 1;
1483
0
}
1484
1485
MSG_PROCESS_RETURN dtls_process_ack(SSL_CONNECTION *s, PACKET *pkt)
1486
0
{
1487
0
    PACKET record_numbers;
1488
1489
0
    if (!PACKET_as_length_prefixed_2(pkt, &record_numbers)) {
1490
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_TOO_LONG);
1491
0
        return MSG_PROCESS_ERROR;
1492
0
    }
1493
1494
0
    while (PACKET_remaining(&record_numbers) > 0) {
1495
        /*
1496
         * rfc9147: section 4.
1497
         *
1498
         * Record numbers are encoded as
1499
         *      struct {
1500
         *           uint64 epoch;
1501
         *           uint64 sequence_number;
1502
         *      } RecordNumber;
1503
         */
1504
0
        pitem *item;
1505
0
        piterator iter;
1506
0
        uint64_t epoch;
1507
0
        uint64_t sequence_number;
1508
1509
0
        if (!PACKET_get_net_8(&record_numbers, &epoch)
1510
0
            || !PACKET_get_net_8(&record_numbers, &sequence_number)) {
1511
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1512
0
            return MSG_PROCESS_ERROR;
1513
0
        }
1514
1515
        /*
1516
         * RFC 9147 section 7: during the initial handshake, an ACK must be
1517
         * carried in an epoch at least as high as the record it acknowledges.
1518
         * Ignore unauthorized entries before changing retransmission state.
1519
         * After the handshake, sending and receiving epochs can differ.
1520
         */
1521
0
        if (SSL_IS_FIRST_HANDSHAKE(s)
1522
0
            && epoch > s->s3.tmp.record_epoch)
1523
0
            continue;
1524
1525
        /*
1526
         * Epoch 2 is the fixed handshake epoch and is never used again once
1527
         * epoch 3 (the first application epoch) is installed. An ACK that
1528
         * only authenticated via a retained epoch-2 layer must not be
1529
         * trusted to cancel retransmission of a post-handshake (epoch 3+)
1530
         * flight. Retained epochs 3+ are unrestricted: unlike epoch 2, which
1531
         * is never reissued, each of those epochs was freshly minted by an
1532
         * SSL_key_update() call and gets superseded by the next one, so a
1533
         * legitimate delayed ACK can authenticate behind a message's own
1534
         * recorded epoch with no protocol violation.
1535
         */
1536
0
        if (dtls_record_from_retained_epoch(s)
1537
0
            && s->s3.tmp.record_epoch == 2
1538
0
            && epoch > 2)
1539
0
            continue;
1540
1541
0
        iter = pqueue_iterator(&s->d1->sent_messages);
1542
1543
0
        while ((item = pqueue_next(&iter)) != NULL) {
1544
0
            dtls_sent_msg *msg = (dtls_sent_msg *)item->data;
1545
0
            DTLS1_RECORD_NUMBER *recnum;
1546
0
            DTLS1_RECORD_NUMBER *recnum_next = ossl_list_record_number_head(&msg->rec_nums);
1547
0
            int matched = 0;
1548
1549
0
            while ((recnum = recnum_next) != NULL) {
1550
0
                recnum_next = ossl_list_record_number_next(recnum_next);
1551
1552
0
                if (recnum->epoch == epoch && recnum->seqnum == sequence_number) {
1553
                    /*
1554
                     * Mark this record's byte range covered *before*
1555
                     * freeing it -- coverage tracks the message as a whole
1556
                     * across every transmission round, not just whether
1557
                     * this one specific record number was ever matched.
1558
                     *
1559
                     * The range check guards against a corrupt recorded
1560
                     * range
1561
                     */
1562
0
                    if (msg->covered != NULL
1563
0
                        && recnum->frag_off <= msg->msg_info.msg_body_len
1564
0
                        && recnum->frag_len
1565
0
                            <= msg->msg_info.msg_body_len - recnum->frag_off)
1566
0
                        RSMBLY_BITMASK_MARK(msg->covered, (long)recnum->frag_off,
1567
0
                            (long)(recnum->frag_off + recnum->frag_len));
1568
0
                    ossl_list_record_number_remove(&msg->rec_nums, recnum);
1569
0
                    OPENSSL_free(recnum);
1570
0
                    matched = 1;
1571
0
                }
1572
0
            }
1573
1574
            /*
1575
             * RFC 9147 section 7.2 is a per-record rule, but completeness is
1576
             * per-message: the peer needs every byte of the message, from
1577
             * any combination of rounds, not just any one matching record.
1578
             * Once this ACK completes coverage of the whole message, fully
1579
             * drain rec_nums -- not just the node that matched -- so every
1580
             * other consumer that keys off list emptiness
1581
             * (dtls_any_sent_messages_are_missing_acknowledge(),
1582
             * dtls1_clear_sent_buffer(), ...) sees it retire, even though
1583
             * other rounds' record numbers may still be sitting unmatched.
1584
             */
1585
0
            if (matched && msg->covered != NULL) {
1586
0
                int is_complete;
1587
1588
0
                RSMBLY_BITMASK_IS_COMPLETE(msg->covered,
1589
0
                    (long)msg->msg_info.msg_body_len, is_complete);
1590
0
                if (is_complete) {
1591
0
                    ossl_list_record_number_elem_free(&msg->rec_nums);
1592
                    /*
1593
                     * Latch this immediately, rather than re-discovering it
1594
                     * later by searching sent_messages for the entry: once
1595
                     * fully acknowledged, this entry is eligible to be freed
1596
                     * by dtls1_clear_sent_buffer() at any later, unrelated
1597
                     * point (e.g. when the peer's own KeyUpdate is
1598
                     * processed), so its continued presence in the queue
1599
                     * cannot be relied on below.
1600
                     */
1601
0
                    if (msg->msg_info.msg_type == SSL3_MT_KEY_UPDATE)
1602
0
                        s->d1->key_update_acked = 1;
1603
0
                }
1604
0
            }
1605
0
        }
1606
0
    }
1607
1608
0
    if (!dtls1_check_deferred_write_key(s))
1609
0
        return MSG_PROCESS_ERROR;
1610
1611
    /* Keep the retransmit timer running until the whole flight is ACKed. */
1612
0
    if (dtls_any_sent_messages_are_missing_acknowledge(s))
1613
0
        return MSG_PROCESS_CONTINUE_READING;
1614
1615
    /*
1616
     * This ACK interrupted a server still reading the client's flight.
1617
     * A complete ACK of our flight does not replace the remaining client
1618
     * messages. It may arrive before Certificate or be reordered after
1619
     * Certificate or CertificateVerify. Finishing the read sub-state-machine
1620
     * here would let write_transition() move to TLS_ST_OK and skip them.
1621
     */
1622
0
    if (s->server
1623
0
        && dtls13_server_waiting_for_client_flight(s->statem.pre_ack_hand_state)) {
1624
        /*
1625
         * We already know above that nothing is left needing
1626
         * retransmission, so this only resets timeout state and clears the
1627
         * (already-empty) sent buffer -- it leaves the read state alone, so
1628
         * the client's flight, including Finished, is still processed on
1629
         * return.
1630
         */
1631
0
        dtls1_stop_timer(s);
1632
0
        return MSG_PROCESS_CONTINUE_READING;
1633
0
    }
1634
1635
0
    return MSG_PROCESS_FINISHED_READING;
1636
0
}
1637
1638
#ifndef OPENSSL_NO_SCTP
1639
/*
1640
 * Wait for a dry event. Should only be called at a point in the handshake
1641
 * where we are not expecting any data from the peer except an alert.
1642
 */
1643
WORK_STATE dtls_wait_for_dry(SSL_CONNECTION *s)
1644
{
1645
    int ret, errtype;
1646
    size_t len;
1647
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1648
1649
    /* read app data until dry event */
1650
    ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(ssl));
1651
    if (ret < 0) {
1652
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1653
        return WORK_ERROR;
1654
    }
1655
1656
    if (ret == 0) {
1657
        /*
1658
         * We're not expecting any more messages from the peer at this point -
1659
         * but we could get an alert. If an alert is waiting then we will never
1660
         * return successfully. Therefore we attempt to read a message. This
1661
         * should never succeed but will process any waiting alerts.
1662
         */
1663
        if (dtls_get_reassembled_message(s, &errtype, &len)) {
1664
            /* The call succeeded! This should never happen */
1665
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1666
            return WORK_ERROR;
1667
        }
1668
1669
        s->s3.in_read_app_data = 2;
1670
        s->rwstate = SSL_READING;
1671
        BIO_clear_retry_flags(SSL_get_rbio(ssl));
1672
        BIO_set_retry_read(SSL_get_rbio(ssl));
1673
        return WORK_MORE_A;
1674
    }
1675
    return WORK_FINISHED_CONTINUE;
1676
}
1677
#endif
1678
1679
int dtls1_read_failed(SSL_CONNECTION *s, int code)
1680
0
{
1681
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1682
1683
0
    if (code > 0) {
1684
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1685
0
        return 0;
1686
0
    }
1687
1688
0
    if (!dtls1_is_timer_expired(s) || ossl_statem_in_error(s)) {
1689
        /*
1690
         * not a timeout, none of our business, let higher layers handle
1691
         * this.  in fact it's probably an error
1692
         */
1693
0
        return code;
1694
0
    }
1695
    /* done, no need to send a retransmit */
1696
0
    if (!SSL_in_init(ssl)) {
1697
0
        BIO *rbio = SSL_get_rbio(ssl);
1698
1699
        /* Connections created by a DTLS listener have no rbio */
1700
0
        if (rbio != NULL)
1701
0
            BIO_set_flags(rbio, BIO_FLAGS_READ);
1702
0
        return code;
1703
0
    }
1704
1705
0
    return dtls1_handle_timeout(s);
1706
0
}
1707
1708
void dtls1_get_queue_priority(unsigned char *prio64be, unsigned short seq,
1709
    int record_type)
1710
0
{
1711
    /*
1712
     * The index of the retransmission queue actually is the message sequence
1713
     * number, since the queue only contains messages of a single handshake.
1714
     * However, the ChangeCipherSpec has no message sequence number and so
1715
     * using only the sequence will result in the CCS and Finished having the
1716
     * same index. To prevent this, the sequence number is multiplied by 2.
1717
     * In case of a CCS 1 is subtracted. This does not only differ CSS and
1718
     * Finished, it also maintains the order of the index (important for
1719
     * priority queues) and fits in the unsigned short variable.
1720
     */
1721
0
    int lsb = (record_type == SSL3_RT_CHANGE_CIPHER_SPEC);
1722
0
    const uint16_t prio = seq * 2 - lsb;
1723
1724
0
    memset(prio64be, 0, 8);
1725
0
    prio64be[6] = (unsigned char)(prio >> 8);
1726
0
    prio64be[7] = (unsigned char)(prio);
1727
0
}
1728
1729
int dtls1_retransmit_sent_messages(SSL_CONNECTION *s)
1730
0
{
1731
0
    piterator iter = pqueue_iterator(&s->d1->sent_messages);
1732
0
    pitem *item;
1733
1734
0
    for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1735
0
        dtls_sent_msg *sent_msg = (dtls_sent_msg *)item->data;
1736
1737
0
        if (SSL_CONNECTION_IS_DTLS13(s)
1738
0
            && ossl_list_record_number_is_empty(&sent_msg->rec_nums))
1739
            /* rfc9147: Implementations must not retransmit acknowledged msgs */
1740
0
            continue;
1741
1742
0
        if (dtls1_retransmit_message(s, sent_msg) <= 0)
1743
0
            return -1;
1744
0
    }
1745
1746
0
    return 1;
1747
0
}
1748
1749
int dtls1_buffer_sent_message(SSL_CONNECTION *s, int record_type)
1750
0
{
1751
0
    pitem *item;
1752
0
    dtls_sent_msg *sent_msg;
1753
0
    unsigned char seq64be[8];
1754
0
    size_t headerlen;
1755
1756
    /*
1757
     * this function is called immediately after a message has been
1758
     * serialized
1759
     */
1760
0
    if (!ossl_assert(s->init_off == 0))
1761
0
        return 0;
1762
1763
0
    sent_msg = dtls1_sent_msg_new(s->init_num, s->d1->w_msg.msg_body_len,
1764
0
        SSL_CONNECTION_IS_DTLS13(s));
1765
0
    if (sent_msg == NULL)
1766
0
        return 0;
1767
1768
0
    memcpy(sent_msg->msg_buf, s->init_buf->data, s->init_num);
1769
1770
0
    if (record_type == SSL3_RT_CHANGE_CIPHER_SPEC)
1771
        /* For DTLS1_BAD_VER the header length is non-standard */
1772
0
        headerlen = (s->version == DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH;
1773
0
    else
1774
0
        headerlen = DTLS1_HM_HEADER_LENGTH;
1775
1776
0
    if (!ossl_assert(s->d1->w_msg.msg_body_len + headerlen == s->init_num)) {
1777
0
        dtls1_sent_msg_free(sent_msg);
1778
0
        return 0;
1779
0
    }
1780
1781
0
    memcpy(&sent_msg->msg_info, &s->d1->w_msg, sizeof(s->d1->w_msg));
1782
1783
    /* save current state */
1784
0
    sent_msg->saved_retransmit_state.wrlmethod = s->rlayer.wrlmethod;
1785
0
    sent_msg->saved_retransmit_state.wrl = s->rlayer.wrl;
1786
1787
0
    dtls1_get_queue_priority(seq64be, sent_msg->msg_info.msg_seq, sent_msg->msg_info.record_type);
1788
1789
0
    item = pitem_new(seq64be, sent_msg);
1790
0
    if (item == NULL) {
1791
0
        dtls1_sent_msg_free(sent_msg);
1792
0
        return 0;
1793
0
    }
1794
1795
0
    if (pqueue_insert(&s->d1->sent_messages, item) == NULL) {
1796
0
        dtls1_sent_msg_free(sent_msg);
1797
0
        pitem_free(item);
1798
0
        return 0;
1799
0
    }
1800
0
    return 1;
1801
0
}
1802
1803
int dtls1_retransmit_message(SSL_CONNECTION *s, dtls_sent_msg *sent_msg)
1804
0
{
1805
0
    int ret;
1806
0
    unsigned long header_length;
1807
0
    struct dtls1_retransmit_state saved_state;
1808
1809
0
    if (sent_msg->msg_info.record_type == SSL3_RT_CHANGE_CIPHER_SPEC)
1810
0
        header_length = DTLS1_CCS_HEADER_LENGTH;
1811
0
    else
1812
0
        header_length = DTLS1_HM_HEADER_LENGTH;
1813
1814
    /*
1815
     * Deliberately not clearing rec_nums here: RFC 9147 section 7.2 requires
1816
     * treating a record as acknowledged if it appears in *any* ACK, so a
1817
     * late ACK matching an earlier round's record number must still be able
1818
     * to match something. rec_nums accumulates across every retransmission
1819
     * round instead; dtls_process_ack() retires entries by tracking byte
1820
     * range coverage, not by this list ever being reset per round.
1821
     */
1822
1823
0
    memcpy(s->init_buf->data, sent_msg->msg_buf,
1824
0
        sent_msg->msg_info.msg_body_len + header_length);
1825
0
    s->init_num = sent_msg->msg_info.msg_body_len + header_length;
1826
    /* Always retransmit from the start, not wherever init_off was left */
1827
0
    s->init_off = 0;
1828
1829
0
    memcpy(&s->d1->w_msg, &sent_msg->msg_info, sizeof(sent_msg->msg_info));
1830
1831
    /* save current state */
1832
0
    saved_state.wrlmethod = s->rlayer.wrlmethod;
1833
0
    saved_state.wrl = s->rlayer.wrl;
1834
1835
0
    s->d1->retransmitting = 1;
1836
1837
    /* restore state in which the message was originally sent */
1838
0
    s->rlayer.wrlmethod = sent_msg->saved_retransmit_state.wrlmethod;
1839
0
    s->rlayer.wrl = sent_msg->saved_retransmit_state.wrl;
1840
1841
    /*
1842
     * The old wrl may be still pointing at an old BIO. Update it to what we're
1843
     * using now.
1844
     */
1845
0
    s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
1846
1847
0
    ret = dtls1_do_write(s, sent_msg->msg_info.record_type);
1848
1849
    /*
1850
     * If the message was retransmitted through a write record layer that is
1851
     * no longer the current one, the retransmission used up record sequence
1852
     * numbers that the current layer does not know about. This only matters
1853
     * for a ClientHello: it is retransmitted through the epoch 0 layer after
1854
     * the client has switched to the early data layer, and a ClientHello sent
1855
     * after a HelloRetryRequest must not reuse any of those sequence numbers.
1856
     * Keep the saved epoch 0 sequence number up to date for that case.
1857
     */
1858
0
    if (s->rlayer.wrl != saved_state.wrl) {
1859
0
        uint64_t epoch, seq;
1860
1861
0
        if (s->rlayer.wrlmethod->get_epoch(s->rlayer.wrl, &epoch) == 1
1862
0
            && epoch == 0
1863
0
            && s->rlayer.wrlmethod->get_sequence(s->rlayer.wrl, &seq) == 1)
1864
0
            s->rlayer.wlayer_epoch_zero_sequence = seq;
1865
0
    }
1866
1867
    /* restore current state */
1868
0
    s->rlayer.wrlmethod = saved_state.wrlmethod;
1869
0
    s->rlayer.wrl = saved_state.wrl;
1870
1871
0
    s->d1->retransmitting = 0;
1872
1873
0
    (void)BIO_flush(s->wbio);
1874
0
    return ret;
1875
0
}
1876
1877
int dtls1_set_handshake_header(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1878
0
{
1879
0
    s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1880
0
    s->d1->w_msg.msg_seq = s->d1->handshake_write_seq;
1881
0
    s->d1->w_msg.msg_body_len = 0;
1882
1883
0
    if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {
1884
0
        s->d1->w_msg.record_type = SSL3_RT_CHANGE_CIPHER_SPEC;
1885
0
        s->d1->w_msg.msg_type = SSL3_MT_CCS;
1886
1887
0
        if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))
1888
0
            return 0;
1889
0
    } else if (htype == DTLS13_MT_ACK) {
1890
0
        s->d1->w_msg.record_type = SSL3_RT_ACK;
1891
0
        s->d1->w_msg.msg_type = 0;
1892
0
    } else {
1893
0
        size_t subpacket_offset = DTLS1_HM_HEADER_LENGTH - SSL3_HM_HEADER_LENGTH;
1894
1895
0
        s->d1->next_handshake_write_seq++;
1896
0
        s->d1->w_msg.record_type = SSL3_RT_HANDSHAKE;
1897
0
        s->d1->w_msg.msg_type = htype;
1898
1899
        /* Set the content type and 3 bytes for the message len */
1900
0
        if (!WPACKET_put_bytes_u8(pkt, htype)
1901
            /*
1902
             * We allocate space for DTLS specific fields.
1903
             * These gets filled later.
1904
             */
1905
0
            || !WPACKET_start_sub_packet_u24_at_offset(pkt, subpacket_offset))
1906
0
            return 0;
1907
0
    }
1908
1909
0
    return 1;
1910
0
}
1911
1912
int dtls1_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1913
0
{
1914
0
    size_t msglen;
1915
1916
0
    if ((s->d1->w_msg.record_type == SSL3_RT_HANDSHAKE && !WPACKET_close(pkt))
1917
0
        || !WPACKET_get_length(pkt, &msglen)
1918
0
        || msglen > INT_MAX)
1919
0
        return 0;
1920
1921
0
    if (s->d1->w_msg.record_type == SSL3_RT_HANDSHAKE)
1922
0
        s->d1->w_msg.msg_body_len = msglen - DTLS1_HM_HEADER_LENGTH;
1923
1924
0
    s->init_num = msglen;
1925
0
    s->init_off = 0;
1926
1927
0
    if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST
1928
0
        && s->d1->w_msg.record_type != SSL3_RT_ACK) {
1929
        /* Buffer the message to handle re-xmits */
1930
0
        if (!dtls1_buffer_sent_message(s, s->d1->w_msg.record_type))
1931
0
            return 0;
1932
0
    }
1933
1934
0
    return 1;
1935
0
}