Coverage Report

Created: 2026-02-14 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/ssl/quic/quic_channel.c
Line
Count
Source
1
/*
2
 * Copyright 2022-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 <openssl/rand.h>
11
#include <openssl/err.h>
12
#include "internal/ssl_unwrap.h"
13
#include "internal/quic_channel.h"
14
#include "internal/quic_error.h"
15
#include "internal/quic_rx_depack.h"
16
#include "internal/quic_lcidm.h"
17
#include "internal/quic_srtm.h"
18
#include "internal/qlog_event_helpers.h"
19
#include "internal/quic_txp.h"
20
#include "internal/quic_tls.h"
21
#include "internal/quic_ssl.h"
22
#include "../ssl_local.h"
23
#include "quic_channel_local.h"
24
#include "quic_port_local.h"
25
#include "quic_engine_local.h"
26
27
89.4k
#define INIT_CRYPTO_RECV_BUF_LEN 16384
28
89.4k
#define INIT_CRYPTO_SEND_BUF_LEN 16384
29
43.7k
#define INIT_APP_BUF_LEN 8192
30
31
/*
32
 * Interval before we force a PING to ensure NATs don't timeout. This is based
33
 * on the lowest commonly seen value of 30 seconds as cited in RFC 9000 s.
34
 * 10.1.2.
35
 */
36
24.4M
#define MAX_NAT_INTERVAL (ossl_ms2time(25000))
37
38
/*
39
 * Our maximum ACK delay on the TX side. This is up to us to choose. Note that
40
 * this could differ from QUIC_DEFAULT_MAX_DELAY in future as that is a protocol
41
 * value which determines the value of the maximum ACK delay if the
42
 * max_ack_delay transport parameter is not set.
43
 */
44
29.8k
#define DEFAULT_MAX_ACK_DELAY QUIC_DEFAULT_MAX_ACK_DELAY
45
46
102k
DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL);
quic_channel.c:ossl_list_ch_insert_tail
Line
Count
Source
46
DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL);
quic_channel.c:ossl_list_ch_remove
Line
Count
Source
46
DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL);
47
48
static void ch_save_err_state(QUIC_CHANNEL *ch);
49
static int ch_rx(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads);
50
static int ch_tx(QUIC_CHANNEL *ch, int *notify_other_threads);
51
static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads);
52
static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only);
53
static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch);
54
static int ch_retry(QUIC_CHANNEL *ch,
55
    const unsigned char *retry_token,
56
    size_t retry_token_len,
57
    const QUIC_CONN_ID *retry_scid,
58
    int drop_later_pn);
59
static int ch_restart(QUIC_CHANNEL *ch);
60
61
static void ch_cleanup(QUIC_CHANNEL *ch);
62
static int ch_generate_transport_params(QUIC_CHANNEL *ch);
63
static int ch_on_transport_params(const unsigned char *params,
64
    size_t params_len,
65
    void *arg);
66
static int ch_on_handshake_alert(void *arg, unsigned char alert_code);
67
static int ch_on_handshake_complete(void *arg);
68
static int ch_on_handshake_yield_secret(uint32_t prot_level, int direction,
69
    uint32_t suite_id, EVP_MD *md,
70
    const unsigned char *secret,
71
    size_t secret_len,
72
    void *arg);
73
static int ch_on_crypto_recv_record(const unsigned char **buf,
74
    size_t *bytes_read, void *arg);
75
static int ch_on_crypto_release_record(size_t bytes_read, void *arg);
76
static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
77
static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
78
    size_t *consumed, void *arg);
79
static OSSL_TIME get_time(void *arg);
80
static uint64_t get_stream_limit(int uni, void *arg);
81
static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg);
82
static void rxku_detected(QUIC_PN pn, void *arg);
83
static int ch_retry(QUIC_CHANNEL *ch,
84
    const unsigned char *retry_token,
85
    size_t retry_token_len,
86
    const QUIC_CONN_ID *retry_scid,
87
    int drop_later_pn);
88
static void ch_update_idle(QUIC_CHANNEL *ch);
89
static int ch_discard_el(QUIC_CHANNEL *ch,
90
    uint32_t enc_level);
91
static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
92
static void ch_update_idle(QUIC_CHANNEL *ch);
93
static void ch_update_ping_deadline(QUIC_CHANNEL *ch);
94
static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
95
static void ch_start_terminating(QUIC_CHANNEL *ch,
96
    const QUIC_TERMINATE_CAUSE *tcause,
97
    int force_immediate);
98
static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
99
    void *arg);
100
static void ch_record_state_transition(QUIC_CHANNEL *ch, uint32_t new_state);
101
102
DEFINE_LHASH_OF_EX(QUIC_SRT_ELEM);
103
104
QUIC_NEEDS_LOCK
105
static QLOG *ch_get_qlog(QUIC_CHANNEL *ch)
106
4.03M
{
107
4.03M
#ifndef OPENSSL_NO_QLOG
108
4.03M
    QLOG_TRACE_INFO qti = { 0 };
109
110
4.03M
    if (ch->qlog != NULL)
111
0
        return ch->qlog;
112
113
4.03M
    if (!ch->use_qlog)
114
3.98M
        return NULL;
115
116
51.3k
    if (ch->is_server && ch->init_dcid.id_len == 0)
117
0
        return NULL;
118
119
51.3k
    qti.odcid = ch->init_dcid;
120
51.3k
    qti.title = ch->qlog_title;
121
51.3k
    qti.description = NULL;
122
51.3k
    qti.group_id = NULL;
123
51.3k
    qti.is_server = ch->is_server;
124
51.3k
    qti.now_cb = get_time;
125
51.3k
    qti.now_cb_arg = ch;
126
51.3k
    if ((ch->qlog = ossl_qlog_new_from_env(&qti)) == NULL) {
127
51.3k
        ch->use_qlog = 0; /* don't try again */
128
51.3k
        return NULL;
129
51.3k
    }
130
131
0
    return ch->qlog;
132
#else
133
    return NULL;
134
#endif
135
51.3k
}
136
137
QUIC_NEEDS_LOCK
138
static QLOG *ch_get_qlog_cb(void *arg)
139
2.18M
{
140
2.18M
    QUIC_CHANNEL *ch = arg;
141
142
2.18M
    return ch_get_qlog(ch);
143
2.18M
}
144
145
/*
146
 * QUIC Channel Initialization and Teardown
147
 * ========================================
148
 */
149
59.6k
#define DEFAULT_INIT_CONN_RXFC_WND (768 * 1024)
150
29.8k
#define DEFAULT_CONN_RXFC_MAX_WND_MUL 20
151
152
89.4k
#define DEFAULT_INIT_STREAM_RXFC_WND (512 * 1024)
153
149k
#define DEFAULT_STREAM_RXFC_MAX_WND_MUL 12
154
155
59.6k
#define DEFAULT_INIT_CONN_MAX_STREAMS 100
156
157
static int ch_init(QUIC_CHANNEL *ch)
158
29.8k
{
159
29.8k
    OSSL_QUIC_TX_PACKETISER_ARGS txp_args = { 0 };
160
29.8k
    OSSL_QTX_ARGS qtx_args = { 0 };
161
29.8k
    OSSL_QRX_ARGS qrx_args = { 0 };
162
29.8k
    QUIC_TLS_ARGS tls_args = { 0 };
163
29.8k
    uint32_t pn_space;
164
29.8k
    size_t rx_short_dcid_len;
165
29.8k
    size_t tx_init_dcid_len;
166
167
29.8k
    if (ch->port == NULL || ch->lcidm == NULL || ch->srtm == NULL)
168
0
        goto err;
169
170
29.8k
    rx_short_dcid_len = ossl_quic_port_get_rx_short_dcid_len(ch->port);
171
29.8k
    tx_init_dcid_len = ossl_quic_port_get_tx_init_dcid_len(ch->port);
172
173
    /* For clients, generate our initial DCID. */
174
29.8k
    if (!ch->is_server
175
29.8k
        && !ossl_quic_gen_rand_conn_id(ch->port->engine->libctx, tx_init_dcid_len,
176
29.8k
            &ch->init_dcid))
177
0
        goto err;
178
179
    /* We plug in a network write BIO to the QTX later when we get one. */
180
29.8k
    qtx_args.libctx = ch->port->engine->libctx;
181
29.8k
    qtx_args.get_qlog_cb = ch_get_qlog_cb;
182
29.8k
    qtx_args.get_qlog_cb_arg = ch;
183
29.8k
    qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN;
184
29.8k
    ch->rx_max_udp_payload_size = qtx_args.mdpl;
185
186
29.8k
    ch->ping_deadline = ossl_time_infinite();
187
188
29.8k
    ch->qtx = ossl_qtx_new(&qtx_args);
189
29.8k
    if (ch->qtx == NULL)
190
0
        goto err;
191
192
29.8k
    ch->txpim = ossl_quic_txpim_new();
193
29.8k
    if (ch->txpim == NULL)
194
0
        goto err;
195
196
29.8k
    ch->cfq = ossl_quic_cfq_new();
197
29.8k
    if (ch->cfq == NULL)
198
0
        goto err;
199
200
29.8k
    if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
201
0
        goto err;
202
203
    /*
204
     * Note: The TP we transmit governs what the peer can transmit and thus
205
     * applies to the RXFC.
206
     */
207
29.8k
    ch->tx_init_max_stream_data_bidi_local = DEFAULT_INIT_STREAM_RXFC_WND;
208
29.8k
    ch->tx_init_max_stream_data_bidi_remote = DEFAULT_INIT_STREAM_RXFC_WND;
209
29.8k
    ch->tx_init_max_stream_data_uni = DEFAULT_INIT_STREAM_RXFC_WND;
210
211
29.8k
    if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
212
29.8k
            DEFAULT_INIT_CONN_RXFC_WND,
213
29.8k
            DEFAULT_CONN_RXFC_MAX_WND_MUL * DEFAULT_INIT_CONN_RXFC_WND,
214
29.8k
            get_time, ch))
215
0
        goto err;
216
217
119k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
218
89.4k
        if (!ossl_quic_rxfc_init_standalone(&ch->crypto_rxfc[pn_space],
219
89.4k
                INIT_CRYPTO_RECV_BUF_LEN,
220
89.4k
                get_time, ch))
221
0
            goto err;
222
223
29.8k
    if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_bidi_rxfc,
224
29.8k
            DEFAULT_INIT_CONN_MAX_STREAMS,
225
29.8k
            get_time, ch))
226
0
        goto err;
227
228
29.8k
    if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_uni_rxfc,
229
29.8k
            DEFAULT_INIT_CONN_MAX_STREAMS,
230
29.8k
            get_time, ch))
231
0
        goto err;
232
233
29.8k
    if (!ossl_statm_init(&ch->statm))
234
0
        goto err;
235
236
29.8k
    ch->have_statm = 1;
237
29.8k
    ch->cc_method = &ossl_cc_newreno_method;
238
29.8k
    if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL)
239
0
        goto err;
240
241
29.8k
    if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm,
242
29.8k
             ch->cc_method, ch->cc_data,
243
29.8k
             ch->is_server))
244
29.8k
        == NULL)
245
0
        goto err;
246
247
29.8k
    if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch,
248
29.8k
            &ch->max_streams_bidi_rxfc,
249
29.8k
            &ch->max_streams_uni_rxfc,
250
29.8k
            ch))
251
0
        goto err;
252
253
29.8k
    ch->have_qsm = 1;
254
255
29.8k
    if (!ch->is_server
256
29.8k
        && !ossl_quic_lcidm_generate_initial(ch->lcidm, ch, &ch->init_scid))
257
0
        goto err;
258
259
29.8k
    txp_args.cur_scid = ch->init_scid;
260
29.8k
    txp_args.cur_dcid = ch->init_dcid;
261
29.8k
    txp_args.ack_delay_exponent = 3;
262
29.8k
    txp_args.qtx = ch->qtx;
263
29.8k
    txp_args.txpim = ch->txpim;
264
29.8k
    txp_args.cfq = ch->cfq;
265
29.8k
    txp_args.ackm = ch->ackm;
266
29.8k
    txp_args.qsm = &ch->qsm;
267
29.8k
    txp_args.conn_txfc = &ch->conn_txfc;
268
29.8k
    txp_args.conn_rxfc = &ch->conn_rxfc;
269
29.8k
    txp_args.max_streams_bidi_rxfc = &ch->max_streams_bidi_rxfc;
270
29.8k
    txp_args.max_streams_uni_rxfc = &ch->max_streams_uni_rxfc;
271
29.8k
    txp_args.cc_method = ch->cc_method;
272
29.8k
    txp_args.cc_data = ch->cc_data;
273
29.8k
    txp_args.now = get_time;
274
29.8k
    txp_args.now_arg = ch;
275
29.8k
    txp_args.get_qlog_cb = ch_get_qlog_cb;
276
29.8k
    txp_args.get_qlog_cb_arg = ch;
277
29.8k
    txp_args.protocol_version = QUIC_VERSION_1;
278
279
119k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
280
89.4k
        ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_SEND_BUF_LEN);
281
89.4k
        if (ch->crypto_send[pn_space] == NULL)
282
0
            goto err;
283
284
89.4k
        txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
285
89.4k
    }
286
287
29.8k
    ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
288
29.8k
    if (ch->txp == NULL)
289
0
        goto err;
290
291
    /* clients have no amplification limit, so are considered always valid */
292
29.8k
    if (!ch->is_server)
293
29.8k
        ossl_quic_tx_packetiser_set_validated(ch->txp);
294
295
29.8k
    ossl_quic_tx_packetiser_set_ack_tx_cb(ch->txp, ch_on_txp_ack_tx, ch);
296
297
    /*
298
     * qrx does not exist yet, then we must be dealing with client channel
299
     * (QUIC connection initiator).
300
     * If qrx exists already, then we are dealing with server channel which
301
     * qrx gets created by port_default_packet_handler() before
302
     * port_default_packet_handler() accepts connection and creates channel
303
     * for it.
304
     * The exception here is tserver which always creates channel,
305
     * before the first packet is ever seen.
306
     */
307
29.8k
    if (ch->qrx == NULL && ch->is_tserver_ch == 0) {
308
        /* we are regular client, create channel */
309
29.8k
        qrx_args.libctx = ch->port->engine->libctx;
310
29.8k
        qrx_args.demux = ch->port->demux;
311
29.8k
        qrx_args.short_conn_id_len = rx_short_dcid_len;
312
29.8k
        qrx_args.max_deferred = 32;
313
314
29.8k
        if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
315
0
            goto err;
316
29.8k
    }
317
318
29.8k
    if (ch->qrx != NULL) {
319
        /*
320
         * callbacks for channels associated with tserver's port
321
         * are set up later when we call ossl_quic_channel_bind_qrx()
322
         * in port_default_packet_handler()
323
         */
324
29.8k
        if (!ossl_qrx_set_late_validation_cb(ch->qrx,
325
29.8k
                rx_late_validate,
326
29.8k
                ch))
327
0
            goto err;
328
329
29.8k
        if (!ossl_qrx_set_key_update_cb(ch->qrx,
330
29.8k
                rxku_detected,
331
29.8k
                ch))
332
0
            goto err;
333
29.8k
    }
334
335
119k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
336
89.4k
        ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL, 0);
337
89.4k
        if (ch->crypto_recv[pn_space] == NULL)
338
0
            goto err;
339
89.4k
    }
340
341
    /* Plug in the TLS handshake layer. */
342
29.8k
    tls_args.s = ch->tls;
343
29.8k
    tls_args.crypto_send_cb = ch_on_crypto_send;
344
29.8k
    tls_args.crypto_send_cb_arg = ch;
345
29.8k
    tls_args.crypto_recv_rcd_cb = ch_on_crypto_recv_record;
346
29.8k
    tls_args.crypto_recv_rcd_cb_arg = ch;
347
29.8k
    tls_args.crypto_release_rcd_cb = ch_on_crypto_release_record;
348
29.8k
    tls_args.crypto_release_rcd_cb_arg = ch;
349
29.8k
    tls_args.yield_secret_cb = ch_on_handshake_yield_secret;
350
29.8k
    tls_args.yield_secret_cb_arg = ch;
351
29.8k
    tls_args.got_transport_params_cb = ch_on_transport_params;
352
29.8k
    tls_args.got_transport_params_cb_arg = ch;
353
29.8k
    tls_args.handshake_complete_cb = ch_on_handshake_complete;
354
29.8k
    tls_args.handshake_complete_cb_arg = ch;
355
29.8k
    tls_args.alert_cb = ch_on_handshake_alert;
356
29.8k
    tls_args.alert_cb_arg = ch;
357
29.8k
    tls_args.is_server = ch->is_server;
358
29.8k
    tls_args.ossl_quic = 1;
359
360
29.8k
    if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
361
0
        goto err;
362
363
29.8k
    ch->tx_max_ack_delay = DEFAULT_MAX_ACK_DELAY;
364
29.8k
    ch->rx_max_ack_delay = QUIC_DEFAULT_MAX_ACK_DELAY;
365
29.8k
    ch->rx_ack_delay_exp = QUIC_DEFAULT_ACK_DELAY_EXP;
366
29.8k
    ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
367
29.8k
    ch->tx_enc_level = QUIC_ENC_LEVEL_INITIAL;
368
29.8k
    ch->rx_enc_level = QUIC_ENC_LEVEL_INITIAL;
369
29.8k
    ch->txku_threshold_override = UINT64_MAX;
370
371
29.8k
    ch->max_idle_timeout_local_req = QUIC_DEFAULT_IDLE_TIMEOUT;
372
29.8k
    ch->max_idle_timeout_remote_req = 0;
373
29.8k
    ch->max_idle_timeout = ch->max_idle_timeout_local_req;
374
375
29.8k
    ossl_ackm_set_tx_max_ack_delay(ch->ackm, ossl_ms2time(ch->tx_max_ack_delay));
376
29.8k
    ossl_ackm_set_rx_max_ack_delay(ch->ackm, ossl_ms2time(ch->rx_max_ack_delay));
377
378
29.8k
    ch_update_idle(ch);
379
29.8k
    ossl_list_ch_insert_tail(&ch->port->channel_list, ch);
380
29.8k
    ch->on_port_list = 1;
381
29.8k
    return 1;
382
383
0
err:
384
0
    ch_cleanup(ch);
385
0
    return 0;
386
29.8k
}
387
388
static void ch_cleanup(QUIC_CHANNEL *ch)
389
20.0k
{
390
20.0k
    uint32_t pn_space;
391
392
20.0k
    if (ch->ackm != NULL)
393
20.0k
        for (pn_space = QUIC_PN_SPACE_INITIAL;
394
80.3k
            pn_space < QUIC_PN_SPACE_NUM;
395
60.2k
            ++pn_space)
396
60.2k
            ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
397
398
20.0k
    if (ch->lcidm != NULL)
399
20.0k
        ossl_quic_lcidm_cull(ch->lcidm, ch);
400
401
20.0k
    if (ch->srtm != NULL)
402
20.0k
        ossl_quic_srtm_cull(ch->srtm, ch);
403
404
20.0k
    ossl_quic_tx_packetiser_free(ch->txp);
405
20.0k
    ossl_quic_txpim_free(ch->txpim);
406
20.0k
    ossl_quic_cfq_free(ch->cfq);
407
20.0k
    ossl_qtx_free(ch->qtx);
408
20.0k
    if (ch->cc_data != NULL)
409
20.0k
        ch->cc_method->free(ch->cc_data);
410
20.0k
    if (ch->have_statm)
411
20.0k
        ossl_statm_destroy(&ch->statm);
412
20.0k
    ossl_ackm_free(ch->ackm);
413
414
20.0k
    if (ch->have_qsm)
415
20.0k
        ossl_quic_stream_map_cleanup(&ch->qsm);
416
417
80.3k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
418
60.2k
        ossl_quic_sstream_free(ch->crypto_send[pn_space]);
419
60.2k
        ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
420
60.2k
    }
421
422
20.0k
    ossl_qrx_pkt_release(ch->qrx_pkt);
423
20.0k
    ch->qrx_pkt = NULL;
424
425
20.0k
    ossl_quic_tls_free(ch->qtls);
426
20.0k
    ossl_qrx_free(ch->qrx);
427
20.0k
    OPENSSL_free(ch->local_transport_params);
428
20.0k
    OPENSSL_free((char *)ch->terminate_cause.reason);
429
20.0k
    OSSL_ERR_STATE_free(ch->err_state);
430
20.0k
    OPENSSL_free(ch->ack_range_scratch);
431
20.0k
    OPENSSL_free(ch->pending_new_token);
432
433
20.0k
    if (ch->on_port_list) {
434
20.0k
        ossl_list_ch_remove(&ch->port->channel_list, ch);
435
20.0k
        ch->on_port_list = 0;
436
20.0k
    }
437
438
20.0k
#ifndef OPENSSL_NO_QLOG
439
20.0k
    if (ch->qlog != NULL)
440
0
        ossl_qlog_flush(ch->qlog); /* best effort */
441
442
20.0k
    OPENSSL_free(ch->qlog_title);
443
20.0k
    ossl_qlog_free(ch->qlog);
