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