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 "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>
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.
23 * TODO(QUIC): Implement address validation and anti-amplification
24 * TODO(QUIC): Implement retry logic
27 #define INIT_DCID_LEN 8
28 #define INIT_CRYPTO_BUF_LEN 8192
29 #define INIT_APP_BUF_LEN 8192
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.
36 #define MAX_NAT_INTERVAL (ossl_ms2time(25000))
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,
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,
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,
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,
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,
92 static int gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid)
94 if (len > QUIC_MAX_CONN_ID_LEN)
97 cid->id_len = (unsigned char)len;
99 if (RAND_bytes_ex(libctx, cid->id, len, len * 8) != 1) {
108 * QUIC Channel Initialization and Teardown
109 * ========================================
111 #define DEFAULT_INIT_CONN_RXFC_WND (2 * 1024 * 1024)
112 #define DEFAULT_CONN_RXFC_MAX_WND_MUL 5
114 #define DEFAULT_INIT_STREAM_RXFC_WND (2 * 1024 * 1024)
115 #define DEFAULT_STREAM_RXFC_MAX_WND_MUL 5
117 #define DEFAULT_INIT_CONN_MAX_STREAMS 100
119 static int ch_init(QUIC_CHANNEL *ch)
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};
126 size_t rx_short_cid_len = ch->is_server ? INIT_DCID_LEN : 0;
128 /* For clients, generate our initial DCID. */
130 && !gen_rand_conn_id(ch->libctx, INIT_DCID_LEN, &ch->init_dcid))
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;
138 ch->ping_deadline = ossl_time_infinite();
140 ch->qtx = ossl_qtx_new(&qtx_args);
144 ch->txpim = ossl_quic_txpim_new();
145 if (ch->txpim == NULL)
148 ch->cfq = ossl_quic_cfq_new();
152 if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
156 * Note: The TP we transmit governs what the peer can transmit and thus
157 * applies to the RXFC.
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;
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,
170 if (!ossl_quic_rxfc_init_for_stream_count(&ch->max_streams_bidi_rxfc,
171 DEFAULT_INIT_CONN_MAX_STREAMS,
175 if (!ossl_quic_rxfc_init_for_stream_count(&ch->max_streams_uni_rxfc,
176 DEFAULT_INIT_CONN_MAX_STREAMS,
180 if (!ossl_statm_init(&ch->statm))
184 ch->cc_method = &ossl_cc_newreno_method;
185 if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL)
188 if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm,
189 ch->cc_method, ch->cc_data)) == NULL)
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,
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;
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)
222 txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
225 ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
229 ossl_quic_tx_packetiser_set_ack_tx_cb(ch->txp, ch_on_txp_ack_tx, ch);
231 if ((ch->demux = ossl_quic_demux_new(/*BIO=*/NULL,
232 /*Short CID Len=*/rx_short_cid_len,
233 get_time, ch)) == NULL)
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
242 ossl_quic_demux_set_default_handler(ch->demux,
243 ch_default_packet_handler,
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;
251 if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
254 if (!ossl_qrx_set_early_validation_cb(ch->qrx,
259 if (!ossl_qrx_set_key_update_cb(ch->qrx,
264 if (!ch->is_server && !ossl_qrx_add_dst_conn_id(ch->qrx, &txp_args.cur_scid))
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)
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;
291 if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
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;
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.)
307 if (!ch->is_server && !ch_generate_transport_params(ch))
311 ossl_quic_reactor_init(&ch->rtor, ch_tick, ch,
312 ch_determine_next_tick_deadline(ch));
320 static void ch_cleanup(QUIC_CHANNEL *ch)
324 if (ch->ackm != NULL)
325 for (pn_space = QUIC_PN_SPACE_INITIAL;
326 pn_space < QUIC_PN_SPACE_NUM;
328 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
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);
337 ossl_statm_destroy(&ch->statm);
338 ossl_ackm_free(ch->ackm);
341 ossl_quic_stream_map_cleanup(&ch->qsm);
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]);
348 ossl_qrx_pkt_release(ch->qrx_pkt);
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);
357 QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
359 QUIC_CHANNEL *ch = NULL;
361 if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
364 ch->libctx = args->libctx;
365 ch->propq = args->propq;
366 ch->is_server = args->is_server;
368 ch->mutex = args->mutex;
369 ch->now_cb = args->now_cb;
370 ch->now_cb_arg = args->now_cb_arg;
380 void ossl_quic_channel_free(QUIC_CHANNEL *ch)
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,
398 ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
402 int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
404 *peer_addr = ch->cur_peer_addr;
408 int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
410 ch->cur_peer_addr = *peer_addr;
414 QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
419 QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
424 OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
429 QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
432 return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
435 int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
437 return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
440 int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
442 if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING
443 || ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING)
449 int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
451 if (ch->state == QUIC_CHANNEL_STATE_TERMINATED)
457 int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
459 return ossl_quic_channel_is_terminating(ch)
460 || ossl_quic_channel_is_terminated(ch);
463 const QUIC_TERMINATE_CAUSE *
464 ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
466 return ossl_quic_channel_is_term_any(ch) ? &ch->terminate_cause : NULL;
469 int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
471 return ch->handshake_complete;
474 int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
476 return ch->handshake_confirmed;
479 QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch)
484 CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch)
490 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
491 * ================================================================
494 /* Used by various components. */
495 static OSSL_TIME get_time(void *arg)
497 QUIC_CHANNEL *ch = arg;
499 if (ch->now_cb == NULL)
500 return ossl_time_now();
502 return ch->now_cb(ch->now_cb_arg);
506 static uint64_t get_stream_limit(int uni, void *arg)
508 QUIC_CHANNEL *ch = arg;
510 return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
514 * Called by QRX to determine if a packet is potentially invalid before trying
517 static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg)
519 QUIC_CHANNEL *ch = arg;
521 /* Potential duplicates should not be processed. */
522 if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
529 * Triggers a TXKU (whether spontaneous or solicited). Does not check whether
530 * spontaneous TXKU is currently allowed.
533 static void ch_trigger_txku(QUIC_CHANNEL *ch)
536 = ossl_quic_tx_packetiser_get_next_pn(ch->txp, QUIC_PN_SPACE_APP);
538 if (!ossl_quic_pn_valid(next_pn)
539 || !ossl_qtx_trigger_key_update(ch->qtx)) {
540 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
545 ch->txku_in_progress = 1;
546 ch->txku_pn = next_pn;
547 ch->rxku_expected = ch->ku_locally_initiated;
551 static int txku_in_progress(QUIC_CHANNEL *ch)
553 if (ch->txku_in_progress
554 && ossl_ackm_get_largest_acked(ch->ackm, QUIC_PN_SPACE_APP) >= ch->txku_pn) {
555 OSSL_TIME pto = ossl_ackm_get_pto_duration(ch->ackm);
558 * RFC 9001 s. 6.5: Endpoints SHOULD wait three times the PTO before
559 * initiating a key update after receiving an acknowledgment that
560 * confirms that the previous key update was received.
562 * Note that by the above wording, this period starts from when we get
563 * the ack for a TXKU-triggering packet, not when the TXKU is initiated.
564 * So we defer TXKU cooldown deadline calculation to this point.
566 ch->txku_in_progress = 0;
567 ch->txku_cooldown_deadline = ossl_time_add(get_time(ch),
568 ossl_time_multiply(pto, 3));
571 return ch->txku_in_progress;
575 static int txku_allowed(QUIC_CHANNEL *ch)
577 return ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT /* Sanity check. */
578 /* Strict RFC 9001 criterion for TXKU. */
579 && ch->handshake_confirmed
580 && !txku_in_progress(ch);
584 static int txku_recommendable(QUIC_CHANNEL *ch)
586 if (!txku_allowed(ch))
590 /* Recommended RFC 9001 criterion for TXKU. */
591 ossl_time_compare(get_time(ch), ch->txku_cooldown_deadline) >= 0
592 /* Some additional sensible criteria. */
593 && !ch->rxku_in_progress
594 && !ch->rxku_pending_confirm;
598 static int txku_desirable(QUIC_CHANNEL *ch)
600 uint64_t cur_pkt_count, max_pkt_count, thresh_pkt_count;
601 const uint32_t enc_level = QUIC_ENC_LEVEL_1RTT;
603 /* Check AEAD limit to determine if we should perform a spontaneous TXKU. */
604 cur_pkt_count = ossl_qtx_get_cur_epoch_pkt_count(ch->qtx, enc_level);
605 max_pkt_count = ossl_qtx_get_max_epoch_pkt_count(ch->qtx, enc_level);
607 thresh_pkt_count = max_pkt_count / 2;
608 if (ch->txku_threshold_override != UINT64_MAX)
609 thresh_pkt_count = ch->txku_threshold_override;
611 return cur_pkt_count >= thresh_pkt_count;
615 static void ch_maybe_trigger_spontaneous_txku(QUIC_CHANNEL *ch)
617 if (!txku_recommendable(ch) || !txku_desirable(ch))
620 ch->ku_locally_initiated = 1;
625 static int rxku_allowed(QUIC_CHANNEL *ch)
628 * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a key update prior to
629 * having confirmed the handshake (Section 4.1.2).
631 * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a subsequent key update
632 * unless it has received an acknowledgment for a packet that was sent
633 * protected with keys from the current key phase.
635 * RFC 9001 s. 6.2: If an endpoint detects a second update before it has
636 * sent any packets with updated keys containing an acknowledgment for the
637 * packet that initiated the key update, it indicates that its peer has
638 * updated keys twice without awaiting confirmation. An endpoint MAY treat
639 * such consecutive key updates as a connection error of type
642 return ch->handshake_confirmed && !ch->rxku_pending_confirm;
646 * Called when the QRX detects a new RX key update event.
650 DECISION_PROTOCOL_VIOLATION,
651 DECISION_SOLICITED_TXKU
654 /* Called when the QRX detects a key update has occurred. */
656 static void rxku_detected(QUIC_PN pn, void *arg)
658 QUIC_CHANNEL *ch = arg;
659 enum rxku_decision decision;
663 * Note: rxku_in_progress is always 0 here as an RXKU cannot be detected
664 * when we are still in UPDATING or COOLDOWN (see quic_record_rx.h).
666 assert(!ch->rxku_in_progress);
668 if (!rxku_allowed(ch))
669 /* Is RXKU even allowed at this time? */
670 decision = DECISION_PROTOCOL_VIOLATION;
672 else if (ch->ku_locally_initiated)
674 * If this key update was locally initiated (meaning that this detected
675 * RXKU event is a result of our own spontaneous TXKU), we do not
676 * trigger another TXKU; after all, to do so would result in an infinite
677 * ping-pong of key updates. We still process it as an RXKU.
679 decision = DECISION_RXKU_ONLY;
683 * Otherwise, a peer triggering a KU means we have to trigger a KU also.
685 decision = DECISION_SOLICITED_TXKU;
687 if (decision == DECISION_PROTOCOL_VIOLATION) {
688 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_KEY_UPDATE_ERROR,
689 0, "RX key update again too soon");
693 pto = ossl_ackm_get_pto_duration(ch->ackm);
695 ch->ku_locally_initiated = 0;
696 ch->rxku_in_progress = 1;
697 ch->rxku_pending_confirm = 1;
698 ch->rxku_trigger_pn = pn;
699 ch->rxku_update_end_deadline = ossl_time_add(get_time(ch), pto);
700 ch->rxku_expected = 0;
702 if (decision == DECISION_SOLICITED_TXKU)
703 /* NOT gated by usual txku_allowed() */
707 * Ordinarily, we only generate ACK when some ACK-eliciting frame has been
708 * received. In some cases, this may not occur for a long time, for example
709 * if transmission of application data is going in only one direction and
710 * nothing else is happening with the connection. However, since the peer
711 * cannot initiate a subsequent (spontaneous) TXKU until its prior
712 * (spontaneous or solicited) TXKU has completed - meaning that prior
713 * TXKU's trigger packet (or subsequent packet) has been acknowledged, this
714 * can lead to very long times before a TXKU is considered 'completed'.
715 * Optimise this by forcing ACK generation after triggering TXKU.
716 * (Basically, we consider a RXKU event something that is 'ACK-eliciting',
717 * which it more or less should be; it is necessarily separate from ordinary
718 * processing of ACK-eliciting frames as key update is not indicated via a
721 ossl_quic_tx_packetiser_schedule_ack(ch->txp, QUIC_PN_SPACE_APP);
724 /* Called per tick to handle RXKU timer events. */
726 static void ch_rxku_tick(QUIC_CHANNEL *ch)
728 if (!ch->rxku_in_progress
729 || ossl_time_compare(get_time(ch), ch->rxku_update_end_deadline) < 0)
732 ch->rxku_update_end_deadline = ossl_time_infinite();
733 ch->rxku_in_progress = 0;
735 if (!ossl_qrx_key_update_timeout(ch->qrx, /*normal=*/1))
736 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
737 "RXKU cooldown internal error");
741 static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
744 QUIC_CHANNEL *ch = arg;
746 if (pn_space != QUIC_PN_SPACE_APP || !ch->rxku_pending_confirm
747 || !ossl_quic_frame_ack_contains_pn(ack, ch->rxku_trigger_pn))
751 * Defer clearing rxku_pending_confirm until TXP generate call returns
754 ch->rxku_pending_confirm_done = 1;
758 * QUIC Channel: Handshake Layer Event Handling
759 * ============================================
761 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
762 size_t *consumed, void *arg)
765 QUIC_CHANNEL *ch = arg;
766 uint32_t enc_level = ch->tx_enc_level;
767 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
768 QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
770 if (!ossl_assert(sstream != NULL))
773 ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
777 static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
785 if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
791 static int ch_on_crypto_recv_record(const unsigned char **buf,
792 size_t *bytes_read, void *arg)
794 QUIC_CHANNEL *ch = arg;
795 QUIC_RSTREAM *rstream;
796 int is_fin = 0; /* crypto stream is never finished, so we don't use this */
800 * After we move to a later EL we must not allow our peer to send any new
801 * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
804 * In practice we will only move to a new EL when we have consumed all bytes
805 * which should be sent on the crypto stream at a previous EL. For example,
806 * the Handshake EL should not be provisioned until we have completely
807 * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
808 * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
809 * given EL is available we simply ensure we have not received any further
810 * bytes at a lower EL.
812 for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
813 if (i != QUIC_ENC_LEVEL_0RTT &&
814 !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
815 /* Protocol violation (RFC 9001 s. 4.1.3) */
816 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
817 OSSL_QUIC_FRAME_TYPE_CRYPTO,
818 "crypto stream data in wrong EL");
822 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
826 return ossl_quic_rstream_get_record(rstream, buf, bytes_read,
830 static int ch_on_crypto_release_record(size_t bytes_read, void *arg)
832 QUIC_CHANNEL *ch = arg;
833 QUIC_RSTREAM *rstream;
835 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
839 return ossl_quic_rstream_release_record(rstream, bytes_read);
842 static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
843 uint32_t suite_id, EVP_MD *md,
844 const unsigned char *secret,
848 QUIC_CHANNEL *ch = arg;
851 if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
858 if (enc_level <= ch->tx_enc_level)
860 * Does not make sense for us to try and provision an EL we have already
865 if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
870 ch->tx_enc_level = enc_level;
873 if (enc_level <= ch->rx_enc_level)
875 * Does not make sense for us to try and provision an EL we have already
881 * Ensure all crypto streams for previous ELs are now empty of available
884 for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
885 if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
886 /* Protocol violation (RFC 9001 s. 4.1.3) */
887 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
888 OSSL_QUIC_FRAME_TYPE_CRYPTO,
889 "crypto stream data in wrong EL");
893 if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
898 ch->have_new_rx_secret = 1;
899 ch->rx_enc_level = enc_level;
905 static int ch_on_handshake_complete(void *arg)
907 QUIC_CHANNEL *ch = arg;
909 if (!ossl_assert(!ch->handshake_complete))
910 return 0; /* this should not happen twice */
912 if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
915 if (!ch->got_remote_transport_params) {
917 * Was not a valid QUIC handshake if we did not get valid transport
920 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
921 OSSL_QUIC_FRAME_TYPE_CRYPTO,
922 "no transport parameters received");
926 /* Don't need transport parameters anymore. */
927 OPENSSL_free(ch->local_transport_params);
928 ch->local_transport_params = NULL;
930 /* Tell TXP the handshake is complete. */
931 ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
933 ch->handshake_complete = 1;
937 * On the server, the handshake is confirmed as soon as it is complete.
939 ossl_quic_channel_on_handshake_confirmed(ch);
941 ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
947 static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
949 QUIC_CHANNEL *ch = arg;
951 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_ERR_BEGIN + alert_code,
952 0, "handshake alert");
957 * QUIC Channel: Transport Parameter Handling
958 * ==========================================
962 * Called by handshake layer when we receive QUIC Transport Parameters from the
963 * peer. Note that these are not authenticated until the handshake is marked
966 #define TP_REASON_SERVER_ONLY(x) \
967 x " may not be sent by a client"
968 #define TP_REASON_DUP(x) \
969 x " appears multiple times"
970 #define TP_REASON_MALFORMED(x) \
972 #define TP_REASON_EXPECTED_VALUE(x) \
973 x " does not match expected value"
974 #define TP_REASON_NOT_RETRY(x) \
975 x " sent when not performing a retry"
976 #define TP_REASON_REQUIRED(x) \
977 x " was not sent but is required"
979 static void txfc_bump_cwm_bidi(QUIC_STREAM *s, void *arg)
981 if (!ossl_quic_stream_is_bidi(s)
982 || ossl_quic_stream_is_server_init(s))
985 ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
988 static void txfc_bump_cwm_uni(QUIC_STREAM *s, void *arg)
990 if (ossl_quic_stream_is_bidi(s)
991 || ossl_quic_stream_is_server_init(s))
994 ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
997 static void do_update(QUIC_STREAM *s, void *arg)
999 QUIC_CHANNEL *ch = arg;
1001 ossl_quic_stream_map_update_state(&ch->qsm, s);
1004 static int ch_on_transport_params(const unsigned char *params,
1008 QUIC_CHANNEL *ch = arg;
1012 const unsigned char *body;
1013 int got_orig_dcid = 0;
1014 int got_initial_scid = 0;
1015 int got_retry_scid = 0;
1016 int got_initial_max_data = 0;
1017 int got_initial_max_stream_data_bidi_local = 0;
1018 int got_initial_max_stream_data_bidi_remote = 0;
1019 int got_initial_max_stream_data_uni = 0;
1020 int got_initial_max_streams_bidi = 0;
1021 int got_initial_max_streams_uni = 0;
1022 int got_ack_delay_exp = 0;
1023 int got_max_ack_delay = 0;
1024 int got_max_udp_payload_size = 0;
1025 int got_max_idle_timeout = 0;
1026 int got_active_conn_id_limit = 0;
1028 const char *reason = "bad transport parameter";
1030 if (ch->got_remote_transport_params)
1033 if (!PACKET_buf_init(&pkt, params, params_len))
1036 while (PACKET_remaining(&pkt) > 0) {
1037 if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
1041 case QUIC_TPARAM_ORIG_DCID:
1042 if (got_orig_dcid) {
1043 reason = TP_REASON_DUP("ORIG_DCID");
1047 if (ch->is_server) {
1048 reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
1052 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1053 reason = TP_REASON_MALFORMED("ORIG_DCID");
1057 /* Must match our initial DCID. */
1058 if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
1059 reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
1066 case QUIC_TPARAM_RETRY_SCID:
1067 if (ch->is_server) {
1068 reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
1072 if (got_retry_scid) {
1073 reason = TP_REASON_DUP("RETRY_SCID");
1077 if (!ch->doing_retry) {
1078 reason = TP_REASON_NOT_RETRY("RETRY_SCID");
1082 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1083 reason = TP_REASON_MALFORMED("RETRY_SCID");
1087 /* Must match Retry packet SCID. */
1088 if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
1089 reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
1096 case QUIC_TPARAM_INITIAL_SCID:
1097 if (got_initial_scid) {
1098 /* must not appear more than once */
1099 reason = TP_REASON_DUP("INITIAL_SCID");
1103 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1104 reason = TP_REASON_MALFORMED("INITIAL_SCID");
1108 /* Must match SCID of first Initial packet from server. */
1109 if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
1110 reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
1114 got_initial_scid = 1;
1117 case QUIC_TPARAM_INITIAL_MAX_DATA:
1118 if (got_initial_max_data) {
1119 /* must not appear more than once */
1120 reason = TP_REASON_DUP("INITIAL_MAX_DATA");
1124 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1125 reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
1129 ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
1130 got_initial_max_data = 1;
1133 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
1134 if (got_initial_max_stream_data_bidi_local) {
1135 /* must not appear more than once */
1136 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1140 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1141 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1146 * This is correct; the BIDI_LOCAL TP governs streams created by
1147 * the endpoint which sends the TP, i.e., our peer.
1149 ch->rx_init_max_stream_data_bidi_remote = v;
1150 got_initial_max_stream_data_bidi_local = 1;
1153 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
1154 if (got_initial_max_stream_data_bidi_remote) {
1155 /* must not appear more than once */
1156 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1160 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1161 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1166 * This is correct; the BIDI_REMOTE TP governs streams created
1167 * by the endpoint which receives the TP, i.e., us.
1169 ch->rx_init_max_stream_data_bidi_local = v;
1171 /* Apply to all existing streams. */
1172 ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_bidi, &v);
1173 got_initial_max_stream_data_bidi_remote = 1;
1176 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
1177 if (got_initial_max_stream_data_uni) {
1178 /* must not appear more than once */
1179 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
1183 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1184 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
1188 ch->rx_init_max_stream_data_uni = v;
1190 /* Apply to all existing streams. */
1191 ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_uni, &v);
1192 got_initial_max_stream_data_uni = 1;
1195 case QUIC_TPARAM_ACK_DELAY_EXP:
1196 if (got_ack_delay_exp) {
1197 /* must not appear more than once */
1198 reason = TP_REASON_DUP("ACK_DELAY_EXP");
1202 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1203 || v > QUIC_MAX_ACK_DELAY_EXP) {
1204 reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
1208 ch->rx_ack_delay_exp = (unsigned char)v;
1209 got_ack_delay_exp = 1;
1212 case QUIC_TPARAM_MAX_ACK_DELAY:
1213 if (got_max_ack_delay) {
1214 /* must not appear more than once */
1215 reason = TP_REASON_DUP("MAX_ACK_DELAY");
1219 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1220 || v >= (((uint64_t)1) << 14)) {
1221 reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
1225 ch->rx_max_ack_delay = v;
1226 got_max_ack_delay = 1;
1229 case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
1230 if (got_initial_max_streams_bidi) {
1231 /* must not appear more than once */
1232 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
1236 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1237 || v > (((uint64_t)1) << 60)) {
1238 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
1242 assert(ch->max_local_streams_bidi == 0);
1243 ch->max_local_streams_bidi = v;
1244 got_initial_max_streams_bidi = 1;
1247 case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
1248 if (got_initial_max_streams_uni) {
1249 /* must not appear more than once */
1250 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
1254 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1255 || v > (((uint64_t)1) << 60)) {
1256 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
1260 assert(ch->max_local_streams_uni == 0);
1261 ch->max_local_streams_uni = v;
1262 got_initial_max_streams_uni = 1;
1265 case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
1266 if (got_max_idle_timeout) {
1267 /* must not appear more than once */
1268 reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
1272 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1273 reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
1277 if (v > 0 && v < ch->max_idle_timeout)
1278 ch->max_idle_timeout = v;
1281 got_max_idle_timeout = 1;
1284 case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
1285 if (got_max_udp_payload_size) {
1286 /* must not appear more than once */
1287 reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
1291 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1292 || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
1293 reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
1297 ch->rx_max_udp_payload_size = v;
1298 got_max_udp_payload_size = 1;
1301 case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
1302 if (got_active_conn_id_limit) {
1303 /* must not appear more than once */
1304 reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
1308 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1309 || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
1310 reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
1314 ch->rx_active_conn_id_limit = v;
1315 got_active_conn_id_limit = 1;
1318 case QUIC_TPARAM_STATELESS_RESET_TOKEN:
1319 /* TODO(QUIC): Handle stateless reset tokens. */
1321 * We ignore these for now, but we must ensure a client doesn't
1324 if (ch->is_server) {
1325 reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
1329 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1330 if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
1331 reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
1337 case QUIC_TPARAM_PREFERRED_ADDR:
1338 /* TODO(QUIC): Handle preferred address. */
1339 if (ch->is_server) {
1340 reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
1344 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1346 reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
1352 case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
1353 /* We do not currently handle migration, so nothing to do. */
1355 /* Skip over and ignore. */
1356 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
1365 if (!got_initial_scid) {
1366 reason = TP_REASON_REQUIRED("INITIAL_SCID");
1370 if (!ch->is_server) {
1371 if (!got_orig_dcid) {
1372 reason = TP_REASON_REQUIRED("ORIG_DCID");
1376 if (ch->doing_retry && !got_retry_scid) {
1377 reason = TP_REASON_REQUIRED("RETRY_SCID");
1382 ch->got_remote_transport_params = 1;
1384 if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
1385 || got_initial_max_streams_bidi || got_initial_max_streams_uni)
1387 * If FC credit was bumped, we may now be able to send. Update all
1390 ossl_quic_stream_map_visit(&ch->qsm, do_update, ch);
1392 /* If we are a server, we now generate our own transport parameters. */
1393 if (ch->is_server && !ch_generate_transport_params(ch)) {
1394 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1402 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
1408 * Called when we want to generate transport parameters. This is called
1409 * immediately at instantiation time for a client and after we receive the
1410 * client's transport parameters for a server.
1412 static int ch_generate_transport_params(QUIC_CHANNEL *ch)
1415 BUF_MEM *buf_mem = NULL;
1420 if (ch->local_transport_params != NULL)
1423 if ((buf_mem = BUF_MEM_new()) == NULL)
1426 if (!WPACKET_init(&wpkt, buf_mem))
1431 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
1435 if (ch->is_server) {
1436 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
1440 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1441 &ch->cur_local_cid))
1444 /* Client always uses an empty SCID. */
1445 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1450 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
1451 ch->max_idle_timeout))
1454 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
1455 QUIC_MIN_INITIAL_DGRAM_LEN))
1458 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
1462 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
1463 ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
1466 /* Send the default CWM for a new RXFC. */
1467 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1468 ch->tx_init_max_stream_data_bidi_local))
1471 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1472 ch->tx_init_max_stream_data_bidi_remote))
1475 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
1476 ch->tx_init_max_stream_data_uni))
1479 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
1480 ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc)))
1483 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
1484 ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc)))
1487 if (!WPACKET_finish(&wpkt))
1492 if (!WPACKET_get_total_written(&wpkt, &buf_len))
1495 ch->local_transport_params = (unsigned char *)buf_mem->data;
1496 buf_mem->data = NULL;
1499 if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
1506 WPACKET_cleanup(&wpkt);
1507 BUF_MEM_free(buf_mem);
1512 * QUIC Channel: Ticker-Mutator
1513 * ============================
1517 * The central ticker function called by the reactor. This does everything, or
1518 * at least everything network I/O related. Best effort - not allowed to fail
1521 static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags)
1523 OSSL_TIME now, deadline;
1524 QUIC_CHANNEL *ch = arg;
1525 int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0;
1528 * When we tick the QUIC connection, we do everything we need to do
1529 * periodically. In order, we:
1531 * - handle any incoming data from the network;
1532 * - handle any timer events which are due to fire (ACKM, etc.)
1533 * - write any data to the network due to be sent, to the extent
1535 * - determine the time at which we should next be ticked.
1538 /* If we are in the TERMINATED state, there is nothing to do. */
1539 if (ossl_quic_channel_is_terminated(ch)) {
1540 res->net_read_desired = 0;
1541 res->net_write_desired = 0;
1542 res->tick_deadline = ossl_time_infinite();
1547 * If we are in the TERMINATING state, check if the terminating timer has
1550 if (ossl_quic_channel_is_terminating(ch)) {
1553 if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
1554 ch_on_terminating_timeout(ch);
1555 res->net_read_desired = 0;
1556 res->net_write_desired = 0;
1557 res->tick_deadline = ossl_time_infinite();
1558 return; /* abort normal processing, nothing to do */
1562 /* Handle RXKU timeouts. */
1565 /* Handle any incoming data from network. */
1569 /* Process queued incoming packets. */
1573 * Allow the handshake layer to check for any new incoming data and generate
1574 * new outgoing data.
1576 ch->have_new_rx_secret = 0;
1578 ossl_quic_tls_tick(ch->qtls);
1581 * If the handshake layer gave us a new secret, we need to do RX again
1582 * because packets that were not previously processable and were
1583 * deferred might now be processable.
1585 * TODO(QUIC): Consider handling this in the yield_secret callback.
1587 } while (ch->have_new_rx_secret);
1590 * Handle any timer events which are due to fire; namely, the loss detection
1591 * deadline and the idle timeout.
1593 * ACKM ACK generation deadline is polled by TXP, so we don't need to handle
1597 if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
1599 * Idle timeout differs from normal protocol violation because we do not
1600 * send a CONN_CLOSE frame; go straight to TERMINATED.
1602 ch_on_idle_timeout(ch);
1603 res->net_read_desired = 0;
1604 res->net_write_desired = 0;
1605 res->tick_deadline = ossl_time_infinite();
1609 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1610 if (!ossl_time_is_zero(deadline) && ossl_time_compare(now, deadline) >= 0)
1611 ossl_ackm_on_timeout(ch->ackm);
1613 /* If a ping is due, inform TXP. */
1614 if (ossl_time_compare(now, ch->ping_deadline) >= 0) {
1615 int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
1617 ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
1620 /* Write any data to the network due to be sent. */
1624 ossl_quic_stream_map_gc(&ch->qsm);
1626 /* Determine the time at which we should next be ticked. */
1627 res->tick_deadline = ch_determine_next_tick_deadline(ch);
1630 * Always process network input unless we are now terminated.
1631 * Although we had not terminated at the beginning of this tick, network
1632 * errors in ch_rx_pre() or ch_tx() may have caused us to transition to the
1635 res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
1637 /* We want to write to the network if we have any in our queue. */
1638 res->net_write_desired
1639 = (!ossl_quic_channel_is_terminated(ch)
1640 && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
1643 /* Process incoming datagrams, if any. */
1644 static void ch_rx_pre(QUIC_CHANNEL *ch)
1648 if (!ch->is_server && !ch->have_sent_any_pkt)
1652 * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
1653 * to the appropriate QRX instance.
1655 ret = ossl_quic_demux_pump(ch->demux);
1656 if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
1658 * We don't care about transient failure, but permanent failure means we
1659 * should tear down the connection as though a protocol violation
1660 * occurred. Skip straight to the Terminating state as there is no point
1661 * trying to send CONNECTION_CLOSE frames if the network BIO is not
1662 * operating correctly.
1664 ch_raise_net_error(ch);
1667 /* Check incoming forged packet limit and terminate connection if needed. */
1668 static void ch_rx_check_forged_pkt_limit(QUIC_CHANNEL *ch)
1671 uint64_t limit = UINT64_MAX, l;
1673 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
1674 enc_level < QUIC_ENC_LEVEL_NUM;
1678 * Different ELs can have different AEADs which can in turn impose
1679 * different limits, so use the lowest value of any currently valid EL.
1681 if ((ch->el_discarded & (1U << enc_level)) != 0)
1684 if (enc_level > ch->rx_enc_level)
1687 l = ossl_qrx_get_max_forged_pkt_count(ch->qrx, enc_level);
1692 if (ossl_qrx_get_cur_forged_pkt_count(ch->qrx) < limit)
1695 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_AEAD_LIMIT_REACHED, 0,
1699 /* Process queued incoming packets and handle frames, if any. */
1700 static int ch_rx(QUIC_CHANNEL *ch)
1702 int handled_any = 0;
1704 if (!ch->is_server && !ch->have_sent_any_pkt)
1706 * We have not sent anything yet, therefore there is no need to check
1707 * for incoming data.
1712 assert(ch->qrx_pkt == NULL);
1714 if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
1720 ch_rx_handle_packet(ch); /* best effort */
1723 * Regardless of the outcome of frame handling, unref the packet.
1724 * This will free the packet unless something added another
1725 * reference to it during frame processing.
1727 ossl_qrx_pkt_release(ch->qrx_pkt);
1730 ch->have_sent_ack_eliciting_since_rx = 0;
1734 ch_rx_check_forged_pkt_limit(ch);
1737 * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
1738 * process one or more incoming packets.
1740 if (handled_any && ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING)
1741 ch->conn_close_queued = 1;
1746 /* Handles the packet currently in ch->qrx_pkt->hdr. */
1747 static void ch_rx_handle_packet(QUIC_CHANNEL *ch)
1751 assert(ch->qrx_pkt != NULL);
1753 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
1754 if (!ch->have_received_enc_pkt) {
1755 ch->cur_remote_dcid = ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
1756 ch->have_received_enc_pkt = 1;
1759 * We change to using the SCID in the first Initial packet as the
1762 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
1765 enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
1766 if ((ch->el_discarded & (1U << enc_level)) != 0)
1767 /* Do not process packets from ELs we have already discarded. */
1771 /* Handle incoming packet. */
1772 switch (ch->qrx_pkt->hdr->type) {
1773 case QUIC_PKT_TYPE_RETRY:
1774 if (ch->doing_retry || ch->is_server)
1776 * It is not allowed to ask a client to do a retry more than
1777 * once. Clients may not send retries.
1781 if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
1782 /* Packets with zero-length Retry Tokens are invalid. */
1786 * TODO(QUIC): Theoretically this should probably be in the QRX.
1787 * However because validation is dependent on context (namely the
1788 * client's initial DCID) we can't do this cleanly. In the future we
1789 * should probably add a callback to the QRX to let it call us (via
1790 * the DEMUX) and ask us about the correct original DCID, rather
1791 * than allow the QRX to emit a potentially malformed packet to the
1792 * upper layers. However, special casing this will do for now.
1794 if (!ossl_quic_validate_retry_integrity_tag(ch->libctx,
1798 /* Malformed retry packet, ignore. */
1801 ch_retry(ch, ch->qrx_pkt->hdr->data,
1802 ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
1803 &ch->qrx_pkt->hdr->src_conn_id);
1806 case QUIC_PKT_TYPE_0RTT:
1808 /* Clients should never receive 0-RTT packets. */
1812 * TODO(QUIC): Implement 0-RTT on the server side. We currently do
1813 * not need to implement this as a client can only do 0-RTT if we
1814 * have given it permission to in a previous session.
1818 case QUIC_PKT_TYPE_INITIAL:
1819 case QUIC_PKT_TYPE_HANDSHAKE:
1820 case QUIC_PKT_TYPE_1RTT:
1821 if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
1823 * We automatically drop INITIAL EL keys when first successfully
1824 * decrypting a HANDSHAKE packet, as per the RFC.
1826 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
1828 if (ch->rxku_in_progress
1829 && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_1RTT
1830 && ch->qrx_pkt->pn >= ch->rxku_trigger_pn
1831 && ch->qrx_pkt->key_epoch < ossl_qrx_get_key_epoch(ch->qrx)) {
1833 * RFC 9001 s. 6.4: Packets with higher packet numbers MUST be
1834 * protected with either the same or newer packet protection keys
1835 * than packets with lower packet numbers. An endpoint that
1836 * successfully removes protection with old keys when newer keys
1837 * were used for packets with lower packet numbers MUST treat this
1838 * as a connection error of type KEY_UPDATE_ERROR.
1840 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_KEY_UPDATE_ERROR,
1841 0, "new packet with old keys");
1845 /* This packet contains frames, pass to the RXDP. */
1846 ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
1856 * This is called by the demux when we get a packet not destined for any known
1859 static void ch_default_packet_handler(QUIC_URXE *e, void *arg)
1861 QUIC_CHANNEL *ch = arg;
1865 if (!ossl_assert(ch->is_server))
1869 * We only support one connection to our server currently, so if we already
1870 * started one, ignore any new connection attempts.
1872 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1876 * We have got a packet for an unknown DCID. This might be an attempt to
1877 * open a new connection.
1879 if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
1882 if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
1886 * We set short_conn_id_len to SIZE_MAX here which will cause the decode
1887 * operation to fail if we get a 1-RTT packet. This is fine since we only
1888 * care about Initial packets.
1890 if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL))
1893 switch (hdr.version) {
1894 case QUIC_VERSION_1:
1897 case QUIC_VERSION_NONE:
1899 /* Unknown version or proactive version negotiation request, bail. */
1900 /* TODO(QUIC): Handle version negotiation on server side */
1905 * We only care about Initial packets which might be trying to establish a
1908 if (hdr.type != QUIC_PKT_TYPE_INITIAL)
1912 * Assume this is a valid attempt to initiate a connection.
1914 * We do not register the DCID in the initial packet we received and that
1915 * DCID is not actually used again, thus after provisioning the correct
1916 * Initial keys derived from it (which is done in the call below) we pass
1917 * the received packet directly to the QRX so that it can process it as a
1918 * one-time thing, instead of going through the usual DEMUX DCID-based
1921 if (!ch_server_on_new_conn(ch, &e->peer,
1926 ossl_qrx_inject_urxe(ch->qrx, e);
1930 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1933 ossl_quic_demux_release_urxe(ch->demux, e);
1936 /* Try to generate packets and if possible, flush them to the network. */
1937 static int ch_tx(QUIC_CHANNEL *ch)
1939 QUIC_TXP_STATUS status;
1941 if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING) {
1943 * While closing, only send CONN_CLOSE if we've received more traffic
1944 * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
1945 * future calls to it generate CONN_CLOSE frames, so otherwise we would
1946 * just constantly generate CONN_CLOSE frames.
1948 if (!ch->conn_close_queued)
1951 ch->conn_close_queued = 0;
1954 /* Do TXKU if we need to. */
1955 ch_maybe_trigger_spontaneous_txku(ch);
1957 ch->rxku_pending_confirm_done = 0;
1960 * Send a packet, if we need to. Best effort. The TXP consults the CC and
1961 * applies any limitations imposed by it, so we don't need to do it here.
1963 * Best effort. In particular if TXP fails for some reason we should still
1964 * flush any queued packets which we already generated.
1966 switch (ossl_quic_tx_packetiser_generate(ch->txp,
1967 TX_PACKETISER_ARCHETYPE_NORMAL,
1969 case TX_PACKETISER_RES_SENT_PKT:
1970 ch->have_sent_any_pkt = 1; /* Packet was sent */
1973 * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when
1974 * sending an ack-eliciting packet if no other ack-eliciting packets
1975 * have been sent since last receiving and processing a packet.'
1977 if (status.sent_ack_eliciting && !ch->have_sent_ack_eliciting_since_rx) {
1979 ch->have_sent_ack_eliciting_since_rx = 1;
1982 if (ch->rxku_pending_confirm_done)
1983 ch->rxku_pending_confirm = 0;
1985 ch_update_ping_deadline(ch);
1988 case TX_PACKETISER_RES_NO_PKT:
1989 break; /* No packet was sent */
1991 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1993 break; /* Internal failure (e.g. allocation, assertion) */
1996 /* Flush packets to network. */
1997 switch (ossl_qtx_flush_net(ch->qtx)) {
1998 case QTX_FLUSH_NET_RES_OK:
1999 case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
2000 /* Best effort, done for now. */
2003 case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
2005 /* Permanent underlying network BIO, start terminating. */
2006 ch_raise_net_error(ch);
2013 /* Determine next tick deadline. */
2014 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
2019 if (ossl_quic_channel_is_terminated(ch))
2020 return ossl_time_infinite();
2022 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
2023 if (ossl_time_is_zero(deadline))
2024 deadline = ossl_time_infinite();
2027 * If the CC will let us send acks, check the ack deadline for all
2028 * enc_levels that are actually provisioned
2030 if (ch->cc_method->get_tx_allowance(ch->cc_data) > 0) {
2031 for (i = 0; i < QUIC_ENC_LEVEL_NUM; i++) {
2032 if (ossl_qtx_is_enc_level_provisioned(ch->qtx, i)) {
2033 deadline = ossl_time_min(deadline,
2034 ossl_ackm_get_ack_deadline(ch->ackm,
2035 ossl_quic_enc_level_to_pn_space(i)));
2040 /* When will CC let us send more? */
2041 if (ossl_quic_tx_packetiser_has_pending(ch->txp, TX_PACKETISER_ARCHETYPE_NORMAL,
2042 TX_PACKETISER_BYPASS_CC))
2043 deadline = ossl_time_min(deadline,
2044 ch->cc_method->get_wakeup_deadline(ch->cc_data));
2046 /* Is the terminating timer armed? */
2047 if (ossl_quic_channel_is_terminating(ch))
2048 deadline = ossl_time_min(deadline,
2049 ch->terminate_deadline);
2050 else if (!ossl_time_is_infinite(ch->idle_deadline))
2051 deadline = ossl_time_min(deadline,
2055 * When do we need to send an ACK-eliciting packet to reset the idle
2056 * deadline timer for the peer?
2058 if (!ossl_time_is_infinite(ch->ping_deadline))
2059 deadline = ossl_time_min(deadline,
2062 /* When does the RXKU process complete? */
2063 if (ch->rxku_in_progress)
2064 deadline = ossl_time_min(deadline, ch->rxku_update_end_deadline);
2070 * QUIC Channel: Network BIO Configuration
2071 * =======================================
2074 /* Determines whether we can support a given poll descriptor. */
2075 static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
2077 if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0)
2083 BIO *ossl_quic_channel_get_net_rbio(QUIC_CHANNEL *ch)
2085 return ch->net_rbio;
2088 BIO *ossl_quic_channel_get_net_wbio(QUIC_CHANNEL *ch)
2090 return ch->net_wbio;
2094 * QUIC_CHANNEL does not ref any BIO it is provided with, nor is any ref
2095 * transferred to it. The caller (i.e., QUIC_CONNECTION) is responsible for
2096 * ensuring the BIO lasts until the channel is freed or the BIO is switched out
2097 * for another BIO by a subsequent successful call to this function.
2099 int ossl_quic_channel_set_net_rbio(QUIC_CHANNEL *ch, BIO *net_rbio)
2101 BIO_POLL_DESCRIPTOR d = {0};
2103 if (ch->net_rbio == net_rbio)
2106 if (net_rbio != NULL) {
2107 if (!BIO_get_rpoll_descriptor(net_rbio, &d))
2108 /* Non-pollable BIO */
2109 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
2111 if (!validate_poll_descriptor(&d))
2115 ossl_quic_reactor_set_poll_r(&ch->rtor, &d);
2116 ossl_quic_demux_set_bio(ch->demux, net_rbio);
2117 ch->net_rbio = net_rbio;
2121 int ossl_quic_channel_set_net_wbio(QUIC_CHANNEL *ch, BIO *net_wbio)
2123 BIO_POLL_DESCRIPTOR d = {0};
2125 if (ch->net_wbio == net_wbio)
2128 if (net_wbio != NULL) {
2129 if (!BIO_get_wpoll_descriptor(net_wbio, &d))
2130 /* Non-pollable BIO */
2131 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
2133 if (!validate_poll_descriptor(&d))
2137 ossl_quic_reactor_set_poll_w(&ch->rtor, &d);
2138 ossl_qtx_set_bio(ch->qtx, net_wbio);
2139 ch->net_wbio = net_wbio;
2144 * QUIC Channel: Lifecycle Events
2145 * ==============================
2147 int ossl_quic_channel_start(QUIC_CHANNEL *ch)
2151 * This is not used by the server. The server moves to active
2152 * automatically on receiving an incoming connection.
2156 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
2157 /* Calls to connect are idempotent */
2160 /* Inform QTX of peer address. */
2161 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2164 /* Plug in secrets for the Initial EL. */
2165 if (!ossl_quic_provide_initial_secret(ch->libctx,
2173 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
2174 ch->doing_proactive_ver_neg = 0; /* not currently supported */
2176 /* Handshake layer: start (e.g. send CH). */
2177 if (!ossl_quic_tls_tick(ch->qtls))
2180 ossl_quic_reactor_tick(&ch->rtor, 0); /* best effort */
2184 /* Start a locally initiated connection shutdown. */
2185 void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code)
2187 QUIC_TERMINATE_CAUSE tcause = {0};
2189 if (ossl_quic_channel_is_term_any(ch))
2193 tcause.error_code = app_error_code;
2194 ch_start_terminating(ch, &tcause, 0);
2197 static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
2199 OPENSSL_free((unsigned char *)buf);
2202 /* Called when a server asks us to do a retry. */
2203 static int ch_retry(QUIC_CHANNEL *ch,
2204 const unsigned char *retry_token,
2205 size_t retry_token_len,
2206 const QUIC_CONN_ID *retry_scid)
2210 /* We change to using the SCID in the Retry packet as the DCID. */
2211 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
2215 * Now we retry. We will release the Retry packet immediately, so copy
2218 if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
2221 ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf, retry_token_len,
2224 ch->retry_scid = *retry_scid;
2225 ch->doing_retry = 1;
2228 * We need to stimulate the Initial EL to generate the first CRYPTO frame
2229 * again. We can do this most cleanly by simply forcing the ACKM to consider
2230 * the first Initial packet as lost, which it effectively was as the server
2231 * hasn't processed it. This also maintains the desired behaviour with e.g.
2232 * PNs not resetting and so on.
2234 * The PN we used initially is always zero, because QUIC does not allow
2237 if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
2242 * Plug in new secrets for the Initial EL. This is the only time we change
2243 * the secrets for an EL after we already provisioned it.
2245 if (!ossl_quic_provide_initial_secret(ch->libctx,
2255 /* Called when an EL is to be discarded. */
2256 static int ch_discard_el(QUIC_CHANNEL *ch,
2259 if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
2262 if ((ch->el_discarded & (1U << enc_level)) != 0)
2266 /* Best effort for all of these. */
2267 ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
2268 ossl_qrx_discard_enc_level(ch->qrx, enc_level);
2269 ossl_qtx_discard_enc_level(ch->qtx, enc_level);
2271 if (enc_level != QUIC_ENC_LEVEL_0RTT) {
2272 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
2274 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
2276 /* We should still have crypto streams at this point. */
2277 if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
2278 || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
2281 /* Get rid of the crypto stream state for the EL. */
2282 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
2283 ch->crypto_send[pn_space] = NULL;
2285 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
2286 ch->crypto_recv[pn_space] = NULL;
2289 ch->el_discarded |= (1U << enc_level);
2293 /* Intended to be called by the RXDP. */
2294 int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
2296 if (ch->handshake_confirmed)
2299 if (!ch->handshake_complete) {
2301 * Does not make sense for handshake to be confirmed before it is
2304 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
2305 OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
2306 "handshake cannot be confirmed "
2307 "before it is completed");
2311 ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
2312 ch->handshake_confirmed = 1;
2313 ossl_ackm_on_handshake_confirmed(ch->ackm);
2318 * Master function used when we want to start tearing down a connection:
2320 * - If the connection is still IDLE we can go straight to TERMINATED;
2322 * - If we are already TERMINATED this is a no-op.
2324 * - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
2325 * from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
2327 * - If we are TERMINATING - DRAINING, we remain here until the terminating
2330 * - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
2331 * if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
2332 * that we are considered to have caused a termination if we sent the first
2333 * CONNECTION_CLOSE frame, even if it is caused by a peer protocol
2334 * violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
2335 * TERMINATING - DRAINING.
2337 * We record the termination cause structure passed on the first call only.
2338 * Any successive calls have their termination cause data discarded;
2339 * once we start sending a CONNECTION_CLOSE frame, we don't change the details
2342 static void ch_start_terminating(QUIC_CHANNEL *ch,
2343 const QUIC_TERMINATE_CAUSE *tcause,
2344 int force_immediate)
2346 switch (ch->state) {
2348 case QUIC_CHANNEL_STATE_IDLE:
2349 ch->terminate_cause = *tcause;
2350 ch_on_terminating_timeout(ch);
2353 case QUIC_CHANNEL_STATE_ACTIVE:
2354 ch->terminate_cause = *tcause;
2356 if (!force_immediate) {
2357 ch->state = tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
2358 : QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
2359 ch->terminate_deadline
2360 = ossl_time_add(get_time(ch),
2361 ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
2364 if (!tcause->remote) {
2365 OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
2368 f.error_code = ch->terminate_cause.error_code;
2369 f.frame_type = ch->terminate_cause.frame_type;
2370 f.is_app = ch->terminate_cause.app;
2371 ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
2372 ch->conn_close_queued = 1;
2375 ch_on_terminating_timeout(ch);
2379 case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
2380 if (force_immediate)
2381 ch_on_terminating_timeout(ch);
2382 else if (tcause->remote)
2383 ch->state = QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
2387 case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
2389 * Other than in the force-immediate case, we remain here until the
2392 if (force_immediate)
2393 ch_on_terminating_timeout(ch);
2397 case QUIC_CHANNEL_STATE_TERMINATED:
2404 void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
2405 OSSL_QUIC_FRAME_CONN_CLOSE *f)
2407 QUIC_TERMINATE_CAUSE tcause = {0};
2409 if (!ossl_quic_channel_is_active(ch))
2413 tcause.app = f->is_app;
2414 tcause.error_code = f->error_code;
2415 tcause.frame_type = f->frame_type;
2417 ch_start_terminating(ch, &tcause, 0);
2420 static void free_frame_data(unsigned char *buf, size_t buf_len, void *arg)
2425 static int ch_enqueue_retire_conn_id(QUIC_CHANNEL *ch, uint64_t seq_num)
2431 if ((buf_mem = BUF_MEM_new()) == NULL)
2434 if (!WPACKET_init(&wpkt, buf_mem))
2437 if (!ossl_quic_wire_encode_frame_retire_conn_id(&wpkt, seq_num)) {
2438 WPACKET_cleanup(&wpkt);
2442 WPACKET_finish(&wpkt);
2443 if (!WPACKET_get_total_written(&wpkt, &l))
2446 if (ossl_quic_cfq_add_frame(ch->cfq, 1, QUIC_PN_SPACE_APP,
2447 OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID,
2448 (unsigned char *)buf_mem->data, l,
2449 free_frame_data, NULL) == NULL)
2452 buf_mem->data = NULL;
2453 BUF_MEM_free(buf_mem);
2457 ossl_quic_channel_raise_protocol_error(ch,
2458 QUIC_ERR_INTERNAL_ERROR,
2459 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2460 "internal error enqueueing retire conn id");
2461 BUF_MEM_free(buf_mem);
2465 void ossl_quic_channel_on_new_conn_id(QUIC_CHANNEL *ch,
2466 OSSL_QUIC_FRAME_NEW_CONN_ID *f)
2468 uint64_t new_remote_seq_num = ch->cur_remote_seq_num;
2469 uint64_t new_retire_prior_to = ch->cur_retire_prior_to;
2471 if (!ossl_quic_channel_is_active(ch))
2474 /* We allow only two active connection ids; first check some constraints */
2476 if (ch->cur_remote_dcid.id_len == 0) {
2477 /* Changing from 0 length connection id is disallowed */
2478 ossl_quic_channel_raise_protocol_error(ch,
2479 QUIC_ERR_PROTOCOL_VIOLATION,
2480 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2481 "zero length connection id in use");
2486 if (f->seq_num > new_remote_seq_num)
2487 new_remote_seq_num = f->seq_num;
2488 if (f->retire_prior_to > new_retire_prior_to)
2489 new_retire_prior_to = f->retire_prior_to;
2492 * RFC 9000-5.1.1: An endpoint MUST NOT provide more connection IDs
2493 * than the peer's limit.
2495 * After processing a NEW_CONNECTION_ID frame and adding and retiring
2496 * active connection IDs, if the number of active connection IDs exceeds
2497 * the value advertised in its active_connection_id_limit transport
2498 * parameter, an endpoint MUST close the connection with an error of
2499 * type CONNECTION_ID_LIMIT_ERROR.
2501 if (new_remote_seq_num - new_retire_prior_to > 1) {
2502 ossl_quic_channel_raise_protocol_error(ch,
2503 QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
2504 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2505 "active_connection_id limit violated");
2510 * RFC 9000-5.1.1: An endpoint MAY send connection IDs that temporarily
2511 * exceed a peer's limit if the NEW_CONNECTION_ID frame also requires
2512 * the retirement of any excess, by including a sufficiently large
2513 * value in the Retire Prior To field.
2515 * RFC 9000-5.1.2: An endpoint SHOULD allow for sending and tracking
2516 * a number of RETIRE_CONNECTION_ID frames of at least twice the value
2517 * of the active_connection_id_limit transport parameter. An endpoint
2518 * MUST NOT forget a connection ID without retiring it, though it MAY
2519 * choose to treat having connection IDs in need of retirement that
2520 * exceed this limit as a connection error of type CONNECTION_ID_LIMIT_ERROR.
2522 * We are a little bit more liberal than the minimum mandated.
2524 if (new_retire_prior_to - ch->cur_retire_prior_to > 10) {
2525 ossl_quic_channel_raise_protocol_error(ch,
2526 QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
2527 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
2528 "retiring connection id limit violated");
2533 if (new_remote_seq_num > ch->cur_remote_seq_num) {
2534 ch->cur_remote_seq_num = new_remote_seq_num;
2535 ch->cur_remote_dcid = f->conn_id;
2536 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid);
2539 * RFC 9000-5.1.2: Upon receipt of an increased Retire Prior To
2540 * field, the peer MUST stop using the corresponding connection IDs
2541 * and retire them with RETIRE_CONNECTION_ID frames before adding the
2542 * newly provided connection ID to the set of active connection IDs.
2544 while (new_retire_prior_to > ch->cur_retire_prior_to) {
2545 if (!ch_enqueue_retire_conn_id(ch, ch->cur_retire_prior_to))
2547 ++ch->cur_retire_prior_to;
2551 static void ch_raise_net_error(QUIC_CHANNEL *ch)
2553 QUIC_TERMINATE_CAUSE tcause = {0};
2555 tcause.error_code = QUIC_ERR_INTERNAL_ERROR;
2558 * Skip Terminating state and go directly to Terminated, no point trying to
2559 * send CONNECTION_CLOSE if we cannot communicate.
2561 ch_start_terminating(ch, &tcause, 1);
2564 void ossl_quic_channel_raise_protocol_error(QUIC_CHANNEL *ch,
2565 uint64_t error_code,
2566 uint64_t frame_type,
2569 QUIC_TERMINATE_CAUSE tcause = {0};
2571 tcause.error_code = error_code;
2572 tcause.frame_type = frame_type;
2574 ch_start_terminating(ch, &tcause, 0);
2578 * Called once the terminating timer expires, meaning we move from TERMINATING
2581 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
2583 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2587 * Updates our idle deadline. Called when an event happens which should bump the
2590 static void ch_update_idle(QUIC_CHANNEL *ch)
2592 if (ch->max_idle_timeout == 0)
2593 ch->idle_deadline = ossl_time_infinite();
2595 ch->idle_deadline = ossl_time_add(get_time(ch),
2596 ossl_ms2time(ch->max_idle_timeout));
2600 * Updates our ping deadline, which determines when we next generate a ping if
2601 * we don't have any other ACK-eliciting frames to send.
2603 static void ch_update_ping_deadline(QUIC_CHANNEL *ch)
2605 if (ch->max_idle_timeout > 0) {
2607 * Maximum amount of time without traffic before we send a PING to keep
2608 * the connection open. Usually we use max_idle_timeout/2, but ensure
2609 * the period never exceeds the assumed NAT interval to ensure NAT
2610 * devices don't have their state time out (RFC 9000 s. 10.1.2).
2613 = ossl_time_divide(ossl_ms2time(ch->max_idle_timeout), 2);
2615 max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL);
2617 ch->ping_deadline = ossl_time_add(get_time(ch), max_span);
2619 ch->ping_deadline = ossl_time_infinite();
2623 /* Called when the idle timeout expires. */
2624 static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
2627 * Idle timeout does not have an error code associated with it because a
2628 * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
2629 * TERMINATED anyway.
2631 ch->terminate_cause.app = 0;
2632 ch->terminate_cause.error_code = UINT64_MAX;
2633 ch->terminate_cause.frame_type = 0;
2635 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2638 /* Called when we, as a server, get a new incoming connection. */
2639 static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
2640 const QUIC_CONN_ID *peer_scid,
2641 const QUIC_CONN_ID *peer_dcid)
2643 if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
2646 /* Generate a SCID we will use for the connection. */
2647 if (!gen_rand_conn_id(ch->libctx, INIT_DCID_LEN,
2648 &ch->cur_local_cid))
2651 /* Note our newly learnt peer address and CIDs. */
2652 ch->cur_peer_addr = *peer;
2653 ch->init_dcid = *peer_dcid;
2654 ch->cur_remote_dcid = *peer_scid;
2656 /* Inform QTX of peer address. */
2657 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2660 /* Inform TXP of desired CIDs. */
2661 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
2664 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
2667 /* Plug in secrets for the Initial EL. */
2668 if (!ossl_quic_provide_initial_secret(ch->libctx,
2675 /* Register our local CID in the DEMUX. */
2676 if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_cid))
2680 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
2681 ch->doing_proactive_ver_neg = 0; /* not currently supported */
2685 SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)
2690 static int ch_init_new_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs,
2691 int can_send, int can_recv)
2694 int server_init = ossl_quic_stream_is_server_init(qs);
2695 int local_init = (ch->is_server == server_init);
2696 int is_uni = !ossl_quic_stream_is_bidi(qs);
2698 if (can_send && (qs->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL)
2702 if ((qs->rstream = ossl_quic_rstream_new(NULL, NULL, 0)) == NULL)
2704 ossl_quic_rstream_set_cleanse(qs->rstream,
2705 (ch->tls->ctx->options
2706 & SSL_OP_CLEANSE_PLAINTEXT) != 0);
2710 if (!ossl_quic_txfc_init(&qs->txfc, &ch->conn_txfc))
2713 if (ch->got_remote_transport_params) {
2715 * If we already got peer TPs we need to apply the initial CWM credit
2716 * now. If we didn't already get peer TPs this will be done
2717 * automatically for all extant streams when we do.
2723 cwm = ch->rx_init_max_stream_data_uni;
2724 else if (local_init)
2725 cwm = ch->rx_init_max_stream_data_bidi_local;
2727 cwm = ch->rx_init_max_stream_data_bidi_remote;
2729 ossl_quic_txfc_bump_cwm(&qs->txfc, cwm);
2737 rxfc_wnd = ch->tx_init_max_stream_data_uni;
2738 else if (local_init)
2739 rxfc_wnd = ch->tx_init_max_stream_data_bidi_local;
2741 rxfc_wnd = ch->tx_init_max_stream_data_bidi_remote;
2743 if (!ossl_quic_rxfc_init(&qs->rxfc, &ch->conn_rxfc,
2745 DEFAULT_STREAM_RXFC_MAX_WND_MUL * rxfc_wnd,
2752 ossl_quic_sstream_free(qs->sstream);
2754 ossl_quic_rstream_free(qs->rstream);
2759 QUIC_STREAM *ossl_quic_channel_new_stream_local(QUIC_CHANNEL *ch, int is_uni)
2763 uint64_t stream_id, *p_next_ordinal;
2765 type = ch->is_server ? QUIC_STREAM_INITIATOR_SERVER
2766 : QUIC_STREAM_INITIATOR_CLIENT;
2769 p_next_ordinal = &ch->next_local_stream_ordinal_uni;
2770 type |= QUIC_STREAM_DIR_UNI;
2772 p_next_ordinal = &ch->next_local_stream_ordinal_bidi;
2773 type |= QUIC_STREAM_DIR_BIDI;
2776 if (*p_next_ordinal >= ((uint64_t)1) << 62)
2779 stream_id = ((*p_next_ordinal) << 2) | type;
2781 if ((qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id, type)) == NULL)
2784 /* Locally-initiated stream, so we always want a send buffer. */
2785 if (!ch_init_new_stream(ch, qs, /*can_send=*/1, /*can_recv=*/!is_uni))
2792 ossl_quic_stream_map_release(&ch->qsm, qs);
2796 QUIC_STREAM *ossl_quic_channel_new_stream_remote(QUIC_CHANNEL *ch,
2803 peer_role = ch->is_server
2804 ? QUIC_STREAM_INITIATOR_CLIENT
2805 : QUIC_STREAM_INITIATOR_SERVER;
2807 if ((stream_id & QUIC_STREAM_INITIATOR_MASK) != peer_role)
2810 is_uni = ((stream_id & QUIC_STREAM_DIR_MASK) == QUIC_STREAM_DIR_UNI);
2812 qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id,
2813 stream_id & (QUIC_STREAM_INITIATOR_MASK
2814 | QUIC_STREAM_DIR_MASK));
2818 if (!ch_init_new_stream(ch, qs, /*can_send=*/!is_uni, /*can_recv=*/1))
2821 if (ch->incoming_stream_auto_reject)
2822 ossl_quic_channel_reject_stream(ch, qs);
2824 ossl_quic_stream_map_push_accept_queue(&ch->qsm, qs);
2829 ossl_quic_stream_map_release(&ch->qsm, qs);
2833 void ossl_quic_channel_set_incoming_stream_auto_reject(QUIC_CHANNEL *ch,
2837 ch->incoming_stream_auto_reject = (enable != 0);
2838 ch->incoming_stream_auto_reject_aec = aec;
2841 void ossl_quic_channel_reject_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs)
2843 ossl_quic_stream_map_stop_sending_recv_part(&ch->qsm, qs,
2844 ch->incoming_stream_auto_reject_aec);
2846 ossl_quic_stream_map_reset_stream_send_part(&ch->qsm, qs,
2847 ch->incoming_stream_auto_reject_aec);
2850 ossl_quic_stream_map_update_state(&ch->qsm, qs);
2853 /* Replace local connection ID in TXP and DEMUX for testing purposes. */
2854 int ossl_quic_channel_replace_local_cid(QUIC_CHANNEL *ch,
2855 const QUIC_CONN_ID *conn_id)
2857 /* Remove the current local CID from the DEMUX. */
2858 if (!ossl_qrx_remove_dst_conn_id(ch->qrx, &ch->cur_local_cid))
2860 ch->cur_local_cid = *conn_id;
2861 /* Set in the TXP, used only for long header packets. */
2862 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
2864 /* Register our new local CID in the DEMUX. */
2865 if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_cid))
2870 void ossl_quic_channel_set_msg_callback(QUIC_CHANNEL *ch,
2871 ossl_msg_cb msg_callback,
2872 SSL *msg_callback_ssl)
2874 ch->msg_callback = msg_callback;
2875 ch->msg_callback_ssl = msg_callback_ssl;
2876 ossl_qtx_set_msg_callback(ch->qtx, msg_callback, msg_callback_ssl);
2877 ossl_quic_tx_packetiser_set_msg_callback(ch->txp, msg_callback,
2879 ossl_qrx_set_msg_callback(ch->qrx, msg_callback, msg_callback_ssl);
2882 void ossl_quic_channel_set_msg_callback_arg(QUIC_CHANNEL *ch,
2883 void *msg_callback_arg)
2885 ch->msg_callback_arg = msg_callback_arg;
2886 ossl_qtx_set_msg_callback_arg(ch->qtx, msg_callback_arg);
2887 ossl_quic_tx_packetiser_set_msg_callback_arg(ch->txp, msg_callback_arg);
2888 ossl_qrx_set_msg_callback_arg(ch->qrx, msg_callback_arg);
2891 void ossl_quic_channel_set_txku_threshold_override(QUIC_CHANNEL *ch,
2892 uint64_t tx_pkt_threshold)
2894 ch->txku_threshold_override = tx_pkt_threshold;
2897 uint64_t ossl_quic_channel_get_tx_key_epoch(QUIC_CHANNEL *ch)
2899 return ossl_qtx_get_key_epoch(ch->qtx);
2902 uint64_t ossl_quic_channel_get_rx_key_epoch(QUIC_CHANNEL *ch)
2904 return ossl_qrx_get_key_epoch(ch->qrx);
2907 int ossl_quic_channel_trigger_txku(QUIC_CHANNEL *ch)
2909 if (!txku_allowed(ch))
2912 ch->ku_locally_initiated = 1;
2913 ch_trigger_txku(ch);