444
20.0k
#endif
445
20.0k
}
446
447
int ossl_quic_channel_init(QUIC_CHANNEL *ch)
448
29.8k
{
449
29.8k
    return ch_init(ch);
450
29.8k
}
451
452
void ossl_quic_channel_bind_qrx(QUIC_CHANNEL *tserver_ch, OSSL_QRX *qrx)
453
0
{
454
0
    if (tserver_ch->qrx == NULL && tserver_ch->is_tserver_ch == 1) {
455
0
        tserver_ch->qrx = qrx;
456
0
        ossl_qrx_set_late_validation_cb(tserver_ch->qrx, rx_late_validate,
457
0
            tserver_ch);
458
0
        ossl_qrx_set_key_update_cb(tserver_ch->qrx, rxku_detected,
459
0
            tserver_ch);
460
0
    }
461
0
}
462
463
QUIC_CHANNEL *ossl_quic_channel_alloc(const QUIC_CHANNEL_ARGS *args)
464
29.8k
{
465
29.8k
    QUIC_CHANNEL *ch = NULL;
466
467
29.8k
    if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
468
0
        return NULL;
469
470
29.8k
    ch->port = args->port;
471
29.8k
    ch->is_server = args->is_server;
472
29.8k
    ch->tls = args->tls;
473
29.8k
    ch->lcidm = args->lcidm;
474
29.8k
    ch->srtm = args->srtm;
475
29.8k
    ch->qrx = args->qrx;
476
29.8k
    ch->is_tserver_ch = args->is_tserver_ch;
477
29.8k
#ifndef OPENSSL_NO_QLOG
478
29.8k
    ch->use_qlog = args->use_qlog;
479
480
29.8k
    if (ch->use_qlog && args->qlog_title != NULL) {
481
0
        if ((ch->qlog_title = OPENSSL_strdup(args->qlog_title)) == NULL) {
482
0
            OPENSSL_free(ch);
483
0
            return NULL;
484
0
        }
485
0
    }
486
29.8k
#endif
487
488
29.8k
    return ch;
489
29.8k
}
490
491
void ossl_quic_channel_free(QUIC_CHANNEL *ch)
492
51.3k
{
493
51.3k
    if (ch == NULL)
494
0
        return;
495
496
51.3k
    ch_cleanup(ch);
497
51.3k
    OPENSSL_free(ch);
498
51.3k
}
499
500
/* Set mutator callbacks for test framework support */
501
int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch,
502
    ossl_mutate_packet_cb mutatecb,
503
    ossl_finish_mutate_cb finishmutatecb,
504
    void *mutatearg)
505
0
{
506
0
    if (ch->qtx == NULL)
507
0
        return 0;
508
509
0
    ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
510
0
    return 1;
511
0
}
512
513
int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
514
0
{
515
0
    if (!ch->addressed_mode)
516
0
        return 0;
517
518
0
    return BIO_ADDR_copy(peer_addr, &ch->cur_peer_addr);
519
0
}
520
521
int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
522
51.3k
{
523
51.3k
    if (ch->state != QUIC_CHANNEL_STATE_IDLE)
524
0
        return 0;
525
526
51.3k
    if (peer_addr == NULL || BIO_ADDR_family(peer_addr) == AF_UNSPEC) {
527
0
        BIO_ADDR_clear(&ch->cur_peer_addr);
528
0
        ch->addressed_mode = 0;
529
0
        return 1;
530
0
    }
531
532
51.3k
    if (!BIO_ADDR_copy(&ch->cur_peer_addr, peer_addr)) {
533
0
        ch->addressed_mode = 0;
534
0
        return 0;
535
0
    }
536
51.3k
    ch->addressed_mode = 1;
537
538
51.3k
    return 1;
539
51.3k
}
540
541
QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
542
79.0M
{
543
79.0M
    return ossl_quic_port_get0_reactor(ch->port);
544
79.0M
}
545
546
QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
547
16.7M
{
548
16.7M
    return &ch->qsm;
549
16.7M
}
550
551
OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
552
84.7k
{
553
84.7k
    return &ch->statm;
554
84.7k
}
555
556
SSL *ossl_quic_channel_get0_tls(QUIC_CHANNEL *ch)
557
0
{
558
0
    return ch->tls;
559
0
}
560
561
static void free_buf_mem(unsigned char *buf, size_t buf_len, void *arg)
562
0
{
563
0
    BUF_MEM_free((BUF_MEM *)arg);
564
0
}
565
566
int ossl_quic_channel_schedule_new_token(QUIC_CHANNEL *ch,
567
    const unsigned char *token,
568
    size_t token_len)
569
0
{
570
0
    int rc = 0;
571
0
    QUIC_CFQ_ITEM *cfq_item;
572
0
    WPACKET wpkt;
573
0
    BUF_MEM *buf_mem = NULL;
574
0
    size_t l = 0;
575
576
0
    buf_mem = BUF_MEM_new();
577
0
    if (buf_mem == NULL)
578
0
        goto err;
579
580
0
    if (!WPACKET_init(&wpkt, buf_mem))
581
0
        goto err;
582
583
0
    if (!ossl_quic_wire_encode_frame_new_token(&wpkt, token,
584
0
            token_len)) {
585
0
        WPACKET_cleanup(&wpkt);
586
0
        goto err;
587
0
    }
588
589
0
    WPACKET_finish(&wpkt);
590
591
0
    if (!WPACKET_get_total_written(&wpkt, &l))
592
0
        goto err;
593
594
0
    cfq_item = ossl_quic_cfq_add_frame(ch->cfq, 1,
595
0
        QUIC_PN_SPACE_APP,
596
0
        OSSL_QUIC_FRAME_TYPE_NEW_TOKEN, 0,
597
0
        (unsigned char *)buf_mem->data, l,
598
0
        free_buf_mem,
599
0
        buf_mem);
600
0
    if (cfq_item == NULL)
601
0
        goto err;
602
603
0
    rc = 1;
604
0
err:
605
0
    if (!rc)
606
0
        BUF_MEM_free(buf_mem);
607
0
    return rc;
608
0
}
609
610
size_t ossl_quic_channel_get_short_header_conn_id_len(QUIC_CHANNEL *ch)
611
0
{
612
0
    return ossl_quic_port_get_rx_short_dcid_len(ch->port);
613
0
}
614
615
QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
616
    uint64_t stream_id)
617
0
{
618
0
    return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
619
0
}
620
621
int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
622
3.92M
{
623
3.92M
    return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
624
3.92M
}
625
626
int ossl_quic_channel_is_closing(const QUIC_CHANNEL *ch)
627
347M
{
628
347M
    return ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
629
347M
}
630
631
static int ossl_quic_channel_is_draining(const QUIC_CHANNEL *ch)
632
285M
{
633
285M
    return ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
634
285M
}
635
636
static int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
637
224M
{
638
224M
    return ossl_quic_channel_is_closing(ch)
639
224M
        || ossl_quic_channel_is_draining(ch);
640
224M
}
641
642
int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
643
346M
{
644
346M
    return ch->state == QUIC_CHANNEL_STATE_TERMINATED;
645
346M
}
646
647
int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
648
101M
{
649
101M
    return ossl_quic_channel_is_terminating(ch)
650
101M
        || ossl_quic_channel_is_terminated(ch);
651
101M
}
652
653
int ossl_quic_channel_is_server(const QUIC_CHANNEL *ch)
654
569k
{
655
569k
    return ch->is_server;
656
569k
}
657
658
void ossl_quic_channel_notify_flush_done(QUIC_CHANNEL *ch)
659
9.88k
{
660
9.88k
    ch_record_state_transition(ch, ch->terminate_cause.remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING : QUIC_CHANNEL_STATE_TERMINATING_CLOSING);
661
    /*
662
     * RFC 9000 s. 10.2 Immediate Close
663
     *  These states SHOULD persist for at least three times
664
     *  the current PTO interval as defined in [QUIC-RECOVERY].
665
     */
666
9.88k
    ch->terminate_deadline
667
9.88k
        = ossl_time_add(get_time(ch),
668
9.88k
            ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm), 3));
669
9.88k
    if (!ch->terminate_cause.remote) {
670
9.58k
        OSSL_QUIC_FRAME_CONN_CLOSE f = { 0 };
671
672
        /* best effort */
673
9.58k
        f.error_code = ch->terminate_cause.error_code;
674
9.58k
        f.frame_type = ch->terminate_cause.frame_type;
675
9.58k
        f.is_app = ch->terminate_cause.app;
676
9.58k
        f.reason = (char *)ch->terminate_cause.reason;
677
9.58k
        f.reason_len = ch->terminate_cause.reason_len;
678
9.58k
        ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
679
        /*
680
         * RFC 9000 s. 10.2.2 Draining Connection State:
681
         *  An endpoint that receives a CONNECTION_CLOSE frame MAY
682
         *  send a single packet containing a CONNECTION_CLOSE
683
         *  frame before entering the draining state, using a
684
         *  NO_ERROR code if appropriate
685
         */
686
9.58k
        ch->conn_close_queued = 1;
687
9.58k
    }
688
9.88k
}
689
690
const QUIC_TERMINATE_CAUSE *
691
ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
692
0
{
693
0
    return ossl_quic_channel_is_term_any(ch) ? &ch->terminate_cause : NULL;
694
0
}
695
696
int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
697
141M
{
698
141M
    return ch->handshake_complete;
699
141M
}
700
701
int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
702
0
{
703
0
    return ch->handshake_confirmed;
704
0
}
705
706
QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch)
707
0
{
708
0
    return ch->port->demux;
709
0
}
710
711
QUIC_PORT *ossl_quic_channel_get0_port(QUIC_CHANNEL *ch)
712
0
{
713
0
    return ch->port;
714
0
}
715
716
QUIC_ENGINE *ossl_quic_channel_get0_engine(QUIC_CHANNEL *ch)
717
0
{
718
0
    return ossl_quic_port_get0_engine(ch->port);
719
0
}
720
721
CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch)
722
0
{
723
0
    return ossl_quic_port_get0_mutex(ch->port);
724
0
}
725
726
int ossl_quic_channel_has_pending(const QUIC_CHANNEL *ch)
727
0
{
728
0
    return ossl_quic_demux_has_pending(ch->port->demux)
729
0
        || ossl_qrx_processed_read_pending(ch->qrx);
730
0
}
731
732
/*
733
 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
734
 * ================================================================
735
 */
736
737
/* Used by various components. */
738
static OSSL_TIME get_time(void *arg)
739
157M
{
740
157M
    QUIC_CHANNEL *ch = arg;
741
742
157M
    return ossl_quic_port_get_time(ch->port);
743
157M
}
744
745
/* Used by QSM. */
746
static uint64_t get_stream_limit(int uni, void *arg)
747
69.0k
{
748
69.0k
    QUIC_CHANNEL *ch = arg;
749
750
69.0k
    return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
751
69.0k
}
752
753
/*
754
 * Called by QRX to determine if a packet is potentially invalid before trying
755
 * to decrypt it.
756
 */
757
static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg)
758
1.19M
{
759
1.19M
    QUIC_CHANNEL *ch = arg;
760
761
    /* Potential duplicates should not be processed. */
762
1.19M
    if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
763
180k
        return 0;
764
765
1.01M
    return 1;
766
1.19M
}
767
768
/*
769
 * Triggers a TXKU (whether spontaneous or solicited). Does not check whether
770
 * spontaneous TXKU is currently allowed.
771
 */
772
QUIC_NEEDS_LOCK
773
static void ch_trigger_txku(QUIC_CHANNEL *ch)
774
31.6k
{
775
31.6k
    uint64_t next_pn
776
31.6k
        = ossl_quic_tx_packetiser_get_next_pn(ch->txp, QUIC_PN_SPACE_APP);
777
778
31.6k
    if (!ossl_quic_pn_valid(next_pn)
779
31.6k
        || !ossl_qtx_trigger_key_update(ch->qtx)) {
780
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
781
0
            "key update");
782
0
        return;
783
0
    }
784
785
31.6k
    ch->txku_in_progress = 1;
786
31.6k
    ch->txku_pn = next_pn;
787
31.6k
    ch->rxku_expected = ch->ku_locally_initiated;
788
31.6k
}
789
790
QUIC_NEEDS_LOCK
791
static int txku_in_progress(QUIC_CHANNEL *ch)
792
18.2M
{
793
18.2M
    if (ch->txku_in_progress
794
4.54M
        && ossl_ackm_get_largest_acked(ch->ackm, QUIC_PN_SPACE_APP) >= ch->txku_pn) {
795
23.9k
        OSSL_TIME pto = ossl_ackm_get_pto_duration(ch->ackm);
796
797
        /*
798
         * RFC 9001 s. 6.5: Endpoints SHOULD wait three times the PTO before
799
         * initiating a key update after receiving an acknowledgment that
800
         * confirms that the previous key update was received.
801
         *
802
         * Note that by the above wording, this period starts from when we get
803
         * the ack for a TXKU-triggering packet, not when the TXKU is initiated.
804
         * So we defer TXKU cooldown deadline calculation to this point.
805
         */
806
23.9k
        ch->txku_in_progress = 0;
807
23.9k
        ch->txku_cooldown_deadline = ossl_time_add(get_time(ch),
808
23.9k
            ossl_time_multiply(pto, 3));
809
23.9k
    }
810
811
18.2M
    return ch->txku_in_progress;
812
18.2M
}
813
814
QUIC_NEEDS_LOCK
815
static int txku_allowed(QUIC_CHANNEL *ch)
816
61.4M
{
817
61.4M
    return ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT /* Sanity check. */
818
        /* Strict RFC 9001 criterion for TXKU. */
819
21.4M
        && ch->handshake_confirmed
820
18.2M
        && !txku_in_progress(ch);
821
61.4M
}
822
823
QUIC_NEEDS_LOCK
824
static int txku_recommendable(QUIC_CHANNEL *ch)
825
61.4M
{
826
61.4M
    if (!txku_allowed(ch))
827
47.6M
        return 0;
828
829
13.7M
    return
830
        /* Recommended RFC 9001 criterion for TXKU. */
831
13.7M
        ossl_time_compare(get_time(ch), ch->txku_cooldown_deadline) >= 0
832
        /* Some additional sensible criteria. */
833
9.45M
        && !ch->rxku_in_progress
834
9.44M
        && !ch->rxku_pending_confirm;
835
61.4M
}
836
837
QUIC_NEEDS_LOCK
838
static int txku_desirable(QUIC_CHANNEL *ch)
839
9.32M
{
840
9.32M
    uint64_t cur_pkt_count, max_pkt_count, thresh_pkt_count;
841
9.32M
    const uint32_t enc_level = QUIC_ENC_LEVEL_1RTT;
842
843
    /* Check AEAD limit to determine if we should perform a spontaneous TXKU. */
844
9.32M
    cur_pkt_count = ossl_qtx_get_cur_epoch_pkt_count(ch->qtx, enc_level);
845
9.32M
    max_pkt_count = ossl_qtx_get_max_epoch_pkt_count(ch->qtx, enc_level);
846
847
9.32M
    thresh_pkt_count = max_pkt_count / 2;
848
9.32M
    if (ch->txku_threshold_override != UINT64_MAX)
849
0
        thresh_pkt_count = ch->txku_threshold_override;
850
851
9.32M
    return cur_pkt_count >= thresh_pkt_count;
852
9.32M
}
853
854
QUIC_NEEDS_LOCK
855
static void ch_maybe_trigger_spontaneous_txku(QUIC_CHANNEL *ch)
856
61.4M
{
857
61.4M
    if (!txku_recommendable(ch) || !txku_desirable(ch))
858
61.4M
        return;
859
860
0
    ch->ku_locally_initiated = 1;
861
0
    ch_trigger_txku(ch);
862
0
}
863
864
QUIC_NEEDS_LOCK
865
static int rxku_allowed(QUIC_CHANNEL *ch)
866
31.8k
{
867
    /*
868
     * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a key update prior to
869
     * having confirmed the handshake (Section 4.1.2).
870
     *
871
     * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a subsequent key update
872
     * unless it has received an acknowledgment for a packet that was sent
873
     * protected with keys from the current key phase.
874
     *
875
     * RFC 9001 s. 6.2: If an endpoint detects a second update before it has
876
     * sent any packets with updated keys containing an acknowledgment for the
877
     * packet that initiated the key update, it indicates that its peer has
878
     * updated keys twice without awaiting confirmation. An endpoint MAY treat
879
     * such consecutive key updates as a connection error of type
880
     * KEY_UPDATE_ERROR.
881
     */
882
31.8k
    return ch->handshake_confirmed && !ch->rxku_pending_confirm;
883
31.8k
}
884
885
/*
886
 * Called when the QRX detects a new RX key update event.
887
 */
888
enum rxku_decision {
889
    DECISION_RXKU_ONLY,
890
    DECISION_PROTOCOL_VIOLATION,
891
    DECISION_SOLICITED_TXKU
892
};
893
894
/* Called when the QRX detects a key update has occurred. */
895
QUIC_NEEDS_LOCK
896
static void rxku_detected(QUIC_PN pn, void *arg)
897
31.8k
{
898
31.8k
    QUIC_CHANNEL *ch = arg;
899
31.8k
    enum rxku_decision decision;
900
31.8k
    OSSL_TIME pto;
901
902
    /*
903
     * Note: rxku_in_progress is always 0 here as an RXKU cannot be detected
904
     * when we are still in UPDATING or COOLDOWN (see quic_record_rx.h).
905
     */
906
31.8k
    assert(!ch->rxku_in_progress);
907
908
31.8k
    if (!rxku_allowed(ch))
909
        /* Is RXKU even allowed at this time? */
910
178
        decision = DECISION_PROTOCOL_VIOLATION;
911
912
31.6k
    else if (ch->ku_locally_initiated)
913
        /*
914
         * If this key update was locally initiated (meaning that this detected
915
         * RXKU event is a result of our own spontaneous TXKU), we do not
916
         * trigger another TXKU; after all, to do so would result in an infinite
917
         * ping-pong of key updates. We still process it as an RXKU.
918
         */
919
0
        decision = DECISION_RXKU_ONLY;
920
921
31.6k
    else
922
        /*
923
         * Otherwise, a peer triggering a KU means we have to trigger a KU also.
924
         */
925
31.6k
        decision = DECISION_SOLICITED_TXKU;
926
927
31.8k
    if (decision == DECISION_PROTOCOL_VIOLATION) {
928
178
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_KEY_UPDATE_ERROR,
929
178
            0, "RX key update again too soon");
930
178
        return;
931
178
    }
932
933
31.6k
    pto = ossl_ackm_get_pto_duration(ch->ackm);
934
935
31.6k
    ch->ku_locally_initiated = 0;
936
31.6k
    ch->rxku_in_progress = 1;
937
31.6k
    ch->rxku_pending_confirm = 1;
938
31.6k
    ch->rxku_trigger_pn = pn;
939
31.6k
    ch->rxku_update_end_deadline = ossl_time_add(get_time(ch), pto);
940
31.6k
    ch->rxku_expected = 0;
941
942
31.6k
    if (decision == DECISION_SOLICITED_TXKU)
943
        /* NOT gated by usual txku_allowed() */
944
31.6k
        ch_trigger_txku(ch);
945
946
    /*
947
     * Ordinarily, we only generate ACK when some ACK-eliciting frame has been
948
     * received. In some cases, this may not occur for a long time, for example
949
     * if transmission of application data is going in only one direction and
950
     * nothing else is happening with the connection. However, since the peer
951
     * cannot initiate a subsequent (spontaneous) TXKU until its prior
952
     * (spontaneous or solicited) TXKU has completed - meaning that prior
953
     * TXKU's trigger packet (or subsequent packet) has been acknowledged, this
954
     * can lead to very long times before a TXKU is considered 'completed'.
955
     * Optimise this by forcing ACK generation after triggering TXKU.
956
     * (Basically, we consider a RXKU event something that is 'ACK-eliciting',
957
     * which it more or less should be; it is necessarily separate from ordinary
958
     * processing of ACK-eliciting frames as key update is not indicated via a
959
     * frame.)
960
     */
961
31.6k
    ossl_quic_tx_packetiser_schedule_ack(ch->txp, QUIC_PN_SPACE_APP);
962
31.6k
}
963
964
/* Called per tick to handle RXKU timer events. */
965
QUIC_NEEDS_LOCK
966
static void ch_rxku_tick(QUIC_CHANNEL *ch)
967
61.4M
{
968
61.4M
    if (!ch->rxku_in_progress
969
3.31M
        || ossl_time_compare(get_time(ch), ch->rxku_update_end_deadline) < 0)
970
61.4M
        return;
971
972
28.8k
    ch->rxku_update_end_deadline = ossl_time_infinite();
973
28.8k
    ch->rxku_in_progress = 0;
974
975
28.8k
    if (!ossl_qrx_key_update_timeout(ch->qrx, /*normal=*/1))
976
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
977
28.8k
            "RXKU cooldown internal error");
978
28.8k
}
979
980
QUIC_NEEDS_LOCK
981
static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
982
    void *arg)
983
4.52M
{
984
4.52M
    QUIC_CHANNEL *ch = arg;
985
986
4.52M
    if (pn_space != QUIC_PN_SPACE_APP || !ch->rxku_pending_confirm
987
53.5k
        || !ossl_quic_frame_ack_contains_pn(ack, ch->rxku_trigger_pn))
988
4.47M
        return;
989
990
    /*
991
     * Defer clearing rxku_pending_confirm until TXP generate call returns
992
     * successfully.
993
     */
994
49.6k
    ch->rxku_pending_confirm_done = 1;
995
49.6k
}
996
997
/*
998
 * QUIC Channel: Handshake Layer Event Handling
999
 * ============================================
1000
 */
1001
static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
1002
    size_t *consumed, void *arg)
