Coverage Report

Created: 2026-07-23 06:28

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