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