Coverage Report

Created: 2025-12-08 06:22

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