1 /* 2 * Copyright 2022-2026 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/ssl_unwrap.h" 13 #include "internal/quic_channel.h" 14 #include "internal/quic_error.h" 15 #include "internal/quic_rx_depack.h" 16 #include "internal/quic_lcidm.h" 17 #include "internal/quic_srtm.h" 18 #include "internal/qlog_event_helpers.h" 19 #include "internal/quic_txp.h" 20 #include "internal/quic_tls.h" 21 #include "internal/quic_ssl.h" 22 #include "../ssl_local.h" 23 #include "quic_channel_local.h" 24 #include "quic_port_local.h" 25 #include "quic_engine_local.h" 26 27 #define INIT_CRYPTO_RECV_BUF_LEN 16384 28 #define INIT_CRYPTO_SEND_BUF_LEN 16384 29 #define INIT_APP_BUF_LEN 8192 30 31 /* 32 * Interval before we force a PING to ensure NATs don't timeout. This is based 33 * on the lowest commonly seen value of 30 seconds as cited in RFC 9000 s. 34 * 10.1.2. 35 */ 36 #define MAX_NAT_INTERVAL (ossl_ms2time(25000)) 37 38 /* 39 * Our maximum ACK delay on the TX side. This is up to us to choose. Note that 40 * this could differ from QUIC_DEFAULT_MAX_DELAY in future as that is a protocol 41 * value which determines the value of the maximum ACK delay if the 42 * max_ack_delay transport parameter is not set. 43 */ 44 #define DEFAULT_MAX_ACK_DELAY QUIC_DEFAULT_MAX_ACK_DELAY 45 46 DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL); 47 48 static void ch_save_err_state(QUIC_CHANNEL *ch); 49 static int ch_rx(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads); 50 static int ch_tx(QUIC_CHANNEL *ch, int *notify_other_threads); 51 static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads); 52 static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only); 53 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch); 54 static int ch_retry(QUIC_CHANNEL *ch, 55 const unsigned char *retry_token, 56 size_t retry_token_len, 57 const QUIC_CONN_ID *retry_scid, 58 int drop_later_pn); 59 static int ch_restart(QUIC_CHANNEL *ch); 60 61 static void ch_cleanup(QUIC_CHANNEL *ch); 62 static int ch_generate_transport_params(QUIC_CHANNEL *ch); 63 static int ch_on_transport_params(const unsigned char *params, 64 size_t params_len, 65 void *arg); 66 static int ch_on_handshake_alert(void *arg, unsigned char alert_code); 67 static int ch_on_handshake_complete(void *arg); 68 static int ch_on_handshake_yield_secret(uint32_t prot_level, int direction, 69 uint32_t suite_id, EVP_MD *md, 70 const unsigned char *secret, 71 size_t secret_len, 72 void *arg); 73 static int ch_on_crypto_recv_record(const unsigned char **buf, 74 size_t *bytes_read, void *arg); 75 static int ch_on_crypto_release_record(size_t bytes_read, void *arg); 76 static int crypto_ensure_empty(QUIC_RSTREAM *rstream); 77 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len, 78 size_t *consumed, void *arg); 79 static OSSL_TIME get_time(void *arg); 80 static uint64_t get_stream_limit(int uni, void *arg); 81 static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg); 82 static void rxku_detected(QUIC_PN pn, void *arg); 83 static int ch_retry(QUIC_CHANNEL *ch, 84 const unsigned char *retry_token, 85 size_t retry_token_len, 86 const QUIC_CONN_ID *retry_scid, 87 int drop_later_pn); 88 static void ch_update_idle(QUIC_CHANNEL *ch); 89 static int ch_discard_el(QUIC_CHANNEL *ch, 90 uint32_t enc_level); 91 static void ch_on_idle_timeout(QUIC_CHANNEL *ch); 92 static void ch_update_idle(QUIC_CHANNEL *ch); 93 static void ch_update_ping_deadline(QUIC_CHANNEL *ch); 94 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch); 95 static void ch_start_terminating(QUIC_CHANNEL *ch, 96 const QUIC_TERMINATE_CAUSE *tcause, 97 int force_immediate); 98 static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space, 99 void *arg); 100 static void ch_record_state_transition(QUIC_CHANNEL *ch, uint32_t new_state); 101 102 DEFINE_LHASH_OF_EX(QUIC_SRT_ELEM); 103 104 QUIC_NEEDS_LOCK 105 static QLOG *ch_get_qlog(QUIC_CHANNEL *ch) 106 { 107 #ifndef OPENSSL_NO_QLOG 108 QLOG_TRACE_INFO qti = { 0 }; 109 110 if (ch->qlog != NULL) 111 return ch->qlog; 112 113 if (!ch->use_qlog) 114 return NULL; 115 116 if (ch->is_server && ch->init_dcid.id_len == 0) 117 return NULL; 118 119 qti.odcid = ch->init_dcid; 120 qti.title = ch->qlog_title; 121 qti.description = NULL; 122 qti.group_id = NULL; 123 qti.is_server = ch->is_server; 124 qti.now_cb = get_time; 125 qti.now_cb_arg = ch; 126 if ((ch->qlog = ossl_qlog_new_from_env(&qti)) == NULL) { 127 ch->use_qlog = 0; /* don't try again */ 128 return NULL; 129 } 130 131 return ch->qlog; 132 #else 133 return NULL; 134 #endif 135 } 136 137 QUIC_NEEDS_LOCK 138 static QLOG *ch_get_qlog_cb(void *arg) 139 { 140 QUIC_CHANNEL *ch = arg; 141 142 return ch_get_qlog(ch); 143 } 144 145 /* 146 * QUIC Channel Initialization and Teardown 147 * ======================================== 148 */ 149 #define DEFAULT_INIT_CONN_RXFC_WND (768 * 1024) 150 #define DEFAULT_CONN_RXFC_MAX_WND_MUL 20 151 152 #define DEFAULT_INIT_STREAM_RXFC_WND (512 * 1024) 153 #define DEFAULT_STREAM_RXFC_MAX_WND_MUL 12 154 155 #define DEFAULT_INIT_CONN_MAX_STREAMS 100 156 157 static int ch_init(QUIC_CHANNEL *ch) 158 { 159 OSSL_QUIC_TX_PACKETISER_ARGS txp_args = { 0 }; 160 OSSL_QTX_ARGS qtx_args = { 0 }; 161 OSSL_QRX_ARGS qrx_args = { 0 }; 162 QUIC_TLS_ARGS tls_args = { 0 }; 163 uint32_t pn_space; 164 size_t rx_short_dcid_len; 165 size_t tx_init_dcid_len; 166 167 if (ch->port == NULL || ch->lcidm == NULL || ch->srtm == NULL) 168 goto err; 169 170 rx_short_dcid_len = ossl_quic_port_get_rx_short_dcid_len(ch->port); 171 tx_init_dcid_len = ossl_quic_port_get_tx_init_dcid_len(ch->port); 172 173 /* For clients, generate our initial DCID. */ 174 if (!ch->is_server 175 && !ossl_quic_gen_rand_conn_id(ch->port->engine->libctx, tx_init_dcid_len, 176 &ch->init_dcid)) 177 goto err; 178 179 /* We plug in a network write BIO to the QTX later when we get one. */ 180 qtx_args.libctx = ch->port->engine->libctx; 181 qtx_args.get_qlog_cb = ch_get_qlog_cb; 182 qtx_args.get_qlog_cb_arg = ch; 183 qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN; 184 ch->rx_max_udp_payload_size = qtx_args.mdpl; 185 186 ch->ping_deadline = ossl_time_infinite(); 187 188 ch->qtx = ossl_qtx_new(&qtx_args); 189 if (ch->qtx == NULL) 190 goto err; 191 192 ch->txpim = ossl_quic_txpim_new(); 193 if (ch->txpim == NULL) 194 goto err; 195 196 ch->cfq = ossl_quic_cfq_new(); 197 if (ch->cfq == NULL) 198 goto err; 199 200 if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL)) 201 goto err; 202 203 /* 204 * Note: The TP we transmit governs what the peer can transmit and thus 205 * applies to the RXFC. 206 */ 207 ch->tx_init_max_stream_data_bidi_local = DEFAULT_INIT_STREAM_RXFC_WND; 208 ch->tx_init_max_stream_data_bidi_remote = DEFAULT_INIT_STREAM_RXFC_WND; 209 ch->tx_init_max_stream_data_uni = DEFAULT_INIT_STREAM_RXFC_WND; 210 211 if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL, 212 DEFAULT_INIT_CONN_RXFC_WND, 213 DEFAULT_CONN_RXFC_MAX_WND_MUL * DEFAULT_INIT_CONN_RXFC_WND, 214 get_time, ch)) 215 goto err; 216 217 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) 218 if (!ossl_quic_rxfc_init_standalone(&ch->crypto_rxfc[pn_space], 219 INIT_CRYPTO_RECV_BUF_LEN, 220 get_time, ch)) 221 goto err; 222 223 if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_bidi_rxfc, 224 DEFAULT_INIT_CONN_MAX_STREAMS, 225 get_time, ch)) 226 goto err; 227 228 if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_uni_rxfc, 229 DEFAULT_INIT_CONN_MAX_STREAMS, 230 get_time, ch)) 231 goto err; 232 233 if (!ossl_statm_init(&ch->statm)) 234 goto err; 235 236 ch->have_statm = 1; 237 ch->cc_method = &ossl_cc_newreno_method; 238 if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL) 239 goto err; 240 241 if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm, 242 ch->cc_method, ch->cc_data, 243 ch->is_server)) 244 == NULL) 245 goto err; 246 247 if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch, 248 &ch->max_streams_bidi_rxfc, 249 &ch->max_streams_uni_rxfc, 250 ch->is_server)) 251 goto err; 252 253 ch->have_qsm = 1; 254 255 if (!ch->is_server 256 && !ossl_quic_lcidm_generate_initial(ch->lcidm, ch, &ch->init_scid)) 257 goto err; 258 259 txp_args.cur_scid = ch->init_scid; 260 txp_args.cur_dcid = ch->init_dcid; 261 txp_args.ack_delay_exponent = 3; 262 txp_args.qtx = ch->qtx; 263 txp_args.txpim = ch->txpim; 264 txp_args.cfq = ch->cfq; 265 txp_args.ackm = ch->ackm; 266 txp_args.qsm = &ch->qsm; 267 txp_args.conn_txfc = &ch->conn_txfc; 268 txp_args.conn_rxfc = &ch->conn_rxfc; 269 txp_args.max_streams_bidi_rxfc = &ch->max_streams_bidi_rxfc; 270 txp_args.max_streams_uni_rxfc = &ch->max_streams_uni_rxfc; 271 txp_args.cc_method = ch->cc_method; 272 txp_args.cc_data = ch->cc_data; 273 txp_args.now = get_time; 274 txp_args.now_arg = ch; 275 txp_args.get_qlog_cb = ch_get_qlog_cb; 276 txp_args.get_qlog_cb_arg = ch; 277 txp_args.protocol_version = QUIC_VERSION_1; 278 279 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) { 280 ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_SEND_BUF_LEN); 281 if (ch->crypto_send[pn_space] == NULL) 282 goto err; 283 284 txp_args.crypto[pn_space] = ch->crypto_send[pn_space]; 285 } 286 287 ch->txp = ossl_quic_tx_packetiser_new(&txp_args); 288 if (ch->txp == NULL) 289 goto err; 290 291 /* clients have no amplification limit, so are considered always valid */ 292 if (!ch->is_server) 293 ossl_quic_tx_packetiser_set_validated(ch->txp); 294 295 ossl_quic_tx_packetiser_set_ack_tx_cb(ch->txp, ch_on_txp_ack_tx, ch); 296 297 /* 298 * qrx does not exist yet, then we must be dealing with client channel 299 * (QUIC connection initiator). 300 * If qrx exists already, then we are dealing with server channel which 301 * qrx gets created by port_default_packet_handler() before 302 * port_default_packet_handler() accepts connection and creates channel 303 * for it. 304 * The exception here is tserver which always creates channel, 305 * before the first packet is ever seen. 306 */ 307 if (ch->qrx == NULL && ch->is_tserver_ch == 0) { 308 /* we are regular client, create channel */ 309 qrx_args.libctx = ch->port->engine->libctx; 310 qrx_args.demux = ch->port->demux; 311 qrx_args.short_conn_id_len = rx_short_dcid_len; 312 qrx_args.max_deferred = 32; 313 314 if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL) 315 goto err; 316 } 317 318 if (ch->qrx != NULL) { 319 /* 320 * callbacks for channels associated with tserver's port 321 * are set up later when we call ossl_quic_channel_bind_qrx() 322 * in port_default_packet_handler() 323 */ 324 if (!ossl_qrx_set_late_validation_cb(ch->qrx, 325 rx_late_validate, 326 ch)) 327 goto err; 328 329 if (!ossl_qrx_set_key_update_cb(ch->qrx, 330 rxku_detected, 331 ch)) 332 goto err; 333 } 334 335 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) { 336 ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL, 0); 337 if (ch->crypto_recv[pn_space] == NULL) 338 goto err; 339 } 340 341 /* Plug in the TLS handshake layer. */ 342 tls_args.s = ch->tls; 343 tls_args.crypto_send_cb = ch_on_crypto_send; 344 tls_args.crypto_send_cb_arg = ch; 345 tls_args.crypto_recv_rcd_cb = ch_on_crypto_recv_record; 346 tls_args.crypto_recv_rcd_cb_arg = ch; 347 tls_args.crypto_release_rcd_cb = ch_on_crypto_release_record; 348 tls_args.crypto_release_rcd_cb_arg = ch; 349 tls_args.yield_secret_cb = ch_on_handshake_yield_secret; 350 tls_args.yield_secret_cb_arg = ch; 351 tls_args.got_transport_params_cb = ch_on_transport_params; 352 tls_args.got_transport_params_cb_arg = ch; 353 tls_args.handshake_complete_cb = ch_on_handshake_complete; 354 tls_args.handshake_complete_cb_arg = ch; 355 tls_args.alert_cb = ch_on_handshake_alert; 356 tls_args.alert_cb_arg = ch; 357 tls_args.is_server = ch->is_server; 358 tls_args.ossl_quic = 1; 359 360 if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL) 361 goto err; 362 363 ch->tx_max_ack_delay = DEFAULT_MAX_ACK_DELAY; 364 ch->rx_max_ack_delay = QUIC_DEFAULT_MAX_ACK_DELAY; 365 ch->rx_ack_delay_exp = QUIC_DEFAULT_ACK_DELAY_EXP; 366 ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT; 367 ch->tx_enc_level = QUIC_ENC_LEVEL_INITIAL; 368 ch->rx_enc_level = QUIC_ENC_LEVEL_INITIAL; 369 ch->txku_threshold_override = UINT64_MAX; 370 371 ch->max_idle_timeout_local_req = QUIC_DEFAULT_IDLE_TIMEOUT; 372 ch->max_idle_timeout_remote_req = 0; 373 ch->max_idle_timeout = ch->max_idle_timeout_local_req; 374 375 ossl_ackm_set_tx_max_ack_delay(ch->ackm, ossl_ms2time(ch->tx_max_ack_delay)); 376 ossl_ackm_set_rx_max_ack_delay(ch->ackm, ossl_ms2time(ch->rx_max_ack_delay)); 377 378 ch_update_idle(ch); 379 ossl_list_ch_insert_tail(&ch->port->channel_list, ch); 380 ch->on_port_list = 1; 381 return 1; 382 383 err: 384 ch_cleanup(ch); 385 return 0; 386 } 387 388 static void ch_cleanup(QUIC_CHANNEL *ch) 389 { 390 uint32_t pn_space; 391 392 if (ch->ackm != NULL) 393 for (pn_space = QUIC_PN_SPACE_INITIAL; 394 pn_space < QUIC_PN_SPACE_NUM; 395 ++pn_space) 396 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space); 397 398 ossl_quic_lcidm_cull(ch->lcidm, ch); 399 ossl_quic_srtm_cull(ch->srtm, ch); 400 ossl_quic_tx_packetiser_free(ch->txp); 401 ossl_quic_txpim_free(ch->txpim); 402 ossl_quic_cfq_free(ch->cfq); 403 ossl_qtx_free(ch->qtx); 404 if (ch->cc_data != NULL) 405 ch->cc_method->free(ch->cc_data); 406 if (ch->have_statm) 407 ossl_statm_destroy(&ch->statm); 408 ossl_ackm_free(ch->ackm); 409 410 if (ch->have_qsm) 411 ossl_quic_stream_map_cleanup(&ch->qsm); 412 413 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) { 414 ossl_quic_sstream_free(ch->crypto_send[pn_space]); 415 ossl_quic_rstream_free(ch->crypto_recv[pn_space]); 416 } 417 418 ossl_qrx_pkt_release(ch->qrx_pkt); 419 ch->qrx_pkt = NULL; 420 421 ossl_quic_tls_free(ch->qtls); 422 ossl_qrx_free(ch->qrx); 423 OPENSSL_free(ch->local_transport_params); 424 OPENSSL_free((char *)ch->terminate_cause.reason); 425 OSSL_ERR_STATE_free(ch->err_state); 426 OPENSSL_free(ch->ack_range_scratch); 427 OPENSSL_free(ch->pending_new_token); 428 429 if (ch->on_port_list) { 430 ossl_list_ch_remove(&ch->port->channel_list, ch); 431 ch->on_port_list = 0; 432 } 433 434 #ifndef OPENSSL_NO_QLOG 435 if (ch->qlog != NULL) 436 ossl_qlog_flush(ch->qlog); /* best effort */ 437 438 OPENSSL_free(ch->qlog_title); 439 ossl_qlog_free(ch->qlog); 440 #endif 441 } 442 443 int ossl_quic_channel_init(QUIC_CHANNEL *ch) 444 { 445 return ch_init(ch); 446 } 447 448 void ossl_quic_channel_bind_qrx(QUIC_CHANNEL *tserver_ch, OSSL_QRX *qrx) 449 { 450 if (tserver_ch->qrx == NULL && tserver_ch->is_tserver_ch == 1) { 451 tserver_ch->qrx = qrx; 452 ossl_qrx_set_late_validation_cb(tserver_ch->qrx, rx_late_validate, 453 tserver_ch); 454 ossl_qrx_set_key_update_cb(tserver_ch->qrx, rxku_detected, 455 tserver_ch); 456 } 457 } 458 459 QUIC_CHANNEL *ossl_quic_channel_alloc(const QUIC_CHANNEL_ARGS *args) 460 { 461 QUIC_CHANNEL *ch = NULL; 462 463 if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL) 464 return NULL; 465 466 ch->port = args->port; 467 ch->is_server = args->is_server; 468 ch->tls = args->tls; 469 ch->lcidm = args->lcidm; 470 ch->srtm = args->srtm; 471 ch->qrx = args->qrx; 472 ch->is_tserver_ch = args->is_tserver_ch; 473 #ifndef OPENSSL_NO_QLOG 474 ch->use_qlog = args->use_qlog; 475 476 if (ch->use_qlog && args->qlog_title != NULL) { 477 if ((ch->qlog_title = OPENSSL_strdup(args->qlog_title)) == NULL) { 478 OPENSSL_free(ch); 479 return NULL; 480 } 481 } 482 #endif 483 484 return ch; 485 } 486 487 void ossl_quic_channel_free(QUIC_CHANNEL *ch) 488 { 489 if (ch == NULL) 490 return; 491 492 ch_cleanup(ch); 493 OPENSSL_free(ch); 494 } 495 496 /* Set mutator callbacks for test framework support */ 497 int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch, 498 ossl_mutate_packet_cb mutatecb, 499 ossl_finish_mutate_cb finishmutatecb, 500 void *mutatearg) 501 { 502 if (ch->qtx == NULL) 503 return 0; 504 505 ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg); 506 return 1; 507 } 508 509 int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr) 510 { 511 if (!ch->addressed_mode) 512 return 0; 513 514 return BIO_ADDR_copy(peer_addr, &ch->cur_peer_addr); 515 } 516 517 int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr) 518 { 519 if (ch->state != QUIC_CHANNEL_STATE_IDLE) 520 return 0; 521 522 if (peer_addr == NULL || BIO_ADDR_family(peer_addr) == AF_UNSPEC) { 523 BIO_ADDR_clear(&ch->cur_peer_addr); 524 ch->addressed_mode = 0; 525 return 1; 526 } 527 528 if (!BIO_ADDR_copy(&ch->cur_peer_addr, peer_addr)) { 529 ch->addressed_mode = 0; 530 return 0; 531 } 532 ch->addressed_mode = 1; 533 534 return 1; 535 } 536 537 QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch) 538 { 539 return ossl_quic_port_get0_reactor(ch->port); 540 } 541 542 QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch) 543 { 544 return &ch->qsm; 545 } 546 547 OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch) 548 { 549 return &ch->statm; 550 } 551 552 SSL *ossl_quic_channel_get0_tls(QUIC_CHANNEL *ch) 553 { 554 return ch->tls; 555 } 556 557 static void free_buf_mem(unsigned char *buf, size_t buf_len, void *arg) 558 { 559 BUF_MEM_free((BUF_MEM *)arg); 560 } 561 562 int ossl_quic_channel_schedule_new_token(QUIC_CHANNEL *ch, 563 const unsigned char *token, 564 size_t token_len) 565 { 566 int rc = 0; 567 QUIC_CFQ_ITEM *cfq_item; 568 WPACKET wpkt; 569 BUF_MEM *buf_mem = NULL; 570 size_t l = 0; 571 572 buf_mem = BUF_MEM_new(); 573 if (buf_mem == NULL) 574 goto err; 575 576 if (!WPACKET_init(&wpkt, buf_mem)) 577 goto err; 578 579 if (!ossl_quic_wire_encode_frame_new_token(&wpkt, token, 580 token_len)) { 581 WPACKET_cleanup(&wpkt); 582 goto err; 583 } 584 585 WPACKET_finish(&wpkt); 586 587 if (!WPACKET_get_total_written(&wpkt, &l)) 588 goto err; 589 590 cfq_item = ossl_quic_cfq_add_frame(ch->cfq, 1, 591 QUIC_PN_SPACE_APP, 592 OSSL_QUIC_FRAME_TYPE_NEW_TOKEN, 0, 593 (unsigned char *)buf_mem->data, l, 594 free_buf_mem, 595 buf_mem); 596 if (cfq_item == NULL) 597 goto err; 598 599 rc = 1; 600 err: 601 if (!rc) 602 BUF_MEM_free(buf_mem); 603 return rc; 604 } 605 606 size_t ossl_quic_channel_get_short_header_conn_id_len(QUIC_CHANNEL *ch) 607 { 608 return ossl_quic_port_get_rx_short_dcid_len(ch->port); 609 } 610 611 QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch, 612 uint64_t stream_id) 613 { 614 return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id); 615 } 616 617 int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch) 618 { 619 return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE; 620 } 621 622 int ossl_quic_channel_is_closing(const QUIC_CHANNEL *ch) 623 { 624 return ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING; 625 } 626 627 static int ossl_quic_channel_is_draining(const QUIC_CHANNEL *ch) 628 { 629 return ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING; 630 } 631 632 static int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch) 633 { 634 return ossl_quic_channel_is_closing(ch) 635 || ossl_quic_channel_is_draining(ch); 636 } 637 638 int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch) 639 { 640 return ch->state == QUIC_CHANNEL_STATE_TERMINATED; 641 } 642 643 int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch) 644 { 645 return ossl_quic_channel_is_terminating(ch) 646 || ossl_quic_channel_is_terminated(ch); 647 } 648 649 const QUIC_TERMINATE_CAUSE * 650 ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch) 651 { 652 return ossl_quic_channel_is_term_any(ch) ? &ch->terminate_cause : NULL; 653 } 654 655 int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch) 656 { 657 return ch->handshake_complete; 658 } 659 660 int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch) 661 { 662 return ch->handshake_confirmed; 663 } 664 665 QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch) 666 { 667 return ch->port->demux; 668 } 669 670 QUIC_PORT *ossl_quic_channel_get0_port(QUIC_CHANNEL *ch) 671 { 672 return ch->port; 673 } 674 675 QUIC_ENGINE *ossl_quic_channel_get0_engine(QUIC_CHANNEL *ch) 676 { 677 return ossl_quic_port_get0_engine(ch->port); 678 } 679 680 CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch) 681 { 682 return ossl_quic_port_get0_mutex(ch->port); 683 } 684 685 int ossl_quic_channel_has_pending(const QUIC_CHANNEL *ch) 686 { 687 return ossl_quic_demux_has_pending(ch->port->demux) 688 || ossl_qrx_processed_read_pending(ch->qrx); 689 } 690 691 /* 692 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components 693 * ================================================================ 694 */ 695 696 /* Used by various components. */ 697 static OSSL_TIME get_time(void *arg) 698 { 699 QUIC_CHANNEL *ch = arg; 700 701 return ossl_quic_port_get_time(ch->port); 702 } 703 704 /* Used by QSM. */ 705 static uint64_t get_stream_limit(int uni, void *arg) 706 { 707 QUIC_CHANNEL *ch = arg; 708 709 return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi; 710 } 711 712 /* 713 * Called by QRX to determine if a packet is potentially invalid before trying 714 * to decrypt it. 715 */ 716 static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg) 717 { 718 QUIC_CHANNEL *ch = arg; 719 720 /* Potential duplicates should not be processed. */ 721 if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space)) 722 return 0; 723 724 return 1; 725 } 726 727 /* 728 * Triggers a TXKU (whether spontaneous or solicited). Does not check whether 729 * spontaneous TXKU is currently allowed. 730 */ 731 QUIC_NEEDS_LOCK 732 static void ch_trigger_txku(QUIC_CHANNEL *ch) 733 { 734 uint64_t next_pn 735 = ossl_quic_tx_packetiser_get_next_pn(ch->txp, QUIC_PN_SPACE_APP); 736 737 if (!ossl_quic_pn_valid(next_pn) 738 || !ossl_qtx_trigger_key_update(ch->qtx)) { 739 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0, 740 "key update"); 741 return; 742 } 743 744 ch->txku_in_progress = 1; 745 ch->txku_pn = next_pn; 746 ch->rxku_expected = ch->ku_locally_initiated; 747 } 748 749 QUIC_NEEDS_LOCK 750 static int txku_in_progress(QUIC_CHANNEL *ch) 751 { 752 if (ch->txku_in_progress 753 && ossl_ackm_get_largest_acked(ch->ackm, QUIC_PN_SPACE_APP) >= ch->txku_pn) { 754 OSSL_TIME pto = ossl_ackm_get_pto_duration(ch->ackm); 755 756 /* 757 * RFC 9001 s. 6.5: Endpoints SHOULD wait three times the PTO before 758 * initiating a key update after receiving an acknowledgment that 759 * confirms that the previous key update was received. 760 * 761 * Note that by the above wording, this period starts from when we get 762 * the ack for a TXKU-triggering packet, not when the TXKU is initiated. 763 * So we defer TXKU cooldown deadline calculation to this point. 764 */ 765 ch->txku_in_progress = 0; 766 ch->txku_cooldown_deadline = ossl_time_add(get_time(ch), 767 ossl_time_multiply(pto, 3)); 768 } 769 770 return ch->txku_in_progress; 771 } 772 773 QUIC_NEEDS_LOCK 774 static int txku_allowed(QUIC_CHANNEL *ch) 775 { 776 return ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT /* Sanity check. */ 777 /* Strict RFC 9001 criterion for TXKU. */ 778 && ch->handshake_confirmed 779 && !txku_in_progress(ch); 780 } 781 782 QUIC_NEEDS_LOCK 783 static int txku_recommendable(QUIC_CHANNEL *ch) 784 { 785 if (!txku_allowed(ch)) 786 return 0; 787 788 return 789 /* Recommended RFC 9001 criterion for TXKU. */ 790 ossl_time_compare(get_time(ch), ch->txku_cooldown_deadline) >= 0 791 /* Some additional sensible criteria. */ 792 && !ch->rxku_in_progress 793 && !ch->rxku_pending_confirm; 794 } 795 796 QUIC_NEEDS_LOCK 797 static int txku_desirable(QUIC_CHANNEL *ch) 798 { 799 uint64_t cur_pkt_count, max_pkt_count, thresh_pkt_count; 800 const uint32_t enc_level = QUIC_ENC_LEVEL_1RTT; 801 802 /* Check AEAD limit to determine if we should perform a spontaneous TXKU. */ 803 cur_pkt_count = ossl_qtx_get_cur_epoch_pkt_count(ch->qtx, enc_level); 804 max_pkt_count = ossl_qtx_get_max_epoch_pkt_count(ch->qtx, enc_level); 805 806 thresh_pkt_count = max_pkt_count / 2; 807 if (ch->txku_threshold_override != UINT64_MAX) 808 thresh_pkt_count = ch->txku_threshold_override; 809 810 return cur_pkt_count >= thresh_pkt_count; 811 } 812 813 QUIC_NEEDS_LOCK 814 static void ch_maybe_trigger_spontaneous_txku(QUIC_CHANNEL *ch) 815 { 816 if (!txku_recommendable(ch) || !txku_desirable(ch)) 817 return; 818 819 ch->ku_locally_initiated = 1; 820 ch_trigger_txku(ch); 821 } 822 823 QUIC_NEEDS_LOCK 824 static int rxku_allowed(QUIC_CHANNEL *ch) 825 { 826 /* 827 * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a key update prior to 828 * having confirmed the handshake (Section 4.1.2). 829 * 830 * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a subsequent key update 831 * unless it has received an acknowledgment for a packet that was sent 832 * protected with keys from the current key phase. 833 * 834 * RFC 9001 s. 6.2: If an endpoint detects a second update before it has 835 * sent any packets with updated keys containing an acknowledgment for the 836 * packet that initiated the key update, it indicates that its peer has 837 * updated keys twice without awaiting confirmation. An endpoint MAY treat 838 * such consecutive key updates as a connection error of type 839 * KEY_UPDATE_ERROR. 840 */ 841 return ch->handshake_confirmed && !ch->rxku_pending_confirm; 842 } 843 844 /* 845 * Called when the QRX detects a new RX key update event. 846 */ 847 enum rxku_decision { 848 DECISION_RXKU_ONLY, 849 DECISION_PROTOCOL_VIOLATION, 850 DECISION_SOLICITED_TXKU 851 }; 852 853 /* Called when the QRX detects a key update has occurred. */ 854 QUIC_NEEDS_LOCK 855 static void rxku_detected(QUIC_PN pn, void *arg) 856 { 857 QUIC_CHANNEL *ch = arg; 858 enum rxku_decision decision; 859 OSSL_TIME pto; 860 861 /* 862 * Note: rxku_in_progress is always 0 here as an RXKU cannot be detected 863 * when we are still in UPDATING or COOLDOWN (see quic_record_rx.h). 864 */ 865 assert(!ch->rxku_in_progress); 866 867 if (!rxku_allowed(ch)) 868 /* Is RXKU even allowed at this time? */ 869 decision = DECISION_PROTOCOL_VIOLATION; 870 871 else if (ch->ku_locally_initiated) 872 /* 873 * If this key update was locally initiated (meaning that this detected 874 * RXKU event is a result of our own spontaneous TXKU), we do not 875 * trigger another TXKU; after all, to do so would result in an infinite 876 * ping-pong of key updates. We still process it as an RXKU. 877 */ 878 decision = DECISION_RXKU_ONLY; 879 880 else 881 /* 882 * Otherwise, a peer triggering a KU means we have to trigger a KU also. 883 */ 884 decision = DECISION_SOLICITED_TXKU; 885 886 if (decision == DECISION_PROTOCOL_VIOLATION) { 887 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_KEY_UPDATE_ERROR, 888 0, "RX key update again too soon"); 889 return; 890 } 891 892 pto = ossl_ackm_get_pto_duration(ch->ackm); 893 894 ch->ku_locally_initiated = 0; 895 ch->rxku_in_progress = 1; 896 ch->rxku_pending_confirm = 1; 897 ch->rxku_trigger_pn = pn; 898 ch->rxku_update_end_deadline = ossl_time_add(get_time(ch), pto); 899 ch->rxku_expected = 0; 900 901 if (decision == DECISION_SOLICITED_TXKU) 902 /* NOT gated by usual txku_allowed() */ 903 ch_trigger_txku(ch); 904 905 /* 906 * Ordinarily, we only generate ACK when some ACK-eliciting frame has been 907 * received. In some cases, this may not occur for a long time, for example 908 * if transmission of application data is going in only one direction and 909 * nothing else is happening with the connection. However, since the peer 910 * cannot initiate a subsequent (spontaneous) TXKU until its prior 911 * (spontaneous or solicited) TXKU has completed - meaning that prior 912 * TXKU's trigger packet (or subsequent packet) has been acknowledged, this 913 * can lead to very long times before a TXKU is considered 'completed'. 914 * Optimise this by forcing ACK generation after triggering TXKU. 915 * (Basically, we consider a RXKU event something that is 'ACK-eliciting', 916 * which it more or less should be; it is necessarily separate from ordinary 917 * processing of ACK-eliciting frames as key update is not indicated via a 918 * frame.) 919 */ 920 ossl_quic_tx_packetiser_schedule_ack(ch->txp, QUIC_PN_SPACE_APP); 921 } 922 923 /* Called per tick to handle RXKU timer events. */ 924 QUIC_NEEDS_LOCK 925 static void ch_rxku_tick(QUIC_CHANNEL *ch) 926 { 927 if (!ch->rxku_in_progress 928 || ossl_time_compare(get_time(ch), ch->rxku_update_end_deadline) < 0) 929 return; 930 931 ch->rxku_update_end_deadline = ossl_time_infinite(); 932 ch->rxku_in_progress = 0; 933 934 if (!ossl_qrx_key_update_timeout(ch->qrx, /*normal=*/1)) 935 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0, 936 "RXKU cooldown internal error"); 937 } 938 939 QUIC_NEEDS_LOCK 940 static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space, 941 void *arg) 942 { 943 QUIC_CHANNEL *ch = arg; 944 945 if (pn_space != QUIC_PN_SPACE_APP || !ch->rxku_pending_confirm 946 || !ossl_quic_frame_ack_contains_pn(ack, ch->rxku_trigger_pn)) 947 return; 948 949 /* 950 * Defer clearing rxku_pending_confirm until TXP generate call returns 951 * successfully. 952 */ 953 ch->rxku_pending_confirm_done = 1; 954 } 955 956 /* 957 * QUIC Channel: Handshake Layer Event Handling 958 * ============================================ 959 */ 960 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len, 961 size_t *consumed, void *arg) 962 { 963 int ret; 964 QUIC_CHANNEL *ch = arg; 965 uint32_t enc_level = ch->tx_enc_level; 966 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level); 967 QUIC_SSTREAM *sstream = ch->crypto_send[pn_space]; 968 969 if (!ossl_assert(sstream != NULL)) 970 return 0; 971 972 ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed); 973 return ret; 974 } 975 976 static int crypto_ensure_empty(QUIC_RSTREAM *rstream) 977 { 978 size_t avail = 0; 979 int is_fin = 0; 980 981 if (rstream == NULL) 982 return 1; 983 984 if (!ossl_quic_rstream_available(rstream, &avail, &is_fin)) 985 return 0; 986 987 return avail == 0; 988 } 989 990 static int ch_on_crypto_recv_record(const unsigned char **buf, 991 size_t *bytes_read, void *arg) 992 { 993 QUIC_CHANNEL *ch = arg; 994 QUIC_RSTREAM *rstream; 995 int is_fin = 0; /* crypto stream is never finished, so we don't use this */ 996 uint32_t i; 997 998 /* 999 * After we move to a later EL we must not allow our peer to send any new 1000 * bytes in the crypto stream on a previous EL. Retransmissions of old bytes 1001 * are allowed. 1002 * 1003 * In practice we will only move to a new EL when we have consumed all bytes 1004 * which should be sent on the crypto stream at a previous EL. For example, 1005 * the Handshake EL should not be provisioned until we have completely 1006 * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output 1007 * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a 1008 * given EL is available we simply ensure we have not received any further 1009 * bytes at a lower EL. 1010 */ 1011 for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i) 1012 if (i != QUIC_ENC_LEVEL_0RTT && !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) { 1013 /* Protocol violation (RFC 9001 s. 4.1.3) */ 1014 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 1015 OSSL_QUIC_FRAME_TYPE_CRYPTO, 1016 "crypto stream data in wrong EL"); 1017 return 0; 1018 } 1019 1020 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)]; 1021 if (rstream == NULL) 1022 return 0; 1023 1024 return ossl_quic_rstream_get_record(rstream, buf, bytes_read, 1025 &is_fin); 1026 } 1027 1028 static int ch_on_crypto_release_record(size_t bytes_read, void *arg) 1029 { 1030 QUIC_CHANNEL *ch = arg; 1031 QUIC_RSTREAM *rstream; 1032 OSSL_RTT_INFO rtt_info; 1033 uint32_t rx_pn_space = ossl_quic_enc_level_to_pn_space(ch->rx_enc_level); 1034 1035 rstream = ch->crypto_recv[rx_pn_space]; 1036 if (rstream == NULL) 1037 return 0; 1038 1039 ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ch), &rtt_info); 1040 if (!ossl_quic_rxfc_on_retire(&ch->crypto_rxfc[rx_pn_space], bytes_read, 1041 rtt_info.smoothed_rtt)) 1042 return 0; 1043 1044 return ossl_quic_rstream_release_record(rstream, bytes_read); 1045 } 1046 1047 static int ch_on_handshake_yield_secret(uint32_t prot_level, int direction, 1048 uint32_t suite_id, EVP_MD *md, 1049 const unsigned char *secret, 1050 size_t secret_len, 1051 void *arg) 1052 { 1053 QUIC_CHANNEL *ch = arg; 1054 uint32_t i; 1055 uint32_t enc_level; 1056 1057 /* Convert TLS protection level to QUIC encryption level */ 1058 switch (prot_level) { 1059 case OSSL_RECORD_PROTECTION_LEVEL_EARLY: 1060 enc_level = QUIC_ENC_LEVEL_0RTT; 1061 break; 1062 1063 case OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE: 1064 enc_level = QUIC_ENC_LEVEL_HANDSHAKE; 1065 break; 1066 1067 case OSSL_RECORD_PROTECTION_LEVEL_APPLICATION: 1068 enc_level = QUIC_ENC_LEVEL_1RTT; 1069 break; 1070 1071 default: 1072 return 0; 1073 } 1074 1075 if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM) 1076 /* Invalid EL. */ 1077 return 0; 1078 1079 if (direction) { 1080 /* TX */ 1081 if (enc_level <= ch->tx_enc_level) 1082 /* 1083 * Does not make sense for us to try and provision an EL we have already 1084 * attained. 1085 */ 1086 return 0; 1087 1088 if (!ossl_qtx_provide_secret(ch->qtx, enc_level, 1089 suite_id, md, 1090 secret, secret_len)) 1091 return 0; 1092 1093 ch->tx_enc_level = enc_level; 1094 } else { 1095 /* RX */ 1096 if (enc_level <= ch->rx_enc_level) 1097 /* 1098 * Does not make sense for us to try and provision an EL we have already 1099 * attained. 1100 */ 1101 return 0; 1102 1103 /* 1104 * Ensure all crypto streams for previous ELs are now empty of available 1105 * data. 1106 */ 1107 for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i) 1108 if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) { 1109 /* Protocol violation (RFC 9001 s. 4.1.3) */ 1110 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 1111 OSSL_QUIC_FRAME_TYPE_CRYPTO, 1112 "crypto stream data in wrong EL"); 1113 return 0; 1114 } 1115 1116 if (!ossl_qrx_provide_secret(ch->qrx, enc_level, 1117 suite_id, md, 1118 secret, secret_len)) 1119 return 0; 1120 1121 ch->have_new_rx_secret = 1; 1122 ch->rx_enc_level = enc_level; 1123 } 1124 1125 return 1; 1126 } 1127 1128 static int ch_on_handshake_complete(void *arg) 1129 { 1130 QUIC_CHANNEL *ch = arg; 1131 1132 if (!ossl_assert(!ch->handshake_complete)) 1133 return 0; /* this should not happen twice */ 1134 1135 if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT)) 1136 return 0; 1137 1138 /* 1139 * When handshake is complete, we no longer need to abide by the 1140 * 3x amplification limit, though we should be validated as soon 1141 * as we see a handshake key encrypted packet (see ossl_quic_handle_packet) 1142 */ 1143 ossl_quic_tx_packetiser_set_validated(ch->txp); 1144 1145 if (!ch->got_remote_transport_params) { 1146 /* 1147 * Was not a valid QUIC handshake if we did not get valid transport 1148 * params. 1149 */ 1150 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_CRYPTO_MISSING_EXT, 1151 OSSL_QUIC_FRAME_TYPE_CRYPTO, 1152 "no transport parameters received"); 1153 return 0; 1154 } 1155 1156 /* Don't need transport parameters anymore. */ 1157 OPENSSL_free(ch->local_transport_params); 1158 ch->local_transport_params = NULL; 1159 1160 /* Tell the QRX it can now process 1-RTT packets. */ 1161 ossl_qrx_allow_1rtt_processing(ch->qrx); 1162 1163 /* Tell TXP the handshake is complete. */ 1164 ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp); 1165 1166 ch->handshake_complete = 1; 1167 1168 if (ch->pending_new_token != NULL) { 1169 /* 1170 * Note this is a best effort operation here 1171 * If scheduling a new token fails, the worst outcome is that 1172 * a client, not having received it, will just have to go through 1173 * an extra roundtrip on a subsequent connection via the retry frame 1174 * path, at which point we get another opportunity to schedule another 1175 * new token. As a result, we don't need to handle any errors here 1176 */ 1177 ossl_quic_channel_schedule_new_token(ch, 1178 ch->pending_new_token, 1179 ch->pending_new_token_len); 1180 OPENSSL_free(ch->pending_new_token); 1181 ch->pending_new_token = NULL; 1182 ch->pending_new_token_len = 0; 1183 } 1184 1185 if (ch->is_server) { 1186 /* 1187 * On the server, the handshake is confirmed as soon as it is complete. 1188 */ 1189 ossl_quic_channel_on_handshake_confirmed(ch); 1190 1191 ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp); 1192 } 1193 1194 ch_record_state_transition(ch, ch->state); 1195 return 1; 1196 } 1197 1198 static int ch_on_handshake_alert(void *arg, unsigned char alert_code) 1199 { 1200 QUIC_CHANNEL *ch = arg; 1201 1202 /* 1203 * RFC 9001 s. 4.4: More specifically, servers MUST NOT send post-handshake 1204 * TLS CertificateRequest messages, and clients MUST treat receipt of such 1205 * messages as a connection error of type PROTOCOL_VIOLATION. 1206 */ 1207 if (alert_code == SSL_AD_UNEXPECTED_MESSAGE 1208 && ch->handshake_complete 1209 && ossl_quic_tls_is_cert_request(ch->qtls)) 1210 ossl_quic_channel_raise_protocol_error(ch, 1211 OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 1212 0, 1213 "Post-handshake TLS " 1214 "CertificateRequest received"); 1215 /* 1216 * RFC 9001 s. 4.6.1: Servers MUST NOT send the early_data extension with a 1217 * max_early_data_size field set to any value other than 0xffffffff. A 1218 * client MUST treat receipt of a NewSessionTicket that contains an 1219 * early_data extension with any other value as a connection error of type 1220 * PROTOCOL_VIOLATION. 1221 */ 1222 else if (alert_code == SSL_AD_ILLEGAL_PARAMETER 1223 && ch->handshake_complete 1224 && ossl_quic_tls_has_bad_max_early_data(ch->qtls)) 1225 ossl_quic_channel_raise_protocol_error(ch, 1226 OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 1227 0, 1228 "Bad max_early_data received"); 1229 else 1230 ossl_quic_channel_raise_protocol_error(ch, 1231 OSSL_QUIC_ERR_CRYPTO_ERR_BEGIN 1232 + alert_code, 1233 0, "handshake alert"); 1234 1235 return 1; 1236 } 1237 1238 /* 1239 * QUIC Channel: Transport Parameter Handling 1240 * ========================================== 1241 */ 1242 1243 /* 1244 * Called by handshake layer when we receive QUIC Transport Parameters from the 1245 * peer. Note that these are not authenticated until the handshake is marked 1246 * as complete. 1247 */ 1248 #define TP_REASON_SERVER_ONLY(x) \ 1249 x " may not be sent by a client" 1250 #define TP_REASON_DUP(x) \ 1251 x " appears multiple times" 1252 #define TP_REASON_MALFORMED(x) \ 1253 x " is malformed" 1254 #define TP_REASON_EXPECTED_VALUE(x) \ 1255 x " does not match expected value" 1256 #define TP_REASON_NOT_RETRY(x) \ 1257 x " sent when not performing a retry" 1258 #define TP_REASON_REQUIRED(x) \ 1259 x " was not sent but is required" 1260 #define TP_REASON_INTERNAL_ERROR(x) \ 1261 x " encountered internal error" 1262 1263 static void txfc_bump_cwm_bidi(QUIC_STREAM *s, void *arg) 1264 { 1265 if (!ossl_quic_stream_is_bidi(s) 1266 || ossl_quic_stream_is_server_init(s)) 1267 return; 1268 1269 ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg); 1270 } 1271 1272 static void txfc_bump_cwm_uni(QUIC_STREAM *s, void *arg) 1273 { 1274 if (ossl_quic_stream_is_bidi(s) 1275 || ossl_quic_stream_is_server_init(s)) 1276 return; 1277 1278 ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg); 1279 } 1280 1281 static void do_update(QUIC_STREAM *s, void *arg) 1282 { 1283 QUIC_CHANNEL *ch = arg; 1284 1285 ossl_quic_stream_map_update_state(&ch->qsm, s); 1286 } 1287 1288 static uint64_t min_u64_ignore_0(uint64_t a, uint64_t b) 1289 { 1290 if (a == 0) 1291 return b; 1292 if (b == 0) 1293 return a; 1294 1295 return a < b ? a : b; 1296 } 1297 1298 static int ch_on_transport_params(const unsigned char *params, 1299 size_t params_len, 1300 void *arg) 1301 { 1302 QUIC_CHANNEL *ch = arg; 1303 PACKET pkt; 1304 uint64_t id, v; 1305 size_t len; 1306 const unsigned char *body; 1307 int got_orig_dcid = 0; 1308 int got_initial_scid = 0; 1309 int got_retry_scid = 0; 1310 int got_initial_max_data = 0; 1311 int got_initial_max_stream_data_bidi_local = 0; 1312 int got_initial_max_stream_data_bidi_remote = 0; 1313 int got_initial_max_stream_data_uni = 0; 1314 int got_initial_max_streams_bidi = 0; 1315 int got_initial_max_streams_uni = 0; 1316 int got_stateless_reset_token = 0; 1317 int got_preferred_addr = 0; 1318 int got_ack_delay_exp = 0; 1319 int got_max_ack_delay = 0; 1320 int got_max_udp_payload_size = 0; 1321 int got_max_idle_timeout = 0; 1322 int got_active_conn_id_limit = 0; 1323 int got_disable_active_migration = 0; 1324 QUIC_CONN_ID cid; 1325 const char *reason = "bad transport parameter"; 1326 ossl_unused uint64_t rx_max_idle_timeout = 0; 1327 ossl_unused const void *stateless_reset_token_p = NULL; 1328 QUIC_PREFERRED_ADDR pfa; 1329 SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(ch->tls); 1330 1331 /* 1332 * When HRR happens the client sends the transport params in the new client 1333 * hello again. Reset the transport params here and load them again. 1334 */ 1335 if (ch->is_server && sc->hello_retry_request != SSL_HRR_NONE 1336 && ch->got_remote_transport_params) { 1337 ch->max_local_streams_bidi = 0; 1338 ch->max_local_streams_uni = 0; 1339 ch->got_local_transport_params = 0; 1340 OPENSSL_free(ch->local_transport_params); 1341 ch->local_transport_params = NULL; 1342 } else if (ch->got_remote_transport_params) { 1343 reason = "multiple transport parameter extensions"; 1344 goto malformed; 1345 } 1346 1347 if (!PACKET_buf_init(&pkt, params, params_len)) { 1348 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0, 1349 "internal error (packet buf init)"); 1350 return 0; 1351 } 1352 1353 while (PACKET_remaining(&pkt) > 0) { 1354 if (!ossl_quic_wire_peek_transport_param(&pkt, &id)) 1355 goto malformed; 1356 1357 switch (id) { 1358 case QUIC_TPARAM_ORIG_DCID: 1359 if (got_orig_dcid) { 1360 reason = TP_REASON_DUP("ORIG_DCID"); 1361 goto malformed; 1362 } 1363 1364 if (ch->is_server) { 1365 reason = TP_REASON_SERVER_ONLY("ORIG_DCID"); 1366 goto malformed; 1367 } 1368 1369 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) { 1370 reason = TP_REASON_MALFORMED("ORIG_DCID"); 1371 goto malformed; 1372 } 1373 1374 #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION 1375 /* Must match our initial DCID. */ 1376 if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) { 1377 reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID"); 1378 goto malformed; 1379 } 1380 #endif 1381 1382 got_orig_dcid = 1; 1383 break; 1384 1385 case QUIC_TPARAM_RETRY_SCID: 1386 if (ch->is_server) { 1387 reason = TP_REASON_SERVER_ONLY("RETRY_SCID"); 1388 goto malformed; 1389 } 1390 1391 if (got_retry_scid) { 1392 reason = TP_REASON_DUP("RETRY_SCID"); 1393 goto malformed; 1394 } 1395 1396 if (!ch->doing_retry) { 1397 reason = TP_REASON_NOT_RETRY("RETRY_SCID"); 1398 goto malformed; 1399 } 1400 1401 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) { 1402 reason = TP_REASON_MALFORMED("RETRY_SCID"); 1403 goto malformed; 1404 } 1405 1406 /* Must match Retry packet SCID. */ 1407 if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) { 1408 reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID"); 1409 goto malformed; 1410 } 1411 1412 got_retry_scid = 1; 1413 break; 1414 1415 case QUIC_TPARAM_INITIAL_SCID: 1416 if (got_initial_scid) { 1417 /* must not appear more than once */ 1418 reason = TP_REASON_DUP("INITIAL_SCID"); 1419 goto malformed; 1420 } 1421 1422 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) { 1423 reason = TP_REASON_MALFORMED("INITIAL_SCID"); 1424 goto malformed; 1425 } 1426 1427 if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) { 1428 reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID"); 1429 goto malformed; 1430 } 1431 1432 got_initial_scid = 1; 1433 break; 1434 1435 case QUIC_TPARAM_INITIAL_MAX_DATA: 1436 if (got_initial_max_data) { 1437 /* must not appear more than once */ 1438 reason = TP_REASON_DUP("INITIAL_MAX_DATA"); 1439 goto malformed; 1440 } 1441 1442 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) { 1443 reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA"); 1444 goto malformed; 1445 } 1446 1447 ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v); 1448 got_initial_max_data = 1; 1449 break; 1450 1451 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL: 1452 if (got_initial_max_stream_data_bidi_local) { 1453 /* must not appear more than once */ 1454 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL"); 1455 goto malformed; 1456 } 1457 1458 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) { 1459 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL"); 1460 goto malformed; 1461 } 1462 1463 /* 1464 * This is correct; the BIDI_LOCAL TP governs streams created by 1465 * the endpoint which sends the TP, i.e., our peer. 1466 */ 1467 ch->rx_init_max_stream_data_bidi_remote = v; 1468 got_initial_max_stream_data_bidi_local = 1; 1469 break; 1470 1471 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE: 1472 if (got_initial_max_stream_data_bidi_remote) { 1473 /* must not appear more than once */ 1474 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE"); 1475 goto malformed; 1476 } 1477 1478 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) { 1479 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE"); 1480 goto malformed; 1481 } 1482 1483 /* 1484 * This is correct; the BIDI_REMOTE TP governs streams created 1485 * by the endpoint which receives the TP, i.e., us. 1486 */ 1487 ch->rx_init_max_stream_data_bidi_local = v; 1488 1489 /* Apply to all existing streams. */ 1490 ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_bidi, &v); 1491 got_initial_max_stream_data_bidi_remote = 1; 1492 break; 1493 1494 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI: 1495 if (got_initial_max_stream_data_uni) { 1496 /* must not appear more than once */ 1497 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI"); 1498 goto malformed; 1499 } 1500 1501 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) { 1502 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI"); 1503 goto malformed; 1504 } 1505 1506 ch->rx_init_max_stream_data_uni = v; 1507 1508 /* Apply to all existing streams. */ 1509 ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_uni, &v); 1510 got_initial_max_stream_data_uni = 1; 1511 break; 1512 1513 case QUIC_TPARAM_ACK_DELAY_EXP: 1514 if (got_ack_delay_exp) { 1515 /* must not appear more than once */ 1516 reason = TP_REASON_DUP("ACK_DELAY_EXP"); 1517 goto malformed; 1518 } 1519 1520 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v) 1521 || v > QUIC_MAX_ACK_DELAY_EXP) { 1522 reason = TP_REASON_MALFORMED("ACK_DELAY_EXP"); 1523 goto malformed; 1524 } 1525 1526 ch->rx_ack_delay_exp = (unsigned char)v; 1527 got_ack_delay_exp = 1; 1528 break; 1529 1530 case QUIC_TPARAM_MAX_ACK_DELAY: 1531 if (got_max_ack_delay) { 1532 /* must not appear more than once */ 1533 reason = TP_REASON_DUP("MAX_ACK_DELAY"); 1534 goto malformed; 1535 } 1536 1537 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v) 1538 || v >= (((uint64_t)1) << 14)) { 1539 reason = TP_REASON_MALFORMED("MAX_ACK_DELAY"); 1540 goto malformed; 1541 } 1542 1543 ch->rx_max_ack_delay = v; 1544 ossl_ackm_set_rx_max_ack_delay(ch->ackm, 1545 ossl_ms2time(ch->rx_max_ack_delay)); 1546 1547 got_max_ack_delay = 1; 1548 break; 1549 1550 case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI: 1551 if (got_initial_max_streams_bidi) { 1552 /* must not appear more than once */ 1553 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI"); 1554 goto malformed; 1555 } 1556 1557 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v) 1558 || v > (((uint64_t)1) << 60)) { 1559 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI"); 1560 goto malformed; 1561 } 1562 1563 assert(ch->max_local_streams_bidi == 0); 1564 ch->max_local_streams_bidi = v; 1565 got_initial_max_streams_bidi = 1; 1566 break; 1567 1568 case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI: 1569 if (got_initial_max_streams_uni) { 1570 /* must not appear more than once */ 1571 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI"); 1572 goto malformed; 1573 } 1574 1575 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v) 1576 || v > (((uint64_t)1) << 60)) { 1577 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI"); 1578 goto malformed; 1579 } 1580 1581 assert(ch->max_local_streams_uni == 0); 1582 ch->max_local_streams_uni = v; 1583 got_initial_max_streams_uni = 1; 1584 break; 1585 1586 case QUIC_TPARAM_MAX_IDLE_TIMEOUT: 1587 if (got_max_idle_timeout) { 1588 /* must not appear more than once */ 1589 reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT"); 1590 goto malformed; 1591 } 1592 1593 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) { 1594 reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT"); 1595 goto malformed; 1596 } 1597 1598 ch->max_idle_timeout_remote_req = v; 1599 1600 ch->max_idle_timeout = min_u64_ignore_0(ch->max_idle_timeout_local_req, 1601 ch->max_idle_timeout_remote_req); 1602 1603 ch_update_idle(ch); 1604 got_max_idle_timeout = 1; 1605 rx_max_idle_timeout = v; 1606 break; 1607 1608 case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE: 1609 if (got_max_udp_payload_size) { 1610 /* must not appear more than once */ 1611 reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE"); 1612 goto malformed; 1613 } 1614 1615 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v) 1616 || v < QUIC_MIN_INITIAL_DGRAM_LEN) { 1617 reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE"); 1618 goto malformed; 1619 } 1620 1621 ch->rx_max_udp_payload_size = v; 1622 got_max_udp_payload_size = 1; 1623 break; 1624 1625 case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT: 1626 if (got_active_conn_id_limit) { 1627 /* must not appear more than once */ 1628 reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT"); 1629 goto malformed; 1630 } 1631 1632 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v) 1633 || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) { 1634 reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT"); 1635 goto malformed; 1636 } 1637 1638 ch->rx_active_conn_id_limit = v; 1639 got_active_conn_id_limit = 1; 1640 break; 1641 1642 case QUIC_TPARAM_STATELESS_RESET_TOKEN: 1643 if (got_stateless_reset_token) { 1644 reason = TP_REASON_DUP("STATELESS_RESET_TOKEN"); 1645 goto malformed; 1646 } 1647 1648 /* 1649 * RFC 9000 s. 18.2: This transport parameter MUST NOT be sent 1650 * by a client but MAY be sent by a server. 1651 */ 1652 if (ch->is_server) { 1653 reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN"); 1654 goto malformed; 1655 } 1656 1657 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len); 1658 if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) { 1659 reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN"); 1660 goto malformed; 1661 } 1662 if (!ossl_quic_srtm_add(ch->srtm, ch, ch->cur_remote_seq_num, 1663 (const QUIC_STATELESS_RESET_TOKEN *)body)) { 1664 reason = TP_REASON_INTERNAL_ERROR("STATELESS_RESET_TOKEN"); 1665 goto malformed; 1666 } 1667 1668 stateless_reset_token_p = body; 1669 got_stateless_reset_token = 1; 1670 break; 1671 1672 case QUIC_TPARAM_PREFERRED_ADDR: 1673 /* TODO(QUIC FUTURE): Handle preferred address. */ 1674 if (got_preferred_addr) { 1675 reason = TP_REASON_DUP("PREFERRED_ADDR"); 1676 goto malformed; 1677 } 1678 1679 /* 1680 * RFC 9000 s. 18.2: "A server that chooses a zero-length 1681 * connection ID MUST NOT provide a preferred address. 1682 * Similarly, a server MUST NOT include a zero-length connection 1683 * ID in this transport parameter. A client MUST treat a 1684 * violation of these requirements as a connection error of type 1685 * TRANSPORT_PARAMETER_ERROR." 1686 */ 1687 if (ch->is_server) { 1688 reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR"); 1689 goto malformed; 1690 } 1691 1692 if (ch->cur_remote_dcid.id_len == 0) { 1693 reason = "PREFERRED_ADDR provided for zero-length CID"; 1694 goto malformed; 1695 } 1696 1697 if (!ossl_quic_wire_decode_transport_param_preferred_addr(&pkt, &pfa)) { 1698 reason = TP_REASON_MALFORMED("PREFERRED_ADDR"); 1699 goto malformed; 1700 } 1701 1702 if (pfa.cid.id_len == 0) { 1703 reason = "zero-length CID in PREFERRED_ADDR"; 1704 goto malformed; 1705 } 1706 1707 got_preferred_addr = 1; 1708 break; 1709 1710 case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION: 1711 /* We do not currently handle migration, so nothing to do. */ 1712 if (got_disable_active_migration) { 1713 /* must not appear more than once */ 1714 reason = TP_REASON_DUP("DISABLE_ACTIVE_MIGRATION"); 1715 goto malformed; 1716 } 1717 1718 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len); 1719 if (body == NULL || len > 0) { 1720 reason = TP_REASON_MALFORMED("DISABLE_ACTIVE_MIGRATION"); 1721 goto malformed; 1722 } 1723 1724 got_disable_active_migration = 1; 1725 break; 1726 1727 default: 1728 /* 1729 * Skip over and ignore. 1730 * 1731 * RFC 9000 s. 7.4: We SHOULD treat duplicated transport parameters 1732 * as a connection error, but we are not required to. Currently, 1733 * handle this programmatically by checking for duplicates in the 1734 * parameters that we recognise, as above, but don't bother 1735 * maintaining a list of duplicates for anything we don't recognise. 1736 */ 1737 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, 1738 &len); 1739 if (body == NULL) 1740 goto malformed; 1741 1742 break; 1743 } 1744 } 1745 1746 if (!got_initial_scid) { 1747 reason = TP_REASON_REQUIRED("INITIAL_SCID"); 1748 goto malformed; 1749 } 1750 1751 if (!ch->is_server) { 1752 if (!got_orig_dcid) { 1753 reason = TP_REASON_REQUIRED("ORIG_DCID"); 1754 goto malformed; 1755 } 1756 1757 if (ch->doing_retry && !got_retry_scid) { 1758 reason = TP_REASON_REQUIRED("RETRY_SCID"); 1759 goto malformed; 1760 } 1761 } 1762 1763 ch->got_remote_transport_params = 1; 1764 1765 #ifndef OPENSSL_NO_QLOG 1766 QLOG_EVENT_BEGIN(ch_get_qlog(ch), transport, parameters_set) 1767 QLOG_STR("owner", "remote"); 1768 1769 if (got_orig_dcid) 1770 QLOG_CID("original_destination_connection_id", 1771 &ch->init_dcid); 1772 if (got_initial_scid) 1773 QLOG_CID("original_source_connection_id", 1774 &ch->init_dcid); 1775 if (got_retry_scid) 1776 QLOG_CID("retry_source_connection_id", 1777 &ch->retry_scid); 1778 if (got_initial_max_data) 1779 QLOG_U64("initial_max_data", 1780 ossl_quic_txfc_get_cwm(&ch->conn_txfc)); 1781 if (got_initial_max_stream_data_bidi_local) 1782 QLOG_U64("initial_max_stream_data_bidi_local", 1783 ch->rx_init_max_stream_data_bidi_local); 1784 if (got_initial_max_stream_data_bidi_remote) 1785 QLOG_U64("initial_max_stream_data_bidi_remote", 1786 ch->rx_init_max_stream_data_bidi_remote); 1787 if (got_initial_max_stream_data_uni) 1788 QLOG_U64("initial_max_stream_data_uni", 1789 ch->rx_init_max_stream_data_uni); 1790 if (got_initial_max_streams_bidi) 1791 QLOG_U64("initial_max_streams_bidi", 1792 ch->max_local_streams_bidi); 1793 if (got_initial_max_streams_uni) 1794 QLOG_U64("initial_max_streams_uni", 1795 ch->max_local_streams_uni); 1796 if (got_ack_delay_exp) 1797 QLOG_U64("ack_delay_exponent", ch->rx_ack_delay_exp); 1798 if (got_max_ack_delay) 1799 QLOG_U64("max_ack_delay", ch->rx_max_ack_delay); 1800 if (got_max_udp_payload_size) 1801 QLOG_U64("max_udp_payload_size", ch->rx_max_udp_payload_size); 1802 if (got_max_idle_timeout) 1803 QLOG_U64("max_idle_timeout", rx_max_idle_timeout); 1804 if (got_active_conn_id_limit) 1805 QLOG_U64("active_connection_id_limit", ch->rx_active_conn_id_limit); 1806 if (got_stateless_reset_token) 1807 QLOG_BIN("stateless_reset_token", stateless_reset_token_p, 1808 QUIC_STATELESS_RESET_TOKEN_LEN); 1809 if (got_preferred_addr) { 1810 QLOG_BEGIN("preferred_addr") 1811 QLOG_U64("port_v4", pfa.ipv4_port); 1812 QLOG_U64("port_v6", pfa.ipv6_port); 1813 QLOG_BIN("ip_v4", pfa.ipv4, sizeof(pfa.ipv4)); 1814 QLOG_BIN("ip_v6", pfa.ipv6, sizeof(pfa.ipv6)); 1815 QLOG_BIN("stateless_reset_token", pfa.stateless_reset.token, 1816 sizeof(pfa.stateless_reset.token)); 1817 QLOG_CID("connection_id", &pfa.cid); 1818 QLOG_END() 1819 } 1820 QLOG_BOOL("disable_active_migration", got_disable_active_migration); 1821 QLOG_EVENT_END() 1822 #endif 1823 1824 if (got_initial_max_data || got_initial_max_stream_data_bidi_remote 1825 || got_initial_max_streams_bidi || got_initial_max_streams_uni) 1826 /* 1827 * If FC credit was bumped, we may now be able to send. Update all 1828 * streams. 1829 */ 1830 ossl_quic_stream_map_visit(&ch->qsm, do_update, ch); 1831 1832 /* If we are a server, we now generate our own transport parameters. */ 1833 if (ch->is_server && !ch_generate_transport_params(ch)) { 1834 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0, 1835 "internal error"); 1836 return 0; 1837 } 1838 1839 return 1; 1840 1841 malformed: 1842 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_TRANSPORT_PARAMETER_ERROR, 1843 0, reason); 1844 return 0; 1845 } 1846 1847 /* 1848 * Called when we want to generate transport parameters. This is called 1849 * immediately at instantiation time for a client and after we receive the 1850 * client's transport parameters for a server. 1851 */ 1852 static int ch_generate_transport_params(QUIC_CHANNEL *ch) 1853 { 1854 int ok = 0; 1855 BUF_MEM *buf_mem = NULL; 1856 WPACKET wpkt; 1857 int wpkt_valid = 0; 1858 size_t buf_len = 0; 1859 QUIC_CONN_ID *id_to_use = NULL; 1860 1861 /* 1862 * We need to select which connection id to encode in the 1863 * QUIC_TPARAM_ORIG_DCID transport parameter 1864 * If we have an odcid, then this connection was established 1865 * in response to a retry request, and we need to use the connection 1866 * id sent in the first initial packet. 1867 * If we don't have an odcid, then this connection was established 1868 * without a retry and the init_dcid is the connection we should use 1869 */ 1870 if (ch->odcid.id_len == 0) 1871 id_to_use = &ch->init_dcid; 1872 else 1873 id_to_use = &ch->odcid; 1874 1875 if (ch->local_transport_params != NULL || ch->got_local_transport_params) 1876 goto err; 1877 1878 if ((buf_mem = BUF_MEM_new()) == NULL) 1879 goto err; 1880 1881 if (!WPACKET_init(&wpkt, buf_mem)) 1882 goto err; 1883 1884 wpkt_valid = 1; 1885 1886 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION, 1887 NULL, 0) 1888 == NULL) 1889 goto err; 1890 1891 if (ch->is_server) { 1892 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID, 1893 id_to_use)) 1894 goto err; 1895 1896 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID, 1897 &ch->cur_local_cid)) 1898 goto err; 1899 if (ch->odcid.id_len != 0) 1900 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, 1901 QUIC_TPARAM_RETRY_SCID, 1902 &ch->init_dcid)) 1903 goto err; 1904 } else { 1905 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID, 1906 &ch->init_scid)) 1907 goto err; 1908 } 1909 1910 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT, 1911 ch->max_idle_timeout_local_req)) 1912 goto err; 1913 1914 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE, 1915 QUIC_MIN_INITIAL_DGRAM_LEN)) 1916 goto err; 1917 1918 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT, 1919 QUIC_MIN_ACTIVE_CONN_ID_LIMIT)) 1920 goto err; 1921 1922 if (ch->tx_max_ack_delay != QUIC_DEFAULT_MAX_ACK_DELAY 1923 && !ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_ACK_DELAY, 1924 ch->tx_max_ack_delay)) 1925 goto err; 1926 1927 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA, 1928 ossl_quic_rxfc_get_cwm(&ch->conn_rxfc))) 1929 goto err; 1930 1931 /* Send the default CWM for a new RXFC. */ 1932 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL, 1933 ch->tx_init_max_stream_data_bidi_local)) 1934 goto err; 1935 1936 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE, 1937 ch->tx_init_max_stream_data_bidi_remote)) 1938 goto err; 1939 1940 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI, 1941 ch->tx_init_max_stream_data_uni)) 1942 goto err; 1943 1944 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI, 1945 ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc))) 1946 goto err; 1947 1948 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI, 1949 ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc))) 1950 goto err; 1951 1952 if (!WPACKET_finish(&wpkt)) 1953 goto err; 1954 1955 wpkt_valid = 0; 1956 1957 if (!WPACKET_get_total_written(&wpkt, &buf_len)) 1958 goto err; 1959 1960 ch->local_transport_params = (unsigned char *)buf_mem->data; 1961 buf_mem->data = NULL; 1962 1963 if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params, 1964 buf_len)) 1965 goto err; 1966 1967 #ifndef OPENSSL_NO_QLOG 1968 QLOG_EVENT_BEGIN(ch_get_qlog(ch), transport, parameters_set) 1969 QLOG_STR("owner", "local"); 1970 QLOG_BOOL("disable_active_migration", 1); 1971 if (ch->is_server) { 1972 QLOG_CID("original_destination_connection_id", &ch->init_dcid); 1973 QLOG_CID("initial_source_connection_id", &ch->cur_local_cid); 1974 } else { 1975 QLOG_STR("initial_source_connection_id", ""); 1976 } 1977 QLOG_U64("max_idle_timeout", ch->max_idle_timeout); 1978 QLOG_U64("max_udp_payload_size", QUIC_MIN_INITIAL_DGRAM_LEN); 1979 QLOG_U64("active_connection_id_limit", QUIC_MIN_ACTIVE_CONN_ID_LIMIT); 1980 QLOG_U64("max_ack_delay", ch->tx_max_ack_delay); 1981 QLOG_U64("initial_max_data", ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)); 1982 QLOG_U64("initial_max_stream_data_bidi_local", 1983 ch->tx_init_max_stream_data_bidi_local); 1984 QLOG_U64("initial_max_stream_data_bidi_remote", 1985 ch->tx_init_max_stream_data_bidi_remote); 1986 QLOG_U64("initial_max_stream_data_uni", 1987 ch->tx_init_max_stream_data_uni); 1988 QLOG_U64("initial_max_streams_bidi", 1989 ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc)); 1990 QLOG_U64("initial_max_streams_uni", 1991 ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc)); 1992 QLOG_EVENT_END() 1993 #endif 1994 1995 ch->got_local_transport_params = 1; 1996 1997 ok = 1; 1998 err: 1999 if (wpkt_valid) 2000 WPACKET_cleanup(&wpkt); 2001 BUF_MEM_free(buf_mem); 2002 return ok; 2003 } 2004 2005 /* 2006 * QUIC Channel: Ticker-Mutator 2007 * ============================ 2008 */ 2009 2010 /* 2011 * The central ticker function called by the reactor. This does everything, or 2012 * at least everything network I/O related. Best effort - not allowed to fail 2013 * "loudly". 2014 */ 2015 void ossl_quic_channel_subtick(QUIC_CHANNEL *ch, QUIC_TICK_RESULT *res, 2016 uint32_t flags) 2017 { 2018 OSSL_TIME now, deadline; 2019 int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0; 2020 int notify_other_threads = 0; 2021 2022 /* 2023 * When we tick the QUIC connection, we do everything we need to do 2024 * periodically. Network I/O handling will already have been performed 2025 * as necessary by the QUIC port. Thus, in order, we: 2026 * 2027 * - handle any packets the DEMUX has queued up for us; 2028 * - handle any timer events which are due to fire (ACKM, etc.); 2029 * - generate any packets which need to be sent; 2030 * - determine the time at which we should next be ticked. 2031 */ 2032 2033 /* 2034 * If the connection has not yet started, or we are in the TERMINATED state, 2035 * there is nothing to do. 2036 */ 2037 if (ch->state == QUIC_CHANNEL_STATE_IDLE 2038 || ossl_quic_channel_is_terminated(ch)) { 2039 res->net_read_desired = 0; 2040 res->net_write_desired = 0; 2041 res->notify_other_threads = 0; 2042 res->tick_deadline = ossl_time_infinite(); 2043 return; 2044 } 2045 2046 /* 2047 * If we are in the TERMINATING state, check if the terminating timer has 2048 * expired. 2049 */ 2050 if (ossl_quic_channel_is_terminating(ch)) { 2051 now = get_time(ch); 2052 2053 if (ossl_time_compare(now, ch->terminate_deadline) >= 0) { 2054 ch_on_terminating_timeout(ch); 2055 res->net_read_desired = 0; 2056 res->net_write_desired = 0; 2057 res->notify_other_threads = 1; 2058 res->tick_deadline = ossl_time_infinite(); 2059 return; /* abort normal processing, nothing to do */ 2060 } 2061 } 2062 2063 if (!ch->port->engine->inhibit_tick) { 2064 /* Handle RXKU timeouts. */ 2065 ch_rxku_tick(ch); 2066 2067 do { 2068 /* Process queued incoming packets. */ 2069 ch->did_tls_tick = 0; 2070 ch->have_new_rx_secret = 0; 2071 ch_rx(ch, channel_only, ¬ify_other_threads); 2072 2073 /* 2074 * Allow the handshake layer to check for any new incoming data and 2075 * generate new outgoing data. 2076 */ 2077 if (!ch->did_tls_tick) 2078 ch_tick_tls(ch, channel_only, ¬ify_other_threads); 2079 2080 /* 2081 * If the handshake layer gave us a new secret, we need to do RX 2082 * again because packets that were not previously processable and 2083 * were deferred might now be processable. 2084 * 2085 * TODO(QUIC FUTURE): Consider handling this in the yield_secret callback. 2086 */ 2087 } while (ch->have_new_rx_secret); 2088 } 2089 2090 /* 2091 * Handle any timer events which are due to fire; namely, the loss 2092 * detection deadline and the idle timeout. 2093 * 2094 * ACKM ACK generation deadline is polled by TXP, so we don't need to 2095 * handle it here. 2096 */ 2097 now = get_time(ch); 2098 if (ossl_time_compare(now, ch->idle_deadline) >= 0) { 2099 /* 2100 * Idle timeout differs from normal protocol violation because we do 2101 * not send a CONN_CLOSE frame; go straight to TERMINATED. 2102 */ 2103 if (!ch->port->engine->inhibit_tick) 2104 ch_on_idle_timeout(ch); 2105 2106 res->net_read_desired = 0; 2107 res->net_write_desired = 0; 2108 res->notify_other_threads = 1; 2109 res->tick_deadline = ossl_time_infinite(); 2110 return; 2111 } 2112 2113 if (!ch->port->engine->inhibit_tick) { 2114 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm); 2115 if (!ossl_time_is_zero(deadline) 2116 && ossl_time_compare(now, deadline) >= 0) 2117 ossl_ackm_on_timeout(ch->ackm); 2118 2119 /* If a ping is due, inform TXP. */ 2120 if (ossl_time_compare(now, ch->ping_deadline) >= 0) { 2121 int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level); 2122 2123 ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space); 2124 2125 /* 2126 * If we have no CC budget at this time we cannot process the above 2127 * PING request immediately. In any case we have scheduled the 2128 * request so bump the ping deadline. If we don't do this we will 2129 * busy-loop endlessly as the above deadline comparison condition 2130 * will still be met. 2131 */ 2132 ch_update_ping_deadline(ch); 2133 } 2134 2135 /* Queue any data to be sent for transmission. */ 2136 ch_tx(ch, ¬ify_other_threads); 2137 2138 /* Do stream GC. */ 2139 ossl_quic_stream_map_gc(&ch->qsm); 2140 } 2141 2142 /* Determine the time at which we should next be ticked. */ 2143 res->tick_deadline = ch_determine_next_tick_deadline(ch); 2144 2145 /* 2146 * Always process network input unless we are now terminated. Although we 2147 * had not terminated at the beginning of this tick, network errors in 2148 * ch_tx() may have caused us to transition to the Terminated state. 2149 */ 2150 res->net_read_desired = !ossl_quic_channel_is_terminated(ch); 2151 2152 /* We want to write to the network if we have any data in our TX queue. */ 2153 res->net_write_desired 2154 = (!ossl_quic_channel_is_terminated(ch) 2155 && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0); 2156 2157 res->notify_other_threads = notify_other_threads; 2158 } 2159 2160 static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads) 2161 { 2162 uint64_t error_code; 2163 const char *error_msg; 2164 ERR_STATE *error_state = NULL; 2165 2166 if (channel_only) 2167 return 1; 2168 2169 ch->did_tls_tick = 1; 2170 ossl_quic_tls_tick(ch->qtls); 2171 2172 if (ossl_quic_tls_get_error(ch->qtls, &error_code, &error_msg, 2173 &error_state)) { 2174 ossl_quic_channel_raise_protocol_error_state(ch, error_code, 0, 2175 error_msg, error_state); 2176 if (notify_other_threads != NULL) 2177 *notify_other_threads = 1; 2178 2179 return 0; 2180 } 2181 2182 return 1; 2183 } 2184 2185 /* Check incoming forged packet limit and terminate connection if needed. */ 2186 static void ch_rx_check_forged_pkt_limit(QUIC_CHANNEL *ch) 2187 { 2188 uint32_t enc_level; 2189 uint64_t limit = UINT64_MAX, l; 2190 2191 for (enc_level = QUIC_ENC_LEVEL_INITIAL; 2192 enc_level < QUIC_ENC_LEVEL_NUM; 2193 ++enc_level) { 2194 /* 2195 * Different ELs can have different AEADs which can in turn impose 2196 * different limits, so use the lowest value of any currently valid EL. 2197 */ 2198 if ((ch->el_discarded & (1U << enc_level)) != 0) 2199 continue; 2200 2201 if (enc_level > ch->rx_enc_level) 2202 break; 2203 2204 l = ossl_qrx_get_max_forged_pkt_count(ch->qrx, enc_level); 2205 if (l < limit) 2206 limit = l; 2207 } 2208 2209 if (ossl_qrx_get_cur_forged_pkt_count(ch->qrx) < limit) 2210 return; 2211 2212 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_AEAD_LIMIT_REACHED, 0, 2213 "forgery limit"); 2214 } 2215 2216 void ossl_ch_reset_rx_state(QUIC_CHANNEL *ch) 2217 { 2218 ch->did_crypto_frame = 0; 2219 ch->seen_path_challenge = 0; 2220 } 2221 2222 /* Process queued incoming packets and handle frames, if any. */ 2223 static int ch_rx(QUIC_CHANNEL *ch, int channel_only, int *notify_other_threads) 2224 { 2225 int handled_any = 0; 2226 const int closing = ossl_quic_channel_is_closing(ch); 2227 2228 if (!ch->is_server && !ch->have_sent_any_pkt) 2229 /* 2230 * We have not sent anything yet, therefore there is no need to check 2231 * for incoming data. 2232 */ 2233 return 1; 2234 2235 for (;;) { 2236 assert(ch->qrx_pkt == NULL); 2237 2238 if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt)) 2239 break; 2240 2241 /* Track the amount of data received while in the closing state */ 2242 if (closing) 2243 ossl_quic_tx_packetiser_record_received_closing_bytes( 2244 ch->txp, ch->qrx_pkt->hdr->len); 2245 2246 if (!handled_any) { 2247 ch_update_idle(ch); 2248 ch_update_ping_deadline(ch); 2249 } 2250 2251 ch_rx_handle_packet(ch, channel_only); /* best effort */ 2252 2253 /* 2254 * Regardless of the outcome of frame handling, unref the packet. 2255 * This will free the packet unless something added another 2256 * reference to it during frame processing. 2257 */ 2258 ossl_qrx_pkt_release(ch->qrx_pkt); 2259 ch->qrx_pkt = NULL; 2260 2261 ch->have_sent_ack_eliciting_since_rx = 0; 2262 handled_any = 1; 2263 } 2264 2265 ch_rx_check_forged_pkt_limit(ch); 2266 2267 if (handled_any && notify_other_threads != NULL) 2268 *notify_other_threads = 1; 2269 2270 /* 2271 * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we 2272 * process one or more incoming packets. 2273 */ 2274 if (handled_any && closing) 2275 ch->conn_close_queued = 1; 2276 2277 return 1; 2278 } 2279 2280 static int bio_addr_eq(const BIO_ADDR *a, const BIO_ADDR *b) 2281 { 2282 if (BIO_ADDR_family(a) != BIO_ADDR_family(b)) 2283 return 0; 2284 2285 switch (BIO_ADDR_family(a)) { 2286 case AF_INET: 2287 return !memcmp(&a->s_in.sin_addr, 2288 &b->s_in.sin_addr, 2289 sizeof(a->s_in.sin_addr)) 2290 && a->s_in.sin_port == b->s_in.sin_port; 2291 #if OPENSSL_USE_IPV6 2292 case AF_INET6: 2293 return !memcmp(&a->s_in6.sin6_addr, 2294 &b->s_in6.sin6_addr, 2295 sizeof(a->s_in6.sin6_addr)) 2296 && a->s_in6.sin6_port == b->s_in6.sin6_port; 2297 #endif 2298 default: 2299 return 0; /* not supported */ 2300 } 2301 2302 return 1; 2303 } 2304 2305 /* Handles the packet currently in ch->qrx_pkt->hdr. */ 2306 static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only) 2307 { 2308 uint32_t enc_level; 2309 int old_have_processed_any_pkt = ch->have_processed_any_pkt; 2310 OSSL_QTX_IOVEC iovec; 2311 PACKET vpkt; 2312 unsigned long supported_ver; 2313 2314 assert(ch->qrx_pkt != NULL); 2315 2316 /* 2317 * RFC 9000 s. 10.2.1 Closing Connection State: 2318 * An endpoint that is closing is not required to process any 2319 * received frame. 2320 */ 2321 if (!ossl_quic_channel_is_active(ch)) 2322 return; 2323 2324 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) { 2325 if (!ch->have_received_enc_pkt) { 2326 ch->cur_remote_dcid = ch->init_scid = ch->qrx_pkt->hdr->src_conn_id; 2327 ch->have_received_enc_pkt = 1; 2328 2329 /* 2330 * We change to using the SCID in the first Initial packet as the 2331 * DCID. 2332 */ 2333 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid); 2334 } 2335 2336 enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type); 2337 if ((ch->el_discarded & (1U << enc_level)) != 0) 2338 /* Do not process packets from ELs we have already discarded. */ 2339 return; 2340 } 2341 2342 /* 2343 * RFC 9000 s. 9.6: "If a client receives packets from a new server address 2344 * when the client has not initiated a migration to that address, the client 2345 * SHOULD discard these packets." 2346 * 2347 * We need to be a bit careful here as due to the BIO abstraction layer an 2348 * application is liable to be weird and lie to us about peer addresses. 2349 * Only apply this check if we actually are using a real AF_INET or AF_INET6 2350 * address. 2351 */ 2352 if (!ch->is_server 2353 && ch->qrx_pkt->peer != NULL 2354 && (BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET 2355 #if OPENSSL_USE_IPV6 2356 || BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET6 2357 #endif 2358 ) 2359 && !bio_addr_eq(ch->qrx_pkt->peer, &ch->cur_peer_addr)) 2360 return; 2361 2362 if (!ch->is_server 2363 && ch->have_received_enc_pkt 2364 && ossl_quic_pkt_type_has_scid(ch->qrx_pkt->hdr->type)) { 2365 /* 2366 * RFC 9000 s. 7.2: "Once a client has received a valid Initial packet 2367 * from the server, it MUST discard any subsequent packet it receives on 2368 * that connection with a different SCID." 2369 */ 2370 if (!ossl_quic_conn_id_eq(&ch->qrx_pkt->hdr->src_conn_id, 2371 &ch->init_scid)) 2372 return; 2373 } 2374 2375 if (ossl_quic_pkt_type_has_version(ch->qrx_pkt->hdr->type) 2376 && ch->qrx_pkt->hdr->version != QUIC_VERSION_1) 2377 /* 2378 * RFC 9000 s. 5.2.1: If a client receives a packet that uses a 2379 * different version than it initially selected, it MUST discard the 2380 * packet. We only ever use v1, so require it. 2381 */ 2382 return; 2383 2384 if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_VERSION_NEG) { 2385 2386 /* 2387 * Sanity check. Version negotiation packet MUST have a version 2388 * value of 0 according to the RFC. We must discard such packets 2389 */ 2390 if (ch->qrx_pkt->hdr->version != 0) 2391 return; 2392 2393 /* 2394 * RFC 9000 s. 6.2: If a client receives a version negotiation 2395 * packet, we need to do the following: 2396 * a) If the negotiation packet lists the version we initially sent 2397 * then we must abandon this connection attempt 2398 * b) We have to select a version from the list provided in the 2399 * version negotiation packet, and retry the connection attempt 2400 * in much the same way that ch_retry does, but we can reuse the 2401 * connection id values 2402 */ 2403 2404 if (old_have_processed_any_pkt == 1) { 2405 /* 2406 * We've gotten previous packets, need to discard this. 2407 */ 2408 return; 2409 } 2410 2411 /* 2412 * Indicate that we have processed a packet, as any subsequently 2413 * received version negotiation packet must be discarded above 2414 */ 2415 ch->have_processed_any_pkt = 1; 2416 2417 /* 2418 * Following the header, version negotiation packets 2419 * contain an array of 32 bit integers representing 2420 * the supported versions that the server honors 2421 * this array, bounded by the hdr->len field 2422 * needs to be traversed so that we can find a matching 2423 * version 2424 */ 2425 if (!PACKET_buf_init(&vpkt, ch->qrx_pkt->hdr->data, 2426 ch->qrx_pkt->hdr->len)) 2427 return; 2428 2429 while (PACKET_remaining(&vpkt) > 0) { 2430 /* 2431 * We only support quic version 1 at the moment, so 2432 * look to see if that's offered 2433 */ 2434 if (!PACKET_get_net_4(&vpkt, &supported_ver)) 2435 return; 2436 2437 if (supported_ver == QUIC_VERSION_1) { 2438 /* 2439 * If the server supports version 1, set it as 2440 * the packetisers version 2441 */ 2442 ossl_quic_tx_packetiser_set_protocol_version(ch->txp, QUIC_VERSION_1); 2443 2444 /* 2445 * And then request a restart of the QUIC connection 2446 */ 2447 if (!ch_restart(ch)) 2448 ossl_quic_channel_raise_protocol_error(ch, 2449 OSSL_QUIC_ERR_INTERNAL_ERROR, 2450 0, "handling ver negotiation packet"); 2451 return; 2452 } 2453 } 2454 2455 /* 2456 * If we get here, then the server doesn't support a version of the 2457 * protocol that we can handle, abandon the connection 2458 */ 2459 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_CONNECTION_REFUSED, 2460 0, "unsupported protocol version"); 2461 return; 2462 } 2463 2464 ch->have_processed_any_pkt = 1; 2465 2466 /* 2467 * RFC 9000 s. 17.2: "An endpoint MUST treat receipt of a packet that has a 2468 * non-zero value for [the reserved bits] after removing both packet and 2469 * header protection as a connection error of type PROTOCOL_VIOLATION." 2470 */ 2471 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type) 2472 && ch->qrx_pkt->hdr->reserved != 0) { 2473 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 2474 0, "packet header reserved bits"); 2475 return; 2476 } 2477 2478 iovec.buf = ch->qrx_pkt->hdr->data; 2479 iovec.buf_len = ch->qrx_pkt->hdr->len; 2480 ossl_qlog_event_transport_packet_received(ch_get_qlog(ch), ch->qrx_pkt->hdr, 2481 ch->qrx_pkt->pn, &iovec, 1, 2482 ch->qrx_pkt->datagram_id); 2483 2484 /* Handle incoming packet. */ 2485 switch (ch->qrx_pkt->hdr->type) { 2486 case QUIC_PKT_TYPE_RETRY: 2487 if (ch->doing_retry || ch->is_server) 2488 /* 2489 * It is not allowed to ask a client to do a retry more than 2490 * once. Clients may not send retries. 2491 */ 2492 return; 2493 2494 /* 2495 * RFC 9000 s 17.2.5.2: After the client has received and processed an 2496 * Initial or Retry packet from the server, it MUST discard any 2497 * subsequent Retry packets that it receives. 2498 */ 2499 if (ch->have_received_enc_pkt) 2500 return; 2501 2502 if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN) 2503 /* Packets with zero-length Retry Tokens are invalid. */ 2504 return; 2505 2506 /* 2507 * TODO(QUIC FUTURE): Theoretically this should probably be in the QRX. 2508 * However because validation is dependent on context (namely the 2509 * client's initial DCID) we can't do this cleanly. In the future we 2510 * should probably add a callback to the QRX to let it call us (via 2511 * the DEMUX) and ask us about the correct original DCID, rather 2512 * than allow the QRX to emit a potentially malformed packet to the 2513 * upper layers. However, special casing this will do for now. 2514 */ 2515 if (!ossl_quic_validate_retry_integrity_tag(ch->port->engine->libctx, 2516 ch->port->engine->propq, 2517 ch->qrx_pkt->hdr, 2518 &ch->init_dcid)) 2519 /* Malformed retry packet, ignore. */ 2520 return; 2521 2522 if (!ch_retry(ch, ch->qrx_pkt->hdr->data, 2523 ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN, 2524 &ch->qrx_pkt->hdr->src_conn_id, old_have_processed_any_pkt)) 2525 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 2526 0, "handling retry packet"); 2527 break; 2528 2529 case QUIC_PKT_TYPE_0RTT: 2530 if (!ch->is_server) 2531 /* Clients should never receive 0-RTT packets. */ 2532 return; 2533 2534 /* 2535 * TODO(QUIC 0RTT): Implement 0-RTT on the server side. We currently 2536 * do not need to implement this as a client can only do 0-RTT if we 2537 * have given it permission to in a previous session. 2538 */ 2539 break; 2540 2541 case QUIC_PKT_TYPE_INITIAL: 2542 case QUIC_PKT_TYPE_HANDSHAKE: 2543 case QUIC_PKT_TYPE_1RTT: 2544 if (ch->is_server && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE) 2545 /* 2546 * We automatically drop INITIAL EL keys when first successfully 2547 * decrypting a HANDSHAKE packet, as per the RFC. 2548 */ 2549 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL); 2550 2551 if (ch->rxku_in_progress 2552 && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_1RTT 2553 && ch->qrx_pkt->pn >= ch->rxku_trigger_pn 2554 && ch->qrx_pkt->key_epoch < ossl_qrx_get_key_epoch(ch->qrx)) { 2555 /* 2556 * RFC 9001 s. 6.4: Packets with higher packet numbers MUST be 2557 * protected with either the same or newer packet protection keys 2558 * than packets with lower packet numbers. An endpoint that 2559 * successfully removes protection with old keys when newer keys 2560 * were used for packets with lower packet numbers MUST treat this 2561 * as a connection error of type KEY_UPDATE_ERROR. 2562 */ 2563 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_KEY_UPDATE_ERROR, 2564 0, "new packet with old keys"); 2565 break; 2566 } 2567 2568 if (!ch->is_server 2569 && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_INITIAL 2570 && ch->qrx_pkt->hdr->token_len > 0) { 2571 /* 2572 * RFC 9000 s. 17.2.2: Clients that receive an Initial packet with a 2573 * non-zero Token Length field MUST either discard the packet or 2574 * generate a connection error of type PROTOCOL_VIOLATION. 2575 * 2576 * TODO(QUIC FUTURE): consider the implications of RFC 9000 s. 10.2.3 2577 * Immediate Close during the Handshake: 2578 * However, at the cost of reducing feedback about 2579 * errors for legitimate peers, some forms of denial of 2580 * service can be made more difficult for an attacker 2581 * if endpoints discard illegal packets rather than 2582 * terminating a connection with CONNECTION_CLOSE. For 2583 * this reason, endpoints MAY discard packets rather 2584 * than immediately close if errors are detected in 2585 * packets that lack authentication. 2586 * I.e. should we drop this packet instead of closing the connection? 2587 */ 2588 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 2589 0, "client received initial token"); 2590 break; 2591 } 2592 2593 /* This packet contains frames, pass to the RXDP. */ 2594 ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */ 2595 2596 if (ch->did_crypto_frame) 2597 ch_tick_tls(ch, channel_only, NULL); 2598 2599 break; 2600 2601 default: 2602 assert(0); 2603 break; 2604 } 2605 } 2606 2607 /* Try to generate packets and if possible, flush them to the network. */ 2608 static int ch_tx(QUIC_CHANNEL *ch, int *notify_other_threads) 2609 { 2610 QUIC_TXP_STATUS status; 2611 int res; 2612 2613 /* 2614 * RFC 9000 s. 10.2.2: Draining Connection State: 2615 * While otherwise identical to the closing state, an endpoint 2616 * in the draining state MUST NOT send any packets. 2617 * and: 2618 * An endpoint MUST NOT send further packets. 2619 */ 2620 if (ossl_quic_channel_is_draining(ch)) 2621 return 0; 2622 2623 if (ossl_quic_channel_is_closing(ch)) { 2624 /* 2625 * While closing, only send CONN_CLOSE if we've received more traffic 2626 * from the peer. Once we tell the TXP to generate CONN_CLOSE, all 2627 * future calls to it generate CONN_CLOSE frames, so otherwise we would 2628 * just constantly generate CONN_CLOSE frames. 2629 * 2630 * Confirming to RFC 9000 s. 10.2.1 Closing Connection State: 2631 * An endpoint SHOULD limit the rate at which it generates 2632 * packets in the closing state. 2633 */ 2634 if (!ch->conn_close_queued) 2635 return 0; 2636 2637 ch->conn_close_queued = 0; 2638 } 2639 2640 /* Do TXKU if we need to. */ 2641 ch_maybe_trigger_spontaneous_txku(ch); 2642 2643 ch->rxku_pending_confirm_done = 0; 2644 2645 /* Loop until we stop generating packets to send */ 2646 do { 2647 /* 2648 * Send packet, if we need to. Best effort. The TXP consults the CC and 2649 * applies any limitations imposed by it, so we don't need to do it here. 2650 * 2651 * Best effort. In particular if TXP fails for some reason we should 2652 * still flush any queued packets which we already generated. 2653 */ 2654 res = ossl_quic_tx_packetiser_generate(ch->txp, &status); 2655 if (status.sent_pkt > 0) { 2656 ch->have_sent_any_pkt = 1; /* Packet(s) were sent */ 2657 ch->port->have_sent_any_pkt = 1; 2658 2659 /* 2660 * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when 2661 * sending an ack-eliciting packet if no other ack-eliciting packets 2662 * have been sent since last receiving and processing a packet.' 2663 */ 2664 if (status.sent_ack_eliciting 2665 && !ch->have_sent_ack_eliciting_since_rx) { 2666 ch_update_idle(ch); 2667 ch->have_sent_ack_eliciting_since_rx = 1; 2668 } 2669 2670 if (!ch->is_server && status.sent_handshake) 2671 /* 2672 * RFC 9001 s. 4.9.1: A client MUST discard Initial keys when it 2673 * first sends a Handshake packet. 2674 */ 2675 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL); 2676 2677 if (ch->rxku_pending_confirm_done) 2678 ch->rxku_pending_confirm = 0; 2679 2680 ch_update_ping_deadline(ch); 2681 } 2682 2683 if (!res) { 2684 /* 2685 * One case where TXP can fail is if we reach a TX PN of 2**62 - 1. 2686 * As per RFC 9000 s. 12.3, if this happens we MUST close the 2687 * connection without sending a CONNECTION_CLOSE frame. This is 2688 * actually handled as an emergent consequence of our design, as the 2689 * TX packetiser will never transmit another packet when the TX PN 2690 * reaches the limit. 2691 * 2692 * Calling the below function terminates the connection; its attempt 2693 * to schedule a CONNECTION_CLOSE frame will not actually cause a 2694 * packet to be transmitted for this reason. 2695 */ 2696 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 2697 0, 2698 "internal error (txp generate)"); 2699 break; 2700 } 2701 } while (status.sent_pkt > 0); 2702 2703 /* Flush packets to network. */ 2704 switch (ossl_qtx_flush_net(ch->qtx)) { 2705 case QTX_FLUSH_NET_RES_OK: 2706 case QTX_FLUSH_NET_RES_TRANSIENT_FAIL: 2707 /* Best effort, done for now. */ 2708 break; 2709 2710 case QTX_FLUSH_NET_RES_PERMANENT_FAIL: 2711 default: 2712 /* Permanent underlying network BIO, start terminating. */ 2713 ossl_quic_port_raise_net_error(ch->port, ch); 2714 break; 2715 } 2716 2717 /* 2718 * If we have datagrams we have yet to successfully transmit, we need to 2719 * notify other threads so that they can switch to polling on POLLOUT as 2720 * well as POLLIN. 2721 */ 2722 if (ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0) 2723 *notify_other_threads = 1; 2724 2725 return 1; 2726 } 2727 2728 /* Determine next tick deadline. */ 2729 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch) 2730 { 2731 OSSL_TIME deadline; 2732 int i; 2733 2734 if (ossl_quic_channel_is_terminated(ch)) 2735 return ossl_time_infinite(); 2736 2737 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm); 2738 if (ossl_time_is_zero(deadline)) 2739 deadline = ossl_time_infinite(); 2740 2741 /* 2742 * Check the ack deadline for all enc_levels that are actually provisioned. 2743 * ACKs aren't restricted by CC. 2744 */ 2745 for (i = 0; i < QUIC_ENC_LEVEL_NUM; i++) { 2746 if (ossl_qtx_is_enc_level_provisioned(ch->qtx, i)) { 2747 deadline = ossl_time_min(deadline, 2748 ossl_ackm_get_ack_deadline(ch->ackm, 2749 ossl_quic_enc_level_to_pn_space(i))); 2750 } 2751 } 2752 2753 /* 2754 * When do we need to send an ACK-eliciting packet to reset the idle 2755 * deadline timer for the peer? 2756 */ 2757 if (!ossl_time_is_infinite(ch->ping_deadline)) 2758 deadline = ossl_time_min(deadline, ch->ping_deadline); 2759 2760 /* Apply TXP wakeup deadline. */ 2761 deadline = ossl_time_min(deadline, 2762 ossl_quic_tx_packetiser_get_deadline(ch->txp)); 2763 2764 /* Is the terminating timer armed? */ 2765 if (ossl_quic_channel_is_terminating(ch)) 2766 deadline = ossl_time_min(deadline, 2767 ch->terminate_deadline); 2768 else if (!ossl_time_is_infinite(ch->idle_deadline)) 2769 deadline = ossl_time_min(deadline, 2770 ch->idle_deadline); 2771 2772 /* When does the RXKU process complete? */ 2773 if (ch->rxku_in_progress) 2774 deadline = ossl_time_min(deadline, ch->rxku_update_end_deadline); 2775 2776 return deadline; 2777 } 2778 2779 /* 2780 * QUIC Channel: Lifecycle Events 2781 * ============================== 2782 */ 2783 2784 /* 2785 * Record a state transition. This is not necessarily a change to ch->state but 2786 * also includes the handshake becoming complete or confirmed, etc. 2787 */ 2788 static void ch_record_state_transition(QUIC_CHANNEL *ch, uint32_t new_state) 2789 { 2790 uint32_t old_state = ch->state; 2791 2792 ch->state = new_state; 2793 2794 ossl_qlog_event_connectivity_connection_state_updated(ch_get_qlog(ch), 2795 old_state, 2796 new_state, 2797 ch->handshake_complete, 2798 ch->handshake_confirmed); 2799 } 2800 2801 static void free_peer_token(const unsigned char *token, 2802 size_t token_len, void *arg) 2803 { 2804 ossl_quic_free_peer_token((QUIC_TOKEN *)arg); 2805 } 2806 2807 int ossl_quic_channel_start(QUIC_CHANNEL *ch) 2808 { 2809 QUIC_TOKEN *token; 2810 2811 if (ch->is_server) 2812 /* 2813 * This is not used by the server. The server moves to active 2814 * automatically on receiving an incoming connection. 2815 */ 2816 return 0; 2817 2818 if (ch->state != QUIC_CHANNEL_STATE_IDLE) 2819 /* Calls to connect are idempotent */ 2820 return 1; 2821 2822 /* Inform QTX of peer address. */ 2823 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr)) 2824 return 0; 2825 2826 /* 2827 * Look to see if we have a token, and if so, set it on the packetiser 2828 */ 2829 if (!ch->is_server 2830 && ossl_quic_get_peer_token(ch->port->channel_ctx, 2831 &ch->cur_peer_addr, 2832 &token) 2833 && !ossl_quic_tx_packetiser_set_initial_token(ch->txp, token->token, 2834 token->token_len, 2835 free_peer_token, 2836 token)) 2837 free_peer_token(NULL, 0, token); 2838 2839 /* Plug in secrets for the Initial EL. */ 2840 if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx, 2841 ch->port->engine->propq, 2842 &ch->init_dcid, 2843 ch->is_server, 2844 ch->qrx, ch->qtx)) 2845 return 0; 2846 2847 /* 2848 * Determine the QUIC Transport Parameters and serialize the transport 2849 * parameters block. (For servers, we do this later as we must defer 2850 * generation until we have received the client's transport parameters.) 2851 */ 2852 if (!ch->is_server && !ch->got_local_transport_params 2853 && !ch_generate_transport_params(ch)) 2854 return 0; 2855 2856 /* Change state. */ 2857 ch_record_state_transition(ch, QUIC_CHANNEL_STATE_ACTIVE); 2858 ch->doing_proactive_ver_neg = 0; /* not currently supported */ 2859 2860 ossl_qlog_event_connectivity_connection_started(ch_get_qlog(ch), 2861 &ch->init_dcid); 2862 2863 /* Handshake layer: start (e.g. send CH). */ 2864 if (!ch_tick_tls(ch, /*channel_only=*/0, NULL)) 2865 return 0; 2866 2867 ossl_quic_reactor_tick(ossl_quic_port_get0_reactor(ch->port), 0); /* best effort */ 2868 return 1; 2869 } 2870 2871 static void free_token(const unsigned char *token, size_t token_len, void *arg) 2872 { 2873 OPENSSL_free((char *)token); 2874 } 2875 2876 /* Start a locally initiated connection shutdown. */ 2877 void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code, 2878 const char *app_reason) 2879 { 2880 QUIC_TERMINATE_CAUSE tcause = { 0 }; 2881 2882 if (ossl_quic_channel_is_term_any(ch)) 2883 return; 2884 2885 tcause.app = 1; 2886 tcause.error_code = app_error_code; 2887 tcause.reason = app_reason; 2888 tcause.reason_len = app_reason != NULL ? strlen(app_reason) : 0; 2889 ch_start_terminating(ch, &tcause, 0); 2890 } 2891 2892 /** 2893 * ch_restart - Restarts the QUIC channel by simulating loss of the initial 2894 * packet. This forces the packet to be regenerated with the updated protocol 2895 * version number. 2896 * 2897 * @ch: Pointer to the QUIC_CHANNEL structure. 2898 * 2899 * Returns 1 on success, 0 on failure. 2900 */ 2901 static int ch_restart(QUIC_CHANNEL *ch) 2902 { 2903 /* 2904 * Just pretend we lost our initial packet, so it gets 2905 * regenerated, with our updated protocol version number 2906 */ 2907 return ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL, 2908 /* PN= */ 0); 2909 } 2910 2911 /* Called when a server asks us to do a retry. */ 2912 static int ch_retry(QUIC_CHANNEL *ch, 2913 const unsigned char *retry_token, 2914 size_t retry_token_len, 2915 const QUIC_CONN_ID *retry_scid, 2916 int drop_later_pn) 2917 { 2918 void *buf; 2919 QUIC_PN pn = 0; 2920 2921 /* 2922 * RFC 9000 s. 17.2.5.1: "A client MUST discard a Retry packet that contains 2923 * a SCID field that is identical to the DCID field of its initial packet." 2924 */ 2925 if (ossl_quic_conn_id_eq(&ch->init_dcid, retry_scid)) 2926 return 1; 2927 2928 /* We change to using the SCID in the Retry packet as the DCID. */ 2929 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid)) 2930 return 0; 2931 2932 /* 2933 * Now we retry. We will release the Retry packet immediately, so copy 2934 * the token. 2935 */ 2936 if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL) 2937 return 0; 2938 2939 if (!ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf, 2940 retry_token_len, 2941 free_token, NULL)) { 2942 /* 2943 * This may fail if the token we receive is too big for us to ever be 2944 * able to transmit in an outgoing Initial packet. 2945 */ 2946 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INVALID_TOKEN, 0, 2947 "received oversize token"); 2948 OPENSSL_free(buf); 2949 return 0; 2950 } 2951 2952 ch->retry_scid = *retry_scid; 2953 ch->doing_retry = 1; 2954 2955 /* 2956 * If a retry isn't our first response, we need to drop packet number 2957 * one instead (i.e. the case where we did version negotiation first 2958 */ 2959 if (drop_later_pn == 1) 2960 pn = 1; 2961 2962 /* 2963 * We need to stimulate the Initial EL to generate the first CRYPTO frame 2964 * again. We can do this most cleanly by simply forcing the ACKM to consider 2965 * the first Initial packet as lost, which it effectively was as the server 2966 * hasn't processed it. This also maintains the desired behaviour with e.g. 2967 * PNs not resetting and so on. 2968 * 2969 * The PN we used initially is always zero, because QUIC does not allow 2970 * repeated retries. 2971 */ 2972 if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL, 2973 pn)) 2974 return 0; 2975 2976 /* 2977 * Plug in new secrets for the Initial EL. This is the only time we change 2978 * the secrets for an EL after we already provisioned it. 2979 */ 2980 if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx, 2981 ch->port->engine->propq, 2982 &ch->retry_scid, 2983 /*is_server=*/0, 2984 ch->qrx, ch->qtx)) 2985 return 0; 2986 2987 return 1; 2988 } 2989 2990 /* Called when an EL is to be discarded. */ 2991 static int ch_discard_el(QUIC_CHANNEL *ch, 2992 uint32_t enc_level) 2993 { 2994 if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT)) 2995 return 0; 2996 2997 if ((ch->el_discarded & (1U << enc_level)) != 0) 2998 /* Already done. */ 2999 return 1; 3000 3001 /* Best effort for all of these. */ 3002 ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level); 3003 ossl_qrx_discard_enc_level(ch->qrx, enc_level); 3004 ossl_qtx_discard_enc_level(ch->qtx, enc_level); 3005 3006 if (enc_level != QUIC_ENC_LEVEL_0RTT) { 3007 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level); 3008 3009 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space); 3010 3011 /* We should still have crypto streams at this point. */ 3012 if (!ossl_assert(ch->crypto_send[pn_space] != NULL) 3013 || !ossl_assert(ch->crypto_recv[pn_space] != NULL)) 3014 return 0; 3015 3016 /* Get rid of the crypto stream state for the EL. */ 3017 ossl_quic_sstream_free(ch->crypto_send[pn_space]); 3018 ch->crypto_send[pn_space] = NULL; 3019 3020 ossl_quic_rstream_free(ch->crypto_recv[pn_space]); 3021 ch->crypto_recv[pn_space] = NULL; 3022 } 3023 3024 ch->el_discarded |= (1U << enc_level); 3025 return 1; 3026 } 3027 3028 /* Intended to be called by the RXDP. */ 3029 int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch) 3030 { 3031 if (ch->handshake_confirmed) 3032 return 1; 3033 3034 if (!ch->handshake_complete) { 3035 /* 3036 * Does not make sense for handshake to be confirmed before it is 3037 * completed. 3038 */ 3039 ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 3040 OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE, 3041 "handshake cannot be confirmed " 3042 "before it is completed"); 3043 return 0; 3044 } 3045 3046 ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE); 3047 ch->handshake_confirmed = 1; 3048 ch_record_state_transition(ch, ch->state); 3049 ossl_ackm_on_handshake_confirmed(ch->ackm); 3050 return 1; 3051 } 3052 3053 /* 3054 * Master function used when we want to start tearing down a connection: 3055 * 3056 * - If the connection is still IDLE we can go straight to TERMINATED; 3057 * 3058 * - If we are already TERMINATED this is a no-op. 3059 * 3060 * - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE 3061 * from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING. 3062 * 3063 * - If we are TERMINATING - DRAINING, we remain here until the terminating 3064 * timer expires. 3065 * 3066 * - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING. 3067 * if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note 3068 * that we are considered to have caused a termination if we sent the first 3069 * CONNECTION_CLOSE frame, even if it is caused by a peer protocol 3070 * violation. If the peer sent the first CONNECTION_CLOSE frame, we move to 3071 * TERMINATING - DRAINING. 3072 * 3073 * We record the termination cause structure passed on the first call only. 3074 * Any successive calls have their termination cause data discarded; 3075 * once we start sending a CONNECTION_CLOSE frame, we don't change the details 3076 * in it. 3077 * 3078 * This conforms to RFC 9000 s. 10.2.1: Closing Connection State: 3079 * To minimize the state that an endpoint maintains for a closing 3080 * connection, endpoints MAY send the exact same packet in response 3081 * to any received packet. 3082 * 3083 * We don't drop any connection state (specifically packet protection keys) 3084 * even though we are permitted to. This conforms to RFC 9000 s. 10.2.1: 3085 * Closing Connection State: 3086 * An endpoint MAY retain packet protection keys for incoming 3087 * packets to allow it to read and process a CONNECTION_CLOSE frame. 3088 * 3089 * Note that we do not conform to these two from the same section: 3090 * An endpoint's selected connection ID and the QUIC version 3091 * are sufficient information to identify packets for a closing 3092 * connection; the endpoint MAY discard all other connection state. 3093 * and: 3094 * An endpoint MAY drop packet protection keys when entering the 3095 * closing state and send a packet containing a CONNECTION_CLOSE 3096 * frame in response to any UDP datagram that is received. 3097 */ 3098 static void copy_tcause(QUIC_TERMINATE_CAUSE *dst, 3099 const QUIC_TERMINATE_CAUSE *src) 3100 { 3101 dst->error_code = src->error_code; 3102 dst->frame_type = src->frame_type; 3103 dst->app = src->app; 3104 dst->remote = src->remote; 3105 3106 dst->reason = NULL; 3107 dst->reason_len = 0; 3108 3109 if (src->reason != NULL && src->reason_len > 0) { 3110 size_t l = src->reason_len; 3111 char *r; 3112 3113 if (l >= SIZE_MAX) 3114 --l; 3115 3116 /* 3117 * If this fails, dst->reason becomes NULL and we simply do not use a 3118 * reason. This ensures termination is infallible. 3119 */ 3120 dst->reason = r = OPENSSL_memdup(src->reason, l + 1); 3121 if (r == NULL) 3122 return; 3123 3124 r[l] = '\0'; 3125 dst->reason_len = l; 3126 } 3127 } 3128 3129 static void ch_start_terminating(QUIC_CHANNEL *ch, 3130 const QUIC_TERMINATE_CAUSE *tcause, 3131 int force_immediate) 3132 { 3133 /* No point sending anything if we haven't sent anything yet. */ 3134 if (!ch->have_sent_any_pkt) 3135 force_immediate = 1; 3136 3137 switch (ch->state) { 3138 default: 3139 case QUIC_CHANNEL_STATE_IDLE: 3140 copy_tcause(&ch->terminate_cause, tcause); 3141 ch_on_terminating_timeout(ch); 3142 break; 3143 3144 case QUIC_CHANNEL_STATE_ACTIVE: 3145 copy_tcause(&ch->terminate_cause, tcause); 3146 3147 ossl_qlog_event_connectivity_connection_closed(ch_get_qlog(ch), tcause); 3148 3149 if (!force_immediate) { 3150 ch_record_state_transition(ch, tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING : QUIC_CHANNEL_STATE_TERMINATING_CLOSING); 3151 /* 3152 * RFC 9000 s. 10.2 Immediate Close 3153 * These states SHOULD persist for at least three times 3154 * the current PTO interval as defined in [QUIC-RECOVERY]. 3155 */ 3156 ch->terminate_deadline 3157 = ossl_time_add(get_time(ch), 3158 ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm), 3159 3)); 3160 3161 if (!tcause->remote) { 3162 OSSL_QUIC_FRAME_CONN_CLOSE f = { 0 }; 3163 3164 /* best effort */ 3165 f.error_code = ch->terminate_cause.error_code; 3166 f.frame_type = ch->terminate_cause.frame_type; 3167 f.is_app = ch->terminate_cause.app; 3168 f.reason = (char *)ch->terminate_cause.reason; 3169 f.reason_len = ch->terminate_cause.reason_len; 3170 ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f); 3171 /* 3172 * RFC 9000 s. 10.2.2 Draining Connection State: 3173 * An endpoint that receives a CONNECTION_CLOSE frame MAY 3174 * send a single packet containing a CONNECTION_CLOSE 3175 * frame before entering the draining state, using a 3176 * NO_ERROR code if appropriate 3177 */ 3178 ch->conn_close_queued = 1; 3179 } 3180 } else { 3181 ch_on_terminating_timeout(ch); 3182 } 3183 break; 3184 3185 case QUIC_CHANNEL_STATE_TERMINATING_CLOSING: 3186 if (force_immediate) 3187 ch_on_terminating_timeout(ch); 3188 else if (tcause->remote) 3189 /* 3190 * RFC 9000 s. 10.2.2 Draining Connection State: 3191 * An endpoint MAY enter the draining state from the 3192 * closing state if it receives a CONNECTION_CLOSE frame, 3193 * which indicates that the peer is also closing or draining. 3194 */ 3195 ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATING_DRAINING); 3196 3197 break; 3198 3199 case QUIC_CHANNEL_STATE_TERMINATING_DRAINING: 3200 /* 3201 * Other than in the force-immediate case, we remain here until the 3202 * timeout expires. 3203 */ 3204 if (force_immediate) 3205 ch_on_terminating_timeout(ch); 3206 3207 break; 3208 3209 case QUIC_CHANNEL_STATE_TERMINATED: 3210 /* No-op. */ 3211 break; 3212 } 3213 } 3214 3215 /* For RXDP use. */ 3216 void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch, 3217 OSSL_QUIC_FRAME_CONN_CLOSE *f) 3218 { 3219 QUIC_TERMINATE_CAUSE tcause = { 0 }; 3220 3221 if (!ossl_quic_channel_is_active(ch)) 3222 return; 3223 3224 tcause.remote = 1; 3225 tcause.app = f->is_app; 3226 tcause.error_code = f->error_code; 3227 tcause.frame_type = f->frame_type; 3228 tcause.reason = f->reason; 3229 tcause.reason_len = f->reason_len; 3230 ch_start_terminating(ch, &tcause, 0); 3231 } 3232 3233 static void free_frame_data(unsigned char *buf, size_t buf_len, void *arg) 3234 { 3235 OPENSSL_free(buf); 3236 } 3237 3238 static int ch_enqueue_retire_conn_id(QUIC_CHANNEL *ch, uint64_t seq_num) 3239 { 3240 BUF_MEM *buf_mem = NULL; 3241 WPACKET wpkt; 3242 size_t l; 3243 3244 ossl_quic_srtm_remove(ch->srtm, ch, seq_num); 3245 3246 if ((buf_mem = BUF_MEM_new()) == NULL) 3247 goto err; 3248 3249 if (!WPACKET_init(&wpkt, buf_mem)) 3250 goto err; 3251 3252 if (!ossl_quic_wire_encode_frame_retire_conn_id(&wpkt, seq_num)) { 3253 WPACKET_cleanup(&wpkt); 3254 goto err; 3255 } 3256 3257 WPACKET_finish(&wpkt); 3258 if (!WPACKET_get_total_written(&wpkt, &l)) 3259 goto err; 3260 3261 if (ossl_quic_cfq_add_frame(ch->cfq, 1, QUIC_PN_SPACE_APP, 3262 OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID, 0, 3263 (unsigned char *)buf_mem->data, l, 3264 free_frame_data, NULL) 3265 == NULL) 3266 goto err; 3267 3268 buf_mem->data = NULL; 3269 BUF_MEM_free(buf_mem); 3270 return 1; 3271 3272 err: 3273 ossl_quic_channel_raise_protocol_error(ch, 3274 OSSL_QUIC_ERR_INTERNAL_ERROR, 3275 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, 3276 "internal error enqueueing retire conn id"); 3277 BUF_MEM_free(buf_mem); 3278 return 0; 3279 } 3280 3281 void ossl_quic_channel_on_new_conn_id(QUIC_CHANNEL *ch, 3282 OSSL_QUIC_FRAME_NEW_CONN_ID *f) 3283 { 3284 uint64_t new_remote_seq_num = ch->cur_remote_seq_num; 3285 uint64_t new_retire_prior_to = ch->cur_retire_prior_to; 3286 3287 if (!ossl_quic_channel_is_active(ch)) 3288 return; 3289 3290 /* We allow only two active connection ids; first check some constraints */ 3291 if (ch->cur_remote_dcid.id_len == 0) { 3292 /* Changing from 0 length connection id is disallowed */ 3293 ossl_quic_channel_raise_protocol_error(ch, 3294 OSSL_QUIC_ERR_PROTOCOL_VIOLATION, 3295 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, 3296 "zero length connection id in use"); 3297 3298 return; 3299 } 3300 3301 if (f->seq_num > new_remote_seq_num) 3302 new_remote_seq_num = f->seq_num; 3303 if (f->retire_prior_to > new_retire_prior_to) 3304 new_retire_prior_to = f->retire_prior_to; 3305 3306 /* 3307 * RFC 9000-5.1.1: An endpoint MUST NOT provide more connection IDs 3308 * than the peer's limit. 3309 * 3310 * After processing a NEW_CONNECTION_ID frame and adding and retiring 3311 * active connection IDs, if the number of active connection IDs exceeds 3312 * the value advertised in its active_connection_id_limit transport 3313 * parameter, an endpoint MUST close the connection with an error of 3314 * type CONNECTION_ID_LIMIT_ERROR. 3315 */ 3316 if (new_remote_seq_num - new_retire_prior_to > 1) { 3317 ossl_quic_channel_raise_protocol_error(ch, 3318 OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR, 3319 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, 3320 "active_connection_id limit violated"); 3321 return; 3322 } 3323 3324 /* 3325 * RFC 9000-5.1.1: An endpoint MAY send connection IDs that temporarily 3326 * exceed a peer's limit if the NEW_CONNECTION_ID frame also requires 3327 * the retirement of any excess, by including a sufficiently large 3328 * value in the Retire Prior To field. 3329 * 3330 * RFC 9000-5.1.2: An endpoint SHOULD allow for sending and tracking 3331 * a number of RETIRE_CONNECTION_ID frames of at least twice the value 3332 * of the active_connection_id_limit transport parameter. An endpoint 3333 * MUST NOT forget a connection ID without retiring it, though it MAY 3334 * choose to treat having connection IDs in need of retirement that 3335 * exceed this limit as a connection error of type CONNECTION_ID_LIMIT_ERROR. 3336 * 3337 * We are a little bit more liberal than the minimum mandated. 3338 */ 3339 if (new_retire_prior_to - ch->cur_retire_prior_to > 10) { 3340 ossl_quic_channel_raise_protocol_error(ch, 3341 OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR, 3342 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, 3343 "retiring connection id limit violated"); 3344 3345 return; 3346 } 3347 3348 if (new_remote_seq_num > ch->cur_remote_seq_num) { 3349 /* Add new stateless reset token */ 3350 if (!ossl_quic_srtm_add(ch->srtm, ch, new_remote_seq_num, 3351 &f->stateless_reset)) { 3352 ossl_quic_channel_raise_protocol_error( 3353 ch, OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR, 3354 OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID, 3355 "unable to store stateless reset token"); 3356 3357 return; 3358 } 3359 ch->cur_remote_seq_num = new_remote_seq_num; 3360 ch->cur_remote_dcid = f->conn_id; 3361 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid); 3362 } 3363 3364 /* 3365 * RFC 9000-5.1.2: Upon receipt of an increased Retire Prior To 3366 * field, the peer MUST stop using the corresponding connection IDs 3367 * and retire them with RETIRE_CONNECTION_ID frames before adding the 3368 * newly provided connection ID to the set of active connection IDs. 3369 */ 3370 3371 /* 3372 * Note: RFC 9000 s. 19.15 says: 3373 * "An endpoint that receives a NEW_CONNECTION_ID frame with a sequence 3374 * number smaller than the Retire Prior To field of a previously received 3375 * NEW_CONNECTION_ID frame MUST send a corresponding 3376 * RETIRE_CONNECTION_ID frame that retires the newly received connection 3377 * ID, unless it has already done so for that sequence number." 3378 * 3379 * Since we currently always queue RETIRE_CONN_ID frames based on the Retire 3380 * Prior To field of a NEW_CONNECTION_ID frame immediately upon receiving 3381 * that NEW_CONNECTION_ID frame, by definition this will always be met. 3382 * This may change in future when we change our CID handling. 3383 */ 3384 while (new_retire_prior_to > ch->cur_retire_prior_to) { 3385 if (!ch_enqueue_retire_conn_id(ch, ch->cur_retire_prior_to)) 3386 break; 3387 ++ch->cur_retire_prior_to; 3388 } 3389 } 3390 3391 static void ch_save_err_state(QUIC_CHANNEL *ch) 3392 { 3393 if (ch->err_state == NULL) 3394 ch->err_state = OSSL_ERR_STATE_new(); 3395 3396 if (ch->err_state == NULL) 3397 return; 3398 3399 OSSL_ERR_STATE_save(ch->err_state); 3400 } 3401 3402 void ossl_quic_channel_inject(QUIC_CHANNEL *ch, QUIC_URXE *e) 3403 { 3404 ossl_qrx_inject_urxe(ch->qrx, e); 3405 } 3406 3407 void ossl_quic_channel_inject_pkt(QUIC_CHANNEL *ch, OSSL_QRX_PKT *qpkt) 3408 { 3409 ossl_qrx_inject_pkt(ch->qrx, qpkt); 3410 } 3411 3412 void ossl_quic_channel_on_stateless_reset(QUIC_CHANNEL *ch) 3413 { 3414 QUIC_TERMINATE_CAUSE tcause = { 0 }; 3415 3416 tcause.error_code = OSSL_QUIC_ERR_NO_ERROR; 3417 tcause.remote = 1; 3418 ch_start_terminating(ch, &tcause, 0); 3419 } 3420 3421 void ossl_quic_channel_raise_net_error(QUIC_CHANNEL *ch) 3422 { 3423 QUIC_TERMINATE_CAUSE tcause = { 0 }; 3424 3425 if (ch->net_error) 3426 return; 3427 3428 ch->net_error = 1; 3429 3430 tcause.error_code = OSSL_QUIC_ERR_INTERNAL_ERROR; 3431 tcause.reason = "network BIO I/O error"; 3432 tcause.reason_len = strlen(tcause.reason); 3433 3434 /* 3435 * Skip Terminating state and go directly to Terminated, no point trying to 3436 * send CONNECTION_CLOSE if we cannot communicate. 3437 */ 3438 ch_start_terminating(ch, &tcause, 1); 3439 } 3440 3441 int ossl_quic_channel_net_error(QUIC_CHANNEL *ch) 3442 { 3443 return ch->net_error; 3444 } 3445 3446 void ossl_quic_channel_restore_err_state(QUIC_CHANNEL *ch) 3447 { 3448 if (ch == NULL) 3449 return; 3450 3451 if (!ossl_quic_port_is_running(ch->port)) 3452 ossl_quic_port_restore_err_state(ch->port); 3453 else 3454 OSSL_ERR_STATE_restore(ch->err_state); 3455 } 3456 3457 void ossl_quic_channel_raise_protocol_error_loc(QUIC_CHANNEL *ch, 3458 uint64_t error_code, 3459 uint64_t frame_type, 3460 const char *reason, 3461 ERR_STATE *err_state, 3462 const char *src_file, 3463 int src_line, 3464 const char *src_func) 3465 { 3466 QUIC_TERMINATE_CAUSE tcause = { 0 }; 3467 int err_reason = error_code == OSSL_QUIC_ERR_INTERNAL_ERROR 3468 ? ERR_R_INTERNAL_ERROR 3469 : SSL_R_QUIC_PROTOCOL_ERROR; 3470 const char *err_str = ossl_quic_err_to_string(error_code); 3471 const char *err_str_pfx = " (", *err_str_sfx = ")"; 3472 const char *ft_str = NULL; 3473 const char *ft_str_pfx = " (", *ft_str_sfx = ")"; 3474 3475 if (ch->protocol_error) 3476 /* Only the first call to this function matters. */ 3477 return; 3478 3479 if (err_str == NULL) { 3480 err_str = ""; 3481 err_str_pfx = ""; 3482 err_str_sfx = ""; 3483 } 3484 3485 /* 3486 * If we were provided an underlying error state, restore it and then append 3487 * our ERR on top as a "cover letter" error. 3488 */ 3489 if (err_state != NULL) 3490 OSSL_ERR_STATE_restore(err_state); 3491 3492 if (frame_type != 0) { 3493 ft_str = ossl_quic_frame_type_to_string(frame_type); 3494 if (ft_str == NULL) { 3495 ft_str = ""; 3496 ft_str_pfx = ""; 3497 ft_str_sfx = ""; 3498 } 3499 3500 ERR_raise_data(ERR_LIB_SSL, err_reason, 3501 "QUIC error code: 0x%llx%s%s%s " 3502 "(triggered by frame type: 0x%llx%s%s%s), reason: \"%s\"", 3503 (unsigned long long)error_code, 3504 err_str_pfx, err_str, err_str_sfx, 3505 (unsigned long long)frame_type, 3506 ft_str_pfx, ft_str, ft_str_sfx, 3507 reason); 3508 } else { 3509 ERR_raise_data(ERR_LIB_SSL, err_reason, 3510 "QUIC error code: 0x%llx%s%s%s, reason: \"%s\"", 3511 (unsigned long long)error_code, 3512 err_str_pfx, err_str, err_str_sfx, 3513 reason); 3514 } 3515 3516 if (src_file != NULL) 3517 ERR_set_debug(src_file, src_line, src_func); 3518 3519 ch_save_err_state(ch); 3520 3521 tcause.error_code = error_code; 3522 tcause.frame_type = frame_type; 3523 tcause.reason = reason; 3524 tcause.reason_len = strlen(reason); 3525 3526 ch->protocol_error = 1; 3527 ch_start_terminating(ch, &tcause, 0); 3528 } 3529 3530 /* 3531 * Called once the terminating timer expires, meaning we move from TERMINATING 3532 * to TERMINATED. 3533 */ 3534 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch) 3535 { 3536 ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATED); 3537 } 3538 3539 /* 3540 * Determines the effective idle timeout duration. This is based on the idle 3541 * timeout values that we and our peer signalled in transport parameters 3542 * but have some limits applied. 3543 */ 3544 static OSSL_TIME ch_get_effective_idle_timeout_duration(QUIC_CHANNEL *ch) 3545 { 3546 OSSL_TIME pto; 3547 3548 if (ch->max_idle_timeout == 0) 3549 return ossl_time_infinite(); 3550 3551 /* 3552 * RFC 9000 s. 10.1: Idle Timeout 3553 * To avoid excessively small idle timeout periods, endpoints 3554 * MUST increase the idle timeout period to be at least three 3555 * times the current Probe Timeout (PTO). This allows for 3556 * multiple PTOs to expire, and therefore multiple probes to 3557 * be sent and lost, prior to idle timeout. 3558 */ 3559 pto = ossl_ackm_get_pto_duration(ch->ackm); 3560 return ossl_time_max(ossl_ms2time(ch->max_idle_timeout), 3561 ossl_time_multiply(pto, 3)); 3562 } 3563 3564 /* 3565 * Updates our idle deadline. Called when an event happens which should bump the 3566 * idle timeout. 3567 */ 3568 static void ch_update_idle(QUIC_CHANNEL *ch) 3569 { 3570 ch->idle_deadline = ossl_time_add(get_time(ch), 3571 ch_get_effective_idle_timeout_duration(ch)); 3572 } 3573 3574 /* 3575 * Updates our ping deadline, which determines when we next generate a ping if 3576 * we don't have any other ACK-eliciting frames to send. 3577 */ 3578 static void ch_update_ping_deadline(QUIC_CHANNEL *ch) 3579 { 3580 OSSL_TIME max_span, idle_duration; 3581 3582 idle_duration = ch_get_effective_idle_timeout_duration(ch); 3583 if (ossl_time_is_infinite(idle_duration)) { 3584 ch->ping_deadline = ossl_time_infinite(); 3585 return; 3586 } 3587 3588 /* 3589 * Maximum amount of time without traffic before we send a PING to keep 3590 * the connection open. Usually we use max_idle_timeout/2, but ensure 3591 * the period never exceeds the assumed NAT interval to ensure NAT 3592 * devices don't have their state time out (RFC 9000 s. 10.1.2). 3593 */ 3594 max_span = ossl_time_divide(idle_duration, 2); 3595 max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL); 3596 ch->ping_deadline = ossl_time_add(get_time(ch), max_span); 3597 } 3598 3599 /* Called when the idle timeout expires. */ 3600 static void ch_on_idle_timeout(QUIC_CHANNEL *ch) 3601 { 3602 /* 3603 * Idle timeout does not have an error code associated with it because a 3604 * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach 3605 * TERMINATED anyway. 3606 */ 3607 ch->terminate_cause.app = 0; 3608 ch->terminate_cause.error_code = OSSL_QUIC_LOCAL_ERR_IDLE_TIMEOUT; 3609 ch->terminate_cause.frame_type = 0; 3610 3611 ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATED); 3612 } 3613 3614 /** 3615 * @brief Common handler for initializing a new QUIC connection. 3616 * 3617 * This function configures a QUIC channel (`QUIC_CHANNEL *ch`) for a new 3618 * connection by setting the peer address, connection IDs, and necessary 3619 * callbacks. It establishes initial secrets, sets up logging, and performs 3620 * required transitions for the channel state. 3621 * 3622 * @param ch Pointer to the QUIC channel being initialized. 3623 * @param peer Address of the peer to which the channel connects. 3624 * @param peer_scid Peer-specified source connection ID. 3625 * @param peer_dcid Peer-specified destination connection ID. 3626 * @param peer_odcid Peer-specified original destination connection ID 3627 * may be NULL if retry frame not sent to client 3628 * @return 1 on success, 0 on failure to set required elements. 3629 */ 3630 static int ch_on_new_conn_common(QUIC_CHANNEL *ch, const BIO_ADDR *peer, 3631 const QUIC_CONN_ID *peer_dcid, 3632 const QUIC_CONN_ID *peer_odcid) 3633 { 3634 /* Note our newly learnt peer address and CIDs. */ 3635 if (!BIO_ADDR_copy(&ch->cur_peer_addr, peer)) 3636 return 0; 3637 3638 ch->init_dcid = *peer_dcid; 3639 ch->odcid.id_len = 0; 3640 3641 if (peer_odcid != NULL) 3642 ch->odcid = *peer_odcid; 3643 3644 /* Inform QTX of peer address. */ 3645 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr)) 3646 return 0; 3647 3648 /* Inform TXP of desired CIDs. */ 3649 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid)) 3650 return 0; 3651 3652 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid)) 3653 return 0; 3654 3655 /* Setup QLOG, which did not happen earlier due to lacking an Initial ODCID. */ 3656 ossl_qtx_set_qlog_cb(ch->qtx, ch_get_qlog_cb, ch); 3657 ossl_quic_tx_packetiser_set_qlog_cb(ch->txp, ch_get_qlog_cb, ch); 3658 3659 /* 3660 * Plug in secrets for the Initial EL. secrets for QRX were created in 3661 * port_default_packet_handler() already. 3662 */ 3663 if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx, 3664 ch->port->engine->propq, 3665 &ch->init_dcid, 3666 /*is_server=*/1, 3667 NULL, ch->qtx)) 3668 return 0; 3669 3670 /* Register the peer ODCID in the LCIDM. */ 3671 if (!ossl_quic_lcidm_enrol_odcid(ch->lcidm, ch, peer_odcid == NULL ? &ch->init_dcid : peer_odcid)) 3672 return 0; 3673 3674 /* Change state. */ 3675 ch_record_state_transition(ch, QUIC_CHANNEL_STATE_ACTIVE); 3676 ch->doing_proactive_ver_neg = 0; /* not currently supported */ 3677 return 1; 3678 } 3679 3680 /* Called when we, as a server, get a new incoming connection. */ 3681 int ossl_quic_channel_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer, 3682 const QUIC_CONN_ID *peer_dcid) 3683 { 3684 if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server)) 3685 return 0; 3686 3687 /* Generate an Initial LCID we will use for the connection. */ 3688 if (!ossl_quic_lcidm_generate_initial(ch->lcidm, ch, &ch->cur_local_cid)) 3689 return 0; 3690 3691 return ch_on_new_conn_common(ch, peer, peer_dcid, NULL); 3692 } 3693 3694 /** 3695 * Binds a QUIC channel to a specific peer's address and connection IDs. 3696 * 3697 * This function is used to establish a binding between a QUIC channel and a 3698 * peer's address and connection IDs. The binding is performed only if the 3699 * channel is idle and is on the server side. The peer's destination connection 3700 * ID (`peer_dcid`) is mandatory, and the channel's current local connection ID 3701 * is set to this value. 3702 * 3703 * @param ch Pointer to the QUIC_CHANNEL structure representing the 3704 * channel to be bound. 3705 * @param peer Pointer to a BIO_ADDR structure representing the peer's 3706 * address. 3707 * @param peer_scid Pointer to the peer's source connection ID (QUIC_CONN_ID). 3708 * @param peer_dcid Pointer to the peer's destination connection ID 3709 * (QUIC_CONN_ID). This must not be NULL. 3710 * @param peer_odcid Pointer to the original destination connection ID 3711 * (QUIC_CONN_ID) chosen by the peer in its first initial 3712 * packet received without a token. 3713 * 3714 * @return 1 on success, or 0 on failure if the conditions for binding are not 3715 * met (e.g., channel is not idle or not a server, or binding fails). 3716 */ 3717 int ossl_quic_bind_channel(QUIC_CHANNEL *ch, const BIO_ADDR *peer, 3718 const QUIC_CONN_ID *peer_dcid, 3719 const QUIC_CONN_ID *peer_odcid) 3720 { 3721 if (peer_dcid == NULL) 3722 return 0; 3723 3724 if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server)) 3725 return 0; 3726 3727 ch->cur_local_cid = *peer_dcid; 3728 if (!ossl_quic_lcidm_bind_channel(ch->lcidm, ch, peer_dcid)) 3729 return 0; 3730 3731 /* 3732 * peer_odcid <=> is initial dst conn id chosen by peer in its 3733 * first initial packet we received without token. 3734 */ 3735 return ch_on_new_conn_common(ch, peer, peer_dcid, peer_odcid); 3736 } 3737 3738 SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch) 3739 { 3740 return ch->tls; 3741 } 3742 3743 static int ch_init_new_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs, 3744 int can_send, int can_recv) 3745 { 3746 uint64_t rxfc_wnd; 3747 int server_init = ossl_quic_stream_is_server_init(qs); 3748 int local_init = (ch->is_server == server_init); 3749 int is_uni = !ossl_quic_stream_is_bidi(qs); 3750 3751 if (can_send) 3752 if ((qs->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL) 3753 goto err; 3754 3755 if (can_recv) 3756 if ((qs->rstream = ossl_quic_rstream_new(NULL, NULL, 0)) == NULL) 3757 goto err; 3758 3759 /* TXFC */ 3760 if (!ossl_quic_txfc_init(&qs->txfc, &ch->conn_txfc)) 3761 goto err; 3762 3763 if (ch->got_remote_transport_params) { 3764 /* 3765 * If we already got peer TPs we need to apply the initial CWM credit 3766 * now. If we didn't already get peer TPs this will be done 3767 * automatically for all extant streams when we do. 3768 */ 3769 if (can_send) { 3770 uint64_t cwm; 3771 3772 if (is_uni) 3773 cwm = ch->rx_init_max_stream_data_uni; 3774 else if (local_init) 3775 cwm = ch->rx_init_max_stream_data_bidi_local; 3776 else 3777 cwm = ch->rx_init_max_stream_data_bidi_remote; 3778 3779 ossl_quic_txfc_bump_cwm(&qs->txfc, cwm); 3780 } 3781 } 3782 3783 /* RXFC */ 3784 if (!can_recv) 3785 rxfc_wnd = 0; 3786 else if (is_uni) 3787 rxfc_wnd = ch->tx_init_max_stream_data_uni; 3788 else if (local_init) 3789 rxfc_wnd = ch->tx_init_max_stream_data_bidi_local; 3790 else 3791 rxfc_wnd = ch->tx_init_max_stream_data_bidi_remote; 3792 3793 if (!ossl_quic_rxfc_init(&qs->rxfc, &ch->conn_rxfc, 3794 rxfc_wnd, 3795 DEFAULT_STREAM_RXFC_MAX_WND_MUL * rxfc_wnd, 3796 get_time, ch)) 3797 goto err; 3798 3799 return 1; 3800 3801 err: 3802 ossl_quic_sstream_free(qs->sstream); 3803 qs->sstream = NULL; 3804 ossl_quic_rstream_free(qs->rstream); 3805 qs->rstream = NULL; 3806 return 0; 3807 } 3808 3809 static uint64_t *ch_get_local_stream_next_ordinal_ptr(QUIC_CHANNEL *ch, 3810 int is_uni) 3811 { 3812 return is_uni ? &ch->next_local_stream_ordinal_uni 3813 : &ch->next_local_stream_ordinal_bidi; 3814 } 3815 3816 static const uint64_t *ch_get_local_stream_max_ptr(const QUIC_CHANNEL *ch, 3817 int is_uni) 3818 { 3819 return is_uni ? &ch->max_local_streams_uni 3820 : &ch->max_local_streams_bidi; 3821 } 3822 3823 static const QUIC_RXFC *ch_get_remote_stream_count_rxfc(const QUIC_CHANNEL *ch, 3824 int is_uni) 3825 { 3826 return is_uni ? &ch->max_streams_uni_rxfc 3827 : &ch->max_streams_bidi_rxfc; 3828 } 3829 3830 int ossl_quic_channel_is_new_local_stream_admissible(QUIC_CHANNEL *ch, 3831 int is_uni) 3832 { 3833 const uint64_t *p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni); 3834 3835 return ossl_quic_stream_map_is_local_allowed_by_stream_limit(&ch->qsm, 3836 *p_next_ordinal, 3837 is_uni); 3838 } 3839 3840 uint64_t ossl_quic_channel_get_local_stream_count_avail(const QUIC_CHANNEL *ch, 3841 int is_uni) 3842 { 3843 const uint64_t *p_next_ordinal, *p_max; 3844 3845 p_next_ordinal = ch_get_local_stream_next_ordinal_ptr((QUIC_CHANNEL *)ch, 3846 is_uni); 3847 p_max = ch_get_local_stream_max_ptr(ch, is_uni); 3848 3849 return *p_max - *p_next_ordinal; 3850 } 3851 3852 uint64_t ossl_quic_channel_get_remote_stream_count_avail(const QUIC_CHANNEL *ch, 3853 int is_uni) 3854 { 3855 return ossl_quic_rxfc_get_credit(ch_get_remote_stream_count_rxfc(ch, is_uni)); 3856 } 3857 3858 QUIC_STREAM *ossl_quic_channel_new_stream_local(QUIC_CHANNEL *ch, int is_uni) 3859 { 3860 QUIC_STREAM *qs; 3861 int type; 3862 uint64_t stream_id; 3863 uint64_t *p_next_ordinal; 3864 3865 type = ch->is_server ? QUIC_STREAM_INITIATOR_SERVER 3866 : QUIC_STREAM_INITIATOR_CLIENT; 3867 3868 p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni); 3869 3870 if (is_uni) 3871 type |= QUIC_STREAM_DIR_UNI; 3872 else 3873 type |= QUIC_STREAM_DIR_BIDI; 3874 3875 if (*p_next_ordinal >= ((uint64_t)1) << 62) 3876 return NULL; 3877 3878 stream_id = ((*p_next_ordinal) << 2) | type; 3879 3880 if ((qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id, type)) == NULL) 3881 return NULL; 3882 3883 /* Locally-initiated stream, so we always want a send buffer. */ 3884 if (!ch_init_new_stream(ch, qs, /*can_send=*/1, /*can_recv=*/!is_uni)) 3885 goto err; 3886 3887 ++*p_next_ordinal; 3888 return qs; 3889 3890 err: 3891 ossl_quic_stream_map_release(&ch->qsm, qs); 3892 return NULL; 3893 } 3894 3895 QUIC_STREAM *ossl_quic_channel_new_stream_remote(QUIC_CHANNEL *ch, 3896 uint64_t stream_id) 3897 { 3898 uint64_t peer_role; 3899 int is_uni; 3900 QUIC_STREAM *qs; 3901 3902 peer_role = ch->is_server 3903 ? QUIC_STREAM_INITIATOR_CLIENT 3904 : QUIC_STREAM_INITIATOR_SERVER; 3905 3906 if ((stream_id & QUIC_STREAM_INITIATOR_MASK) != peer_role) 3907 return NULL; 3908 3909 is_uni = ((stream_id & QUIC_STREAM_DIR_MASK) == QUIC_STREAM_DIR_UNI); 3910 3911 qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id, 3912 stream_id & (QUIC_STREAM_INITIATOR_MASK | QUIC_STREAM_DIR_MASK)); 3913 if (qs == NULL) 3914 return NULL; 3915 3916 if (!ch_init_new_stream(ch, qs, /*can_send=*/!is_uni, /*can_recv=*/1)) 3917 goto err; 3918 3919 if (ch->incoming_stream_auto_reject) 3920 ossl_quic_channel_reject_stream(ch, qs); 3921 else 3922 ossl_quic_stream_map_push_accept_queue(&ch->qsm, qs); 3923 3924 return qs; 3925 3926 err: 3927 ossl_quic_stream_map_release(&ch->qsm, qs); 3928 return NULL; 3929 } 3930 3931 void ossl_quic_channel_set_incoming_stream_auto_reject(QUIC_CHANNEL *ch, 3932 int enable, 3933 uint64_t aec) 3934 { 3935 ch->incoming_stream_auto_reject = (enable != 0); 3936 ch->incoming_stream_auto_reject_aec = aec; 3937 } 3938 3939 void ossl_quic_channel_reject_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs) 3940 { 3941 ossl_quic_stream_map_stop_sending_recv_part(&ch->qsm, qs, 3942 ch->incoming_stream_auto_reject_aec); 3943 3944 ossl_quic_stream_map_reset_stream_send_part(&ch->qsm, qs, 3945 ch->incoming_stream_auto_reject_aec); 3946 qs->deleted = 1; 3947 3948 ossl_quic_stream_map_update_state(&ch->qsm, qs); 3949 } 3950 3951 /* Replace local connection ID in TXP and DEMUX for testing purposes. */ 3952 int ossl_quic_channel_replace_local_cid(QUIC_CHANNEL *ch, 3953 const QUIC_CONN_ID *conn_id) 3954 { 3955 /* Remove the current LCID from the LCIDM. */ 3956 if (!ossl_quic_lcidm_debug_remove(ch->lcidm, &ch->cur_local_cid)) 3957 return 0; 3958 ch->cur_local_cid = *conn_id; 3959 /* Set in the TXP, used only for long header packets. */ 3960 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid)) 3961 return 0; 3962 /* Add the new LCID to the LCIDM. */ 3963 if (!ossl_quic_lcidm_debug_add(ch->lcidm, ch, &ch->cur_local_cid, 3964 100)) 3965 return 0; 3966 return 1; 3967 } 3968 3969 void ossl_quic_channel_set_msg_callback(QUIC_CHANNEL *ch, 3970 ossl_msg_cb msg_callback, 3971 SSL *msg_callback_ssl) 3972 { 3973 ch->msg_callback = msg_callback; 3974 ch->msg_callback_ssl = msg_callback_ssl; 3975 ossl_qtx_set_msg_callback(ch->qtx, msg_callback, msg_callback_ssl); 3976 ossl_quic_tx_packetiser_set_msg_callback(ch->txp, msg_callback, 3977 msg_callback_ssl); 3978 /* 3979 * postpone msg callback setting for tserver until port calls 3980 * port_bind_channel(). 3981 */ 3982 if (ch->is_tserver_ch == 0) 3983 ossl_qrx_set_msg_callback(ch->qrx, msg_callback, msg_callback_ssl); 3984 } 3985 3986 void ossl_quic_channel_set_msg_callback_arg(QUIC_CHANNEL *ch, 3987 void *msg_callback_arg) 3988 { 3989 ch->msg_callback_arg = msg_callback_arg; 3990 ossl_qtx_set_msg_callback_arg(ch->qtx, msg_callback_arg); 3991 ossl_quic_tx_packetiser_set_msg_callback_arg(ch->txp, msg_callback_arg); 3992 3993 /* 3994 * postpone msg callback setting for tserver until port calls 3995 * port_bind_channel(). 3996 */ 3997 if (ch->is_tserver_ch == 0) 3998 ossl_qrx_set_msg_callback_arg(ch->qrx, msg_callback_arg); 3999 } 4000 4001 void ossl_quic_channel_set_txku_threshold_override(QUIC_CHANNEL *ch, 4002 uint64_t tx_pkt_threshold) 4003 { 4004 ch->txku_threshold_override = tx_pkt_threshold; 4005 } 4006 4007 uint64_t ossl_quic_channel_get_tx_key_epoch(QUIC_CHANNEL *ch) 4008 { 4009 return ossl_qtx_get_key_epoch(ch->qtx); 4010 } 4011 4012 uint64_t ossl_quic_channel_get_rx_key_epoch(QUIC_CHANNEL *ch) 4013 { 4014 return ossl_qrx_get_key_epoch(ch->qrx); 4015 } 4016 4017 int ossl_quic_channel_trigger_txku(QUIC_CHANNEL *ch) 4018 { 4019 if (!txku_allowed(ch)) 4020 return 0; 4021 4022 ch->ku_locally_initiated = 1; 4023 ch_trigger_txku(ch); 4024 return 1; 4025 } 4026 4027 int ossl_quic_channel_ping(QUIC_CHANNEL *ch) 4028 { 4029 int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level); 4030 4031 ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space); 4032 4033 return 1; 4034 } 4035 4036 uint16_t ossl_quic_channel_get_diag_num_rx_ack(QUIC_CHANNEL *ch) 4037 { 4038 return ch->diag_num_rx_ack; 4039 } 4040 4041 void ossl_quic_channel_get_diag_local_cid(QUIC_CHANNEL *ch, QUIC_CONN_ID *cid) 4042 { 4043 *cid = ch->cur_local_cid; 4044 } 4045 4046 int ossl_quic_channel_have_generated_transport_params(const QUIC_CHANNEL *ch) 4047 { 4048 return ch->got_local_transport_params; 4049 } 4050 4051 void ossl_quic_channel_set_max_idle_timeout_request(QUIC_CHANNEL *ch, uint64_t ms) 4052 { 4053 ch->max_idle_timeout_local_req = ms; 4054 } 4055 uint64_t ossl_quic_channel_get_max_idle_timeout_request(const QUIC_CHANNEL *ch) 4056 { 4057 return ch->max_idle_timeout_local_req; 4058 } 4059 4060 uint64_t ossl_quic_channel_get_max_idle_timeout_peer_request(const QUIC_CHANNEL *ch) 4061 { 4062 return ch->max_idle_timeout_remote_req; 4063 } 4064 4065 uint64_t ossl_quic_channel_get_max_idle_timeout_actual(const QUIC_CHANNEL *ch) 4066 { 4067 return ch->max_idle_timeout; 4068 } 4069 4070 uint64_t ossl_quic_channel_get_path_challenge_count(const QUIC_CHANNEL *ch) 4071 { 4072 return ch->path_challenge_rx; 4073 } 4074 4075 uint64_t ossl_quic_channel_get_path_response_count(const QUIC_CHANNEL *ch) 4076 { 4077 return ch->path_response_tx; 4078 } 4079