1003
64.1k
{
1004
64.1k
    int ret;
1005
64.1k
    QUIC_CHANNEL *ch = arg;
1006
64.1k
    uint32_t enc_level = ch->tx_enc_level;
1007
64.1k
    uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1008
64.1k
    QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
1009
1010
64.1k
    if (!ossl_assert(sstream != NULL))
1011
0
        return 0;
1012
1013
64.1k
    ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
1014
64.1k
    return ret;
1015
64.1k
}
1016
1017
static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
1018
47.3M
{
1019
47.3M
    size_t avail = 0;
1020
47.3M
    int is_fin = 0;
1021
1022
47.3M
    if (rstream == NULL)
1023
34.3M
        return 1;
1024
1025
13.0M
    if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
1026
0
        return 0;
1027
1028
13.0M
    return avail == 0;
1029
13.0M
}
1030
1031
static int ch_on_crypto_recv_record(const unsigned char **buf,
1032
    size_t *bytes_read, void *arg)
1033
61.5M
{
1034
61.5M
    QUIC_CHANNEL *ch = arg;
1035
61.5M
    QUIC_RSTREAM *rstream;
1036
61.5M
    int is_fin = 0; /* crypto stream is never finished, so we don't use this */
1037
61.5M
    uint32_t i;
1038
1039
    /*
1040
     * After we move to a later EL we must not allow our peer to send any new
1041
     * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
1042
     * are allowed.
1043
     *
1044
     * In practice we will only move to a new EL when we have consumed all bytes
1045
     * which should be sent on the crypto stream at a previous EL. For example,
1046
     * the Handshake EL should not be provisioned until we have completely
1047
     * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
1048
     * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
1049
     * given EL is available we simply ensure we have not received any further
1050
     * bytes at a lower EL.
1051
     */
1052
132M
    for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
1053
71.1M
        if (i != QUIC_ENC_LEVEL_0RTT && !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
1054
            /* Protocol violation (RFC 9001 s. 4.1.3) */
1055
16
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
1056
16
                OSSL_QUIC_FRAME_TYPE_CRYPTO,
1057
16
                "crypto stream data in wrong EL");
1058
16
            return 0;
1059
16
        }
1060
1061
61.5M
    rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
1062
61.5M
    if (rstream == NULL)
1063
0
        return 0;
1064
1065
61.5M
    return ossl_quic_rstream_get_record(rstream, buf, bytes_read,
1066
61.5M
        &is_fin);
1067
61.5M
}
1068
1069
static int ch_on_crypto_release_record(size_t bytes_read, void *arg)
1070
71.6k
{
1071
71.6k
    QUIC_CHANNEL *ch = arg;
1072
71.6k
    QUIC_RSTREAM *rstream;
1073
71.6k
    OSSL_RTT_INFO rtt_info;
1074
71.6k
    uint32_t rx_pn_space = ossl_quic_enc_level_to_pn_space(ch->rx_enc_level);
1075
1076
71.6k
    rstream = ch->crypto_recv[rx_pn_space];
1077
71.6k
    if (rstream == NULL)
1078
0
        return 0;
1079
1080
71.6k
    ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ch), &rtt_info);
1081
71.6k
    if (!ossl_quic_rxfc_on_retire(&ch->crypto_rxfc[rx_pn_space], bytes_read,
1082
71.6k
            rtt_info.smoothed_rtt))
1083
0
        return 0;
1084
1085
71.6k
    return ossl_quic_rstream_release_record(rstream, bytes_read);
1086
71.6k
}
1087
1088
static int ch_on_handshake_yield_secret(uint32_t prot_level, int direction,
1089
    uint32_t suite_id, EVP_MD *md,
1090
    const unsigned char *secret,
1091
    size_t secret_len,
1092
    void *arg)
1093
43.1k
{
1094
43.1k
    QUIC_CHANNEL *ch = arg;
1095
43.1k
    uint32_t i;
1096
43.1k
    uint32_t enc_level;
1097
1098
    /* Convert TLS protection level to QUIC encryption level */
1099
43.1k
    switch (prot_level) {
1100
0
    case OSSL_RECORD_PROTECTION_LEVEL_EARLY:
1101
0
        enc_level = QUIC_ENC_LEVEL_0RTT;
1102
0
        break;
1103
1104
28.5k
    case OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE:
1105
28.5k
        enc_level = QUIC_ENC_LEVEL_HANDSHAKE;
1106
28.5k
        break;
1107
1108
14.6k
    case OSSL_RECORD_PROTECTION_LEVEL_APPLICATION:
1109
14.6k
        enc_level = QUIC_ENC_LEVEL_1RTT;
1110
14.6k
        break;
1111
1112
0
    default:
1113
0
        return 0;
1114
43.1k
    }
1115
1116
43.1k
    if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
1117
        /* Invalid EL. */
1118
0
        return 0;
1119
1120
43.1k
    if (direction) {
1121
        /* TX */
1122
21.5k
        if (enc_level <= ch->tx_enc_level)
1123
            /*
1124
             * Does not make sense for us to try and provision an EL we have already
1125
             * attained.
1126
             */
1127
0
            return 0;
1128
1129
21.5k
        if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
1130
21.5k
                suite_id, md,
1131
21.5k
                secret, secret_len))
1132
0
            return 0;
1133
1134
21.5k
        ch->tx_enc_level = enc_level;
1135
21.5k
    } else {
1136
        /* RX */
1137
21.5k
        if (enc_level <= ch->rx_enc_level)
1138
            /*
1139
             * Does not make sense for us to try and provision an EL we have already
1140
             * attained.
1141
             */
1142
0
            return 0;
1143
1144
        /*
1145
         * Ensure all crypto streams for previous ELs are now empty of available
1146
         * data.
1147
         */
1148
72.0k
        for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
1149
50.4k
            if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
1150
                /* Protocol violation (RFC 9001 s. 4.1.3) */
1151
23
                ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
1152
23
                    OSSL_QUIC_FRAME_TYPE_CRYPTO,
1153
23
                    "crypto stream data in wrong EL");
1154
23
                return 0;
1155
23
            }
1156
1157
21.5k
        if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
1158
21.5k
                suite_id, md,
1159
21.5k
                secret, secret_len))
1160
0
            return 0;
1161
1162
21.5k
        ch->have_new_rx_secret = 1;
1163
21.5k
        ch->rx_enc_level = enc_level;
1164
21.5k
    }
1165
1166
43.1k
    return 1;
1167
43.1k
}
1168
1169
static int ch_on_handshake_complete(void *arg)
1170
7.30k
{
1171
7.30k
    QUIC_CHANNEL *ch = arg;
1172
1173
7.30k
    if (!ossl_assert(!ch->handshake_complete))
1174
0
        return 0; /* this should not happen twice */
1175
1176
7.30k
    if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
1177
0
        return 0;
1178
1179
    /*
1180
     * When handshake is complete, we no longer need to abide by the
1181
     * 3x amplification limit, though we should be validated as soon
1182
     * as we see a handshake key encrypted packet (see ossl_quic_handle_packet)
1183
     */
1184
7.30k
    ossl_quic_tx_packetiser_set_validated(ch->txp);
1185
1186
7.30k
    if (!ch->got_remote_transport_params) {
1187
        /*
1188
         * Was not a valid QUIC handshake if we did not get valid transport
1189
         * params.
1190
         */
1191
45
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_CRYPTO_MISSING_EXT,
1192
45
            OSSL_QUIC_FRAME_TYPE_CRYPTO,
1193
45
            "no transport parameters received");
1194
45
        return 0;
1195
45
    }
1196
1197
    /* Don't need transport parameters anymore. */
1198
7.25k
    OPENSSL_free(ch->local_transport_params);
1199
7.25k
    ch->local_transport_params = NULL;
1200
1201
    /* Tell the QRX it can now process 1-RTT packets. */
1202
7.25k
    ossl_qrx_allow_1rtt_processing(ch->qrx);
1203
1204
    /* Tell TXP the handshake is complete. */
1205
7.25k
    ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
1206
1207
7.25k
    ch->handshake_complete = 1;
1208
1209
7.25k
    if (ch->pending_new_token != NULL) {
1210
        /*
1211
         * Note this is a best effort operation here
1212
         * If scheduling a new token fails, the worst outcome is that
1213
         * a client, not having received it, will just have to go through
1214
         * an extra roundtrip on a subsequent connection via the retry frame
1215
         * path, at which point we get another opportunity to schedule another
1216
         * new token.  As a result, we don't need to handle any errors here
1217
         */
1218
0
        ossl_quic_channel_schedule_new_token(ch,
1219
0
            ch->pending_new_token,
1220
0
            ch->pending_new_token_len);
1221
0
        OPENSSL_free(ch->pending_new_token);
1222
0
        ch->pending_new_token = NULL;
1223
0
        ch->pending_new_token_len = 0;
1224
0
    }
1225
1226
7.25k
    if (ch->is_server) {
1227
        /*
1228
         * On the server, the handshake is confirmed as soon as it is complete.
1229
         */
1230
0
        ossl_quic_channel_on_handshake_confirmed(ch);
1231
1232
0
        ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
1233
0
    }
1234
1235
7.25k
    ch_record_state_transition(ch, ch->state);
1236
7.25k
    return 1;
1237
7.30k
}
1238
1239
static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
1240
10.9k
{
1241
10.9k
    QUIC_CHANNEL *ch = arg;
1242
1243
    /*
1244
     * RFC 9001 s. 4.4: More specifically, servers MUST NOT send post-handshake
1245
     * TLS CertificateRequest messages, and clients MUST treat receipt of such
1246
     * messages as a connection error of type PROTOCOL_VIOLATION.
1247
     */
1248
10.9k
    if (alert_code == SSL_AD_UNEXPECTED_MESSAGE
1249
4.39k
        && ch->handshake_complete
1250
177
        && ossl_quic_tls_is_cert_request(ch->qtls))
1251
5
        ossl_quic_channel_raise_protocol_error(ch,
1252
10.9k
            OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
1253
10.9k
            0,
1254
10.9k
            "Post-handshake TLS "
1255
10.9k
            "CertificateRequest received");
1256
    /*
1257
     * RFC 9001 s. 4.6.1: Servers MUST NOT send the early_data extension with a
1258
     * max_early_data_size field set to any value other than 0xffffffff. A
1259
     * client MUST treat receipt of a NewSessionTicket that contains an
1260
     * early_data extension with any other value as a connection error of type
1261
     * PROTOCOL_VIOLATION.
1262
     */
1263
10.9k
    else if (alert_code == SSL_AD_ILLEGAL_PARAMETER
1264
747
        && ch->handshake_complete
1265
14
        && ossl_quic_tls_has_bad_max_early_data(ch->qtls))
1266
0
        ossl_quic_channel_raise_protocol_error(ch,
1267
10.9k
            OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
1268
10.9k
            0,
1269
10.9k
            "Bad max_early_data received");
1270
10.9k
    else
1271
10.9k
        ossl_quic_channel_raise_protocol_error(ch,
1272
10.9k
            OSSL_QUIC_ERR_CRYPTO_ERR_BEGIN
1273
10.9k
                + alert_code,
1274
10.9k
            0, "handshake alert");
1275
1276
10.9k
    return 1;
1277
10.9k
}
1278
1279
/*
1280
 * QUIC Channel: Transport Parameter Handling
1281
 * ==========================================
1282
 */
1283
1284
/*
1285
 * Called by handshake layer when we receive QUIC Transport Parameters from the
1286
 * peer. Note that these are not authenticated until the handshake is marked
1287
 * as complete.
1288
 */
1289
#define TP_REASON_SERVER_ONLY(x) \
1290
0
    x " may not be sent by a client"
1291
#define TP_REASON_DUP(x) \
1292
85
    x " appears multiple times"
1293
#define TP_REASON_MALFORMED(x) \
1294
293
    x " is malformed"
1295
#define TP_REASON_EXPECTED_VALUE(x) \
1296
25
    x " does not match expected value"
1297
#define TP_REASON_NOT_RETRY(x) \
1298
2
    x " sent when not performing a retry"
1299
#define TP_REASON_REQUIRED(x) \
1300
9
    x " was not sent but is required"
1301
#define TP_REASON_INTERNAL_ERROR(x) \
1302
0
    x " encountered internal error"
1303
1304
static void txfc_bump_cwm_bidi(QUIC_STREAM *s, void *arg)
1305
0
{
1306
0
    if (!ossl_quic_stream_is_bidi(s)
1307
0
        || ossl_quic_stream_is_server_init(s))
1308
0
        return;
1309
1310
0
    ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
1311
0
}
1312
1313
static void txfc_bump_cwm_uni(QUIC_STREAM *s, void *arg)
1314
0
{
1315
0
    if (ossl_quic_stream_is_bidi(s)
1316
0
        || ossl_quic_stream_is_server_init(s))
1317
0
        return;
1318
1319
0
    ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
1320
0
}
1321
1322
static void do_update(QUIC_STREAM *s, void *arg)
1323
0
{
1324
0
    QUIC_CHANNEL *ch = arg;
1325
1326
0
    ossl_quic_stream_map_update_state(&ch->qsm, s);
1327
0
}
1328
1329
static uint64_t min_u64_ignore_0(uint64_t a, uint64_t b)
1330
19.5k
{
1331
19.5k
    if (a == 0)
1332
0
        return b;
1333
19.5k
    if (b == 0)
1334
16
        return a;
1335
1336
19.5k
    return a < b ? a : b;
1337
19.5k
}
1338
1339
static int ch_on_transport_params(const unsigned char *params,
1340
    size_t params_len,
1341
    void *arg)
1342
7.69k
{
1343
7.69k
    QUIC_CHANNEL *ch = arg;
1344
7.69k
    PACKET pkt;
1345
7.69k
    uint64_t id, v;
1346
7.69k
    size_t len;
1347
7.69k
    const unsigned char *body;
1348
7.69k
    int got_orig_dcid = 0;
1349
7.69k
    int got_initial_scid = 0;
1350
7.69k
    int got_retry_scid = 0;
1351
7.69k
    int got_initial_max_data = 0;
1352
7.69k
    int got_initial_max_stream_data_bidi_local = 0;
1353
7.69k
    int got_initial_max_stream_data_bidi_remote = 0;
1354
7.69k
    int got_initial_max_stream_data_uni = 0;
1355
7.69k
    int got_initial_max_streams_bidi = 0;
1356
7.69k
    int got_initial_max_streams_uni = 0;
1357
7.69k
    int got_stateless_reset_token = 0;
1358
7.69k
    int got_preferred_addr = 0;
1359
7.69k
    int got_ack_delay_exp = 0;
1360
7.69k
    int got_max_ack_delay = 0;
1361
7.69k
    int got_max_udp_payload_size = 0;
1362
7.69k
    int got_max_idle_timeout = 0;
1363
7.69k
    int got_active_conn_id_limit = 0;
1364
7.69k
    int got_disable_active_migration = 0;
1365
7.69k
    QUIC_CONN_ID cid;
1366
7.69k
    const char *reason = "bad transport parameter";
1367
7.69k
    ossl_unused uint64_t rx_max_idle_timeout = 0;
1368
7.69k
    ossl_unused const void *stateless_reset_token_p = NULL;
1369
7.69k
    QUIC_PREFERRED_ADDR pfa;
1370
7.69k
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ch->tls);
1371
1372
7.69k
    if (sc == NULL) {
1373
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
1374
0
            "could not get ssl connection");
1375
0
        return 0;
1376
0
    }
1377
    /*
1378
     * When HRR happens the client sends the transport params in the new client
1379
     * hello again. Reset the transport params here and load them again.
1380
     */
1381
7.69k
    if (ch->is_server && sc->hello_retry_request != SSL_HRR_NONE
1382
0
        && ch->got_remote_transport_params) {
1383
0
        ch->max_local_streams_bidi = 0;
1384
0
        ch->max_local_streams_uni = 0;
1385
0
        ch->got_local_transport_params = 0;
1386
0
        OPENSSL_free(ch->local_transport_params);
1387
0
        ch->local_transport_params = NULL;
1388
7.69k
    } else if (ch->got_remote_transport_params) {
1389
0
        reason = "multiple transport parameter extensions";
1390
0
        goto malformed;
1391
0
    }
1392
1393
7.69k
    if (!PACKET_buf_init(&pkt, params, params_len)) {
1394
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
1395
0
            "internal error (packet buf init)");
1396
0
        return 0;
1397
0
    }
1398
1399
95.0k
    while (PACKET_remaining(&pkt) > 0) {
1400
87.7k
        if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
1401
2
            goto malformed;
1402
1403
87.7k
        switch (id) {
1404
7.67k
        case QUIC_TPARAM_ORIG_DCID:
1405
7.67k
            if (got_orig_dcid) {
1406
34
                reason = TP_REASON_DUP("ORIG_DCID");
1407
34
                goto malformed;
1408
34
            }
1409
1410
7.63k
            if (ch->is_server) {
1411
0
                reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
1412
0
                goto malformed;
1413
0
            }
1414
1415
7.63k
            if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1416
4
                reason = TP_REASON_MALFORMED("ORIG_DCID");
1417
4
                goto malformed;
1418
4
            }
1419
1420
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1421
            /* Must match our initial DCID. */
1422
            if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
1423
                reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
1424
                goto malformed;
1425
            }
1426
#endif
1427
1428
7.63k
            got_orig_dcid = 1;
1429
7.63k
            break;
1430
1431
16
        case QUIC_TPARAM_RETRY_SCID:
1432
16
            if (ch->is_server) {
1433
0
                reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
1434
0
                goto malformed;
1435
0
            }
1436
1437
16
            if (got_retry_scid) {
1438
2
                reason = TP_REASON_DUP("RETRY_SCID");
1439
2
                goto malformed;
1440
2
            }
1441
1442
14
            if (!ch->doing_retry) {
1443
2
                reason = TP_REASON_NOT_RETRY("RETRY_SCID");
1444
2
                goto malformed;
1445
2
            }
1446
1447
12
            if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1448
2
                reason = TP_REASON_MALFORMED("RETRY_SCID");
1449
2
                goto malformed;
1450
2
            }
1451
1452
            /* Must match Retry packet SCID. */
1453
10
            if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
1454
5
                reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
1455
5
                goto malformed;
1456
5
            }
1457
1458
5
            got_retry_scid = 1;
1459
5
            break;
1460
1461
7.42k
        case QUIC_TPARAM_INITIAL_SCID:
1462
7.42k
            if (got_initial_scid) {
1463
                /* must not appear more than once */
1464
2
                reason = TP_REASON_DUP("INITIAL_SCID");
1465
2
                goto malformed;
1466
2
            }
1467
1468
7.41k
            if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1469
2
                reason = TP_REASON_MALFORMED("INITIAL_SCID");
1470
2
                goto malformed;
1471
2
            }
1472
1473
7.41k
            if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
1474
20
                reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
1475
20
                goto malformed;
1476
20
            }
1477
1478
7.39k
            got_initial_scid = 1;
1479
7.39k
            break;
1480
1481
6.62k
        case QUIC_TPARAM_INITIAL_MAX_DATA:
1482
6.62k
            if (got_initial_max_data) {
1483
                /* must not appear more than once */
1484
5
                reason = TP_REASON_DUP("INITIAL_MAX_DATA");
1485
5
                goto malformed;
1486
5
            }
1487
1488
6.61k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1489
30
                reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
1490
30
                goto malformed;
1491
30
            }
1492
1493
6.58k
            ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
1494
6.58k
            got_initial_max_data = 1;
1495
6.58k
            break;
1496
1497
6.89k
        case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
1498
6.89k
            if (got_initial_max_stream_data_bidi_local) {
1499
                /* must not appear more than once */
1500
3
                reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1501
3
                goto malformed;
1502
3
            }
1503
1504
6.89k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1505
4
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1506
4
                goto malformed;
1507
4
            }
1508
1509
            /*
1510
             * This is correct; the BIDI_LOCAL TP governs streams created by
1511
             * the endpoint which sends the TP, i.e., our peer.
1512
             */
1513
6.88k
            ch->rx_init_max_stream_data_bidi_remote = v;
1514
6.88k
            got_initial_max_stream_data_bidi_local = 1;
1515
6.88k
            break;
1516
1517
7.11k
        case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
1518
7.11k
            if (got_initial_max_stream_data_bidi_remote) {
1519
                /* must not appear more than once */
1520
4
                reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1521
4
                goto malformed;
1522
4
            }
1523
1524
7.11k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1525
7
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1526
7
                goto malformed;
1527
7
            }
1528
1529
            /*
1530
             * This is correct; the BIDI_REMOTE TP governs streams created
1531
             * by the endpoint which receives the TP, i.e., us.
1532
             */
1533
7.10k
            ch->rx_init_max_stream_data_bidi_local = v;
1534
1535
            /* Apply to all existing streams. */
1536
7.10k
            ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_bidi, &v);
1537
7.10k
            got_initial_max_stream_data_bidi_remote = 1;
1538
7.10k
            break;
1539
1540
7.18k
        case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
1541
7.18k
            if (got_initial_max_stream_data_uni) {
1542
                /* must not appear more than once */
1543
2
                reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
1544
2
                goto malformed;
1545
2
            }
1546
1547
7.18k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1548
3
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
1549
3
                goto malformed;
1550
3
            }
1551
1552
7.17k
            ch->rx_init_max_stream_data_uni = v;
1553
1554
            /* Apply to all existing streams. */
1555
7.17k
            ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_uni, &v);
1556
7.17k
            got_initial_max_stream_data_uni = 1;
1557
7.17k
            break;
1558
1559
67
        case QUIC_TPARAM_ACK_DELAY_EXP:
