Coverage Report

Created: 2025-12-31 06:58

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