Coverage Report

Created: 2025-06-13 06:58

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