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