Coverage Report

Created: 2026-05-20 07:05

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