1560
67
            if (got_ack_delay_exp) {
1561
                /* must not appear more than once */
1562
2
                reason = TP_REASON_DUP("ACK_DELAY_EXP");
1563
2
                goto malformed;
1564
2
            }
1565
1566
65
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1567
61
                || v > QUIC_MAX_ACK_DELAY_EXP) {
1568
44
                reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
1569
44
                goto malformed;
1570
44
            }
1571
1572
21
            ch->rx_ack_delay_exp = (unsigned char)v;
1573
21
            got_ack_delay_exp = 1;
1574
21
            break;
1575
1576
242
        case QUIC_TPARAM_MAX_ACK_DELAY:
1577
242
            if (got_max_ack_delay) {
1578
                /* must not appear more than once */
1579
2
                reason = TP_REASON_DUP("MAX_ACK_DELAY");
1580
2
                goto malformed;
1581
2
            }
1582
1583
240
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1584
235
                || v >= (((uint64_t)1) << 14)) {
1585
39
                reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
1586
39
                goto malformed;
1587
39
            }
1588
1589
201
            ch->rx_max_ack_delay = v;
1590
201
            ossl_ackm_set_rx_max_ack_delay(ch->ackm,
1591
201
                ossl_ms2time(ch->rx_max_ack_delay));
1592
1593
201
            got_max_ack_delay = 1;
1594
201
            break;
1595
1596
7.19k
        case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
1597
7.19k
            if (got_initial_max_streams_bidi) {
1598
                /* must not appear more than once */
1599
3
                reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
1600
3
                goto malformed;
1601
3
            }
1602
1603
7.19k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1604
7.18k
                || v > (((uint64_t)1) << 60)) {
1605
33
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
1606
33
                goto malformed;
1607
33
            }
1608
1609
7.19k
            assert(ch->max_local_streams_bidi == 0);
1610
7.15k
            ch->max_local_streams_bidi = v;
1611
7.15k
            got_initial_max_streams_bidi = 1;
1612
7.15k
            break;
1613
1614
7.00k
        case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
1615
7.00k
            if (got_initial_max_streams_uni) {
1616
                /* must not appear more than once */
1617
5
                reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
1618
5
                goto malformed;
1619
5
            }
1620
1621
7.00k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1622
6.99k
                || v > (((uint64_t)1) << 60)) {
1623
30
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
1624
30
                goto malformed;
1625
30
            }
1626
1627
7.00k
            assert(ch->max_local_streams_uni == 0);
1628
6.97k
            ch->max_local_streams_uni = v;
1629
6.97k
            got_initial_max_streams_uni = 1;
1630
6.97k
            break;
1631
1632
7.45k
        case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
1633
7.45k
            if (got_max_idle_timeout) {
1634
                /* must not appear more than once */
1635
4
                reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
1636
4
                goto malformed;
1637
4
            }
1638
1639
7.45k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1640
19
                reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
1641
19
                goto malformed;
1642
19
            }
1643
1644
7.43k
            ch->max_idle_timeout_remote_req = v;
1645
1646
7.43k
            ch->max_idle_timeout = min_u64_ignore_0(ch->max_idle_timeout_local_req,
1647
7.43k
                ch->max_idle_timeout_remote_req);
1648
1649
7.43k
            ch_update_idle(ch);
1650
7.43k
            got_max_idle_timeout = 1;
1651
7.43k
            rx_max_idle_timeout = v;
1652
7.43k
            break;
1653
1654
6.90k
        case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
1655
6.90k
            if (got_max_udp_payload_size) {
1656
                /* must not appear more than once */
1657
2
                reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
1658
2
                goto malformed;
1659
2
            }
1660
1661
6.90k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1662
6.89k
                || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
1663
16
                reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
1664
16
                goto malformed;
1665
16
            }
1666
1667
6.88k
            ch->rx_max_udp_payload_size = v;
1668
6.88k
            got_max_udp_payload_size = 1;
1669
6.88k
            break;
1670
1671
6.52k
        case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
1672
6.52k
            if (got_active_conn_id_limit) {
1673
                /* must not appear more than once */
1674
6
                reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
1675
6
                goto malformed;
1676
6
            }
1677
1678
6.51k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1679
6.51k
                || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
1680
5
                reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
1681
5
                goto malformed;
1682
5
            }
1683
1684
6.51k
            ch->rx_active_conn_id_limit = v;
1685
6.51k
            got_active_conn_id_limit = 1;
1686
6.51k
            break;
1687
1688
29
        case QUIC_TPARAM_STATELESS_RESET_TOKEN:
1689
29
            if (got_stateless_reset_token) {
1690
2
                reason = TP_REASON_DUP("STATELESS_RESET_TOKEN");
1691
2
                goto malformed;
1692
2
            }
1693
1694
            /*
1695
             * RFC 9000 s. 18.2: This transport parameter MUST NOT be sent
1696
             * by a client but MAY be sent by a server.
1697
             */
1698
27
            if (ch->is_server) {
1699
0
                reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
1700
0
                goto malformed;
1701
0
            }
1702
1703
27
            body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1704
27
            if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
1705
22
                reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
1706
22
                goto malformed;
1707
22
            }
1708
5
            if (!ossl_quic_srtm_add(ch->srtm, ch, ch->cur_remote_seq_num,
1709
5
                    (const QUIC_STATELESS_RESET_TOKEN *)body)) {
1710
0
                reason = TP_REASON_INTERNAL_ERROR("STATELESS_RESET_TOKEN");
1711
0
                goto malformed;
1712
0
            }
1713
1714
5
            stateless_reset_token_p = body;
1715
5
            got_stateless_reset_token = 1;
1716
5
            break;
1717
1718
36
        case QUIC_TPARAM_PREFERRED_ADDR:
1719
            /* TODO(QUIC FUTURE): Handle preferred address. */
1720
36
            if (got_preferred_addr) {
1721
2
                reason = TP_REASON_DUP("PREFERRED_ADDR");
1722
2
                goto malformed;
1723
2
            }
1724
1725
            /*
1726
             * RFC 9000 s. 18.2: "A server that chooses a zero-length
1727
             * connection ID MUST NOT provide a preferred address.
1728
             * Similarly, a server MUST NOT include a zero-length connection
1729
             * ID in this transport parameter. A client MUST treat a
1730
             * violation of these requirements as a connection error of type
1731
             * TRANSPORT_PARAMETER_ERROR."
1732
             */
1733
34
            if (ch->is_server) {
1734
0
                reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
1735
0
                goto malformed;
1736
0
            }
1737
1738
34
            if (ch->cur_remote_dcid.id_len == 0) {
1739
0
                reason = "PREFERRED_ADDR provided for zero-length CID";
1740
0
                goto malformed;
1741
0
            }
1742
1743
34
            if (!ossl_quic_wire_decode_transport_param_preferred_addr(&pkt, &pfa)) {
1744
29
                reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
1745
29
                goto malformed;
1746
29
            }
1747
1748
5
            if (pfa.cid.id_len == 0) {
1749
2
                reason = "zero-length CID in PREFERRED_ADDR";
1750
2
                goto malformed;
1751
2
            }
1752
1753
3
            got_preferred_addr = 1;
1754
3
            break;
1755
1756
7.63k
        case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
1757
            /* We do not currently handle migration, so nothing to do. */
1758
7.63k
            if (got_disable_active_migration) {
1759
                /* must not appear more than once */
1760
5
                reason = TP_REASON_DUP("DISABLE_ACTIVE_MIGRATION");
1761
5
                goto malformed;
1762
5
            }
1763
1764
7.63k
            body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1765
7.63k
            if (body == NULL || len > 0) {
1766
4
                reason = TP_REASON_MALFORMED("DISABLE_ACTIVE_MIGRATION");
1767
4
                goto malformed;
1768
4
            }
1769
1770
7.62k
            got_disable_active_migration = 1;
1771
7.62k
            break;
1772
1773
1.76k
        default:
1774
            /*
1775
             * Skip over and ignore.
1776
             *
1777
             * RFC 9000 s. 7.4: We SHOULD treat duplicated transport parameters
1778
             * as a connection error, but we are not required to. Currently,
1779
             * handle this programmatically by checking for duplicates in the
1780
             * parameters that we recognise, as above, but don't bother
1781
             * maintaining a list of duplicates for anything we don't recognise.
1782
             */
1783
1.76k
            body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
1784
1.76k
                &len);
1785
1.76k
            if (body == NULL)
1786
64
                goto malformed;
1787
1788
1.70k
            break;
1789
87.7k
        }
1790
87.7k
    }
1791
1792
7.22k
    if (!got_initial_scid) {
1793
5
        reason = TP_REASON_REQUIRED("INITIAL_SCID");
1794
5
        goto malformed;
1795
5
    }
1796
1797
7.22k
    if (!ch->is_server) {
1798
7.22k
        if (!got_orig_dcid) {
1799
2
            reason = TP_REASON_REQUIRED("ORIG_DCID");
1800
2
            goto malformed;
1801
2
        }
1802
1803
7.21k
        if (ch->doing_retry && !got_retry_scid) {
1804
2
            reason = TP_REASON_REQUIRED("RETRY_SCID");
1805
2
            goto malformed;
1806
2
        }
1807
7.21k
    }
1808
1809
7.21k
    ch->got_remote_transport_params = 1;
1810
1811
7.21k
#ifndef OPENSSL_NO_QLOG
1812
7.21k
    QLOG_EVENT_BEGIN(ch_get_qlog(ch), transport, parameters_set)
1813
0
    QLOG_STR("owner", "remote");
1814
1815
0
    if (got_orig_dcid)
1816
0
        QLOG_CID("original_destination_connection_id",
1817
0
            &ch->init_dcid);
1818
0
    if (got_initial_scid)
1819
0
        QLOG_CID("original_source_connection_id",
1820
0
            &ch->init_dcid);
1821
0
    if (got_retry_scid)
1822
0
        QLOG_CID("retry_source_connection_id",
1823
0
            &ch->retry_scid);
1824
0
    if (got_initial_max_data)
1825
0
        QLOG_U64("initial_max_data",
1826
0
            ossl_quic_txfc_get_cwm(&ch->conn_txfc));
1827
0
    if (got_initial_max_stream_data_bidi_local)
1828
0
        QLOG_U64("initial_max_stream_data_bidi_local",
1829
0
            ch->rx_init_max_stream_data_bidi_local);
1830
0
    if (got_initial_max_stream_data_bidi_remote)
1831
0
        QLOG_U64("initial_max_stream_data_bidi_remote",
1832
0
            ch->rx_init_max_stream_data_bidi_remote);
1833
0
    if (got_initial_max_stream_data_uni)
1834
0
        QLOG_U64("initial_max_stream_data_uni",
1835
0
            ch->rx_init_max_stream_data_uni);
1836
0
    if (got_initial_max_streams_bidi)
1837
0
        QLOG_U64("initial_max_streams_bidi",
1838
0
            ch->max_local_streams_bidi);
1839
0
    if (got_initial_max_streams_uni)
1840
0
        QLOG_U64("initial_max_streams_uni",
1841
0
            ch->max_local_streams_uni);
1842
0
    if (got_ack_delay_exp)
1843
0
        QLOG_U64("ack_delay_exponent", ch->rx_ack_delay_exp);
1844
0
    if (got_max_ack_delay)
1845
0
        QLOG_U64("max_ack_delay", ch->rx_max_ack_delay);
1846
0
    if (got_max_udp_payload_size)
1847
0
        QLOG_U64("max_udp_payload_size", ch->rx_max_udp_payload_size);
1848
0
    if (got_max_idle_timeout)
1849
0
        QLOG_U64("max_idle_timeout", rx_max_idle_timeout);
1850
0
    if (got_active_conn_id_limit)
1851
0
        QLOG_U64("active_connection_id_limit", ch->rx_active_conn_id_limit);
1852
0
    if (got_stateless_reset_token)
1853
0
        QLOG_BIN("stateless_reset_token", stateless_reset_token_p,
1854
0
            QUIC_STATELESS_RESET_TOKEN_LEN);
1855
0
    if (got_preferred_addr) {
1856
0
        QLOG_BEGIN("preferred_addr")
1857
0
        QLOG_U64("port_v4", pfa.ipv4_port);
1858
0
        QLOG_U64("port_v6", pfa.ipv6_port);
1859
0
        QLOG_BIN("ip_v4", pfa.ipv4, sizeof(pfa.ipv4));
1860
0
        QLOG_BIN("ip_v6", pfa.ipv6, sizeof(pfa.ipv6));
1861
0
        QLOG_BIN("stateless_reset_token", pfa.stateless_reset.token,
1862
0
            sizeof(pfa.stateless_reset.token));
1863
0
        QLOG_CID("connection_id", &pfa.cid);
1864
0
        QLOG_END()
1865
0
    }
1866
0
    QLOG_BOOL("disable_active_migration", got_disable_active_migration);
1867
0
    QLOG_EVENT_END()
1868
7.21k
#endif
1869
1870
7.21k
    if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
1871
141
        || got_initial_max_streams_bidi || got_initial_max_streams_uni)
1872
        /*
1873
         * If FC credit was bumped, we may now be able to send. Update all
1874
         * streams.
1875
         */
1876
7.21k
        ossl_quic_stream_map_visit(&ch->qsm, do_update, ch);
1877
1878
    /* If we are a server, we now generate our own transport parameters. */
1879
7.21k
    if (ch->is_server && !ch_generate_transport_params(ch)) {
1880
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
1881
0
            "internal error");
1882
0
        return 0;
1883
0
    }
1884
1885
7.21k
    return 1;
1886
1887
482
malformed:
1888
482
    ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
1889
482
        0, reason);
1890
482
    return 0;
1891
7.21k
}
1892
1893
/*
1894
 * Called when we want to generate transport parameters. This is called
1895
 * immediately at instantiation time for a client and after we receive the
1896
 * client's transport parameters for a server.
1897
 */
1898
static int ch_generate_transport_params(QUIC_CHANNEL *ch)
1899
29.8k
{
1900
29.8k
    int ok = 0;
1901
29.8k
    BUF_MEM *buf_mem = NULL;
1902
29.8k
    WPACKET wpkt;
1903
29.8k
    int wpkt_valid = 0;
1904
29.8k
    size_t buf_len = 0;
1905
29.8k
    QUIC_CONN_ID *id_to_use = NULL;
1906
1907
    /*
1908
     * We need to select which connection id to encode in the
1909
     * QUIC_TPARAM_ORIG_DCID transport parameter
1910
     * If we have an odcid, then this connection was established
1911
     * in response to a retry request, and we need to use the connection
1912
     * id sent in the first initial packet.
1913
     * If we don't have an odcid, then this connection was established
1914
     * without a retry and the init_dcid is the connection we should use
1915
     */
1916
29.8k
    if (ch->odcid.id_len == 0)
1917
29.8k
        id_to_use = &ch->init_dcid;
1918
0
    else
1919
0
        id_to_use = &ch->odcid;
1920
1921
29.8k
    if (ch->local_transport_params != NULL || ch->got_local_transport_params)
1922
0
        goto err;
1923
1924
29.8k
    if ((buf_mem = BUF_MEM_new()) == NULL)
1925
0
        goto err;
1926
1927
29.8k
    if (!WPACKET_init(&wpkt, buf_mem))
1928
0
        goto err;
1929
1930
29.8k
    wpkt_valid = 1;
1931
1932
29.8k
    if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
1933
29.8k
            NULL, 0)
1934
29.8k
        == NULL)
1935
0
        goto err;
1936
1937
29.8k
    if (ch->is_server) {
1938
0
        if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
1939
0
                id_to_use))
1940
0
            goto err;
1941
1942
0
        if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1943
0
                &ch->cur_local_cid))
1944
0
            goto err;
1945
0
        if (ch->odcid.id_len != 0)
1946
0
            if (!ossl_quic_wire_encode_transport_param_cid(&wpkt,
1947
0
                    QUIC_TPARAM_RETRY_SCID,
1948
0
                    &ch->init_dcid))
1949
0
                goto err;
1950
29.8k
    } else {
1951
29.8k
        if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1952
29.8k
                &ch->init_scid))
1953
0
            goto err;
1954
29.8k
    }
1955
1956
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
1957
29.8k
            ch->max_idle_timeout_local_req))
1958
0
        goto err;
1959
1960
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
1961
29.8k
            QUIC_MIN_INITIAL_DGRAM_LEN))
1962
0
        goto err;
1963
1964
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
1965
29.8k
            QUIC_MIN_ACTIVE_CONN_ID_LIMIT))
1966
0
        goto err;
1967
1968
29.8k
    if (ch->tx_max_ack_delay != QUIC_DEFAULT_MAX_ACK_DELAY
1969
0
        && !ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_ACK_DELAY,
1970
0
            ch->tx_max_ack_delay))
1971
0
        goto err;
1972
1973
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
1974
29.8k
            ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
1975
0
        goto err;
1976
1977
    /* Send the default CWM for a new RXFC. */
1978
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1979
29.8k
            ch->tx_init_max_stream_data_bidi_local))
1980
0
        goto err;
1981
1982
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1983
29.8k
            ch->tx_init_max_stream_data_bidi_remote))
1984
0
        goto err;
1985
1986
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
1987
29.8k
            ch->tx_init_max_stream_data_uni))
1988
0
        goto err;
1989
1990
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
1991
29.8k
            ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc)))
1992
0
        goto err;
1993
1994
29.8k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
1995
29.8k
            ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc)))
1996
0
        goto err;
1997
1998
29.8k
    if (!WPACKET_finish(&wpkt))
1999
0
        goto err;
2000
2001
29.8k
    wpkt_valid = 0;
2002
2003
29.8k
    if (!WPACKET_get_total_written(&wpkt, &buf_len))
2004
0
        goto err;
2005
2006
29.8k
    ch->local_transport_params = (unsigned char *)buf_mem->data;
2007
29.8k
    buf_mem->data = NULL;
2008
2009
29.8k
    if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
2010
29.8k
            buf_len))
2011
0
        goto err;
2012
2013
29.8k
#ifndef OPENSSL_NO_QLOG
2014
29.8k
    QLOG_EVENT_BEGIN(ch_get_qlog(ch), transport, parameters_set)
2015
0
    QLOG_STR("owner", "local");
2016
0
    QLOG_BOOL("disable_active_migration", 1);
2017
0
    if (ch->is_server) {
2018
0
        QLOG_CID("original_destination_connection_id", &ch->init_dcid);
2019
0
        QLOG_CID("initial_source_connection_id", &ch->cur_local_cid);
2020
0
    } else {
2021
0
        QLOG_STR("initial_source_connection_id", "");
2022
0
    }
2023
0
    QLOG_U64("max_idle_timeout", ch->max_idle_timeout);
2024
0
    QLOG_U64("max_udp_payload_size", QUIC_MIN_INITIAL_DGRAM_LEN);
2025
0
    QLOG_U64("active_connection_id_limit", QUIC_MIN_ACTIVE_CONN_ID_LIMIT);
2026
0
    QLOG_U64("max_ack_delay", ch->tx_max_ack_delay);
2027
0
    QLOG_U64("initial_max_data", ossl_quic_rxfc_get_cwm(&ch->conn_rxfc));
2028
0
    QLOG_U64("initial_max_stream_data_bidi_local",
2029
0
        ch->tx_init_max_stream_data_bidi_local);
2030
0
    QLOG_U64("initial_max_stream_data_bidi_remote",
2031
0
        ch->tx_init_max_stream_data_bidi_remote);
2032
0
    QLOG_U64("initial_max_stream_data_uni",
2033
0
        ch->tx_init_max_stream_data_uni);
2034
0
    QLOG_U64("initial_max_streams_bidi",
2035
0
        ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc));
2036
0
    QLOG_U64("initial_max_streams_uni",
2037
0
        ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc));
2038
0
    QLOG_EVENT_END()
2039
29.8k
#endif
2040
2041
29.8k
    ch->got_local_transport_params = 1;
2042
2043
29.8k
    ok = 1;
2044
29.8k
err:
2045
29.8k
    if (wpkt_valid)
2046
0
        WPACKET_cleanup(&wpkt);
2047
29.8k
    BUF_MEM_free(buf_mem);
2048
29.8k
    return ok;
2049
29.8k
}
2050
2051
/*
2052
 * QUIC Channel: Ticker-Mutator
2053
 * ============================
2054
 */
2055
2056
/*
2057
 * The central ticker function called by the reactor. This does everything, or
2058
 * at least everything network I/O related. Best effort - not allowed to fail
2059
 * "loudly".
2060
 */
2061
void ossl_quic_channel_subtick(QUIC_CHANNEL *ch, QUIC_TICK_RESULT *res,
2062
    uint32_t flags)
2063
33.3M
{
2064
33.3M
    OSSL_TIME now, deadline;
2065
33.3M
    int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0;
2066
33.3M
    int notify_other_threads = 0;
2067
2068
    /*
2069
     * When we tick the QUIC connection, we do everything we need to do
2070
     * periodically. Network I/O handling will already have been performed
2071
     * as necessary by the QUIC port. Thus, in order, we:
2072
     *
2073
     *   - handle any packets the DEMUX has queued up for us;
2074
     *   - handle any timer events which are due to fire (ACKM, etc.);
2075
     *   - generate any packets which need to be sent;
2076
     *   - determine the time at which we should next be ticked.
2077
     */
2078
2079
    /*
2080
     * If the connection has not yet started, or we are in the TERMINATED state,
2081
     * there is nothing to do.
2082
     */
2083
33.3M
    if (ch->state == QUIC_CHANNEL_STATE_IDLE
2084
33.3M
        || ossl_quic_channel_is_terminated(ch)) {
2085
0
        res->net_read_desired = 0;
2086
0
        res->net_write_desired = 0;
2087
0
        res->notify_other_threads = 0;
2088
0
        res->tick_deadline = ossl_time_infinite();
2089
0
        return;
2090
0
    }
2091
2092
    /*
2093
     * If we are in the TERMINATING state, check if the terminating timer has
2094
     * expired.
2095
     */
2096
33.3M
    if (ossl_quic_channel_is_terminating(ch)) {
2097
232
        now = get_time(ch);
2098
2099
232
        if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
2100
4
            ch_on_terminating_timeout(ch);
2101
4
            res->net_read_desired = 0;
2102
4
            res->net_write_desired = 0;
2103
4
            res->notify_other_threads = 1;
2104
4
            res->tick_deadline = ossl_time_infinite();
2105
4
            return; /* abort normal processing, nothing to do */
2106
4
        }
2107
232
    }
