Coverage Report

Created: 2025-12-14 06:48

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