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