2108
2109
33.3M
    if (!ch->port->engine->inhibit_tick) {
2110
        /* Handle RXKU timeouts. */
2111
33.3M
        ch_rxku_tick(ch);
2112
2113
33.3M
        do {
2114
            /* Process queued incoming packets. */
2115
33.3M
            ch->did_tls_tick = 0;
2116
33.3M
            ch->have_new_rx_secret = 0;
2117
33.3M
            ch_rx(ch, channel_only, &notify_other_threads);
2118
2119
            /*
2120
             * Allow the handshake layer to check for any new incoming data and
2121
             * generate new outgoing data.
2122
             */
2123
33.3M
            if (!ch->did_tls_tick)
2124
33.2M
                ch_tick_tls(ch, channel_only, &notify_other_threads);
2125
2126
            /*
2127
             * If the handshake layer gave us a new secret, we need to do RX
2128
             * again because packets that were not previously processable and
2129
             * were deferred might now be processable.
2130
             *
2131
             * TODO(QUIC FUTURE): Consider handling this in the yield_secret callback.
2132
             */
2133
33.3M
        } while (ch->have_new_rx_secret);
2134
33.3M
    }
2135
2136
    /*
2137
     * Handle any timer events which are due to fire; namely, the loss
2138
     * detection deadline and the idle timeout.
2139
     *
2140
     * ACKM ACK generation deadline is polled by TXP, so we don't need to
2141
     * handle it here.
2142
     */
2143
33.3M
    now = get_time(ch);
2144
33.3M
    if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
2145
        /*
2146
         * Idle timeout differs from normal protocol violation because we do
2147
         * not send a CONN_CLOSE frame; go straight to TERMINATED.
2148
         */
2149
10.0k
        if (!ch->port->engine->inhibit_tick)
2150
10.0k
            ch_on_idle_timeout(ch);
2151
2152
10.0k
        res->net_read_desired = 0;
2153
10.0k
        res->net_write_desired = 0;
2154
10.0k
        res->notify_other_threads = 1;
2155
10.0k
        res->tick_deadline = ossl_time_infinite();
2156
10.0k
        return;
2157
10.0k
    }
2158
2159
33.3M
    if (!ch->port->engine->inhibit_tick) {
2160
33.3M
        deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
2161
33.3M
        if (!ossl_time_is_zero(deadline)
2162
33.1M
            && ossl_time_compare(now, deadline) >= 0)
2163
215k
            ossl_ackm_on_timeout(ch->ackm);
2164
2165
        /* If a ping is due, inform TXP. */
2166
33.3M
        if (ossl_time_compare(now, ch->ping_deadline) >= 0) {
2167
8.67M
            int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
2168
2169
8.67M
            ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
2170
2171
            /*
2172
             * If we have no CC budget at this time we cannot process the above
2173
             * PING request immediately. In any case we have scheduled the
2174
             * request so bump the ping deadline. If we don't do this we will
2175
             * busy-loop endlessly as the above deadline comparison condition
2176
             * will still be met.
2177
             */
2178
8.67M
            ch_update_ping_deadline(ch);
2179
8.67M
        }
2180
2181
        /* Queue any data to be sent for transmission. */
2182
33.3M
        ch_tx(ch, &notify_other_threads);
2183
2184
        /* Do stream GC. */
2185
33.3M
        ossl_quic_stream_map_gc(&ch->qsm);
2186
33.3M
    }
2187
2188
    /* Determine the time at which we should next be ticked. */
2189
33.3M
    res->tick_deadline = ch_determine_next_tick_deadline(ch);
2190
2191
    /*
2192
     * Always process network input unless we are now terminated. Although we
2193
     * had not terminated at the beginning of this tick, network errors in
2194
     * ch_tx() may have caused us to transition to the Terminated state.
2195
     */
2196
33.3M
    res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
2197
2198
    /* We want to write to the network if we have any data in our TX queue. */
2199
33.3M
    res->net_write_desired
2200
33.3M
        = (!ossl_quic_channel_is_terminated(ch)
2201
33.3M
            && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
2202
2203
33.3M
    res->notify_other_threads = notify_other_threads;
2204
33.3M
}
2205
2206
static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads)
2207
33.4M
{
2208
33.4M
    uint64_t error_code;
2209
33.4M
    const char *error_msg;
2210
33.4M
    ERR_STATE *error_state = NULL;
2211
2212
33.4M
    if (channel_only)
2213
0
        return 1;
2214
2215
33.4M
    ch->did_tls_tick = 1;
2216
33.4M
    ossl_quic_tls_tick(ch->qtls);
2217
2218
33.4M
    if (ossl_quic_tls_get_error(ch->qtls, &error_code, &error_msg,
2219
33.4M
            &error_state)) {
2220
10.3k
        ossl_quic_channel_raise_protocol_error_state(ch, error_code, 0,
2221
10.3k
            error_msg, error_state);
2222
10.3k
        if (notify_other_threads != NULL)
2223
4.00k
            *notify_other_threads = 1;
2224
2225
10.3k
        return 0;
2226
10.3k
    }
2227
2228
33.4M
    return 1;
2229
33.4M
}
2230
2231
/* Check incoming forged packet limit and terminate connection if needed. */
2232
static void ch_rx_check_forged_pkt_limit(QUIC_CHANNEL *ch)
2233
61.4M
{
2234
61.4M
    uint32_t enc_level;
2235
61.4M
    uint64_t limit = UINT64_MAX, l;
2236
2237
61.4M
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
2238
193M
        enc_level < QUIC_ENC_LEVEL_NUM;
2239
172M
        ++enc_level) {
2240
        /*
2241
         * Different ELs can have different AEADs which can in turn impose
2242
         * different limits, so use the lowest value of any currently valid EL.
2243
         */
2244
172M
        if ((ch->el_discarded & (1U << enc_level)) != 0)
2245
34.3M
            continue;
2246
2247
138M
        if (enc_level > ch->rx_enc_level)
2248
39.9M
            break;
2249
2250
98.1M
        l = ossl_qrx_get_max_forged_pkt_count(ch->qrx, enc_level);
2251
98.1M
        if (l < limit)
2252
61.8M
            limit = l;
2253
98.1M
    }
2254
2255
61.4M
    if (ossl_qrx_get_cur_forged_pkt_count(ch->qrx) < limit)
2256
61.4M
        return;
2257
2258
0
    ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_AEAD_LIMIT_REACHED, 0,
2259
0
        "forgery limit");
2260
0
}
2261
2262
/* Process queued incoming packets and handle frames, if any. */
2263
static int ch_rx(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads)
2264
33.3M
{
2265
33.3M
    int handled_any = 0;
2266
33.3M
    const int closing = ossl_quic_channel_is_closing(ch);
2267
2268
33.3M
    if (!ch->is_server && !ch->have_sent_any_pkt)
2269
        /*
2270
         * We have not sent anything yet, therefore there is no need to check
2271
         * for incoming data.
2272
         */
2273
29.8k
        return 1;
2274
2275
35.4M
    for (;;) {
2276
35.4M
        assert(ch->qrx_pkt == NULL);
2277
2278
35.4M
        if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
2279
33.3M
            break;
2280
2281
        /* Track the amount of data received while in the closing state */
2282
2.10M
        if (closing)
2283
39
            ossl_quic_tx_packetiser_record_received_closing_bytes(
2284
39
                ch->txp, ch->qrx_pkt->hdr->len);
2285
2286
2.10M
        if (!handled_any) {
2287
2.08M
            ch_update_idle(ch);
2288
2.08M
            ch_update_ping_deadline(ch);
2289
2.08M
        }
2290
2291
2.10M
        ch_rx_handle_packet(ch, channel_only); /* best effort */
2292
2293
        /*
2294
         * Regardless of the outcome of frame handling, unref the packet.
2295
         * This will free the packet unless something added another
2296
         * reference to it during frame processing.
2297
         */
2298
2.10M
        ossl_qrx_pkt_release(ch->qrx_pkt);
2299
2.10M
        ch->qrx_pkt = NULL;
2300
2301
2.10M
        ch->have_sent_ack_eliciting_since_rx = 0;
2302
2.10M
        handled_any = 1;
2303
2.10M
    }
2304
2305
33.3M
    ch_rx_check_forged_pkt_limit(ch);
2306
2307
33.3M
    if (handled_any && notify_other_threads != NULL)
2308
2.08M
        *notify_other_threads = 1;
2309
2310
    /*
2311
     * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
2312
     * process one or more incoming packets.
2313
     */
2314
33.3M
    if (handled_any && closing)
2315
36
        ch->conn_close_queued = 1;
2316
2317
33.3M
    return 1;
2318
33.3M
}
2319
2320
static int bio_addr_eq(const BIO_ADDR *a, const BIO_ADDR *b)
2321
0
{
2322
0
    if (BIO_ADDR_family(a) != BIO_ADDR_family(b))
2323
0
        return 0;
2324
2325
0
    switch (BIO_ADDR_family(a)) {
2326
0
    case AF_INET:
2327
0
        return !memcmp(&a->s_in.sin_addr,
2328
0
                   &b->s_in.sin_addr,
2329
0
                   sizeof(a->s_in.sin_addr))
2330
0
            && a->s_in.sin_port == b->s_in.sin_port;
2331
0
#if OPENSSL_USE_IPV6
2332
0
    case AF_INET6:
2333
0
        return !memcmp(&a->s_in6.sin6_addr,
2334
0
                   &b->s_in6.sin6_addr,
2335
0
                   sizeof(a->s_in6.sin6_addr))
2336
0
            && a->s_in6.sin6_port == b->s_in6.sin6_port;
2337
0
#endif
2338
0
    default:
2339
0
        return 0; /* not supported */
2340
0
    }
2341
2342
0
    return 1;
2343
0
}
2344
2345
/* Handles the packet currently in ch->qrx_pkt->hdr. */
2346
static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only)
2347
2.10M
{
2348
2.10M
    uint32_t enc_level;
2349
2.10M
    int old_have_processed_any_pkt = ch->have_processed_any_pkt;
2350
2.10M
    OSSL_QTX_IOVEC iovec;
2351
2.10M
    PACKET vpkt;
2352
2.10M
    unsigned long supported_ver;
2353
2354
2.10M
    assert(ch->qrx_pkt != NULL);
2355
2356
    /*
2357
     * RFC 9000 s. 10.2.1 Closing Connection State:
2358
     *      An endpoint that is closing is not required to process any
2359
     *      received frame.
2360
     */
2361
2.10M
    if (!ossl_quic_channel_is_active(ch))
2362
1.29k
        return;
2363
2364
2.10M
    if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
2365
522k
        if (!ch->have_received_enc_pkt) {
2366
26.2k
            ch->cur_remote_dcid = ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
2367
26.2k
            ch->have_received_enc_pkt = 1;
2368
2369
            /*
2370
             * We change to using the SCID in the first Initial packet as the
2371
             * DCID.
2372
             */
2373
26.2k
            ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
2374
26.2k
        }
2375
2376
522k
        enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
2377
522k
        if ((ch->el_discarded & (1U << enc_level)) != 0)
2378
            /* Do not process packets from ELs we have already discarded. */
2379
23
            return;
2380
522k
    }
2381
2382
    /*
2383
     * RFC 9000 s. 9.6: "If a client receives packets from a new server address
2384
     * when the client has not initiated a migration to that address, the client
2385
     * SHOULD discard these packets."
2386
     *
2387
     * We need to be a bit careful here as due to the BIO abstraction layer an
2388
     * application is liable to be weird and lie to us about peer addresses.
2389
     * Only apply this check if we actually are using a real AF_INET or AF_INET6
2390
     * address.
2391
     */
2392
2.10M
    if (!ch->is_server
2393
2.10M
        && ch->qrx_pkt->peer != NULL
2394
0
        && (BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET
2395
0
#if OPENSSL_USE_IPV6
2396
0
            || BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET6
2397
0
#endif
2398
0
            )
2399
0
        && !bio_addr_eq(ch->qrx_pkt->peer, &ch->cur_peer_addr))
2400
0
        return;
2401
2402
2.10M
    if (!ch->is_server
2403
2.10M
        && ch->have_received_enc_pkt
2404
1.77M
        && ossl_quic_pkt_type_has_scid(ch->qrx_pkt->hdr->type)) {
2405
        /*
2406
         * RFC 9000 s. 7.2: "Once a client has received a valid Initial packet
2407
         * from the server, it MUST discard any subsequent packet it receives on
2408
         * that connection with a different SCID."
2409
         */
2410
1.73M
        if (!ossl_quic_conn_id_eq(&ch->qrx_pkt->hdr->src_conn_id,
2411
1.73M
                &ch->init_scid))
2412
1.18M
            return;
2413
1.73M
    }
2414
2415
923k
    if (ossl_quic_pkt_type_has_version(ch->qrx_pkt->hdr->type)
2416
732k
        && ch->qrx_pkt->hdr->version != QUIC_VERSION_1)
2417
        /*
2418
         * RFC 9000 s. 5.2.1: If a client receives a packet that uses a
2419
         * different version than it initially selected, it MUST discard the
2420
         * packet. We only ever use v1, so require it.
2421
         */
2422
0
        return;
2423
2424
923k
    if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_VERSION_NEG) {
2425
2426
        /*
2427
         * Sanity check.  Version negotiation packet MUST have a version
2428
         * value of 0 according to the RFC.  We must discard such packets
2429
         */
2430
149k
        if (ch->qrx_pkt->hdr->version != 0)
2431
0
            return;
2432
2433
        /*
2434
         * RFC 9000 s. 6.2: If a client receives a version negotiation
2435
         * packet, we need to do the following:
2436
         * a) If the negotiation packet lists the version we initially sent
2437
         *    then we must abandon this connection attempt
2438
         * b) We have to select a version from the list provided in the
2439
         *    version negotiation packet, and retry the connection attempt
2440
         *    in much the same way that ch_retry does, but we can reuse the
2441
         *    connection id values
2442
         */
2443
2444
149k
        if (old_have_processed_any_pkt == 1) {
2445
            /*
2446
             * We've gotten previous packets, need to discard this.
2447
             */
2448
149k
            return;
2449
149k
        }
2450
2451
        /*
2452
         * Indicate that we have processed a packet, as any subsequently
2453
         * received version negotiation packet must be discarded above
2454
         */
2455
158
        ch->have_processed_any_pkt = 1;
2456
2457
        /*
2458
         * Following the header, version negotiation packets
2459
         * contain an array of 32 bit integers representing
2460
         * the supported versions that the server honors
2461
         * this array, bounded by the hdr->len field
2462
         * needs to be traversed so that we can find a matching
2463
         * version
2464
         */
2465
158
        if (!PACKET_buf_init(&vpkt, ch->qrx_pkt->hdr->data,
2466
158
                ch->qrx_pkt->hdr->len))
2467
0
            return;
2468
2469
1.11k
        while (PACKET_remaining(&vpkt) > 0) {
2470
            /*
2471
             * We only support quic version 1 at the moment, so
2472
             * look to see if that's offered
2473
             */
2474
1.01k
            if (!PACKET_get_net_4(&vpkt, &supported_ver))
2475
0
                return;
2476
2477
1.01k
            if (supported_ver == QUIC_VERSION_1) {
2478
                /*
2479
                 * If the server supports version 1, set it as
2480
                 * the packetisers version
2481
                 */
2482
62
                ossl_quic_tx_packetiser_set_protocol_version(ch->txp, QUIC_VERSION_1);
2483
2484
                /*
2485
                 * And then request a restart of the QUIC connection
2486
                 */
2487
62
                if (!ch_restart(ch))
2488
0
                    ossl_quic_channel_raise_protocol_error(ch,
2489
62
                        OSSL_QUIC_ERR_INTERNAL_ERROR,
2490
62
                        0, "handling ver negotiation packet");
2491
62
                return;
2492
62
            }
2493
1.01k
        }
2494
2495
        /*
2496
         * If we get here, then the server doesn't support a version of the
2497
         * protocol that we can handle, abandon the connection
2498
         */
2499
96
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_CONNECTION_REFUSED,
2500
96
            0, "unsupported protocol version");
2501
96
        return;
2502
158
    }
2503
2504
773k
    ch->have_processed_any_pkt = 1;
2505
2506
    /*
2507
     * RFC 9000 s. 17.2: "An endpoint MUST treat receipt of a packet that has a
2508
     * non-zero value for [the reserved bits] after removing both packet and
2509
     * header protection as a connection error of type PROTOCOL_VIOLATION."
2510
     */
2511
773k
    if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)
2512
385k
        && ch->qrx_pkt->hdr->reserved != 0) {
2513
178
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
2514
178
            0, "packet header reserved bits");
2515
178
        return;
2516
178
    }
2517
2518
773k
    iovec.buf = ch->qrx_pkt->hdr->data;
2519
773k
    iovec.buf_len = ch->qrx_pkt->hdr->len;
2520
773k
    ossl_qlog_event_transport_packet_received(ch_get_qlog(ch), ch->qrx_pkt->hdr,
2521
773k
        ch->qrx_pkt->pn, &iovec, 1,
2522
773k
        ch->qrx_pkt->datagram_id);
2523
2524
    /* Handle incoming packet. */
2525
773k
    switch (ch->qrx_pkt->hdr->type) {
2526
388k
    case QUIC_PKT_TYPE_RETRY:
2527
388k
        if (ch->doing_retry || ch->is_server)
2528
            /*
2529
             * It is not allowed to ask a client to do a retry more than
2530
             * once. Clients may not send retries.
2531
             */
2532
62.2k
            return;
2533
2534
        /*
2535
         * RFC 9000 s 17.2.5.2: After the client has received and processed an
2536
         * Initial or Retry packet from the server, it MUST discard any
2537
         * subsequent Retry packets that it receives.
2538
         */
2539
325k
        if (ch->have_received_enc_pkt)
2540
60.2k
            return;
2541
2542
265k
        if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
2543
            /* Packets with zero-length Retry Tokens are invalid. */
2544
776
            return;
2545
2546
        /*
2547
         * TODO(QUIC FUTURE): Theoretically this should probably be in the QRX.
2548
         * However because validation is dependent on context (namely the
2549
         * client's initial DCID) we can't do this cleanly. In the future we
2550
         * should probably add a callback to the QRX to let it call us (via
2551
         * the DEMUX) and ask us about the correct original DCID, rather
2552
         * than allow the QRX to emit a potentially malformed packet to the
2553
         * upper layers. However, special casing this will do for now.
2554
         */
2555
264k
        if (!ossl_quic_validate_retry_integrity_tag(ch->port->engine->libctx,
2556
264k
                ch->port->engine->propq,
2557
264k
                ch->qrx_pkt->hdr,
2558
264k
                &ch->init_dcid))
2559
            /* Malformed retry packet, ignore. */
2560
264k
            return;
2561
2562
539
        if (!ch_retry(ch, ch->qrx_pkt->hdr->data,
2563
539
                ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
2564
539
                &ch->qrx_pkt->hdr->src_conn_id, old_have_processed_any_pkt))
2565
7
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR,
2566
539
                0, "handling retry packet");
2567
539
        break;
2568
2569
0
    case QUIC_PKT_TYPE_0RTT:
2570
0
        if (!ch->is_server)
2571
            /* Clients should never receive 0-RTT packets. */
2572
0
            return;
2573
2574
        /*
2575
         * TODO(QUIC 0RTT): Implement 0-RTT on the server side. We currently
2576
         * do not need to implement this as a client can only do 0-RTT if we
2577
         * have given it permission to in a previous session.
2578
         */
2579
0
        break;
2580
2581
322k
    case QUIC_PKT_TYPE_INITIAL:
2582
344k
    case QUIC_PKT_TYPE_HANDSHAKE:
2583
385k
    case QUIC_PKT_TYPE_1RTT:
2584
385k
        if (ch->is_server && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
2585
            /*
2586
             * We automatically drop INITIAL EL keys when first successfully
2587
             * decrypting a HANDSHAKE packet, as per the RFC.
2588
             */
2589
0
            ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
2590
2591
385k
        if (ch->rxku_in_progress
2592
22.7k
            && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_1RTT
2593
22.5k
            && ch->qrx_pkt->pn >= ch->rxku_trigger_pn
2594
22.0k
            && ch->qrx_pkt->key_epoch < ossl_qrx_get_key_epoch(ch->qrx)) {
2595
            /*
2596
             * RFC 9001 s. 6.4: Packets with higher packet numbers MUST be
2597
             * protected with either the same or newer packet protection keys
2598
             * than packets with lower packet numbers. An endpoint that
2599
             * successfully removes protection with old keys when newer keys
2600
             * were used for packets with lower packet numbers MUST treat this
2601
             * as a connection error of type KEY_UPDATE_ERROR.
2602
             */
2603
2
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_KEY_UPDATE_ERROR,
2604
2
                0, "new packet with old keys");
2605
2
            break;
2606
2
        }
