Coverage Report

Created: 2026-03-09 06:55

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