2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include <openssl/rand.h>
11 #include <openssl/err.h>
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"
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.
24 * TODO(QUIC): Implement address validation and anti-amplification
25 * TODO(QUIC): Implement retry logic
28 #define INIT_DCID_LEN 8
29 #define INIT_CRYPTO_BUF_LEN 8192
30 #define INIT_APP_BUF_LEN 8192
33 * Interval before we force a PING to ensure NATs don't timeout. This is based
34 * on the lowest commonly seen value of 30 seconds as cited in RFC 9000 s.
37 #define MAX_NAT_INTERVAL (ossl_ms2time(25000))
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.
45 #define DEFAULT_MAX_ACK_DELAY QUIC_DEFAULT_MAX_ACK_DELAY
47 static void ch_rx_pre(QUIC_CHANNEL *ch);
48 static int ch_rx(QUIC_CHANNEL *ch);
49 static int ch_tx(QUIC_CHANNEL *ch);
50 static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags);
51 static void ch_rx_handle_packet(QUIC_CHANNEL *ch);
52 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch);
53 static 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);
57 static void ch_cleanup(QUIC_CHANNEL *ch);
58 static int ch_generate_transport_params(QUIC_CHANNEL *ch);
59 static int ch_on_transport_params(const unsigned char *params,
62 static int ch_on_handshake_alert(void *arg, unsigned char alert_code);
63 static int ch_on_handshake_complete(void *arg);
64 static 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,
69 static int ch_on_crypto_recv_record(const unsigned char **buf,
70 size_t *bytes_read, void *arg);
71 static int ch_on_crypto_release_record(size_t bytes_read, void *arg);
72 static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
73 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
74 size_t *consumed, void *arg);
75 static OSSL_TIME get_time(void *arg);
76 static uint64_t get_stream_limit(int uni, void *arg);
77 static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg);
78 static void rxku_detected(QUIC_PN pn, void *arg);
79 static 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);
83 static void ch_update_idle(QUIC_CHANNEL *ch);
84 static int ch_discard_el(QUIC_CHANNEL *ch,
86 static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
87 static void ch_update_idle(QUIC_CHANNEL *ch);
88 static void ch_update_ping_deadline(QUIC_CHANNEL *ch);
89 static void ch_raise_net_error(QUIC_CHANNEL *ch);
90 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
91 static void ch_start_terminating(QUIC_CHANNEL *ch,
92 const QUIC_TERMINATE_CAUSE *tcause,
94 static void ch_default_packet_handler(QUIC_URXE *e, void *arg);
95 static 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);
98 static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
101 static int gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid)
103 if (len > QUIC_MAX_CONN_ID_LEN)
106 cid->id_len = (unsigned char)len;
108 if (RAND_bytes_ex(libctx, cid->id, len, len * 8) != 1) {
117 * QUIC Channel Initialization and Teardown
118 * ========================================
120 #define DEFAULT_INIT_CONN_RXFC_WND (2 * 1024 * 1024)
121 #define DEFAULT_CONN_RXFC_MAX_WND_MUL 5
123 #define DEFAULT_INIT_STREAM_RXFC_WND (2 * 1024 * 1024)
124 #define DEFAULT_STREAM_RXFC_MAX_WND_MUL 5
126 #define DEFAULT_INIT_CONN_MAX_STREAMS 100
128 static int ch_init(QUIC_CHANNEL *ch)
130 OSSL_QUIC_TX_PACKETISER_ARGS txp_args = {0};
131 OSSL_QTX_ARGS qtx_args = {0};
132 OSSL_QRX_ARGS qrx_args = {0};
133 QUIC_TLS_ARGS tls_args = {0};
135 size_t rx_short_cid_len = ch->is_server ? INIT_DCID_LEN : 0;
137 /* For clients, generate our initial DCID. */
139 && !gen_rand_conn_id(ch->libctx, INIT_DCID_LEN, &ch->init_dcid))
142 /* We plug in a network write BIO to the QTX later when we get one. */
143 qtx_args.libctx = ch->libctx;
144 qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN;
145 ch->rx_max_udp_payload_size = qtx_args.mdpl;
147 ch->ping_deadline = ossl_time_infinite();
149 ch->qtx = ossl_qtx_new(&qtx_args);
153 ch->txpim = ossl_quic_txpim_new();
154 if (ch->txpim == NULL)
157 ch->cfq = ossl_quic_cfq_new();
161 if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
165 * Note: The TP we transmit governs what the peer can transmit and thus
166 * applies to the RXFC.
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;
172 if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
173 DEFAULT_INIT_CONN_RXFC_WND,
174 DEFAULT_CONN_RXFC_MAX_WND_MUL *
175 DEFAULT_INIT_CONN_RXFC_WND,
179 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
180 if (!ossl_quic_rxfc_init_standalone(&ch->crypto_rxfc[pn_space],
185 if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_bidi_rxfc,
186 DEFAULT_INIT_CONN_MAX_STREAMS,
190 if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_uni_rxfc,
191 DEFAULT_INIT_CONN_MAX_STREAMS,
195 if (!ossl_statm_init(&ch->statm))
199 ch->cc_method = &ossl_cc_newreno_method;
200 if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL)
203 if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm,
204 ch->cc_method, ch->cc_data)) == NULL)
207 if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch,
208 &ch->max_streams_bidi_rxfc,
209 &ch->max_streams_uni_rxfc,
215 /* We use a zero-length SCID. */
216 txp_args.cur_dcid = ch->init_dcid;
217 txp_args.ack_delay_exponent = 3;
218 txp_args.qtx = ch->qtx;
219 txp_args.txpim = ch->txpim;
220 txp_args.cfq = ch->cfq;
221 txp_args.ackm = ch->ackm;
222 txp_args.qsm = &ch->qsm;
223 txp_args.conn_txfc = &ch->conn_txfc;
224 txp_args.conn_rxfc = &ch->conn_rxfc;
225 txp_args.max_streams_bidi_rxfc = &ch->max_streams_bidi_rxfc;
226 txp_args.max_streams_uni_rxfc = &ch->max_streams_uni_rxfc;
227 txp_args.cc_method = ch->cc_method;
228 txp_args.cc_data = ch->cc_data;
229 txp_args.now = get_time;
230 txp_args.now_arg = ch;
232 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
233 ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_BUF_LEN);
234 if (ch->crypto_send[pn_space] == NULL)
237 txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
240 ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
244 ossl_quic_tx_packetiser_set_ack_tx_cb(ch->txp, ch_on_txp_ack_tx, ch);
246 if ((ch->demux = ossl_quic_demux_new(/*BIO=*/NULL,
247 /*Short CID Len=*/rx_short_cid_len,
248 get_time, ch)) == NULL)
252 * If we are a server, setup our handler for packets not corresponding to
253 * any known DCID on our end. This is for handling clients establishing new
257 ossl_quic_demux_set_default_handler(ch->demux,
258 ch_default_packet_handler,
261 qrx_args.libctx = ch->libctx;
262 qrx_args.demux = ch->demux;
263 qrx_args.short_conn_id_len = rx_short_cid_len;
264 qrx_args.max_deferred = 32;
266 if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
269 if (!ossl_qrx_set_late_validation_cb(ch->qrx,
274 if (!ossl_qrx_set_key_update_cb(ch->qrx,
279 if (!ch->is_server && !ossl_qrx_add_dst_conn_id(ch->qrx, &txp_args.cur_scid))
282 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
283 ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL, 0);
284 if (ch->crypto_recv[pn_space] == NULL)
288 /* Plug in the TLS handshake layer. */
289 tls_args.s = ch->tls;
290 tls_args.crypto_send_cb = ch_on_crypto_send;
291 tls_args.crypto_send_cb_arg = ch;
292 tls_args.crypto_recv_rcd_cb = ch_on_crypto_recv_record;
293 tls_args.crypto_recv_rcd_cb_arg = ch;
294 tls_args.crypto_release_rcd_cb = ch_on_crypto_release_record;
295 tls_args.crypto_release_rcd_cb_arg = ch;
296 tls_args.yield_secret_cb = ch_on_handshake_yield_secret;
297 tls_args.yield_secret_cb_arg = ch;
298 tls_args.got_transport_params_cb = ch_on_transport_params;
299 tls_args.got_transport_params_cb_arg= ch;
300 tls_args.handshake_complete_cb = ch_on_handshake_complete;
301 tls_args.handshake_complete_cb_arg = ch;
302 tls_args.alert_cb = ch_on_handshake_alert;
303 tls_args.alert_cb_arg = ch;
304 tls_args.is_server = ch->is_server;
306 if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
309 ch->tx_max_ack_delay = DEFAULT_MAX_ACK_DELAY;
310 ch->rx_max_ack_delay = QUIC_DEFAULT_MAX_ACK_DELAY;
311 ch->rx_ack_delay_exp = QUIC_DEFAULT_ACK_DELAY_EXP;
312 ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
313 ch->max_idle_timeout = QUIC_DEFAULT_IDLE_TIMEOUT;
314 ch->tx_enc_level = QUIC_ENC_LEVEL_INITIAL;
315 ch->rx_enc_level = QUIC_ENC_LEVEL_INITIAL;
316 ch->txku_threshold_override = UINT64_MAX;
318 ossl_ackm_set_tx_max_ack_delay(ch->ackm, ossl_ms2time(ch->tx_max_ack_delay));
319 ossl_ackm_set_rx_max_ack_delay(ch->ackm, ossl_ms2time(ch->rx_max_ack_delay));
322 * Determine the QUIC Transport Parameters and serialize the transport
323 * parameters block. (For servers, we do this later as we must defer
324 * generation until we have received the client's transport parameters.)
326 if (!ch->is_server && !ch_generate_transport_params(ch))
330 ossl_quic_reactor_init(&ch->rtor, ch_tick, ch,
331 ch_determine_next_tick_deadline(ch));
339 static void ch_cleanup(QUIC_CHANNEL *ch)
343 if (ch->ackm != NULL)
344 for (pn_space = QUIC_PN_SPACE_INITIAL;
345 pn_space < QUIC_PN_SPACE_NUM;
347 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
349 ossl_quic_tx_packetiser_free(ch->txp);
350 ossl_quic_txpim_free(ch->txpim);
351 ossl_quic_cfq_free(ch->cfq);
352 ossl_qtx_free(ch->qtx);
353 if (ch->cc_data != NULL)
354 ch->cc_method->free(ch->cc_data);
356 ossl_statm_destroy(&ch->statm);
357 ossl_ackm_free(ch->ackm);
360 ossl_quic_stream_map_cleanup(&ch->qsm);
362 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
363 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
364 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
367 ossl_qrx_pkt_release(ch->qrx_pkt);
370 ossl_quic_tls_free(ch->qtls);
371 ossl_qrx_free(ch->qrx);
372 ossl_quic_demux_free(ch->demux);
373 OPENSSL_free(ch->local_transport_params);
374 OSSL_ERR_STATE_free(ch->err_state);
377 QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
379 QUIC_CHANNEL *ch = NULL;
381 if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
384 ch->libctx = args->libctx;
385 ch->propq = args->propq;
386 ch->is_server = args->is_server;
388 ch->mutex = args->mutex;
389 ch->now_cb = args->now_cb;
390 ch->now_cb_arg = args->now_cb_arg;
400 void ossl_quic_channel_free(QUIC_CHANNEL *ch)
409 /* Set mutator callbacks for test framework support */
410 int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch,
411 ossl_mutate_packet_cb mutatecb,
412 ossl_finish_mutate_cb finishmutatecb,
418 ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
422 int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
424 *peer_addr = ch->cur_peer_addr;
428 int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
430 ch->cur_peer_addr = *peer_addr;
434 QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
439 QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
444 OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
449 QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
452 return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
455 int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
457 return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
460 static int ossl_quic_channel_is_closing(const QUIC_CHANNEL *ch)
462 return ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
465 static int ossl_quic_channel_is_draining(const QUIC_CHANNEL *ch)
467 return ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
470 static int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
472 return ossl_quic_channel_is_closing(ch)
473 || ossl_quic_channel_is_draining(ch);
476 int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
478 return ch->state == QUIC_CHANNEL_STATE_TERMINATED;
481 int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
483 return ossl_quic_channel_is_terminating(ch)
484 || ossl_quic_channel_is_terminated(ch);
487 const QUIC_TERMINATE_CAUSE *
488 ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
490 return ossl_quic_channel_is_term_any(ch) ? &ch->terminate_cause : NULL;
493 int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
495 return ch->handshake_complete;
498 int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
500 return ch->handshake_confirmed;
503 QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch)
508 CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch)
513 int ossl_quic_channel_has_pending(const QUIC_CHANNEL *ch)
515 return ossl_quic_demux_has_pending(ch->demux)
516 || ossl_qrx_processed_read_pending(ch->qrx);
520 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
521 * ================================================================
524 /* Used by various components. */
525 static OSSL_TIME get_time(void *arg)
527 QUIC_CHANNEL *ch = arg;
529 if (ch->now_cb == NULL)
530 return ossl_time_now();
532 return ch->now_cb(ch->now_cb_arg);
536 static uint64_t get_stream_limit(int uni, void *arg)
538 QUIC_CHANNEL *ch = arg;
540 return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
544 * Called by QRX to determine if a packet is potentially invalid before trying
547 static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg)
549 QUIC_CHANNEL *ch = arg;
551 /* Potential duplicates should not be processed. */
552 if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
559 * Triggers a TXKU (whether spontaneous or solicited). Does not check whether
560 * spontaneous TXKU is currently allowed.
563 static void ch_trigger_txku(QUIC_CHANNEL *ch)
566 = ossl_quic_tx_packetiser_get_next_pn(ch->txp, QUIC_PN_SPACE_APP);
568 if (!ossl_quic_pn_valid(next_pn)
569 || !ossl_qtx_trigger_key_update(ch->qtx)) {
570 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
575 ch->txku_in_progress = 1;
576 ch->txku_pn = next_pn;
577 ch->rxku_expected = ch->ku_locally_initiated;
581 static int txku_in_progress(QUIC_CHANNEL *ch)
583 if (ch->txku_in_progress
584 && ossl_ackm_get_largest_acked(ch->ackm, QUIC_PN_SPACE_APP) >= ch->txku_pn) {
585 OSSL_TIME pto = ossl_ackm_get_pto_duration(ch->ackm);
588 * RFC 9001 s. 6.5: Endpoints SHOULD wait three times the PTO before
589 * initiating a key update after receiving an acknowledgment that
590 * confirms that the previous key update was received.
592 * Note that by the above wording, this period starts from when we get
593 * the ack for a TXKU-triggering packet, not when the TXKU is initiated.
594 * So we defer TXKU cooldown deadline calculation to this point.
596 ch->txku_in_progress = 0;
597 ch->txku_cooldown_deadline = ossl_time_add(get_time(ch),
598 ossl_time_multiply(pto, 3));
601 return ch->txku_in_progress;
605 static int txku_allowed(QUIC_CHANNEL *ch)
607 return ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT /* Sanity check. */
608 /* Strict RFC 9001 criterion for TXKU. */
609 && ch->handshake_confirmed
610 && !txku_in_progress(ch);
614 static int txku_recommendable(QUIC_CHANNEL *ch)
616 if (!txku_allowed(ch))
620 /* Recommended RFC 9001 criterion for TXKU. */
621 ossl_time_compare(get_time(ch), ch->txku_cooldown_deadline) >= 0
622 /* Some additional sensible criteria. */
623 && !ch->rxku_in_progress
624 && !ch->rxku_pending_confirm;
628 static int txku_desirable(QUIC_CHANNEL *ch)
630 uint64_t cur_pkt_count, max_pkt_count, thresh_pkt_count;
631 const uint32_t enc_level = QUIC_ENC_LEVEL_1RTT;
633 /* Check AEAD limit to determine if we should perform a spontaneous TXKU. */
634 cur_pkt_count = ossl_qtx_get_cur_epoch_pkt_count(ch->qtx, enc_level);
635 max_pkt_count = ossl_qtx_get_max_epoch_pkt_count(ch->qtx, enc_level);
637 thresh_pkt_count = max_pkt_count / 2;
638 if (ch->txku_threshold_override != UINT64_MAX)
639 thresh_pkt_count = ch->txku_threshold_override;
641 return cur_pkt_count >= thresh_pkt_count;
645 static void ch_maybe_trigger_spontaneous_txku(QUIC_CHANNEL *ch)
647 if (!txku_recommendable(ch) || !txku_desirable(ch))
650 ch->ku_locally_initiated = 1;
655 static int rxku_allowed(QUIC_CHANNEL *ch)
658 * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a key update prior to
659 * having confirmed the handshake (Section 4.1.2).
661 * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a subsequent key update
662 * unless it has received an acknowledgment for a packet that was sent
663 * protected with keys from the current key phase.
665 * RFC 9001 s. 6.2: If an endpoint detects a second update before it has
666 * sent any packets with updated keys containing an acknowledgment for the
667 * packet that initiated the key update, it indicates that its peer has
668 * updated keys twice without awaiting confirmation. An endpoint MAY treat
669 * such consecutive key updates as a connection error of type
672 return ch->handshake_confirmed && !ch->rxku_pending_confirm;
676 * Called when the QRX detects a new RX key update event.
680 DECISION_PROTOCOL_VIOLATION,
681 DECISION_SOLICITED_TXKU
684 /* Called when the QRX detects a key update has occurred. */
686 static void rxku_detected(QUIC_PN pn, void *arg)
688 QUIC_CHANNEL *ch = arg;
689 enum rxku_decision decision;
693 * Note: rxku_in_progress is always 0 here as an RXKU cannot be detected
694 * when we are still in UPDATING or COOLDOWN (see quic_record_rx.h).
696 assert(!ch->rxku_in_progress);
698 if (!rxku_allowed(ch))
699 /* Is RXKU even allowed at this time? */
700 decision = DECISION_PROTOCOL_VIOLATION;
702 else if (ch->ku_locally_initiated)
704 * If this key update was locally initiated (meaning that this detected
705 * RXKU event is a result of our own spontaneous TXKU), we do not
706 * trigger another TXKU; after all, to do so would result in an infinite
707 * ping-pong of key updates. We still process it as an RXKU.
709 decision = DECISION_RXKU_ONLY;
713 * Otherwise, a peer triggering a KU means we have to trigger a KU also.
715 decision = DECISION_SOLICITED_TXKU;
717 if (decision == DECISION_PROTOCOL_VIOLATION) {
718 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_KEY_UPDATE_ERROR,
719 0, "RX key update again too soon");
723 pto = ossl_ackm_get_pto_duration(ch->ackm);
725 ch->ku_locally_initiated = 0;
726 ch->rxku_in_progress = 1;
727 ch->rxku_pending_confirm = 1;
728 ch->rxku_trigger_pn = pn;
729 ch->rxku_update_end_deadline = ossl_time_add(get_time(ch), pto);
730 ch->rxku_expected = 0;
732 if (decision == DECISION_SOLICITED_TXKU)
733 /* NOT gated by usual txku_allowed() */
737 * Ordinarily, we only generate ACK when some ACK-eliciting frame has been
738 * received. In some cases, this may not occur for a long time, for example
739 * if transmission of application data is going in only one direction and
740 * nothing else is happening with the connection. However, since the peer
741 * cannot initiate a subsequent (spontaneous) TXKU until its prior
742 * (spontaneous or solicited) TXKU has completed - meaning that prior
743 * TXKU's trigger packet (or subsequent packet) has been acknowledged, this
744 * can lead to very long times before a TXKU is considered 'completed'.
745 * Optimise this by forcing ACK generation after triggering TXKU.
746 * (Basically, we consider a RXKU event something that is 'ACK-eliciting',
747 * which it more or less should be; it is necessarily separate from ordinary
748 * processing of ACK-eliciting frames as key update is not indicated via a
751 ossl_quic_tx_packetiser_schedule_ack(ch->txp, QUIC_PN_SPACE_APP);
754 /* Called per tick to handle RXKU timer events. */
756 static void ch_rxku_tick(QUIC_CHANNEL *ch)
758 if (!ch->rxku_in_progress
759 || ossl_time_compare(get_time(ch), ch->rxku_update_end_deadline) < 0)
762 ch->rxku_update_end_deadline = ossl_time_infinite();
763 ch->rxku_in_progress = 0;
765 if (!ossl_qrx_key_update_timeout(ch->qrx, /*normal=*/1))
766 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
767 "RXKU cooldown internal error");
771 static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
774 QUIC_CHANNEL *ch = arg;
776 if (pn_space != QUIC_PN_SPACE_APP || !ch->rxku_pending_confirm
777 || !ossl_quic_frame_ack_contains_pn(ack, ch->rxku_trigger_pn))
781 * Defer clearing rxku_pending_confirm until TXP generate call returns
784 ch->rxku_pending_confirm_done = 1;
788 * QUIC Channel: Handshake Layer Event Handling
789 * ============================================
791 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
792 size_t *consumed, void *arg)
795 QUIC_CHANNEL *ch = arg;
796 uint32_t enc_level = ch->tx_enc_level;
797 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
798 QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
800 if (!ossl_assert(sstream != NULL))
803 ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
807 static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
815 if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
821 static int ch_on_crypto_recv_record(const unsigned char **buf,
822 size_t *bytes_read, void *arg)
824 QUIC_CHANNEL *ch = arg;
825 QUIC_RSTREAM *rstream;
826 int is_fin = 0; /* crypto stream is never finished, so we don't use this */
830 * After we move to a later EL we must not allow our peer to send any new
831 * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
834 * In practice we will only move to a new EL when we have consumed all bytes
835 * which should be sent on the crypto stream at a previous EL. For example,
836 * the Handshake EL should not be provisioned until we have completely
837 * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
838 * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
839 * given EL is available we simply ensure we have not received any further
840 * bytes at a lower EL.
842 for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
843 if (i != QUIC_ENC_LEVEL_0RTT &&
844 !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
845 /* Protocol violation (RFC 9001 s. 4.1.3) */
846 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
847 OSSL_QUIC_FRAME_TYPE_CRYPTO,
848 "crypto stream data in wrong EL");
852 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
856 return ossl_quic_rstream_get_record(rstream, buf, bytes_read,
860 static int ch_on_crypto_release_record(size_t bytes_read, void *arg)
862 QUIC_CHANNEL *ch = arg;
863 QUIC_RSTREAM *rstream;
864 OSSL_RTT_INFO rtt_info;
865 uint32_t rx_pn_space = ossl_quic_enc_level_to_pn_space(ch->rx_enc_level);
867 rstream = ch->crypto_recv[rx_pn_space];
871 ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ch), &rtt_info);
872 if (!ossl_quic_rxfc_on_retire(&ch->crypto_rxfc[rx_pn_space], bytes_read,
873 rtt_info.smoothed_rtt))
876 return ossl_quic_rstream_release_record(rstream, bytes_read);
879 static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
880 uint32_t suite_id, EVP_MD *md,
881 const unsigned char *secret,
885 QUIC_CHANNEL *ch = arg;
888 if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
895 if (enc_level <= ch->tx_enc_level)
897 * Does not make sense for us to try and provision an EL we have already
902 if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
907 ch->tx_enc_level = enc_level;
910 if (enc_level <= ch->rx_enc_level)
912 * Does not make sense for us to try and provision an EL we have already
918 * Ensure all crypto streams for previous ELs are now empty of available
921 for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
922 if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
923 /* Protocol violation (RFC 9001 s. 4.1.3) */
924 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
925 OSSL_QUIC_FRAME_TYPE_CRYPTO,
926 "crypto stream data in wrong EL");
930 if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
935 ch->have_new_rx_secret = 1;
936 ch->rx_enc_level = enc_level;
942 static int ch_on_handshake_complete(void *arg)
944 QUIC_CHANNEL *ch = arg;
946 if (!ossl_assert(!ch->handshake_complete))
947 return 0; /* this should not happen twice */
949 if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
952 if (!ch->got_remote_transport_params) {
954 * Was not a valid QUIC handshake if we did not get valid transport
957 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_MISSING_EXT,
958 OSSL_QUIC_FRAME_TYPE_CRYPTO,
959 "no transport parameters received");
963 /* Don't need transport parameters anymore. */
964 OPENSSL_free(ch->local_transport_params);
965 ch->local_transport_params = NULL;
967 /* Tell the QRX it can now process 1-RTT packets. */
968 ossl_qrx_allow_1rtt_processing(ch->qrx);
970 /* Tell TXP the handshake is complete. */
971 ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
973 ch->handshake_complete = 1;
977 * On the server, the handshake is confirmed as soon as it is complete.
979 ossl_quic_channel_on_handshake_confirmed(ch);
981 ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
987 static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
989 QUIC_CHANNEL *ch = arg;
991 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_ERR_BEGIN + alert_code,
992 0, "handshake alert");
997 * QUIC Channel: Transport Parameter Handling
998 * ==========================================
1002 * Called by handshake layer when we receive QUIC Transport Parameters from the
1003 * peer. Note that these are not authenticated until the handshake is marked
1006 #define TP_REASON_SERVER_ONLY(x) \
1007 x " may not be sent by a client"
1008 #define TP_REASON_DUP(x) \
1009 x " appears multiple times"
1010 #define TP_REASON_MALFORMED(x) \
1012 #define TP_REASON_EXPECTED_VALUE(x) \
1013 x " does not match expected value"
1014 #define TP_REASON_NOT_RETRY(x) \
1015 x " sent when not performing a retry"
1016 #define TP_REASON_REQUIRED(x) \
1017 x " was not sent but is required"
1019 static void txfc_bump_cwm_bidi(QUIC_STREAM *s, void *arg)
1021 if (!ossl_quic_stream_is_bidi(s)
1022 || ossl_quic_stream_is_server_init(s))
1025 ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
1028 static void txfc_bump_cwm_uni(QUIC_STREAM *s, void *arg)
1030 if (ossl_quic_stream_is_bidi(s)
1031 || ossl_quic_stream_is_server_init(s))
1034 ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
1037 static void do_update(QUIC_STREAM *s, void *arg)
1039 QUIC_CHANNEL *ch = arg;
1041 ossl_quic_stream_map_update_state(&ch->qsm, s);
1044 static int ch_on_transport_params(const unsigned char *params,
1048 QUIC_CHANNEL *ch = arg;
1052 const unsigned char *body;
1053 int got_orig_dcid = 0;
1054 int got_initial_scid = 0;
1055 int got_retry_scid = 0;
1056 int got_initial_max_data = 0;
1057 int got_initial_max_stream_data_bidi_local = 0;
1058 int got_initial_max_stream_data_bidi_remote = 0;
1059 int got_initial_max_stream_data_uni = 0;
1060 int got_initial_max_streams_bidi = 0;
1061 int got_initial_max_streams_uni = 0;
1062 int got_ack_delay_exp = 0;
1063 int got_max_ack_delay = 0;
1064 int got_max_udp_payload_size = 0;
1065 int got_max_idle_timeout = 0;
1066 int got_active_conn_id_limit = 0;
1067 int got_disable_active_migration = 0;
1069 const char *reason = "bad transport parameter";
1071 if (ch->got_remote_transport_params)
1074 if (!PACKET_buf_init(&pkt, params, params_len))
1077 while (PACKET_remaining(&pkt) > 0) {
1078 if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
1082 case QUIC_TPARAM_ORIG_DCID:
1083 if (got_orig_dcid) {
1084 reason = TP_REASON_DUP("ORIG_DCID");
1088 if (ch->is_server) {
1089 reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
1093 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1094 reason = TP_REASON_MALFORMED("ORIG_DCID");
1098 /* Must match our initial DCID. */
1099 if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
1100 reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
1107 case QUIC_TPARAM_RETRY_SCID:
1108 if (ch->is_server) {
1109 reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
1113 if (got_retry_scid) {
1114 reason = TP_REASON_DUP("RETRY_SCID");
1118 if (!ch->doing_retry) {
1119 reason = TP_REASON_NOT_RETRY("RETRY_SCID");
1123 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1124 reason = TP_REASON_MALFORMED("RETRY_SCID");
1128 /* Must match Retry packet SCID. */
1129 if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
1130 reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
1137 case QUIC_TPARAM_INITIAL_SCID:
1138 if (got_initial_scid) {
1139 /* must not appear more than once */
1140 reason = TP_REASON_DUP("INITIAL_SCID");
1144 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1145 reason = TP_REASON_MALFORMED("INITIAL_SCID");
1149 /* Must match SCID of first Initial packet from server. */
1150 if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
1151 reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
1155 got_initial_scid = 1;
1158 case QUIC_TPARAM_INITIAL_MAX_DATA:
1159 if (got_initial_max_data) {
1160 /* must not appear more than once */
1161 reason = TP_REASON_DUP("INITIAL_MAX_DATA");
1165 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1166 reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
1170 ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
1171 got_initial_max_data = 1;
1174 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
1175 if (got_initial_max_stream_data_bidi_local) {
1176 /* must not appear more than once */
1177 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1181 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1182 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1187 * This is correct; the BIDI_LOCAL TP governs streams created by
1188 * the endpoint which sends the TP, i.e., our peer.
1190 ch->rx_init_max_stream_data_bidi_remote = v;
1191 got_initial_max_stream_data_bidi_local = 1;
1194 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
1195 if (got_initial_max_stream_data_bidi_remote) {
1196 /* must not appear more than once */
1197 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1201 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1202 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1207 * This is correct; the BIDI_REMOTE TP governs streams created
1208 * by the endpoint which receives the TP, i.e., us.
1210 ch->rx_init_max_stream_data_bidi_local = v;
1212 /* Apply to all existing streams. */
1213 ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_bidi, &v);
1214 got_initial_max_stream_data_bidi_remote = 1;
1217 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
1218 if (got_initial_max_stream_data_uni) {
1219 /* must not appear more than once */
1220 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
1224 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1225 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
1229 ch->rx_init_max_stream_data_uni = v;
1231 /* Apply to all existing streams. */
1232 ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_uni, &v);
1233 got_initial_max_stream_data_uni = 1;
1236 case QUIC_TPARAM_ACK_DELAY_EXP:
1237 if (got_ack_delay_exp) {
1238 /* must not appear more than once */
1239 reason = TP_REASON_DUP("ACK_DELAY_EXP");
1243 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1244 || v > QUIC_MAX_ACK_DELAY_EXP) {
1245 reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
1249 ch->rx_ack_delay_exp = (unsigned char)v;
1250 got_ack_delay_exp = 1;
1253 case QUIC_TPARAM_MAX_ACK_DELAY:
1254 if (got_max_ack_delay) {
1255 /* must not appear more than once */
1256 reason = TP_REASON_DUP("MAX_ACK_DELAY");
1260 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1261 || v >= (((uint64_t)1) << 14)) {
1262 reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
1266 ch->rx_max_ack_delay = v;
1267 ossl_ackm_set_rx_max_ack_delay(ch->ackm,
1268 ossl_ms2time(ch->rx_max_ack_delay));
1270 got_max_ack_delay = 1;
1273 case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
1274 if (got_initial_max_streams_bidi) {
1275 /* must not appear more than once */
1276 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
1280 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1281 || v > (((uint64_t)1) << 60)) {
1282 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
1286 assert(ch->max_local_streams_bidi == 0);
1287 ch->max_local_streams_bidi = v;
1288 got_initial_max_streams_bidi = 1;
1291 case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
1292 if (got_initial_max_streams_uni) {
1293 /* must not appear more than once */
1294 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
1298 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1299 || v > (((uint64_t)1) << 60)) {
1300 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
1304 assert(ch->max_local_streams_uni == 0);
1305 ch->max_local_streams_uni = v;
1306 got_initial_max_streams_uni = 1;
1309 case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
1310 if (got_max_idle_timeout) {
1311 /* must not appear more than once */
1312 reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
1316 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1317 reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
1321 if (v > 0 && v < ch->max_idle_timeout)
1322 ch->max_idle_timeout = v;
1325 got_max_idle_timeout = 1;
1328 case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
1329 if (got_max_udp_payload_size) {
1330 /* must not appear more than once */
1331 reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
1335 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1336 || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
1337 reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
1341 ch->rx_max_udp_payload_size = v;
1342 got_max_udp_payload_size = 1;
1345 case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
1346 if (got_active_conn_id_limit) {
1347 /* must not appear more than once */
1348 reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
1352 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1353 || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
1354 reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
1358 ch->rx_active_conn_id_limit = v;
1359 got_active_conn_id_limit = 1;
1362 case QUIC_TPARAM_STATELESS_RESET_TOKEN:
1363 /* TODO(QUIC): Handle stateless reset tokens. */
1365 * We ignore these for now, but we must ensure a client doesn't
1368 if (ch->is_server) {
1369 reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
1373 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1374 if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
1375 reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
1381 case QUIC_TPARAM_PREFERRED_ADDR:
1383 /* TODO(QUIC): Handle preferred address. */
1384 QUIC_PREFERRED_ADDR pfa;
1387 * RFC 9000 s. 18.2: "A server that chooses a zero-length
1388 * connection ID MUST NOT provide a preferred address.
1389 * Similarly, a server MUST NOT include a zero-length connection
1390 * ID in this transport parameter. A client MUST treat a
1391 * violation of these requirements as a connection error of type
1392 * TRANSPORT_PARAMETER_ERROR."
1394 if (ch->is_server) {
1395 reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
1399 if (ch->cur_remote_dcid.id_len == 0) {
1400 reason = "PREFERRED_ADDR provided for zero-length CID";
1404 if (!ossl_quic_wire_decode_transport_param_preferred_addr(&pkt, &pfa)) {
1405 reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
1409 if (pfa.cid.id_len == 0) {
1410 reason = "zero-length CID in PREFERRED_ADDR";
1416 case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
1417 /* We do not currently handle migration, so nothing to do. */
1418 if (got_disable_active_migration) {
1419 /* must not appear more than once */
1420 reason = TP_REASON_DUP("DISABLE_ACTIVE_MIGRATION");
1424 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1425 if (body == NULL || len > 0) {
1426 reason = TP_REASON_MALFORMED("DISABLE_ACTIVE_MIGRATION");
1430 got_disable_active_migration = 1;
1435 * Skip over and ignore.
1437 * RFC 9000 s. 7.4: We SHOULD treat duplicated transport parameters
1438 * as a connection error, but we are not required to. Currently,
1439 * handle this programmatically by checking for duplicates in the
1440 * parameters that we recognise, as above, but don't bother
1441 * maintaining a list of duplicates for anything we don't recognise.
1443 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
1452 if (!got_initial_scid) {
1453 reason = TP_REASON_REQUIRED("INITIAL_SCID");
1457 if (!ch->is_server) {
1458 if (!got_orig_dcid) {
1459 reason = TP_REASON_REQUIRED("ORIG_DCID");
1463 if (ch->doing_retry && !got_retry_scid) {
1464 reason = TP_REASON_REQUIRED("RETRY_SCID");
1469 ch->got_remote_transport_params = 1;
1471 if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
1472 || got_initial_max_streams_bidi || got_initial_max_streams_uni)
1474 * If FC credit was bumped, we may now be able to send. Update all
1477 ossl_quic_stream_map_visit(&ch->qsm, do_update, ch);
1479 /* If we are a server, we now generate our own transport parameters. */
1480 if (ch->is_server && !ch_generate_transport_params(ch)) {
1481 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1489 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
1495 * Called when we want to generate transport parameters. This is called
1496 * immediately at instantiation time for a client and after we receive the
1497 * client's transport parameters for a server.
1499 static int ch_generate_transport_params(QUIC_CHANNEL *ch)
1502 BUF_MEM *buf_mem = NULL;
1507 if (ch->local_transport_params != NULL)
1510 if ((buf_mem = BUF_MEM_new()) == NULL)
1513 if (!WPACKET_init(&wpkt, buf_mem))
1518 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
1522 if (ch->is_server) {
1523 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
1527 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1528 &ch->cur_local_cid))
1531 /* Client always uses an empty SCID. */
1532 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1537 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
1538 ch->max_idle_timeout))
1541 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
1542 QUIC_MIN_INITIAL_DGRAM_LEN))
1545 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
1546 QUIC_MIN_ACTIVE_CONN_ID_LIMIT))
1549 if (ch->tx_max_ack_delay != QUIC_DEFAULT_MAX_ACK_DELAY
1550 && !ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_ACK_DELAY,
1551 ch->tx_max_ack_delay))
1554 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
1555 ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
1558 /* Send the default CWM for a new RXFC. */
1559 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1560 ch->tx_init_max_stream_data_bidi_local))
1563 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1564 ch->tx_init_max_stream_data_bidi_remote))
1567 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
1568 ch->tx_init_max_stream_data_uni))
1571 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
1572 ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc)))
1575 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
1576 ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc)))
1579 if (!WPACKET_finish(&wpkt))
1584 if (!WPACKET_get_total_written(&wpkt, &buf_len))
1587 ch->local_transport_params = (unsigned char *)buf_mem->data;
1588 buf_mem->data = NULL;
1591 if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
1598 WPACKET_cleanup(&wpkt);
1599 BUF_MEM_free(buf_mem);
1604 * QUIC Channel: Ticker-Mutator
1605 * ============================
1609 * The central ticker function called by the reactor. This does everything, or
1610 * at least everything network I/O related. Best effort - not allowed to fail
1613 static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags)
1615 OSSL_TIME now, deadline;
1616 QUIC_CHANNEL *ch = arg;
1617 int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0;
1618 uint64_t error_code;
1619 const char *error_msg, *error_src_file, *error_src_func;
1623 * When we tick the QUIC connection, we do everything we need to do
1624 * periodically. In order, we:
1626 * - handle any incoming data from the network;
1627 * - handle any timer events which are due to fire (ACKM, etc.)
1628 * - write any data to the network due to be sent, to the extent
1630 * - determine the time at which we should next be ticked.
1633 /* If we are in the TERMINATED state, there is nothing to do. */
1634 if (ossl_quic_channel_is_terminated(ch)) {
1635 res->net_read_desired = 0;
1636 res->net_write_desired = 0;
1637 res->tick_deadline = ossl_time_infinite();
1642 * If we are in the TERMINATING state, check if the terminating timer has
1645 if (ossl_quic_channel_is_terminating(ch)) {
1648 if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
1649 ch_on_terminating_timeout(ch);
1650 res->net_read_desired = 0;
1651 res->net_write_desired = 0;
1652 res->tick_deadline = ossl_time_infinite();
1653 return; /* abort normal processing, nothing to do */
1657 if (!ch->inhibit_tick) {
1658 /* Handle RXKU timeouts. */
1661 /* Handle any incoming data from network. */
1665 /* Process queued incoming packets. */
1669 * Allow the handshake layer to check for any new incoming data and
1670 * generate new outgoing data.
1672 ch->have_new_rx_secret = 0;
1673 if (!channel_only) {
1674 ossl_quic_tls_tick(ch->qtls);
1676 if (ossl_quic_tls_get_error(ch->qtls, &error_code, &error_msg,
1680 ossl_quic_channel_raise_protocol_error_loc(ch, error_code, 0,
1689 * If the handshake layer gave us a new secret, we need to do RX
1690 * again because packets that were not previously processable and
1691 * were deferred might now be processable.
1693 * TODO(QUIC): Consider handling this in the yield_secret callback.
1695 } while (ch->have_new_rx_secret);
1699 * Handle any timer events which are due to fire; namely, the loss
1700 * detection deadline and the idle timeout.
1702 * ACKM ACK generation deadline is polled by TXP, so we don't need to
1706 if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
1708 * Idle timeout differs from normal protocol violation because we do
1709 * not send a CONN_CLOSE frame; go straight to TERMINATED.
1711 if (!ch->inhibit_tick)
1712 ch_on_idle_timeout(ch);
1714 res->net_read_desired = 0;
1715 res->net_write_desired = 0;
1716 res->tick_deadline = ossl_time_infinite();
1720 if (!ch->inhibit_tick) {
1721 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1722 if (!ossl_time_is_zero(deadline)
1723 && ossl_time_compare(now, deadline) >= 0)
1724 ossl_ackm_on_timeout(ch->ackm);
1726 /* If a ping is due, inform TXP. */
1727 if (ossl_time_compare(now, ch->ping_deadline) >= 0) {
1728 int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
1730 ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
1733 /* Write any data to the network due to be sent. */
1737 ossl_quic_stream_map_gc(&ch->qsm);
1740 /* Determine the time at which we should next be ticked. */
1741 res->tick_deadline = ch_determine_next_tick_deadline(ch);
1744 * Always process network input unless we are now terminated.
1745 * Although we had not terminated at the beginning of this tick, network
1746 * errors in ch_rx_pre() or ch_tx() may have caused us to transition to the
1749 res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
1751 /* We want to write to the network if we have any in our queue. */
1752 res->net_write_desired
1753 = (!ossl_quic_channel_is_terminated(ch)
1754 && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
1757 /* Process incoming datagrams, if any. */
1758 static void ch_rx_pre(QUIC_CHANNEL *ch)
1762 if (!ch->is_server && !ch->have_sent_any_pkt)
1766 * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
1767 * to the appropriate QRX instance.
1769 ret = ossl_quic_demux_pump(ch->demux);
1770 if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
1772 * We don't care about transient failure, but permanent failure means we
1773 * should tear down the connection as though a protocol violation
1774 * occurred. Skip straight to the Terminating state as there is no point
1775 * trying to send CONNECTION_CLOSE frames if the network BIO is not
1776 * operating correctly.
1778 ch_raise_net_error(ch);
1781 /* Check incoming forged packet limit and terminate connection if needed. */
1782 static void ch_rx_check_forged_pkt_limit(QUIC_CHANNEL *ch)
1785 uint64_t limit = UINT64_MAX, l;
1787 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
1788 enc_level < QUIC_ENC_LEVEL_NUM;
1792 * Different ELs can have different AEADs which can in turn impose
1793 * different limits, so use the lowest value of any currently valid EL.
1795 if ((ch->el_discarded & (1U << enc_level)) != 0)
1798 if (enc_level > ch->rx_enc_level)
1801 l = ossl_qrx_get_max_forged_pkt_count(ch->qrx, enc_level);
1806 if (ossl_qrx_get_cur_forged_pkt_count(ch->qrx) < limit)
1809 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_AEAD_LIMIT_REACHED, 0,
1813 /* Process queued incoming packets and handle frames, if any. */
1814 static int ch_rx(QUIC_CHANNEL *ch)
1816 int handled_any = 0;
1817 const int closing = ossl_quic_channel_is_closing(ch);
1819 if (!ch->is_server && !ch->have_sent_any_pkt)
1821 * We have not sent anything yet, therefore there is no need to check
1822 * for incoming data.
1827 assert(ch->qrx_pkt == NULL);
1829 if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
1832 /* Track the amount of data received while in the closing state */
1834 ossl_quic_tx_packetiser_record_received_closing_bytes(
1835 ch->txp, ch->qrx_pkt->hdr->len);
1840 ch_rx_handle_packet(ch); /* best effort */
1843 * Regardless of the outcome of frame handling, unref the packet.
1844 * This will free the packet unless something added another
1845 * reference to it during frame processing.
1847 ossl_qrx_pkt_release(ch->qrx_pkt);
1850 ch->have_sent_ack_eliciting_since_rx = 0;
1854 ch_rx_check_forged_pkt_limit(ch);
1857 * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
1858 * process one or more incoming packets.
1860 if (handled_any && closing)
1861 ch->conn_close_queued = 1;
1866 static int bio_addr_eq(const BIO_ADDR *a, const BIO_ADDR *b)
1868 if (BIO_ADDR_family(a) != BIO_ADDR_family(b))
1871 switch (BIO_ADDR_family(a)) {
1873 return !memcmp(&a->s_in.sin_addr,
1875 sizeof(a->s_in.sin_addr))
1876 && a->s_in.sin_port == b->s_in.sin_port;
1877 #if OPENSSL_USE_IPV6
1879 return !memcmp(&a->s_in6.sin6_addr,
1880 &b->s_in6.sin6_addr,
1881 sizeof(a->s_in6.sin6_addr))
1882 && a->s_in6.sin6_port == b->s_in6.sin6_port;
1885 return 0; /* not supported */
1891 /* Handles the packet currently in ch->qrx_pkt->hdr. */
1892 static void ch_rx_handle_packet(QUIC_CHANNEL *ch)
1896 assert(ch->qrx_pkt != NULL);
1899 * RFC 9000 s. 10.2.1 Closing Connection State:
1900 * An endpoint that is closing is not required to process any
1903 if (!ossl_quic_channel_is_active(ch))
1906 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
1907 if (!ch->have_received_enc_pkt) {
1908 ch->cur_remote_dcid = ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
1909 ch->have_received_enc_pkt = 1;
1912 * We change to using the SCID in the first Initial packet as the
1915 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
1918 enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
1919 if ((ch->el_discarded & (1U << enc_level)) != 0)
1920 /* Do not process packets from ELs we have already discarded. */
1925 * RFC 9000 s. 9.6: "If a client receives packets from a new server address
1926 * when the client has not initiated a migration to that address, the client
1927 * SHOULD discard these packets."
1929 * We need to be a bit careful here as due to the BIO abstraction layer an
1930 * application is liable to be weird and lie to us about peer addresses.
1931 * Only apply this check if we actually are using a real AF_INET or AF_INET6
1935 && ch->qrx_pkt->peer != NULL
1937 BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET
1938 #if OPENSSL_USE_IPV6
1939 || BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET6
1942 && !bio_addr_eq(ch->qrx_pkt->peer, &ch->cur_peer_addr))
1946 && ch->have_received_enc_pkt
1947 && ossl_quic_pkt_type_has_scid(ch->qrx_pkt->hdr->type)) {
1949 * RFC 9000 s. 7.2: "Once a client has received a valid Initial packet
1950 * from the server, it MUST discard any subsequent packet it receives on
1951 * that connection with a different SCID."
1953 if (!ossl_quic_conn_id_eq(&ch->qrx_pkt->hdr->src_conn_id,
1958 if (ossl_quic_pkt_type_has_version(ch->qrx_pkt->hdr->type)
1959 && ch->qrx_pkt->hdr->version != QUIC_VERSION_1)
1961 * RFC 9000 s. 5.2.1: If a client receives a packet that uses a
1962 * different version than it initially selected, it MUST discard the
1963 * packet. We only ever use v1, so require it.
1968 * RFC 9000 s. 17.2: "An endpoint MUST treat receipt of a packet that has a
1969 * non-zero value for [the reserved bits] after removing both packet and
1970 * header protection as a connection error of type PROTOCOL_VIOLATION."
1972 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)
1973 && ch->qrx_pkt->hdr->reserved != 0) {
1974 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
1975 0, "packet header reserved bits");
1979 /* Handle incoming packet. */
1980 switch (ch->qrx_pkt->hdr->type) {
1981 case QUIC_PKT_TYPE_RETRY:
1982 if (ch->doing_retry || ch->is_server)
1984 * It is not allowed to ask a client to do a retry more than
1985 * once. Clients may not send retries.
1989 if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
1990 /* Packets with zero-length Retry Tokens are invalid. */
1994 * TODO(QUIC): Theoretically this should probably be in the QRX.
1995 * However because validation is dependent on context (namely the
1996 * client's initial DCID) we can't do this cleanly. In the future we
1997 * should probably add a callback to the QRX to let it call us (via
1998 * the DEMUX) and ask us about the correct original DCID, rather
1999 * than allow the QRX to emit a potentially malformed packet to the
2000 * upper layers. However, special casing this will do for now.
2002 if (!ossl_quic_validate_retry_integrity_tag(ch->libctx,
2006 /* Malformed retry packet, ignore. */
2009 ch_retry(ch, ch->qrx_pkt->hdr->data,
2010 ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
2011 &ch->qrx_pkt->hdr->src_conn_id);
2014 case QUIC_PKT_TYPE_0RTT:
2016 /* Clients should never receive 0-RTT packets. */
2020 * TODO(QUIC): Implement 0-RTT on the server side. We currently do
2021 * not need to implement this as a client can only do 0-RTT if we
2022 * have given it permission to in a previous session.
2026 case QUIC_PKT_TYPE_INITIAL:
2027 case QUIC_PKT_TYPE_HANDSHAKE:
2028 case QUIC_PKT_TYPE_1RTT:
2029 if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
2031 * We automatically drop INITIAL EL keys when first successfully
2032 * decrypting a HANDSHAKE packet, as per the RFC.
2034 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
2036 if (ch->rxku_in_progress
2037 && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_1RTT
2038 && ch->qrx_pkt->pn >= ch->rxku_trigger_pn
2039 && ch->qrx_pkt->key_epoch < ossl_qrx_get_key_epoch(ch->qrx)) {
2041 * RFC 9001 s. 6.4: Packets with higher packet numbers MUST be
2042 * protected with either the same or newer packet protection keys
2043 * than packets with lower packet numbers. An endpoint that
2044 * successfully removes protection with old keys when newer keys
2045 * were used for packets with lower packet numbers MUST treat this
2046 * as a connection error of type KEY_UPDATE_ERROR.
2048 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_KEY_UPDATE_ERROR,
2049 0, "new packet with old keys");
2054 && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_INITIAL
2055 && ch->qrx_pkt->hdr->token_len > 0) {
2057 * RFC 9000 s. 17.2.2: Clients that receive an Initial packet with a
2058 * non-zero Token Length field MUST either discard the packet or
2059 * generate a connection error of type PROTOCOL_VIOLATION.
2061 * TODO(QUIC): consider the implications of RFC 9000 s. 10.2.3
2062 * Immediate Close during the Handshake:
2063 * However, at the cost of reducing feedback about
2064 * errors for legitimate peers, some forms of denial of
2065 * service can be made more difficult for an attacker
2066 * if endpoints discard illegal packets rather than
2067 * terminating a connection with CONNECTION_CLOSE. For
2068 * this reason, endpoints MAY discard packets rather
2069 * than immediately close if errors are detected in
2070 * packets that lack authentication.
2071 * I.e. should we drop this packet instead of closing the connection?
2073 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
2074 0, "client received initial token");
2078 /* This packet contains frames, pass to the RXDP. */
2079 ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
2089 * This is called by the demux when we get a packet not destined for any known
2092 static void ch_default_packet_handler(QUIC_URXE *e, void *arg)
2094 QUIC_CHANNEL *ch = arg;
2098 if (!ossl_assert(ch->is_server))
2102 * We only support one connection to our server currently, so if we already
2103 * started one, ignore any new connection attempts.
2105 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
2109 * We have got a packet for an unknown DCID. This might be an attempt to
2110 * open a new connection.
2112 if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
2115 if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
2119 * We set short_conn_id_len to SIZE_MAX here which will cause the decode
2120 * operation to fail if we get a 1-RTT packet. This is fine since we only
2121 * care about Initial packets.
2123 if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL))
2126 switch (hdr.version) {
2127 case QUIC_VERSION_1:
2130 case QUIC_VERSION_NONE:
2132 /* Unknown version or proactive version negotiation request, bail. */
2133 /* TODO(QUIC): Handle version negotiation on server side */
2138 * We only care about Initial packets which might be trying to establish a
2141 if (hdr.type != QUIC_PKT_TYPE_INITIAL)
2145 * Assume this is a valid attempt to initiate a connection.
2147 * We do not register the DCID in the initial packet we received and that
2148 * DCID is not actually used again, thus after provisioning the correct
2149 * Initial keys derived from it (which is done in the call below) we pass
2150 * the received packet directly to the QRX so that it can process it as a
2151 * one-time thing, instead of going through the usual DEMUX DCID-based
2154 if (!ch_server_on_new_conn(ch, &e->peer,
2159 ossl_qrx_inject_urxe(ch->qrx, e);
2163 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
2166 ossl_quic_demux_release_urxe(ch->demux, e);
2169 /* Try to generate packets and if possible, flush them to the network. */
2170 static int ch_tx(QUIC_CHANNEL *ch)
2172 QUIC_TXP_STATUS status;
2175 * RFC 9000 s. 10.2.2: Draining Connection State:
2176 * While otherwise identical to the closing state, an endpoint
2177 * in the draining state MUST NOT send any packets.
2179 * An endpoint MUST NOT send further packets.
2181 if (ossl_quic_channel_is_draining(ch))
2184 if (ossl_quic_channel_is_closing(ch)) {
2186 * While closing, only send CONN_CLOSE if we've received more traffic
2187 * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
2188 * future calls to it generate CONN_CLOSE frames, so otherwise we would
2189 * just constantly generate CONN_CLOSE frames.
2191 * Confirming to RFC 9000 s. 10.2.1 Closing Connection State:
2192 * An endpoint SHOULD limit the rate at which it generates
2193 * packets in the closing state.
2195 if (!ch->conn_close_queued)
2198 ch->conn_close_queued = 0;
2201 /* Do TXKU if we need to. */
2202 ch_maybe_trigger_spontaneous_txku(ch);
2204 ch->rxku_pending_confirm_done = 0;
2207 * Send a packet, if we need to. Best effort. The TXP consults the CC and
2208 * applies any limitations imposed by it, so we don't need to do it here.
2210 * Best effort. In particular if TXP fails for some reason we should still
2211 * flush any queued packets which we already generated.
2213 switch (ossl_quic_tx_packetiser_generate(ch->txp, &status)) {
2214 case TX_PACKETISER_RES_SENT_PKT:
2215 ch->have_sent_any_pkt = 1; /* Packet was sent */
2218 * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when
2219 * sending an ack-eliciting packet if no other ack-eliciting packets
2220 * have been sent since last receiving and processing a packet.'
2222 if (status.sent_ack_eliciting && !ch->have_sent_ack_eliciting_since_rx) {
2224 ch->have_sent_ack_eliciting_since_rx = 1;
2227 if (!ch->is_server && status.sent_handshake)
2229 * RFC 9001 s. 4.9.1: A client MUST discard Initial keys when it
2230 * first sends a Handshake packet.
2232 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
2234 if (ch->rxku_pending_confirm_done)
2235 ch->rxku_pending_confirm = 0;
2237 ch_update_ping_deadline(ch);
2240 case TX_PACKETISER_RES_NO_PKT:
2241 break; /* No packet was sent */
2245 * One case where TXP can fail is if we reach a TX PN of 2**62 - 1. As
2246 * per RFC 9000 s. 12.3, if this happens we MUST close the connection
2247 * without sending a CONNECTION_CLOSE frame. This is actually handled as
2248 * an emergent consequence of our design, as the TX packetiser will
2249 * never transmit another packet when the TX PN reaches the limit.
2251 * Calling the below function terminates the connection; its attempt to
2252 * schedule a CONNECTION_CLOSE frame will not actually cause a packet to
2253 * be transmitted for this reason.
2255 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
2257 break; /* Internal failure (e.g. allocation, assertion) */
2260 /* Flush packets to network. */
2261 switch (ossl_qtx_flush_net(ch->qtx)) {
2262 case QTX_FLUSH_NET_RES_OK:
2263 case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
2264 /* Best effort, done for now. */
2267 case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
2269 /* Permanent underlying network BIO, start terminating. */
2270 ch_raise_net_error(ch);
2277 /* Determine next tick deadline. */
2278 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
2283 if (ossl_quic_channel_is_terminated(ch))
2284 return ossl_time_infinite();
2286 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
2287 if (ossl_time_is_zero(deadline))
2288 deadline = ossl_time_infinite();
2291 * If the CC will let us send acks, check the ack deadline for all
2292 * enc_levels that are actually provisioned
2294 if (ch->cc_method->get_tx_allowance(ch->cc_data) > 0) {
2295 for (i = 0; i < QUIC_ENC_LEVEL_NUM; i++) {
2296 if (ossl_qtx_is_enc_level_provisioned(ch->qtx, i)) {
2297 deadline = ossl_time_min(deadline,
2298 ossl_ackm_get_ack_deadline(ch->ackm,
2299 ossl_quic_enc_level_to_pn_space(i)));
2304 /* Apply TXP wakeup deadline. */
2305 deadline = ossl_time_min(deadline,
2306 ossl_quic_tx_packetiser_get_deadline(ch->txp));
2308 /* Is the terminating timer armed? */
2309 if (ossl_quic_channel_is_terminating(ch))
2310 deadline = ossl_time_min(deadline,
2311 ch->terminate_deadline);
2312 else if (!ossl_time_is_infinite(ch->idle_deadline))
2313 deadline = ossl_time_min(deadline,
2317 * When do we need to send an ACK-eliciting packet to reset the idle
2318 * deadline timer for the peer?
2320 if (!ossl_time_is_infinite(ch->ping_deadline))
2321 deadline = ossl_time_min(deadline,
2324 /* When does the RXKU process complete? */
2325 if (ch->rxku_in_progress)
2326 deadline = ossl_time_min(deadline, ch->rxku_update_end_deadline);
2332 * QUIC Channel: Network BIO Configuration
2333 * =======================================
2336 /* Determines whether we can support a given poll descriptor. */
2337 static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
2339 if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0)
2345 BIO *ossl_quic_channel_get_net_rbio(QUIC_CHANNEL *ch)
2347 return ch->net_rbio;
2350 BIO *ossl_quic_channel_get_net_wbio(QUIC_CHANNEL *ch)
2352 return ch->net_wbio;
2356 * QUIC_CHANNEL does not ref any BIO it is provided with, nor is any ref
2357 * transferred to it. The caller (i.e., QUIC_CONNECTION) is responsible for
2358 * ensuring the BIO lasts until the channel is freed or the BIO is switched out
2359 * for another BIO by a subsequent successful call to this function.
2361 int ossl_quic_channel_set_net_rbio(QUIC_CHANNEL *ch, BIO *net_rbio)
2363 BIO_POLL_DESCRIPTOR d = {0};
2365 if (ch->net_rbio == net_rbio)
2368 if (net_rbio != NULL) {
2369 if (!BIO_get_rpoll_descriptor(net_rbio, &d))
2370 /* Non-pollable BIO */
2371 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
2373 if (!validate_poll_descriptor(&d))
2377 ossl_quic_reactor_set_poll_r(&ch->rtor, &d);
2378 ossl_quic_demux_set_bio(ch->demux, net_rbio);
2379 ch->net_rbio = net_rbio;
2383 int ossl_quic_channel_set_net_wbio(QUIC_CHANNEL *ch, BIO *net_wbio)
2385 BIO_POLL_DESCRIPTOR d = {0};
2387 if (ch->net_wbio == net_wbio)
2390 if (net_wbio != NULL) {
2391 if (!BIO_get_wpoll_descriptor(net_wbio, &d))
2392 /* Non-pollable BIO */
2393 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
2395 if (!validate_poll_descriptor(&d))
2399 ossl_quic_reactor_set_poll_w(&ch->rtor, &d);
2400 ossl_qtx_set_bio(ch->qtx, net_wbio);
2401 ch->net_wbio = net_wbio;
2406 * QUIC Channel: Lifecycle Events
2407 * ==============================
2409 int ossl_quic_channel_start(QUIC_CHANNEL *ch)
2413 * This is not used by the server. The server moves to active
2414 * automatically on receiving an incoming connection.
2418 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
2419 /* Calls to connect are idempotent */
2422 /* Inform QTX of peer address. */
2423 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2426 /* Plug in secrets for the Initial EL. */
2427 if (!ossl_quic_provide_initial_secret(ch->libctx,
2435 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
2436 ch->doing_proactive_ver_neg = 0; /* not currently supported */
2438 /* Handshake layer: start (e.g. send CH). */
2439 if (!ossl_quic_tls_tick(ch->qtls))
2442 ossl_quic_reactor_tick(&ch->rtor, 0); /* best effort */
2446 /* Start a locally initiated connection shutdown. */
2447 void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code)
2449 QUIC_TERMINATE_CAUSE tcause = {0};
2451 if (ossl_quic_channel_is_term_any(ch))
2455 tcause.error_code = app_error_code;
2456 ch_start_terminating(ch, &tcause, 0);
2459 static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
2461 OPENSSL_free((unsigned char *)buf);
2464 /* Called when a server asks us to do a retry. */
2465 static int ch_retry(QUIC_CHANNEL *ch,
2466 const unsigned char *retry_token,
2467 size_t retry_token_len,
2468 const QUIC_CONN_ID *retry_scid)
2473 * RFC 9000 s. 17.2.5.1: "A client MUST discard a Retry packet that contains
2474 * a SCID field that is identical to the DCID field of its initial packet."
2476 if (ossl_quic_conn_id_eq(&ch->init_dcid, retry_scid))
2479 /* We change to using the SCID in the Retry packet as the DCID. */
2480 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
2484 * Now we retry. We will release the Retry packet immediately, so copy
2487 if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
2490 ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf, retry_token_len,
2493 ch->retry_scid = *retry_scid;
2494 ch->doing_retry = 1;
2497 * We need to stimulate the Initial EL to generate the first CRYPTO frame
2498 * again. We can do this most cleanly by simply forcing the ACKM to consider
2499 * the first Initial packet as lost, which it effectively was as the server
2500 * hasn't processed it. This also maintains the desired behaviour with e.g.
2501 * PNs not resetting and so on.
2503 * The PN we used initially is always zero, because QUIC does not allow
2506 if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
2511 * Plug in new secrets for the Initial EL. This is the only time we change
2512 * the secrets for an EL after we already provisioned it.
2514 if (!ossl_quic_provide_initial_secret(ch->libctx,
2524 /* Called when an EL is to be discarded. */
2525 static int ch_discard_el(QUIC_CHANNEL *ch,
2528 if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
2531 if ((ch->el_discarded & (1U << enc_level)) != 0)
2535 /* Best effort for all of these. */
2536 ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
2537 ossl_qrx_discard_enc_level(ch->qrx, enc_level);
2538 ossl_qtx_discard_enc_level(ch->qtx, enc_level);
2540 if (enc_level != QUIC_ENC_LEVEL_0RTT) {
2541 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
2543 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
2545 /* We should still have crypto streams at this point. */
2546 if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
2547 || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
2550 /* Get rid of the crypto stream state for the EL. */
2551 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
2552 ch->crypto_send[pn_space] = NULL;
2554 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
2555 ch->crypto_recv[pn_space] = NULL;
2558 ch->el_discarded |= (1U << enc_level);
2562 /* Intended to be called by the RXDP. */
2563 int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
2565 if (ch->handshake_confirmed)
2568 if (!ch->handshake_complete) {
2570 * Does not make sense for handshake to be confirmed before it is
2573 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
2574 OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
2575 "handshake cannot be confirmed "
2576 "before it is completed");
2580 ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
2581 ch->handshake_confirmed = 1;
2582 ossl_ackm_on_handshake_confirmed(ch->ackm);
2587 * Master function used when we want to start tearing down a connection:
2589 * - If the connection is still IDLE we can go straight to TERMINATED;
2591 * - If we are already TERMINATED this is a no-op.
2593 * - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
2594 * from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
2596 * - If we are TERMINATING - DRAINING, we remain here until the terminating
2599 * - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
2600 * if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
2601 * that we are considered to have caused a termination if we sent the first
2602 * CONNECTION_CLOSE frame, even if it is caused by a peer protocol
2603 * violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
2604 * TERMINATING - DRAINING.
2606 * We record the termination cause structure passed on the first call only.
2607 * Any successive calls have their termination cause data discarded;
2608 * once we start sending a CONNECTION_CLOSE frame, we don't change the details
2611 * This conforms to RFC 9000 s. 10.2.1: Closing Connection State:
2612 * To minimize the state that an endpoint maintains for a closing
2613 * connection, endpoints MAY send the exact same packet in response
2614 * to any received packet.
2616 * We don't drop any connection state (specifically packet protection keys)
2617 * even though we are permitted to. This conforms to RFC 9000 s. 10.2.1:
2618 * Closing Connection State:
2619 * An endpoint MAY retain packet protection keys for incoming
2620 * packets to allow it to read and process a CONNECTION_CLOSE frame.
2622 * Note that we do not conform to these two from the same section:
2623 * An endpoint's selected connection ID and the QUIC version
2624 * are sufficient information to identify packets for a closing
2625 * connection; the endpoint MAY discard all other connection state.
2627 * An endpoint MAY drop packet protection keys when entering the
2628 * closing state and send a packet containing a CONNECTION_CLOSE
2629 * frame in response to any UDP datagram that is received.
2631 static void ch_start_terminating(QUIC_CHANNEL *ch,
2632 const QUIC_TERMINATE_CAUSE *tcause,
2633 int force_immediate)
2635 switch (ch->state) {
2637 case QUIC_CHANNEL_STATE_IDLE:
2638 ch->terminate_cause = *tcause;
2639 ch_on_terminating_timeout(ch);
2642 case QUIC_CHANNEL_STATE_ACTIVE:
2643 ch->terminate_cause = *tcause;
2645 if (!force_immediate) {
2646 ch->state = tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
2647 : QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
2649 * RFC 9000 s. 10.2 Immediate Close
2650 * These states SHOULD persist for at least three times
2651 * the current PTO interval as defined in [QUIC-RECOVERY].
2653 ch->terminate_deadline
2654 = ossl_time_add(get_time(ch),
2655 ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
2658 if (!tcause->remote) {
2659 OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
2662 f.error_code = ch->terminate_cause.error_code;
2663 f.frame_type = ch->terminate_cause.frame_type;
2664 f.is_app = ch->terminate_cause.app;
2665 ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
2667 * RFC 9000 s. 10.2.2 Draining Connection State:
2668 * An endpoint that receives a CONNECTION_CLOSE frame MAY
2669 * send a single packet containing a CONNECTION_CLOSE
2670 * frame before entering the draining state, using a
2671 * NO_ERROR code if appropriate
2673 ch->conn_close_queued = 1;
2676 ch_on_terminating_timeout(ch);
2680 case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
2681 if (force_immediate)
2682 ch_on_terminating_timeout(ch);
2683 else if (tcause->remote)
2685 * RFC 9000 s. 10.2.2 Draining Connection State:
2686 * An endpoint MAY enter the draining state from the
2687 * closing state if it receives a CONNECTION_CLOSE frame,
2688 * which indicates that the peer is also closing or draining.
2690 ch->state = QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
2694 case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
2696 * Other than in the force-immediate case, we remain here until the
2699 if (force_immediate)
2700 ch_on_terminating_timeout(ch);
2704 case QUIC_CHANNEL_STATE_TERMINATED:
2711 void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
2712 OSSL_QUIC_FRAME_CONN_CLOSE *f)
2714 QUIC_TERMINATE_CAUSE tcause = {0};
2716 if (!ossl_quic_channel_is_active(ch))
2720 tcause.app = f->is_app;
2721 tcause.error_code = f->error_code;
2722 tcause.frame_type = f->frame_type;
2724 ch_start_terminating(ch, &tcause, 0);
2727 static void free_frame_data(unsigned char *buf, size_t buf_len, void *arg)
2732 static int ch_enqueue_retire_conn_id(QUIC_CHANNEL *ch, uint64_t seq_num)
2738 if ((buf_mem = BUF_MEM_new()) == NULL)
2741 if (!WPACKET_init(&wpkt, buf_mem))
2744 if (!ossl_quic_wire_encode_frame_retire_conn_id(&wpkt, seq_num)) {
2745 WPACKET_cleanup(&wpkt);
2749 WPACKET_finish(&wpkt);
2750 if (!WPACKET_get_total_written(&wpkt, &l))
2753 if (ossl_quic_cfq_add_frame(ch->cfq, 1, QUIC_PN_SPACE_APP,
2754 OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID, 0,
2755 (unsigned char *)buf_mem->data, l,
2756 free_frame_data, NULL) == NULL)
2759 buf_mem->data = NULL;
2760 BUF_MEM_free(buf_mem);
2764 ossl_quic_channel_raise_protocol_error(ch,
2765 QUIC_ERR_INTERNAL_ERROR,
2766 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2767 "internal error enqueueing retire conn id");
2768 BUF_MEM_free(buf_mem);
2772 void ossl_quic_channel_on_new_conn_id(QUIC_CHANNEL *ch,
2773 OSSL_QUIC_FRAME_NEW_CONN_ID *f)
2775 uint64_t new_remote_seq_num = ch->cur_remote_seq_num;
2776 uint64_t new_retire_prior_to = ch->cur_retire_prior_to;
2778 if (!ossl_quic_channel_is_active(ch))
2781 /* We allow only two active connection ids; first check some constraints */
2782 if (ch->cur_remote_dcid.id_len == 0) {
2783 /* Changing from 0 length connection id is disallowed */
2784 ossl_quic_channel_raise_protocol_error(ch,
2785 QUIC_ERR_PROTOCOL_VIOLATION,
2786 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2787 "zero length connection id in use");
2792 if (f->seq_num > new_remote_seq_num)
2793 new_remote_seq_num = f->seq_num;
2794 if (f->retire_prior_to > new_retire_prior_to)
2795 new_retire_prior_to = f->retire_prior_to;
2798 * RFC 9000-5.1.1: An endpoint MUST NOT provide more connection IDs
2799 * than the peer's limit.
2801 * After processing a NEW_CONNECTION_ID frame and adding and retiring
2802 * active connection IDs, if the number of active connection IDs exceeds
2803 * the value advertised in its active_connection_id_limit transport
2804 * parameter, an endpoint MUST close the connection with an error of
2805 * type CONNECTION_ID_LIMIT_ERROR.
2807 if (new_remote_seq_num - new_retire_prior_to > 1) {
2808 ossl_quic_channel_raise_protocol_error(ch,
2809 QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
2810 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2811 "active_connection_id limit violated");
2816 * RFC 9000-5.1.1: An endpoint MAY send connection IDs that temporarily
2817 * exceed a peer's limit if the NEW_CONNECTION_ID frame also requires
2818 * the retirement of any excess, by including a sufficiently large
2819 * value in the Retire Prior To field.
2821 * RFC 9000-5.1.2: An endpoint SHOULD allow for sending and tracking
2822 * a number of RETIRE_CONNECTION_ID frames of at least twice the value
2823 * of the active_connection_id_limit transport parameter. An endpoint
2824 * MUST NOT forget a connection ID without retiring it, though it MAY
2825 * choose to treat having connection IDs in need of retirement that
2826 * exceed this limit as a connection error of type CONNECTION_ID_LIMIT_ERROR.
2828 * We are a little bit more liberal than the minimum mandated.
2830 if (new_retire_prior_to - ch->cur_retire_prior_to > 10) {
2831 ossl_quic_channel_raise_protocol_error(ch,
2832 QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
2833 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2834 "retiring connection id limit violated");
2839 if (new_remote_seq_num > ch->cur_remote_seq_num) {
2840 ch->cur_remote_seq_num = new_remote_seq_num;
2841 ch->cur_remote_dcid = f->conn_id;
2842 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid);
2846 * RFC 9000-5.1.2: Upon receipt of an increased Retire Prior To
2847 * field, the peer MUST stop using the corresponding connection IDs
2848 * and retire them with RETIRE_CONNECTION_ID frames before adding the
2849 * newly provided connection ID to the set of active connection IDs.
2853 * Note: RFC 9000 s. 19.15 says:
2854 * "An endpoint that receives a NEW_CONNECTION_ID frame with a sequence
2855 * number smaller than the Retire Prior To field of a previously received
2856 * NEW_CONNECTION_ID frame MUST send a corresponding
2857 * RETIRE_CONNECTION_ID frame that retires the newly received connection
2858 * ID, unless it has already done so for that sequence number."
2860 * Since we currently always queue RETIRE_CONN_ID frames based on the Retire
2861 * Prior To field of a NEW_CONNECTION_ID frame immediately upon receiving
2862 * that NEW_CONNECTION_ID frame, by definition this will always be met.
2863 * This may change in future when we change our CID handling.
2865 while (new_retire_prior_to > ch->cur_retire_prior_to) {
2866 if (!ch_enqueue_retire_conn_id(ch, ch->cur_retire_prior_to))
2868 ++ch->cur_retire_prior_to;
2872 static void ch_save_err_state(QUIC_CHANNEL *ch)
2874 if (ch->err_state == NULL)
2875 ch->err_state = OSSL_ERR_STATE_new();
2877 if (ch->err_state == NULL)
2880 OSSL_ERR_STATE_save(ch->err_state);
2883 static void ch_raise_net_error(QUIC_CHANNEL *ch)
2885 QUIC_TERMINATE_CAUSE tcause = {0};
2889 ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,
2890 "connection terminated due to network error");
2891 ch_save_err_state(ch);
2893 tcause.error_code = QUIC_ERR_INTERNAL_ERROR;
2896 * Skip Terminating state and go directly to Terminated, no point trying to
2897 * send CONNECTION_CLOSE if we cannot communicate.
2899 ch_start_terminating(ch, &tcause, 1);
2902 int ossl_quic_channel_net_error(QUIC_CHANNEL *ch)
2904 return ch->net_error;
2907 void ossl_quic_channel_restore_err_state(QUIC_CHANNEL *ch)
2912 OSSL_ERR_STATE_restore(ch->err_state);
2915 void ossl_quic_channel_raise_protocol_error_loc(QUIC_CHANNEL *ch,
2916 uint64_t error_code,
2917 uint64_t frame_type,
2919 const char *src_file,
2921 const char *src_func)
2923 QUIC_TERMINATE_CAUSE tcause = {0};
2924 int err_reason = error_code == QUIC_ERR_INTERNAL_ERROR
2925 ? ERR_R_INTERNAL_ERROR : SSL_R_QUIC_PROTOCOL_ERROR;
2926 const char *err_str = ossl_quic_err_to_string(error_code);
2927 const char *err_str_pfx = " (", *err_str_sfx = ")";
2928 const char *ft_str = NULL;
2929 const char *ft_str_pfx = " (", *ft_str_sfx = ")";
2931 if (err_str == NULL) {
2937 if (frame_type != 0) {
2938 ft_str = ossl_quic_frame_type_to_string(frame_type);
2939 if (ft_str == NULL) {
2945 ERR_raise_data(ERR_LIB_SSL, err_reason,
2946 "QUIC error code: 0x%llx%s%s%s "
2947 "(triggered by frame type: 0x%llx%s%s%s), reason: \"%s\"",
2948 (unsigned long long) error_code,
2949 err_str_pfx, err_str, err_str_sfx,
2950 (unsigned long long) frame_type,
2951 ft_str_pfx, ft_str, ft_str_sfx,
2954 ERR_raise_data(ERR_LIB_SSL, err_reason,
2955 "QUIC error code: 0x%llx%s%s%s, reason: \"%s\"",
2956 (unsigned long long) error_code,
2957 err_str_pfx, err_str, err_str_sfx,
2961 if (src_file != NULL)
2962 ERR_set_debug(src_file, src_line, src_func);
2964 ch_save_err_state(ch);
2966 tcause.error_code = error_code;
2967 tcause.frame_type = frame_type;
2969 ch_start_terminating(ch, &tcause, 0);
2973 * Called once the terminating timer expires, meaning we move from TERMINATING
2976 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
2978 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2982 * Updates our idle deadline. Called when an event happens which should bump the
2985 static void ch_update_idle(QUIC_CHANNEL *ch)
2987 if (ch->max_idle_timeout == 0)
2988 ch->idle_deadline = ossl_time_infinite();
2990 /* RFC 9000 s. 10.1: Idle Timeout
2991 * To avoid excessively small idle timeout periods, endpoints
2992 * MUST increase the idle timeout period to be at least three
2993 * times the current Probe Timeout (PTO). This allows for
2994 * multiple PTOs to expire, and therefore multiple probes to
2995 * be sent and lost, prior to idle timeout.
2997 OSSL_TIME pto = ossl_ackm_get_pto_duration(ch->ackm);
2998 OSSL_TIME timeout = ossl_time_max(ossl_ms2time(ch->max_idle_timeout),
2999 ossl_time_multiply(pto, 3));
3001 ch->idle_deadline = ossl_time_add(get_time(ch), timeout);
3006 * Updates our ping deadline, which determines when we next generate a ping if
3007 * we don't have any other ACK-eliciting frames to send.
3009 static void ch_update_ping_deadline(QUIC_CHANNEL *ch)
3011 if (ch->max_idle_timeout > 0) {
3013 * Maximum amount of time without traffic before we send a PING to keep
3014 * the connection open. Usually we use max_idle_timeout/2, but ensure
3015 * the period never exceeds the assumed NAT interval to ensure NAT
3016 * devices don't have their state time out (RFC 9000 s. 10.1.2).
3019 = ossl_time_divide(ossl_ms2time(ch->max_idle_timeout), 2);
3021 max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL);
3023 ch->ping_deadline = ossl_time_add(get_time(ch), max_span);
3025 ch->ping_deadline = ossl_time_infinite();
3029 /* Called when the idle timeout expires. */
3030 static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
3033 * Idle timeout does not have an error code associated with it because a
3034 * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
3035 * TERMINATED anyway.
3037 ch->terminate_cause.app = 0;
3038 ch->terminate_cause.error_code = UINT64_MAX;
3039 ch->terminate_cause.frame_type = 0;
3041 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
3044 /* Called when we, as a server, get a new incoming connection. */
3045 static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
3046 const QUIC_CONN_ID *peer_scid,
3047 const QUIC_CONN_ID *peer_dcid)
3049 if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
3052 /* Generate a SCID we will use for the connection. */
3053 if (!gen_rand_conn_id(ch->libctx, INIT_DCID_LEN,
3054 &ch->cur_local_cid))
3057 /* Note our newly learnt peer address and CIDs. */
3058 ch->cur_peer_addr = *peer;
3059 ch->init_dcid = *peer_dcid;
3060 ch->cur_remote_dcid = *peer_scid;
3062 /* Inform QTX of peer address. */
3063 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
3066 /* Inform TXP of desired CIDs. */
3067 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
3070 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
3073 /* Plug in secrets for the Initial EL. */
3074 if (!ossl_quic_provide_initial_secret(ch->libctx,
3081 /* Register our local CID in the DEMUX. */
3082 if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_cid))
3086 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
3087 ch->doing_proactive_ver_neg = 0; /* not currently supported */
3091 SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)
3096 static int ch_init_new_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs,
3097 int can_send, int can_recv)
3100 int server_init = ossl_quic_stream_is_server_init(qs);
3101 int local_init = (ch->is_server == server_init);
3102 int is_uni = !ossl_quic_stream_is_bidi(qs);
3105 if ((qs->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL)
3109 if ((qs->rstream = ossl_quic_rstream_new(NULL, NULL, 0)) == NULL)
3113 if (!ossl_quic_txfc_init(&qs->txfc, &ch->conn_txfc))
3116 if (ch->got_remote_transport_params) {
3118 * If we already got peer TPs we need to apply the initial CWM credit
3119 * now. If we didn't already get peer TPs this will be done
3120 * automatically for all extant streams when we do.
3126 cwm = ch->rx_init_max_stream_data_uni;
3127 else if (local_init)
3128 cwm = ch->rx_init_max_stream_data_bidi_local;
3130 cwm = ch->rx_init_max_stream_data_bidi_remote;
3132 ossl_quic_txfc_bump_cwm(&qs->txfc, cwm);
3140 rxfc_wnd = ch->tx_init_max_stream_data_uni;
3141 else if (local_init)
3142 rxfc_wnd = ch->tx_init_max_stream_data_bidi_local;
3144 rxfc_wnd = ch->tx_init_max_stream_data_bidi_remote;
3146 if (!ossl_quic_rxfc_init(&qs->rxfc, &ch->conn_rxfc,
3148 DEFAULT_STREAM_RXFC_MAX_WND_MUL * rxfc_wnd,
3155 ossl_quic_sstream_free(qs->sstream);
3157 ossl_quic_rstream_free(qs->rstream);
3162 QUIC_STREAM *ossl_quic_channel_new_stream_local(QUIC_CHANNEL *ch, int is_uni)
3166 uint64_t stream_id, *p_next_ordinal;
3168 type = ch->is_server ? QUIC_STREAM_INITIATOR_SERVER
3169 : QUIC_STREAM_INITIATOR_CLIENT;
3172 p_next_ordinal = &ch->next_local_stream_ordinal_uni;
3173 type |= QUIC_STREAM_DIR_UNI;
3175 p_next_ordinal = &ch->next_local_stream_ordinal_bidi;
3176 type |= QUIC_STREAM_DIR_BIDI;
3179 if (*p_next_ordinal >= ((uint64_t)1) << 62)
3182 stream_id = ((*p_next_ordinal) << 2) | type;
3184 if ((qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id, type)) == NULL)
3187 /* Locally-initiated stream, so we always want a send buffer. */
3188 if (!ch_init_new_stream(ch, qs, /*can_send=*/1, /*can_recv=*/!is_uni))
3195 ossl_quic_stream_map_release(&ch->qsm, qs);
3199 QUIC_STREAM *ossl_quic_channel_new_stream_remote(QUIC_CHANNEL *ch,
3206 peer_role = ch->is_server
3207 ? QUIC_STREAM_INITIATOR_CLIENT
3208 : QUIC_STREAM_INITIATOR_SERVER;
3210 if ((stream_id & QUIC_STREAM_INITIATOR_MASK) != peer_role)
3213 is_uni = ((stream_id & QUIC_STREAM_DIR_MASK) == QUIC_STREAM_DIR_UNI);
3215 qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id,
3216 stream_id & (QUIC_STREAM_INITIATOR_MASK
3217 | QUIC_STREAM_DIR_MASK));
3221 if (!ch_init_new_stream(ch, qs, /*can_send=*/!is_uni, /*can_recv=*/1))
3224 if (ch->incoming_stream_auto_reject)
3225 ossl_quic_channel_reject_stream(ch, qs);
3227 ossl_quic_stream_map_push_accept_queue(&ch->qsm, qs);
3232 ossl_quic_stream_map_release(&ch->qsm, qs);
3236 void ossl_quic_channel_set_incoming_stream_auto_reject(QUIC_CHANNEL *ch,
3240 ch->incoming_stream_auto_reject = (enable != 0);
3241 ch->incoming_stream_auto_reject_aec = aec;
3244 void ossl_quic_channel_reject_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs)
3246 ossl_quic_stream_map_stop_sending_recv_part(&ch->qsm, qs,
3247 ch->incoming_stream_auto_reject_aec);
3249 ossl_quic_stream_map_reset_stream_send_part(&ch->qsm, qs,
3250 ch->incoming_stream_auto_reject_aec);
3253 ossl_quic_stream_map_update_state(&ch->qsm, qs);
3256 /* Replace local connection ID in TXP and DEMUX for testing purposes. */
3257 int ossl_quic_channel_replace_local_cid(QUIC_CHANNEL *ch,
3258 const QUIC_CONN_ID *conn_id)
3260 /* Remove the current local CID from the DEMUX. */
3261 if (!ossl_qrx_remove_dst_conn_id(ch->qrx, &ch->cur_local_cid))
3263 ch->cur_local_cid = *conn_id;
3264 /* Set in the TXP, used only for long header packets. */
3265 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
3267 /* Register our new local CID in the DEMUX. */
3268 if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_cid))
3273 void ossl_quic_channel_set_msg_callback(QUIC_CHANNEL *ch,
3274 ossl_msg_cb msg_callback,
3275 SSL *msg_callback_ssl)
3277 ch->msg_callback = msg_callback;
3278 ch->msg_callback_ssl = msg_callback_ssl;
3279 ossl_qtx_set_msg_callback(ch->qtx, msg_callback, msg_callback_ssl);
3280 ossl_quic_tx_packetiser_set_msg_callback(ch->txp, msg_callback,
3282 ossl_qrx_set_msg_callback(ch->qrx, msg_callback, msg_callback_ssl);
3285 void ossl_quic_channel_set_msg_callback_arg(QUIC_CHANNEL *ch,
3286 void *msg_callback_arg)
3288 ch->msg_callback_arg = msg_callback_arg;
3289 ossl_qtx_set_msg_callback_arg(ch->qtx, msg_callback_arg);
3290 ossl_quic_tx_packetiser_set_msg_callback_arg(ch->txp, msg_callback_arg);
3291 ossl_qrx_set_msg_callback_arg(ch->qrx, msg_callback_arg);
3294 void ossl_quic_channel_set_txku_threshold_override(QUIC_CHANNEL *ch,
3295 uint64_t tx_pkt_threshold)
3297 ch->txku_threshold_override = tx_pkt_threshold;
3300 uint64_t ossl_quic_channel_get_tx_key_epoch(QUIC_CHANNEL *ch)
3302 return ossl_qtx_get_key_epoch(ch->qtx);
3305 uint64_t ossl_quic_channel_get_rx_key_epoch(QUIC_CHANNEL *ch)
3307 return ossl_qrx_get_key_epoch(ch->qrx);
3310 int ossl_quic_channel_trigger_txku(QUIC_CHANNEL *ch)
3312 if (!txku_allowed(ch))
3315 ch->ku_locally_initiated = 1;
3316 ch_trigger_txku(ch);
3320 int ossl_quic_channel_ping(QUIC_CHANNEL *ch)
3322 int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
3324 ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
3329 void ossl_quic_channel_set_inhibit_tick(QUIC_CHANNEL *ch, int inhibit)
3331 ch->inhibit_tick = (inhibit != 0);