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