Coverage Report

Created: 2024-07-27 06:35

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