Coverage Report

Created: 2025-08-28 07:07

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