2607
2608
385k
        if (!ch->is_server
2609
385k
            && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_INITIAL
2610
322k
            && ch->qrx_pkt->hdr->token_len > 0) {
2611
            /*
2612
             * RFC 9000 s. 17.2.2: Clients that receive an Initial packet with a
2613
             * non-zero Token Length field MUST either discard the packet or
2614
             * generate a connection error of type PROTOCOL_VIOLATION.
2615
             *
2616
             * TODO(QUIC FUTURE): consider the implications of RFC 9000 s. 10.2.3
2617
             * Immediate Close during the Handshake:
2618
             *      However, at the cost of reducing feedback about
2619
             *      errors for legitimate peers, some forms of denial of
2620
             *      service can be made more difficult for an attacker
2621
             *      if endpoints discard illegal packets rather than
2622
             *      terminating a connection with CONNECTION_CLOSE. For
2623
             *      this reason, endpoints MAY discard packets rather
2624
             *      than immediately close if errors are detected in
2625
             *      packets that lack authentication.
2626
             * I.e. should we drop this packet instead of closing the connection?
2627
             */
2628
37
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
2629
37
                0, "client received initial token");
2630
37
            break;
2631
37
        }
2632
2633
        /* This packet contains frames, pass to the RXDP. */
2634
385k
        ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
2635
2636
385k
        if (ch->did_crypto_frame)
2637
116k
            ch_tick_tls(ch, channel_only, NULL);
2638
2639
385k
        break;
2640
2641
0
    default:
2642
0
        assert(0);
2643
0
        break;
2644
773k
    }
2645
773k
}
2646
2647
/* Try to generate packets and if possible, flush them to the network. */
2648
static int ch_tx(QUIC_CHANNEL *ch, int *notify_other_threads)
2649
33.3M
{
2650
33.3M
    QUIC_TXP_STATUS status;
2651
33.3M
    int res;
2652
2653
    /*
2654
     * RFC 9000 s. 10.2.2: Draining Connection State:
2655
     *      While otherwise identical to the closing state, an endpoint
2656
     *      in the draining state MUST NOT send any packets.
2657
     * and:
2658
     *      An endpoint MUST NOT send further packets.
2659
     */
2660
33.3M
    if (ossl_quic_channel_is_draining(ch))
2661
527
        return 0;
2662
2663
33.3M
    if (ossl_quic_channel_is_closing(ch)) {
2664
        /*
2665
         * While closing, only send CONN_CLOSE if we've received more traffic
2666
         * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
2667
         * future calls to it generate CONN_CLOSE frames, so otherwise we would
2668
         * just constantly generate CONN_CLOSE frames.
2669
         *
2670
         * Confirming to RFC 9000 s. 10.2.1 Closing Connection State:
2671
         *      An endpoint SHOULD limit the rate at which it generates
2672
         *      packets in the closing state.
2673
         */
2674
14.7k
        if (!ch->conn_close_queued)
2675
142
            return 0;
2676
2677
14.5k
        ch->conn_close_queued = 0;
2678
14.5k
    }
2679
2680
    /* Do TXKU if we need to. */
2681
33.3M
    ch_maybe_trigger_spontaneous_txku(ch);
2682
2683
33.3M
    ch->rxku_pending_confirm_done = 0;
2684
2685
    /* Loop until we stop generating packets to send */
2686
34.4M
    do {
2687
        /*
2688
         * Send packet, if we need to. Best effort. The TXP consults the CC and
2689
         * applies any limitations imposed by it, so we don't need to do it here.
2690
         *
2691
         * Best effort. In particular if TXP fails for some reason we should
2692
         * still flush any queued packets which we already generated.
2693
         */
2694
34.4M
        res = ossl_quic_tx_packetiser_generate(ch->txp, &status);
2695
34.4M
        if (status.sent_pkt > 0) {
2696
1.13M
            ch->have_sent_any_pkt = 1; /* Packet(s) were sent */
2697
1.13M
            ch->port->have_sent_any_pkt = 1;
2698
2699
            /*
2700
             * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when
2701
             * sending an ack-eliciting packet if no other ack-eliciting packets
2702
             * have been sent since last receiving and processing a packet.'
2703
             */
2704
1.13M
            if (status.sent_ack_eliciting
2705
1.07M
                && !ch->have_sent_ack_eliciting_since_rx) {
2706
645k
                ch_update_idle(ch);
2707
645k
                ch->have_sent_ack_eliciting_since_rx = 1;
2708
645k
            }
2709
2710
1.13M
            if (!ch->is_server && status.sent_handshake)
2711
                /*
2712
                 * RFC 9001 s. 4.9.1: A client MUST discard Initial keys when it
2713
                 * first sends a Handshake packet.
2714
                 */
2715
136k
                ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
2716
2717
1.13M
            if (ch->rxku_pending_confirm_done)
2718
18.3k
                ch->rxku_pending_confirm = 0;
2719
2720
1.13M
            ch_update_ping_deadline(ch);
2721
1.13M
        }
2722
2723
34.4M
        if (!res) {
2724
            /*
2725
             * One case where TXP can fail is if we reach a TX PN of 2**62 - 1.
2726
             * As per RFC 9000 s. 12.3, if this happens we MUST close the
2727
             * connection without sending a CONNECTION_CLOSE frame. This is
2728
             * actually handled as an emergent consequence of our design, as the
2729
             * TX packetiser will never transmit another packet when the TX PN
2730
             * reaches the limit.
2731
             *
2732
             * Calling the below function terminates the connection; its attempt
2733
             * to schedule a CONNECTION_CLOSE frame will not actually cause a
2734
             * packet to be transmitted for this reason.
2735
             */
2736
2
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR,
2737
2
                0,
2738
2
                "internal error (txp generate)");
2739
2
            break;
2740
2
        }
2741
34.4M
    } while (status.sent_pkt > 0);
2742
2743
    /* Flush packets to network. */
2744
33.3M
    switch (ossl_qtx_flush_net(ch->qtx)) {
2745
33.3M
    case QTX_FLUSH_NET_RES_OK:
2746
33.3M
    case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
2747
        /* Best effort, done for now. */
2748
33.3M
        break;
2749
2750
0
    case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
2751
0
    default:
2752
        /* Permanent underlying network BIO, start terminating. */
2753
0
        ossl_quic_port_raise_net_error(ch->port, ch);
2754
0
        break;
2755
33.3M
    }
2756
2757
    /*
2758
     * If we have datagrams we have yet to successfully transmit, we need to
2759
     * notify other threads so that they can switch to polling on POLLOUT as
2760
     * well as POLLIN.
2761
     */
2762
33.3M
    if (ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0)
2763
0
        *notify_other_threads = 1;
2764
2765
33.3M
    return 1;
2766
33.3M
}
2767
2768
/* Determine next tick deadline. */
2769
static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
2770
61.4M
{
2771
61.4M
    OSSL_TIME deadline;
2772
61.4M
    int i;
2773
2774
61.4M
    if (ossl_quic_channel_is_terminated(ch))
2775
29
        return ossl_time_infinite();
2776
2777
61.4M
    deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
2778
61.4M
    if (ossl_time_is_zero(deadline))
2779
169k
        deadline = ossl_time_infinite();
2780
2781
    /*
2782
     * Check the ack deadline for all enc_levels that are actually provisioned.
2783
     * ACKs aren't restricted by CC.
2784
     */
2785
307M
    for (i = 0; i < QUIC_ENC_LEVEL_NUM; i++) {
2786
245M
        if (ossl_qtx_is_enc_level_provisioned(ch->qtx, i)) {
2787
74.2M
            deadline = ossl_time_min(deadline,
2788
74.2M
                ossl_ackm_get_ack_deadline(ch->ackm,
2789
74.2M
                    ossl_quic_enc_level_to_pn_space(i)));
2790
74.2M
        }
2791
245M
    }
2792
2793
    /*
2794
     * When do we need to send an ACK-eliciting packet to reset the idle
2795
     * deadline timer for the peer?
2796
     */
2797
61.4M
    if (!ossl_time_is_infinite(ch->ping_deadline))
2798
61.4M
        deadline = ossl_time_min(deadline, ch->ping_deadline);
2799
2800
    /* Apply TXP wakeup deadline. */
2801
61.4M
    deadline = ossl_time_min(deadline,
2802
61.4M
        ossl_quic_tx_packetiser_get_deadline(ch->txp));
2803
2804
    /* Is the terminating timer armed? */
2805
61.4M
    if (ossl_quic_channel_is_terminating(ch))
2806
26.5k
        deadline = ossl_time_min(deadline,
2807
26.5k
            ch->terminate_deadline);
2808
61.3M
    else if (!ossl_time_is_infinite(ch->idle_deadline))
2809
61.3M
        deadline = ossl_time_min(deadline,
2810
61.3M
            ch->idle_deadline);
2811
2812
    /* When does the RXKU process complete? */
2813
61.4M
    if (ch->rxku_in_progress)
2814
3.32M
        deadline = ossl_time_min(deadline, ch->rxku_update_end_deadline);
2815
2816
61.4M
    return deadline;
2817
61.4M
}
2818
2819
/*
2820
 * QUIC Channel: Lifecycle Events
2821
 * ==============================
2822
 */
2823
2824
/*
2825
 * Record a state transition. This is not necessarily a change to ch->state but
2826
 * also includes the handshake becoming complete or confirmed, etc.
2827
 */
2828
static void ch_record_state_transition(QUIC_CHANNEL *ch, uint32_t new_state)
2829
113k
{
2830
113k
    uint32_t old_state = ch->state;
2831
2832
113k
    ch->state = new_state;
2833
2834
113k
    ossl_qlog_event_connectivity_connection_state_updated(ch_get_qlog(ch),
2835
113k
        old_state,
2836
113k
        new_state,
2837
113k
        ch->handshake_complete,
2838
113k
        ch->handshake_confirmed);
2839
113k
}
2840
2841
static void free_peer_token(const unsigned char *token,
2842
    size_t token_len, void *arg)
2843
0
{
2844
0
    ossl_quic_free_peer_token((QUIC_TOKEN *)arg);
2845
0
}
2846
2847
int ossl_quic_channel_start(QUIC_CHANNEL *ch)
2848
29.8k
{
2849
29.8k
    QUIC_TOKEN *token;
2850
2851
29.8k
    if (ch->is_server)
2852
        /*
2853
         * This is not used by the server. The server moves to active
2854
         * automatically on receiving an incoming connection.
2855
         */
2856
0
        return 0;
2857
2858
29.8k
    if (ch->state != QUIC_CHANNEL_STATE_IDLE)
2859
        /* Calls to connect are idempotent */
2860
0
        return 1;
2861
2862
    /* Inform QTX of peer address. */
2863
29.8k
    if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2864
0
        return 0;
2865
2866
    /*
2867
     * Look to see if we have a token, and if so, set it on the packetiser
2868
     */
2869
29.8k
    if (!ch->is_server
2870
29.8k
        && ossl_quic_get_peer_token(ch->port->channel_ctx,
2871
29.8k
            &ch->cur_peer_addr,
2872
29.8k
            &token)
2873
0
        && !ossl_quic_tx_packetiser_set_initial_token(ch->txp, token->token,
2874
0
            token->token_len,
2875
0
            free_peer_token,
2876
0
            token))
2877
0
        free_peer_token(NULL, 0, token);
2878
2879
    /* Plug in secrets for the Initial EL. */
2880
29.8k
    if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,
2881
29.8k
            ch->port->engine->propq,
2882
29.8k
            &ch->init_dcid,
2883
29.8k
            ch->is_server,
2884
29.8k
            ch->qrx, ch->qtx))
2885
0
        return 0;
2886
2887
    /*
2888
     * Determine the QUIC Transport Parameters and serialize the transport
2889
     * parameters block. (For servers, we do this later as we must defer
2890
     * generation until we have received the client's transport parameters.)
2891
     */
2892
29.8k
    if (!ch->is_server && !ch->got_local_transport_params
2893
29.8k
        && !ch_generate_transport_params(ch))
2894
0
        return 0;
2895
2896
    /* Change state. */
2897
29.8k
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_ACTIVE);
2898
29.8k
    ch->doing_proactive_ver_neg = 0; /* not currently supported */
2899
2900
29.8k
    ossl_qlog_event_connectivity_connection_started(ch_get_qlog(ch),
2901
29.8k
        &ch->init_dcid);
2902
2903
    /* Handshake layer: start (e.g. send CH). */
2904
29.8k
    if (!ch_tick_tls(ch, /*channel_only=*/0, NULL))
2905
0
        return 0;
2906
2907
29.8k
    ossl_quic_reactor_tick(ossl_quic_port_get0_reactor(ch->port), 0); /* best effort */
2908
29.8k
    return 1;
2909
29.8k
}
2910
2911
static void free_token(const unsigned char *token, size_t token_len, void *arg)
2912
856
{
2913
856
    OPENSSL_free((char *)token);
2914
856
}
2915
2916
/* Start a locally initiated connection shutdown. */
2917
void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code,
2918
    const char *app_reason)
2919
0
{
2920
0
    QUIC_TERMINATE_CAUSE tcause = { 0 };
2921
2922
0
    if (ossl_quic_channel_is_term_any(ch))
2923
0
        return;
2924
2925
0
    tcause.app = 1;
2926
0
    tcause.error_code = app_error_code;
2927
0
    tcause.reason = app_reason;
2928
0
    tcause.reason_len = app_reason != NULL ? strlen(app_reason) : 0;
2929
0
    ch_start_terminating(ch, &tcause, 0);
2930
0
}
2931
2932
/**
2933
 * ch_restart - Restarts the QUIC channel by simulating loss of the initial
2934
 * packet. This forces the packet to be regenerated with the updated protocol
2935
 * version number.
2936
 *
2937
 * @ch: Pointer to the QUIC_CHANNEL structure.
2938
 *
2939
 * Returns 1 on success, 0 on failure.
2940
 */
2941
static int ch_restart(QUIC_CHANNEL *ch)
2942
62
{
2943
    /*
2944
     * Just pretend we lost our initial packet, so it gets
2945
     * regenerated, with our updated protocol version number
2946
     */
2947
62
    return ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
2948
62
        /* PN= */ 0);
2949
62
}
2950
2951
/* Called when a server asks us to do a retry. */
2952
static int ch_retry(QUIC_CHANNEL *ch,
2953
    const unsigned char *retry_token,
2954
    size_t retry_token_len,
2955
    const QUIC_CONN_ID *retry_scid,
2956
    int drop_later_pn)
2957
539
{
2958
539
    void *buf;
2959
539
    QUIC_PN pn = 0;
2960
2961
    /*
2962
     * RFC 9000 s. 17.2.5.1: "A client MUST discard a Retry packet that contains
2963
     * a SCID field that is identical to the DCID field of its initial packet."
2964
     */
2965
539
    if (ossl_quic_conn_id_eq(&ch->init_dcid, retry_scid))
2966
0
        return 1;
2967
2968
    /* We change to using the SCID in the Retry packet as the DCID. */
2969
539
    if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
2970
0
        return 0;
2971
2972
    /*
2973
     * Now we retry. We will release the Retry packet immediately, so copy
2974
     * the token.
2975
     */
2976
539
    if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
2977
0
        return 0;
2978
2979
539
    if (!ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf,
2980
539
            retry_token_len,
2981
539
            free_token, NULL)) {
2982
        /*
2983
         * This may fail if the token we receive is too big for us to ever be
2984
         * able to transmit in an outgoing Initial packet.
2985
         */
2986
7
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INVALID_TOKEN, 0,
2987
7
            "received oversize token");
2988
7
        OPENSSL_free(buf);
2989
7
        return 0;
2990
7
    }
2991
2992
532
    ch->retry_scid = *retry_scid;
2993
532
    ch->doing_retry = 1;
2994
2995
    /*
2996
     * If a retry isn't our first response, we need to drop packet number
2997
     * one instead (i.e. the case where we did version negotiation first
2998
     */
2999
532
    if (drop_later_pn == 1)
3000
289
        pn = 1;
3001
3002
    /*
3003
     * We need to stimulate the Initial EL to generate the first CRYPTO frame
3004
     * again. We can do this most cleanly by simply forcing the ACKM to consider
3005
     * the first Initial packet as lost, which it effectively was as the server
3006
     * hasn't processed it. This also maintains the desired behaviour with e.g.
3007
     * PNs not resetting and so on.
3008
     *
3009
     * The PN we used initially is always zero, because QUIC does not allow
3010
     * repeated retries.
3011
     */
3012
532
    if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
3013
532
            pn))
3014
0
        return 0;
3015
3016
    /*
3017
     * Plug in new secrets for the Initial EL. This is the only time we change
3018
     * the secrets for an EL after we already provisioned it.
3019
     */
3020
532
    if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,
3021
532
            ch->port->engine->propq,
3022
532
            &ch->retry_scid,
3023
532
            /*is_server=*/0,
3024
532
            ch->qrx, ch->qtx))
3025
0
        return 0;
3026
3027
532
    return 1;
3028
532
}
3029
3030
/* Called when an EL is to be discarded. */
3031
static int ch_discard_el(QUIC_CHANNEL *ch,
3032
    uint32_t enc_level)
3033
263k
{
3034
263k
    if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
3035
0
        return 0;
3036
3037
263k
    if ((ch->el_discarded & (1U << enc_level)) != 0)
3038
        /* Already done. */
3039
234k
        return 1;
3040
3041
    /* Best effort for all of these. */
3042
29.0k
    ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
3043
29.0k
    ossl_qrx_discard_enc_level(ch->qrx, enc_level);
3044
29.0k
    ossl_qtx_discard_enc_level(ch->qtx, enc_level);
3045
3046
29.0k
    if (enc_level != QUIC_ENC_LEVEL_0RTT) {
3047
29.0k
        uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
3048
3049
29.0k
        ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
3050
3051
        /* We should still have crypto streams at this point. */
3052
29.0k
        if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
3053
29.0k
            || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
3054
0
            return 0;
3055
3056
        /* Get rid of the crypto stream state for the EL. */
3057
29.0k
        ossl_quic_sstream_free(ch->crypto_send[pn_space]);
3058
29.0k
        ch->crypto_send[pn_space] = NULL;
3059
3060
29.0k
        ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
3061
29.0k
        ch->crypto_recv[pn_space] = NULL;
3062
29.0k
    }
3063
3064
29.0k
    ch->el_discarded |= (1U << enc_level);
3065
29.0k
    return 1;
3066
29.0k
}
3067
3068
/* Intended to be called by the RXDP. */
3069
int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
3070
544k
{
3071
544k
    if (ch->handshake_confirmed)
3072
537k
        return 1;
3073
3074
6.61k
    if (!ch->handshake_complete) {
3075
        /*
3076
         * Does not make sense for handshake to be confirmed before it is
3077
         * completed.
3078
         */
3079
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
3080
0
            OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
3081
0
            "handshake cannot be confirmed "
3082
0
            "before it is completed");
3083
0
        return 0;
3084
0
    }
3085
3086
6.61k
    ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
3087
6.61k
    ch->handshake_confirmed = 1;
3088
6.61k
    ch_record_state_transition(ch, ch->state);
3089
6.61k
    ossl_ackm_on_handshake_confirmed(ch->ackm);
3090
6.61k
    return 1;
3091
6.61k
}
3092
3093
/*
3094
 * Master function used when we want to start tearing down a connection:
3095
 *
3096
 *   - If the connection is still IDLE we can go straight to TERMINATED;
3097
 *
3098
 *   - If we are already TERMINATED this is a no-op.
3099
 *
3100
 *   - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
3101
 *     from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
3102
 *
3103
 *   - If we are TERMINATING - DRAINING, we remain here until the terminating
3104
 *     timer expires.
3105
 *
3106
 *   - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
3107
 *     if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
3108
 *     that we are considered to have caused a termination if we sent the first
3109
 *     CONNECTION_CLOSE frame, even if it is caused by a peer protocol
3110
 *     violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
3111
 *     TERMINATING - DRAINING.
3112
 *
3113
 * We record the termination cause structure passed on the first call only.
3114
 * Any successive calls have their termination cause data discarded;
3115
 * once we start sending a CONNECTION_CLOSE frame, we don't change the details
3116
 * in it.
3117
 *
3118
 * This conforms to RFC 9000 s. 10.2.1: Closing Connection State:
3119
 *      To minimize the state that an endpoint maintains for a closing
3120
 *      connection, endpoints MAY send the exact same packet in response
3121
 *      to any received packet.
3122
 *
3123
 * We don't drop any connection state (specifically packet protection keys)
3124
 * even though we are permitted to.  This conforms to RFC 9000 s. 10.2.1:
3125
 * Closing Connection State:
3126
 *       An endpoint MAY retain packet protection keys for incoming
3127
 *       packets to allow it to read and process a CONNECTION_CLOSE frame.
3128
 *
3129
 * Note that we do not conform to these two from the same section:
3130
 *      An endpoint's selected connection ID and the QUIC version
3131
 *      are sufficient information to identify packets for a closing
3132
 *      connection; the endpoint MAY discard all other connection state.
3133
 * and:
3134
 *      An endpoint MAY drop packet protection keys when entering the
3135
 *      closing state and send a packet containing a CONNECTION_CLOSE
3136
 *      frame in response to any UDP datagram that is received.
3137
 */
