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