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