3138
static void copy_tcause(QUIC_TERMINATE_CAUSE *dst,
3139
    const QUIC_TERMINATE_CAUSE *src)
3140
9.88k
{
3141
    /*
3142
     * do not override reason once it got set.
3143
     */
3144
9.88k
    if (dst->reason != NULL)
3145
0
        return;
3146
3147
9.88k
    dst->error_code = src->error_code;
3148
9.88k
    dst->frame_type = src->frame_type;
3149
9.88k
    dst->app = src->app;
3150
9.88k
    dst->remote = src->remote;
3151
3152
9.88k
    if (src->reason != NULL && src->reason_len > 0) {
3153
9.74k
        size_t l = src->reason_len;
3154
9.74k
        char *r;
3155
3156
9.74k
        if (l >= SIZE_MAX)
3157
0
            --l;
3158
3159
        /*
3160
         * If this fails, dst->reason becomes NULL and we simply do not use a
3161
         * reason. This ensures termination is infallible.
3162
         */
3163
9.74k
        dst->reason = r = OPENSSL_memdup(src->reason, l + 1);
3164
9.74k
        if (r == NULL)
3165
0
            return;
3166
3167
9.74k
        r[l] = '\0';
3168
9.74k
        dst->reason_len = l;
3169
9.74k
    }
3170
9.88k
}
3171
3172
void ossl_quic_channel_set_tcause(QUIC_CHANNEL *ch, uint64_t app_error_code,
3173
    const char *app_reason)
3174
0
{
3175
0
    QUIC_TERMINATE_CAUSE tcause = { 0 };
3176
3177
0
    tcause.app = 1;
3178
0
    tcause.error_code = app_error_code;
3179
0
    tcause.reason = app_reason;
3180
0
    tcause.reason_len = app_reason != NULL ? strlen(app_reason) : 0;
3181
0
    copy_tcause(&ch->terminate_cause, &tcause);
3182
0
}
3183
3184
static void ch_start_terminating(QUIC_CHANNEL *ch,
3185
    const QUIC_TERMINATE_CAUSE *tcause,
3186
    int force_immediate)
3187
10.0k
{
3188
    /* No point sending anything if we haven't sent anything yet. */
3189
10.0k
    if (!ch->have_sent_any_pkt)
3190
0
        force_immediate = 1;
3191
3192
10.0k
    switch (ch->state) {
3193
0
    default:
3194
0
    case QUIC_CHANNEL_STATE_IDLE:
3195
0
        copy_tcause(&ch->terminate_cause, tcause);
3196
0
        ch_on_terminating_timeout(ch);
3197
0
        break;
3198
3199
9.88k
    case QUIC_CHANNEL_STATE_ACTIVE:
3200
9.88k
        copy_tcause(&ch->terminate_cause, tcause);
3201
3202
9.88k
        ossl_qlog_event_connectivity_connection_closed(ch_get_qlog(ch), tcause);
3203
3204
9.88k
        if (!force_immediate) {
3205
9.88k
            ossl_quic_channel_notify_flush_done(ch);
3206
9.88k
        } else {
3207
0
            ch_on_terminating_timeout(ch);
3208
0
        }
3209
9.88k
        break;
3210
3211
3
    case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
3212
3
        if (force_immediate)
3213
0
            ch_on_terminating_timeout(ch);
3214
3
        else if (tcause->remote)
3215
            /*
3216
             * RFC 9000 s. 10.2.2 Draining Connection State:
3217
             *  An endpoint MAY enter the draining state from the
3218
             *  closing state if it receives a CONNECTION_CLOSE frame,
3219
             *  which indicates that the peer is also closing or draining.
3220
             */
3221
3
            ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATING_DRAINING);
3222
3223
3
        break;
3224
3225
204
    case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
3226
        /*
3227
         * Other than in the force-immediate case, we remain here until the
3228
         * timeout expires.
3229
         */
3230
204
        if (force_immediate)
3231
0
            ch_on_terminating_timeout(ch);
3232
3233
204
        break;
3234
3235
0
    case QUIC_CHANNEL_STATE_TERMINATED:
3236
        /* No-op. */
3237
0
        break;
3238
10.0k
    }
3239
10.0k
}
3240
3241
/* For RXDP use. */
3242
void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
3243
    OSSL_QUIC_FRAME_CONN_CLOSE *f)
3244
1.97k
{
3245
1.97k
    QUIC_TERMINATE_CAUSE tcause = { 0 };
3246
3247
1.97k
    if (!ossl_quic_channel_is_active(ch))
3248
1.13k
        return;
3249
3250
844
    tcause.remote = 1;
3251
844
    tcause.app = f->is_app;
3252
844
    tcause.error_code = f->error_code;
3253
844
    tcause.frame_type = f->frame_type;
3254
844
    tcause.reason = f->reason;
3255
844
    tcause.reason_len = f->reason_len;
3256
844
    ch_start_terminating(ch, &tcause, 0);
3257
844
}
3258
3259
static void free_frame_data(unsigned char *buf, size_t buf_len, void *arg)
3260
11.2k
{
3261
11.2k
    OPENSSL_free(buf);
3262
11.2k
}
3263
3264
static int ch_enqueue_retire_conn_id(QUIC_CHANNEL *ch, uint64_t seq_num)
3265
11.2k
{
3266
11.2k
    BUF_MEM *buf_mem = NULL;
3267
11.2k
    WPACKET wpkt;
3268
11.2k
    size_t l;
3269
3270
11.2k
    ossl_quic_srtm_remove(ch->srtm, ch, seq_num);
3271
3272
11.2k
    if ((buf_mem = BUF_MEM_new()) == NULL)
3273
0
        goto err;
3274
3275
11.2k
    if (!WPACKET_init(&wpkt, buf_mem))
3276
0
        goto err;
3277
3278
11.2k
    if (!ossl_quic_wire_encode_frame_retire_conn_id(&wpkt, seq_num)) {
3279
0
        WPACKET_cleanup(&wpkt);
3280
0
        goto err;
3281
0
    }
3282
3283
11.2k
    WPACKET_finish(&wpkt);
3284
11.2k
    if (!WPACKET_get_total_written(&wpkt, &l))
3285
0
        goto err;
3286
3287
11.2k
    if (ossl_quic_cfq_add_frame(ch->cfq, 1, QUIC_PN_SPACE_APP,
3288
11.2k
            OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID, 0,
3289
11.2k
            (unsigned char *)buf_mem->data, l,
3290
11.2k
            free_frame_data, NULL)
3291
11.2k
        == NULL)
3292
0
        goto err;
3293
3294
11.2k
    buf_mem->data = NULL;
3295
11.2k
    BUF_MEM_free(buf_mem);
3296
11.2k
    return 1;
3297
3298
0
err:
3299
0
    ossl_quic_channel_raise_protocol_error(ch,
3300
0
        OSSL_QUIC_ERR_INTERNAL_ERROR,
3301
0
        OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3302
0
        "internal error enqueueing retire conn id");
3303
0
    BUF_MEM_free(buf_mem);
3304
0
    return 0;
3305
11.2k
}
3306
3307
void ossl_quic_channel_on_new_conn_id(QUIC_CHANNEL *ch,
3308
    OSSL_QUIC_FRAME_NEW_CONN_ID *f)
3309
17.8k
{
3310
17.8k
    uint64_t new_remote_seq_num = ch->cur_remote_seq_num;
3311
17.8k
    uint64_t new_retire_prior_to = ch->cur_retire_prior_to;
3312
3313
17.8k
    if (!ossl_quic_channel_is_active(ch))
3314
707
        return;
3315
3316
    /* We allow only two active connection ids; first check some constraints */
3317
17.1k
    if (ch->cur_remote_dcid.id_len == 0) {
3318
        /* Changing from 0 length connection id is disallowed */
3319
0
        ossl_quic_channel_raise_protocol_error(ch,
3320
0
            OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
3321
0
            OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3322
0
            "zero length connection id in use");
3323
3324
0
        return;
3325
0
    }
3326
3327
17.1k
    if (f->seq_num > new_remote_seq_num)
3328
6.87k
        new_remote_seq_num = f->seq_num;
3329
17.1k
    if (f->retire_prior_to > new_retire_prior_to)
3330
6.49k
        new_retire_prior_to = f->retire_prior_to;
3331
3332
    /*
3333
     * RFC 9000-5.1.1: An endpoint MUST NOT provide more connection IDs
3334
     * than the peer's limit.
3335
     *
3336
     * After processing a NEW_CONNECTION_ID frame and adding and retiring
3337
     * active connection IDs, if the number of active connection IDs exceeds
3338
     * the value advertised in its active_connection_id_limit transport
3339
     * parameter, an endpoint MUST close the connection with an error of
3340
     * type CONNECTION_ID_LIMIT_ERROR.
3341
     */
3342
17.1k
    if (new_remote_seq_num - new_retire_prior_to > 1) {
3343
623
        ossl_quic_channel_raise_protocol_error(ch,
3344
623
            OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
3345
623
            OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3346
623
            "active_connection_id limit violated");
3347
623
        return;
3348
623
    }
3349
3350
    /*
3351
     * RFC 9000-5.1.1: An endpoint MAY send connection IDs that temporarily
3352
     * exceed a peer's limit if the NEW_CONNECTION_ID frame also requires
3353
     * the retirement of any excess, by including a sufficiently large
3354
     * value in the Retire Prior To field.
3355
     *
3356
     * RFC 9000-5.1.2: An endpoint SHOULD allow for sending and tracking
3357
     * a number of RETIRE_CONNECTION_ID frames of at least twice the value
3358
     * of the active_connection_id_limit transport parameter.  An endpoint
3359
     * MUST NOT forget a connection ID without retiring it, though it MAY
3360
     * choose to treat having connection IDs in need of retirement that
3361
     * exceed this limit as a connection error of type CONNECTION_ID_LIMIT_ERROR.
3362
     *
3363
     * We are a little bit more liberal than the minimum mandated.
3364
     */
3365
16.5k
    if (new_retire_prior_to - ch->cur_retire_prior_to > 10) {
3366
57
        ossl_quic_channel_raise_protocol_error(ch,
3367
57
            OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
3368
57
            OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3369
57
            "retiring connection id limit violated");
3370
3371
57
        return;
3372
57
    }
3373
3374
16.4k
    if (new_remote_seq_num > ch->cur_remote_seq_num) {
3375
        /* Add new stateless reset token */
3376
6.19k
        if (!ossl_quic_srtm_add(ch->srtm, ch, new_remote_seq_num,
3377
6.19k
                &f->stateless_reset)) {
3378
0
            ossl_quic_channel_raise_protocol_error(
3379
0
                ch, OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
3380
0
                OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3381
0
                "unable to store stateless reset token");
3382
3383
0
            return;
3384
0
        }
3385
6.19k
        ch->cur_remote_seq_num = new_remote_seq_num;
3386
6.19k
        ch->cur_remote_dcid = f->conn_id;
3387
6.19k
        ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid);
3388
6.19k
    }
3389
3390
    /*
3391
     * RFC 9000-5.1.2: Upon receipt of an increased Retire Prior To
3392
     * field, the peer MUST stop using the corresponding connection IDs
3393
     * and retire them with RETIRE_CONNECTION_ID frames before adding the
3394
     * newly provided connection ID to the set of active connection IDs.
3395
     */
3396
3397
    /*
3398
     * Note: RFC 9000 s. 19.15 says:
3399
     *   "An endpoint that receives a NEW_CONNECTION_ID frame with a sequence
3400
     *    number smaller than the Retire Prior To field of a previously received
3401
     *    NEW_CONNECTION_ID frame MUST send a corresponding
3402
     *    RETIRE_CONNECTION_ID frame that retires the newly received connection
3403
     *    ID, unless it has already done so for that sequence number."
3404
     *
3405
     * Since we currently always queue RETIRE_CONN_ID frames based on the Retire
3406
     * Prior To field of a NEW_CONNECTION_ID frame immediately upon receiving
3407
     * that NEW_CONNECTION_ID frame, by definition this will always be met.
3408
     * This may change in future when we change our CID handling.
3409
     */
3410
27.6k
    while (new_retire_prior_to > ch->cur_retire_prior_to) {
3411
11.2k
        if (!ch_enqueue_retire_conn_id(ch, ch->cur_retire_prior_to))
3412
0
            break;
3413
11.2k
        ++ch->cur_retire_prior_to;
3414
11.2k
    }
3415
16.4k
}
3416
3417
static void ch_save_err_state(QUIC_CHANNEL *ch)
3418
25.4k
{
3419
25.4k
    if (ch->err_state == NULL)
3420
25.4k
        ch->err_state = OSSL_ERR_STATE_new();
3421
3422
25.4k
    if (ch->err_state == NULL)
3423
0
        return;
3424
3425
25.4k
    OSSL_ERR_STATE_save(ch->err_state);
3426
25.4k
}
3427
3428
void ossl_quic_channel_inject(QUIC_CHANNEL *ch, QUIC_URXE *e)
3429
4.33M
{
3430
4.33M
    ossl_qrx_inject_urxe(ch->qrx, e);
3431
4.33M
}
3432
3433
void ossl_quic_channel_inject_pkt(QUIC_CHANNEL *ch, OSSL_QRX_PKT *qpkt)
3434
0
{
3435
0
    ossl_qrx_inject_pkt(ch->qrx, qpkt);
3436
0
}
3437
3438
void ossl_quic_channel_on_stateless_reset(QUIC_CHANNEL *ch)
3439
20
{
3440
20
    QUIC_TERMINATE_CAUSE tcause = { 0 };
3441
3442
20
    tcause.error_code = OSSL_QUIC_ERR_NO_ERROR;
3443
20
    tcause.remote = 1;
3444
20
    ch_start_terminating(ch, &tcause, 0);
3445
20
}
3446
3447
void ossl_quic_channel_raise_net_error(QUIC_CHANNEL *ch)
3448
0
{
3449
0
    QUIC_TERMINATE_CAUSE tcause = { 0 };
3450
3451
0
    if (ch->net_error)
3452
0
        return;
3453
3454
0
    ch->net_error = 1;
3455
3456
0
    tcause.error_code = OSSL_QUIC_ERR_INTERNAL_ERROR;
3457
0
    tcause.reason = "network BIO I/O error";
3458
0
    tcause.reason_len = strlen(tcause.reason);
3459
3460
    /*
3461
     * Skip Terminating state and go directly to Terminated, no point trying to
3462
     * send CONNECTION_CLOSE if we cannot communicate.
3463
     */
3464
0
    ch_start_terminating(ch, &tcause, 1);
3465
0
}
3466
3467
int ossl_quic_channel_net_error(QUIC_CHANNEL *ch)
3468
61.3M
{
3469
61.3M
    return ch->net_error;
3470
61.3M
}
3471
3472
void ossl_quic_channel_restore_err_state(QUIC_CHANNEL *ch)
3473
43.6k
{
3474
43.6k
    if (ch == NULL)
3475
0
        return;
3476
3477
43.6k
    if (!ossl_quic_port_is_running(ch->port))
3478
0
        ossl_quic_port_restore_err_state(ch->port);
3479
43.6k
    else
3480
43.6k
        OSSL_ERR_STATE_restore(ch->err_state);
3481
43.6k
}
3482
3483
void ossl_quic_channel_raise_protocol_error_loc(QUIC_CHANNEL *ch,
3484
    uint64_t error_code,
3485
    uint64_t frame_type,
3486
    const char *reason,
3487
    ERR_STATE *err_state,
3488
    const char *src_file,
3489
    int src_line,
3490
    const char *src_func)
3491
47.7k
{
3492
47.7k
    QUIC_TERMINATE_CAUSE tcause = { 0 };
3493
47.7k
    int err_reason = error_code == OSSL_QUIC_ERR_INTERNAL_ERROR
3494
47.7k
        ? ERR_R_INTERNAL_ERROR
3495
47.7k
        : SSL_R_QUIC_PROTOCOL_ERROR;
3496
47.7k
    const char *err_str = ossl_quic_err_to_string(error_code);
3497
47.7k
    const char *err_str_pfx = " (", *err_str_sfx = ")";
3498
47.7k
    const char *ft_str = NULL;
3499
47.7k
    const char *ft_str_pfx = " (", *ft_str_sfx = ")";
3500
3501
47.7k
    if (ch->protocol_error)
3502
        /* Only the first call to this function matters. */
3503
22.3k
        return;
3504
3505
25.4k
    if (err_str == NULL) {
3506
8.58k
        err_str = "";
3507
8.58k
        err_str_pfx = "";
3508
8.58k
        err_str_sfx = "";
3509
8.58k
    }
3510
3511
    /*
3512
     * If we were provided an underlying error state, restore it and then append
3513
     * our ERR on top as a "cover letter" error.
3514
     */
3515
25.4k
    if (err_state != NULL)
3516
42
        OSSL_ERR_STATE_restore(err_state);
3517
3518
25.4k
    if (frame_type != 0) {
3519
14.2k
        ft_str = ossl_quic_frame_type_to_string(frame_type);
3520
14.2k
        if (ft_str == NULL) {
3521
5.01k
            ft_str = "";
3522
5.01k
            ft_str_pfx = "";
3523
5.01k
            ft_str_sfx = "";
3524
5.01k
        }
3525
3526
14.2k
        ERR_raise_data(ERR_LIB_SSL, err_reason,
3527
14.2k
            "QUIC error code: 0x%llx%s%s%s "
3528
14.2k
            "(triggered by frame type: 0x%llx%s%s%s), reason: \"%s\"",
3529
14.2k
            (unsigned long long)error_code,
3530
14.2k
            err_str_pfx, err_str, err_str_sfx,
3531
14.2k
            (unsigned long long)frame_type,
3532
14.2k
            ft_str_pfx, ft_str, ft_str_sfx,
3533
14.2k
            reason);
3534
14.2k
    } else {
3535
11.1k
        ERR_raise_data(ERR_LIB_SSL, err_reason,
3536
11.1k
            "QUIC error code: 0x%llx%s%s%s, reason: \"%s\"",
3537
11.1k
            (unsigned long long)error_code,
3538
11.1k
            err_str_pfx, err_str, err_str_sfx,
3539
11.1k
            reason);
3540
11.1k
    }
3541
3542
25.4k
    if (src_file != NULL)
3543
25.4k
        ERR_set_debug(src_file, src_line, src_func);
3544
3545
25.4k
    ch_save_err_state(ch);
3546
3547
25.4k
    tcause.error_code = error_code;
3548
25.4k
    tcause.frame_type = frame_type;
3549
25.4k
    tcause.reason = reason;
3550
25.4k
    tcause.reason_len = strlen(reason);
3551
3552
25.4k
    ch->protocol_error = 1;
3553
25.4k
    ch_start_terminating(ch, &tcause, 0);
3554
25.4k
}
3555
3556
/*
3557
 * Called once the terminating timer expires, meaning we move from TERMINATING
3558
 * to TERMINATED.
3559
 */
3560
static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
3561
33
{
3562
33
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATED);
3563
33
}
3564
3565
/*
3566
 * Determines the effective idle timeout duration. This is based on the idle
3567
 * timeout values that we and our peer signalled in transport parameters
3568
 * but have some limits applied.
3569
 */
3570
static OSSL_TIME ch_get_effective_idle_timeout_duration(QUIC_CHANNEL *ch)
3571
29.5M
{
3572
29.5M
    OSSL_TIME pto;
3573
3574
29.5M
    if (ch->max_idle_timeout == 0)
3575
0
        return ossl_time_infinite();
3576
3577
    /*
3578
     * RFC 9000 s. 10.1: Idle Timeout
3579
     *  To avoid excessively small idle timeout periods, endpoints
3580
     *  MUST increase the idle timeout period to be at least three
3581
     *  times the current Probe Timeout (PTO). This allows for
3582
     *  multiple PTOs to expire, and therefore multiple probes to
3583
     *  be sent and lost, prior to idle timeout.
3584
     */
3585
29.5M
    pto = ossl_ackm_get_pto_duration(ch->ackm);
3586
29.5M
    return ossl_time_max(ossl_ms2time(ch->max_idle_timeout),
3587
29.5M
        ossl_time_multiply(pto, 3));
3588
29.5M
}
3589
3590
/*
3591
 * Updates our idle deadline. Called when an event happens which should bump the
3592
 * idle timeout.
3593
 */
3594
static void ch_update_idle(QUIC_CHANNEL *ch)
3595
5.10M
{
3596
5.10M
    ch->idle_deadline = ossl_time_add(get_time(ch),
3597
5.10M
        ch_get_effective_idle_timeout_duration(ch));
3598
5.10M
}
3599
3600
/*
3601
 * Updates our ping deadline, which determines when we next generate a ping if
3602
 * we don't have any other ACK-eliciting frames to send.
3603
 */
3604
static void ch_update_ping_deadline(QUIC_CHANNEL *ch)
3605
24.4M
{
3606
24.4M
    OSSL_TIME max_span, idle_duration;
3607
3608
24.4M
    idle_duration = ch_get_effective_idle_timeout_duration(ch);
3609
24.4M
    if (ossl_time_is_infinite(idle_duration)) {
3610
0
        ch->ping_deadline = ossl_time_infinite();
3611
0
        return;
3612
0
    }
3613
3614
    /*
3615
     * Maximum amount of time without traffic before we send a PING to keep
3616
     * the connection open. Usually we use max_idle_timeout/2, but ensure
3617
     * the period never exceeds the assumed NAT interval to ensure NAT
3618
     * devices don't have their state time out (RFC 9000 s. 10.1.2).
3619
     */
3620
24.4M
    max_span = ossl_time_divide(idle_duration, 2);
3621
24.4M
    max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL);
3622
24.4M
    ch->ping_deadline = ossl_time_add(get_time(ch), max_span);
3623
24.4M
}
3624
3625
/* Called when the idle timeout expires. */
3626
static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
3627
17.4k
{
3628
    /*
3629
     * Idle timeout does not have an error code associated with it because a
3630
     * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
3631
     * TERMINATED anyway.
3632
     */
3633
17.4k
    ch->terminate_cause.app = 0;
3634
17.4k
    ch->terminate_cause.error_code = OSSL_QUIC_LOCAL_ERR_IDLE_TIMEOUT;
3635
17.4k
    ch->terminate_cause.frame_type = 0;
3636
3637
17.4k
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATED);
3638
17.4k
}
3639
3640
/**
3641
 * @brief Common handler for initializing a new QUIC connection.
3642
 *
3643
 * This function configures a QUIC channel (`QUIC_CHANNEL *ch`) for a new
3644
 * connection by setting the peer address, connection IDs, and necessary
3645
 * callbacks. It establishes initial secrets, sets up logging, and performs
3646
 * required transitions for the channel state.
3647
 *
3648
 * @param ch       Pointer to the QUIC channel being initialized.
3649
 * @param peer     Address of the peer to which the channel connects.
3650
 * @param peer_scid Peer-specified source connection ID.
3651
 * @param peer_dcid Peer-specified destination connection ID.
3652
 * @param peer_odcid Peer-specified original destination connection ID
3653
 *                   may be NULL if retry frame not sent to client
3654
 * @return         1 on success, 0 on failure to set required elements.
3655
 */
3656
static int ch_on_new_conn_common(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
3657
    const QUIC_CONN_ID *peer_scid,
3658
    const QUIC_CONN_ID *peer_dcid,
3659
    const QUIC_CONN_ID *peer_odcid)
3660
0
{
3661
    /* Note our newly learnt peer address and CIDs. */
3662
0
    if (!BIO_ADDR_copy(&ch->cur_peer_addr, peer))
3663
0
        return 0;
3664
3665
0
    ch->init_dcid = *peer_dcid;
3666
0
    ch->cur_remote_dcid = *peer_scid;
3667
0
    ch->odcid.id_len = 0;
3668
3669
0
    if (peer_odcid != NULL)
3670
0
        ch->odcid = *peer_odcid;
3671
3672
    /* Inform QTX of peer address. */
3673
0
    if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
3674
0
        return 0;
3675
3676
    /* Inform TXP of desired CIDs. */
3677
0
    if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
3678
0
        return 0;
3679
3680
0
    if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
3681
0
        return 0;
3682
3683
    /* Setup QLOG, which did not happen earlier due to lacking an Initial ODCID. */
3684
0
    ossl_qtx_set_qlog_cb(ch->qtx, ch_get_qlog_cb, ch);
3685
0
    ossl_quic_tx_packetiser_set_qlog_cb(ch->txp, ch_get_qlog_cb, ch);
3686
3687
    /*
3688
     * Plug in secrets for the Initial EL. secrets for QRX were created in
3689
     * port_default_packet_handler() already.
3690
     */
3691
0
    if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,
3692
0
            ch->port->engine->propq,
3693
0
            &ch->init_dcid,
3694
0
            /*is_server=*/1,
3695
0
            NULL, ch->qtx))
3696
0
        return 0;
3697
3698
    /* Register the peer ODCID in the LCIDM. */
3699
0
    if (!ossl_quic_lcidm_enrol_odcid(ch->lcidm, ch, peer_odcid == NULL ? &ch->init_dcid : peer_odcid))
3700
0
        return 0;
3701
3702
    /* Change state. */
3703
0
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_ACTIVE);
3704
0
    ch->doing_proactive_ver_neg = 0; /* not currently supported */
3705
0
    return 1;
3706
0
}
3707
3708
/* Called when we, as a server, get a new incoming connection. */
3709
int ossl_quic_channel_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
3710
    const QUIC_CONN_ID *peer_scid,
3711
    const QUIC_CONN_ID *peer_dcid)
3712
0
{
3713
0
    if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
3714
0
        return 0;
3715
3716
    /* Generate an Initial LCID we will use for the connection. */
3717
0
    if (!ossl_quic_lcidm_generate_initial(ch->lcidm, ch, &ch->cur_local_cid))
3718
0
        return 0;
3719
3720
0
    return ch_on_new_conn_common(ch, peer, peer_scid, peer_dcid, NULL);
3721
0
}
3722
3723
/**
3724
 * Binds a QUIC channel to a specific peer's address and connection IDs.
3725
 *
3726
 * This function is used to establish a binding between a QUIC channel and a
3727
 * peer's address and connection IDs. The binding is performed only if the
3728
 * channel is idle and is on the server side. The peer's destination connection
3729
 * ID (`peer_dcid`) is mandatory, and the channel's current local connection ID
3730
 * is set to this value.
3731
 *
3732
 * @param ch          Pointer to the QUIC_CHANNEL structure representing the
3733
 *                    channel to be bound.
3734
 * @param peer        Pointer to a BIO_ADDR structure representing the peer's
3735
 *                    address.
3736
 * @param peer_scid   Pointer to the peer's source connection ID (QUIC_CONN_ID).
3737
 * @param peer_dcid   Pointer to the peer's destination connection ID
3738
 *                    (QUIC_CONN_ID). This must not be NULL.
3739
 * @param peer_odcid  Pointer to the original destination connection ID
3740
 *                    (QUIC_CONN_ID) chosen by the peer in its first initial
3741
 *                    packet received without a token.
3742
 *
3743
 * @return 1 on success, or 0 on failure if the conditions for binding are not
3744
 *         met (e.g., channel is not idle or not a server, or binding fails).
3745
 */
3746
int ossl_quic_bind_channel(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
3747
    const QUIC_CONN_ID *peer_scid,
3748
    const QUIC_CONN_ID *peer_dcid,
3749
    const QUIC_CONN_ID *peer_odcid)
3750
0
{
3751
0
    if (peer_dcid == NULL)
3752
0
        return 0;
3753
3754
0
    if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
3755
0
        return 0;
3756
3757
0
    ch->cur_local_cid = *peer_dcid;
3758
0
    if (!ossl_quic_lcidm_bind_channel(ch->lcidm, ch, peer_dcid))
3759
0
        return 0;
3760
3761
    /*
3762
     * peer_odcid <=> is initial dst conn id chosen by peer in its
3763
     * first initial packet we received without token.
3764
     */
3765
0
    return ch_on_new_conn_common(ch, peer, peer_scid, peer_dcid, peer_odcid);
3766
0
}
3767
3768
SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)
3769
0
{
3770
0
    return ch->tls;
3771
0
}
3772
3773
static int ch_init_new_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs,
3774
    int can_send, int can_recv)
3775
149k
{
3776
149k
    uint64_t rxfc_wnd;
3777
149k
    int server_init = ossl_quic_stream_is_server_init(qs);
3778
149k
    int local_init = (ch->is_server == server_init);
3779
149k
    int is_uni = !ossl_quic_stream_is_bidi(qs);
3780
3781
149k
    if (can_send)
3782
43.7k
        if ((qs->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL)
3783
0
            goto err;
3784
3785
149k
    if (can_recv)
3786
149k
        if ((qs->rstream = ossl_quic_rstream_new(NULL, NULL, 0)) == NULL)
3787
0
            goto err;
3788
3789
    /* TXFC */
3790
149k
    if (!ossl_quic_txfc_init(&qs->txfc, &ch->conn_txfc))
3791
0
        goto err;
3792
3793
149k
    if (ch->got_remote_transport_params) {
3794
        /*
3795
         * If we already got peer TPs we need to apply the initial CWM credit
3796
         * now. If we didn't already get peer TPs this will be done
3797
         * automatically for all extant streams when we do.
3798
         */
3799
149k
        if (can_send) {
3800
43.7k
            uint64_t cwm;
3801
3802
43.7k
            if (is_uni)
3803
0
                cwm = ch->rx_init_max_stream_data_uni;
3804
43.7k
            else if (local_init)
3805
5.21k
                cwm = ch->rx_init_max_stream_data_bidi_local;
3806
38.5k
            else
3807
38.5k
                cwm = ch->rx_init_max_stream_data_bidi_remote;
3808
3809
43.7k
            ossl_quic_txfc_bump_cwm(&qs->txfc, cwm);
3810
43.7k
        }
3811
149k
    }
3812
3813
    /* RXFC */
3814
149k
    if (!can_recv)
3815
0
        rxfc_wnd = 0;
3816
149k
    else if (is_uni)
3817
105k
        rxfc_wnd = ch->tx_init_max_stream_data_uni;
3818
43.7k
    else if (local_init)
3819
5.21k
        rxfc_wnd = ch->tx_init_max_stream_data_bidi_local;
3820
38.5k
    else
3821
38.5k
        rxfc_wnd = ch->tx_init_max_stream_data_bidi_remote;
3822
3823
149k
    if (!ossl_quic_rxfc_init(&qs->rxfc, &ch->conn_rxfc,
3824
149k
            rxfc_wnd,
3825
149k
            DEFAULT_STREAM_RXFC_MAX_WND_MUL * rxfc_wnd,
3826
149k
            get_time, ch))
3827
0
        goto err;
3828
3829
149k
    return 1;
3830
3831
0
err:
3832
0
    ossl_quic_sstream_free(qs->sstream);
3833
0
    qs->sstream = NULL;
3834
0
    ossl_quic_rstream_free(qs->rstream);
3835
0
    qs->rstream = NULL;
3836
0
    return 0;
3837
149k
}
3838
3839
static uint64_t *ch_get_local_stream_next_ordinal_ptr(QUIC_CHANNEL *ch,
3840
    int is_uni)
3841
13.5k
{
3842
13.5k
    return is_uni ? &ch->next_local_stream_ordinal_uni
3843
13.5k
                  : &ch->next_local_stream_ordinal_bidi;
3844
13.5k
}
3845
3846
static const uint64_t *ch_get_local_stream_max_ptr(const QUIC_CHANNEL *ch,
3847
    int is_uni)
3848
0
{
3849
0
    return is_uni ? &ch->max_local_streams_uni
3850
0
                  : &ch->max_local_streams_bidi;
3851
0
}
3852
3853
static const QUIC_RXFC *ch_get_remote_stream_count_rxfc(const QUIC_CHANNEL *ch,
3854
    int is_uni)
3855
0
{
3856
0
    return is_uni ? &ch->max_streams_uni_rxfc
3857
0
                  : &ch->max_streams_bidi_rxfc;
3858
0
}
3859
3860
int ossl_quic_channel_is_new_local_stream_admissible(QUIC_CHANNEL *ch,
3861
    int is_uni)
3862
8.38k
{
3863
8.38k
    const uint64_t *p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni);
3864
3865
8.38k
    return ossl_quic_stream_map_is_local_allowed_by_stream_limit(&ch->qsm,
3866
8.38k
        *p_next_ordinal,
3867
8.38k
        is_uni);
3868
8.38k
}
3869
3870
uint64_t ossl_quic_channel_get_local_stream_count_avail(const QUIC_CHANNEL *ch,
3871
    int is_uni)
3872
0
{
3873
0
    const uint64_t *p_next_ordinal, *p_max;
3874
3875
0
    p_next_ordinal = ch_get_local_stream_next_ordinal_ptr((QUIC_CHANNEL *)ch,
3876
0
        is_uni);
3877
0
    p_max = ch_get_local_stream_max_ptr(ch, is_uni);
3878
3879
0
    return *p_max - *p_next_ordinal;
3880
0
}
3881
3882
uint64_t ossl_quic_channel_get_remote_stream_count_avail(const QUIC_CHANNEL *ch,
3883
    int is_uni)
3884
0
{
3885
0
    return ossl_quic_rxfc_get_credit(ch_get_remote_stream_count_rxfc(ch, is_uni));
3886
0
}
3887
3888
QUIC_STREAM *ossl_quic_channel_new_stream_local(QUIC_CHANNEL *ch, int is_uni)
3889
5.21k
{
3890
5.21k
    QUIC_STREAM *qs;
3891
5.21k
    int type;
3892
5.21k
    uint64_t stream_id;
3893
5.21k
    uint64_t *p_next_ordinal;
3894
3895
5.21k
    type = ch->is_server ? QUIC_STREAM_INITIATOR_SERVER
3896
5.21k
                         : QUIC_STREAM_INITIATOR_CLIENT;
3897
3898
5.21k
    p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni);
3899
3900
5.21k
    if (is_uni)
3901
0
        type |= QUIC_STREAM_DIR_UNI;
3902
5.21k
    else
3903
5.21k
        type |= QUIC_STREAM_DIR_BIDI;
3904
3905
5.21k
    if (*p_next_ordinal >= ((uint64_t)1) << 62)
3906
0
        return NULL;
3907
3908
5.21k
    stream_id = ((*p_next_ordinal) << 2) | type;
3909
3910
5.21k
    if ((qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id, type)) == NULL)
3911
0
        return NULL;
3912
3913
    /* Locally-initiated stream, so we always want a send buffer. */
3914
5.21k
    if (!ch_init_new_stream(ch, qs, /*can_send=*/1, /*can_recv=*/!is_uni))
3915
0
        goto err;
3916
3917
5.21k
    ++*p_next_ordinal;
3918
5.21k
    return qs;
3919
3920
0
err:
3921
0
    ossl_quic_stream_map_release(&ch->qsm, qs);
3922
0
    return NULL;
3923
5.21k
}
3924
3925
QUIC_STREAM *ossl_quic_channel_new_stream_remote(QUIC_CHANNEL *ch,
3926
    uint64_t stream_id)
3927
144k
{
3928
144k
    uint64_t peer_role;
3929
144k
    int is_uni;
3930
144k
    QUIC_STREAM *qs;
3931
3932
144k
    peer_role = ch->is_server
3933
144k
        ? QUIC_STREAM_INITIATOR_CLIENT
3934
144k
        : QUIC_STREAM_INITIATOR_SERVER;
3935
3936
144k
    if ((stream_id & QUIC_STREAM_INITIATOR_MASK) != peer_role)
3937
0
        return NULL;
3938
3939
144k
    is_uni = ((stream_id & QUIC_STREAM_DIR_MASK) == QUIC_STREAM_DIR_UNI);
3940
3941
144k
    qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id,
3942
144k
        stream_id & (QUIC_STREAM_INITIATOR_MASK | QUIC_STREAM_DIR_MASK));
3943
144k
    if (qs == NULL)
3944
0
        return NULL;
3945
3946
144k
    if (!ch_init_new_stream(ch, qs, /*can_send=*/!is_uni, /*can_recv=*/1))
3947
0
        goto err;
3948
3949
144k
    if (ch->incoming_stream_auto_reject)
3950
0
        ossl_quic_channel_reject_stream(ch, qs);
3951
144k
    else
3952
144k
        ossl_quic_stream_map_push_accept_queue(&ch->qsm, qs);
3953
3954
144k
    return qs;
3955
3956
0
err:
3957
0
    ossl_quic_stream_map_release(&ch->qsm, qs);
3958
0
    return NULL;
3959
144k
}
3960
3961
void ossl_quic_channel_set_incoming_stream_auto_reject(QUIC_CHANNEL *ch,
3962
    int enable,
3963
    uint64_t aec)
3964
115k
{
3965
115k
    ch->incoming_stream_auto_reject = (enable != 0);
3966
115k
    ch->incoming_stream_auto_reject_aec = aec;
3967
115k
}
3968
3969
void ossl_quic_channel_reject_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs)
3970
0
{
3971
0
    ossl_quic_stream_map_stop_sending_recv_part(&ch->qsm, qs,
3972
0
        ch->incoming_stream_auto_reject_aec);
3973
3974
0
    ossl_quic_stream_map_reset_stream_send_part(&ch->qsm, qs,
3975
0
        ch->incoming_stream_auto_reject_aec);
3976
0
    qs->deleted = 1;
3977
3978
0
    ossl_quic_stream_map_update_state(&ch->qsm, qs);
3979
0
}
3980
3981
/* Replace local connection ID in TXP and DEMUX for testing purposes. */
3982
int ossl_quic_channel_replace_local_cid(QUIC_CHANNEL *ch,
3983
    const QUIC_CONN_ID *conn_id)
3984
0
{
3985
    /* Remove the current LCID from the LCIDM. */
3986
0
    if (!ossl_quic_lcidm_debug_remove(ch->lcidm, &ch->cur_local_cid))
3987
0
        return 0;
3988
0
    ch->cur_local_cid = *conn_id;
3989
    /* Set in the TXP, used only for long header packets. */
3990
0
    if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
3991
0
        return 0;
3992
    /* Add the new LCID to the LCIDM. */
3993
0
    if (!ossl_quic_lcidm_debug_add(ch->lcidm, ch, &ch->cur_local_cid,
3994
0
            100))
3995
0
        return 0;
3996
0
    return 1;
3997
0
}
3998
3999
void ossl_quic_channel_set_msg_callback(QUIC_CHANNEL *ch,
4000
    ossl_msg_cb msg_callback,
4001
    SSL *msg_callback_ssl)
4002
29.8k
{
4003
29.8k
    ch->msg_callback = msg_callback;
4004
29.8k
    ch->msg_callback_ssl = msg_callback_ssl;
4005
29.8k
    ossl_qtx_set_msg_callback(ch->qtx, msg_callback, msg_callback_ssl);
4006
29.8k
    ossl_quic_tx_packetiser_set_msg_callback(ch->txp, msg_callback,
4007
29.8k
        msg_callback_ssl);
4008
    /*
4009
     * postpone msg callback setting for tserver until port calls
4010
     * port_bind_channel().
4011
     */
4012
29.8k
    if (ch->is_tserver_ch == 0)
4013
29.8k
        ossl_qrx_set_msg_callback(ch->qrx, msg_callback, msg_callback_ssl);
4014
29.8k
}
4015
4016
void ossl_quic_channel_set_msg_callback_arg(QUIC_CHANNEL *ch,
4017
    void *msg_callback_arg)
4018
29.8k
{
4019
29.8k
    ch->msg_callback_arg = msg_callback_arg;
4020
29.8k
    ossl_qtx_set_msg_callback_arg(ch->qtx, msg_callback_arg);
4021
29.8k
    ossl_quic_tx_packetiser_set_msg_callback_arg(ch->txp, msg_callback_arg);
4022
4023
    /*
4024
     * postpone msg callback setting for tserver until port calls
4025
     * port_bind_channel().
4026
     */
4027
29.8k
    if (ch->is_tserver_ch == 0)
4028
29.8k
        ossl_qrx_set_msg_callback_arg(ch->qrx, msg_callback_arg);
4029
29.8k
}
4030
4031
void ossl_quic_channel_set_txku_threshold_override(QUIC_CHANNEL *ch,
4032
    uint64_t tx_pkt_threshold)
4033
0
{
4034
0
    ch->txku_threshold_override = tx_pkt_threshold;
4035
0
}
4036
4037
uint64_t ossl_quic_channel_get_tx_key_epoch(QUIC_CHANNEL *ch)
4038
0
{
4039
0
    return ossl_qtx_get_key_epoch(ch->qtx);
4040
0
}
4041
4042
uint64_t ossl_quic_channel_get_rx_key_epoch(QUIC_CHANNEL *ch)
4043
0
{
4044
0
    return ossl_qrx_get_key_epoch(ch->qrx);
4045
0
}
4046
4047
int ossl_quic_channel_trigger_txku(QUIC_CHANNEL *ch)
4048
0
{
4049
0
    if (!txku_allowed(ch))
4050
0
        return 0;
4051
4052
0
    ch->ku_locally_initiated = 1;
4053
0
    ch_trigger_txku(ch);
4054
0
    return 1;
4055
0
}
4056
4057
int ossl_quic_channel_ping(QUIC_CHANNEL *ch)
4058
0
{
4059
0
    int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
4060
4061
0
    ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
4062
4063
0
    return 1;
4064
0
}
4065
4066
uint16_t ossl_quic_channel_get_diag_num_rx_ack(QUIC_CHANNEL *ch)
4067
0
{
4068
0
    return ch->diag_num_rx_ack;
4069
0
}
4070
4071
void ossl_quic_channel_get_diag_local_cid(QUIC_CHANNEL *ch, QUIC_CONN_ID *cid)
4072
0
{
4073
0
    *cid = ch->cur_local_cid;
4074
0
}
4075
4076
int ossl_quic_channel_have_generated_transport_params(const QUIC_CHANNEL *ch)
4077
0
{
4078
0
    return ch->got_local_transport_params;
4079
0
}
4080
4081
void ossl_quic_channel_set_max_idle_timeout_request(QUIC_CHANNEL *ch, uint64_t ms)
4082
0
{
4083
0
    ch->max_idle_timeout_local_req = ms;
4084
0
}
4085
uint64_t ossl_quic_channel_get_max_idle_timeout_request(const QUIC_CHANNEL *ch)
4086
0
{
4087
0
    return ch->max_idle_timeout_local_req;
4088
0
}
4089
4090
uint64_t ossl_quic_channel_get_max_idle_timeout_peer_request(const QUIC_CHANNEL *ch)
4091
0
{
4092
0
    return ch->max_idle_timeout_remote_req;
4093
0
}
4094
4095
uint64_t ossl_quic_channel_get_max_idle_timeout_actual(const QUIC_CHANNEL *ch)
4096
0
{
4097
0
    return ch->max_idle_timeout;
4098
0
}