Path: blob/main/crypto/openssl/ssl/quic/quic_port.c
48261 views
/*1* Copyright 2023-2025 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89#include "internal/quic_port.h"10#include "internal/quic_channel.h"11#include "internal/quic_lcidm.h"12#include "internal/quic_srtm.h"13#include "internal/quic_txp.h"14#include "internal/ssl_unwrap.h"15#include "quic_port_local.h"16#include "quic_channel_local.h"17#include "quic_engine_local.h"18#include "quic_local.h"19#include "../ssl_local.h"20#include <openssl/rand.h>2122/*23* QUIC Port Structure24* ===================25*/26#define INIT_DCID_LEN 82728static int port_init(QUIC_PORT *port);29static void port_cleanup(QUIC_PORT *port);30static OSSL_TIME get_time(void *arg);31static void port_default_packet_handler(QUIC_URXE *e, void *arg,32const QUIC_CONN_ID *dcid);33static void port_rx_pre(QUIC_PORT *port);3435/**36* @struct validation_token37* @brief Represents a validation token for secure connection handling.38*39* This struct is used to store information related to a validation token.40*41* @var validation_token::is_retry42* True iff this validation token is for a token sent in a RETRY packet.43* Otherwise, this token is from a NEW_TOKEN_packet. Iff this value is true,44* then ODCID and RSCID are set.45*46* @var validation_token::timestamp47* Time that the validation token was minted.48*49* @var validation_token::odcid50* An original connection ID (`QUIC_CONN_ID`) used to identify the QUIC51* connection. This ID helps associate the token with a specific connection.52* This will only be valid for validation tokens from RETRY packets.53*54* @var validation_token::rscid55* DCID that the client will use as the DCID of the subsequent initial packet56* i.e the "new" DCID.57* This will only be valid for validation tokens from RETRY packets.58*59* @var validation_token::remote_addr_len60* Length of the following character array.61*62* @var validation_token::remote_addr63* A character array holding the raw address of the client requesting the64* connection.65*/66typedef struct validation_token {67OSSL_TIME timestamp;68QUIC_CONN_ID odcid;69QUIC_CONN_ID rscid;70size_t remote_addr_len;71unsigned char *remote_addr;72unsigned char is_retry;73} QUIC_VALIDATION_TOKEN;7475/*76* Maximum length of a marshalled validation token.77*78* - timestamp is 8 bytes79* - odcid and rscid are maximally 42 bytes in total80* - remote_addr_len is a size_t (8 bytes)81* - remote_addr is in the worst case 110 bytes (in the case of using a82* maximally sized AF_UNIX socket)83* - is_retry is a single byte84*/85#define MARSHALLED_TOKEN_MAX_LEN 1698687/*88* Maximum length of an encrypted marshalled validation token.89*90* This will include the size of the marshalled validation token plus a 16 byte91* tag and a 12 byte IV, so in total 197 bytes.92*/93#define ENCRYPTED_TOKEN_MAX_LEN (MARSHALLED_TOKEN_MAX_LEN + 16 + 12)9495DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL);96DEFINE_LIST_OF_IMPL(incoming_ch, QUIC_CHANNEL);97DEFINE_LIST_OF_IMPL(port, QUIC_PORT);9899QUIC_PORT *ossl_quic_port_new(const QUIC_PORT_ARGS *args)100{101QUIC_PORT *port;102103if ((port = OPENSSL_zalloc(sizeof(QUIC_PORT))) == NULL)104return NULL;105106port->engine = args->engine;107port->channel_ctx = args->channel_ctx;108port->is_multi_conn = args->is_multi_conn;109port->validate_addr = args->do_addr_validation;110port->get_conn_user_ssl = args->get_conn_user_ssl;111port->user_ssl_arg = args->user_ssl_arg;112113if (!port_init(port)) {114OPENSSL_free(port);115return NULL;116}117118return port;119}120121void ossl_quic_port_free(QUIC_PORT *port)122{123if (port == NULL)124return;125126port_cleanup(port);127OPENSSL_free(port);128}129130static int port_init(QUIC_PORT *port)131{132size_t rx_short_dcid_len = (port->is_multi_conn ? INIT_DCID_LEN : 0);133int key_len;134EVP_CIPHER *cipher = NULL;135unsigned char *token_key = NULL;136int ret = 0;137138if (port->engine == NULL || port->channel_ctx == NULL)139goto err;140141if ((port->err_state = OSSL_ERR_STATE_new()) == NULL)142goto err;143144if ((port->demux = ossl_quic_demux_new(/*BIO=*/NULL,145/*Short CID Len=*/rx_short_dcid_len,146get_time, port)) == NULL)147goto err;148149ossl_quic_demux_set_default_handler(port->demux,150port_default_packet_handler,151port);152153if ((port->srtm = ossl_quic_srtm_new(port->engine->libctx,154port->engine->propq)) == NULL)155goto err;156157if ((port->lcidm = ossl_quic_lcidm_new(port->engine->libctx,158rx_short_dcid_len)) == NULL)159goto err;160161port->rx_short_dcid_len = (unsigned char)rx_short_dcid_len;162port->tx_init_dcid_len = INIT_DCID_LEN;163port->state = QUIC_PORT_STATE_RUNNING;164165ossl_list_port_insert_tail(&port->engine->port_list, port);166port->on_engine_list = 1;167port->bio_changed = 1;168169/* Generate random key for token encryption */170if ((port->token_ctx = EVP_CIPHER_CTX_new()) == NULL171|| (cipher = EVP_CIPHER_fetch(port->engine->libctx,172"AES-256-GCM", NULL)) == NULL173|| !EVP_EncryptInit_ex(port->token_ctx, cipher, NULL, NULL, NULL)174|| (key_len = EVP_CIPHER_CTX_get_key_length(port->token_ctx)) <= 0175|| (token_key = OPENSSL_malloc(key_len)) == NULL176|| !RAND_bytes_ex(port->engine->libctx, token_key, key_len, 0)177|| !EVP_EncryptInit_ex(port->token_ctx, NULL, NULL, token_key, NULL))178goto err;179180ret = 1;181err:182EVP_CIPHER_free(cipher);183OPENSSL_free(token_key);184if (!ret)185port_cleanup(port);186return ret;187}188189static void port_cleanup(QUIC_PORT *port)190{191assert(ossl_list_ch_num(&port->channel_list) == 0);192193ossl_quic_demux_free(port->demux);194port->demux = NULL;195196ossl_quic_srtm_free(port->srtm);197port->srtm = NULL;198199ossl_quic_lcidm_free(port->lcidm);200port->lcidm = NULL;201202OSSL_ERR_STATE_free(port->err_state);203port->err_state = NULL;204205if (port->on_engine_list) {206ossl_list_port_remove(&port->engine->port_list, port);207port->on_engine_list = 0;208}209210EVP_CIPHER_CTX_free(port->token_ctx);211port->token_ctx = NULL;212}213214static void port_transition_failed(QUIC_PORT *port)215{216if (port->state == QUIC_PORT_STATE_FAILED)217return;218219port->state = QUIC_PORT_STATE_FAILED;220}221222int ossl_quic_port_is_running(const QUIC_PORT *port)223{224return port->state == QUIC_PORT_STATE_RUNNING;225}226227QUIC_ENGINE *ossl_quic_port_get0_engine(QUIC_PORT *port)228{229return port->engine;230}231232QUIC_REACTOR *ossl_quic_port_get0_reactor(QUIC_PORT *port)233{234return ossl_quic_engine_get0_reactor(port->engine);235}236237QUIC_DEMUX *ossl_quic_port_get0_demux(QUIC_PORT *port)238{239return port->demux;240}241242CRYPTO_MUTEX *ossl_quic_port_get0_mutex(QUIC_PORT *port)243{244return ossl_quic_engine_get0_mutex(port->engine);245}246247OSSL_TIME ossl_quic_port_get_time(QUIC_PORT *port)248{249return ossl_quic_engine_get_time(port->engine);250}251252static OSSL_TIME get_time(void *port)253{254return ossl_quic_port_get_time((QUIC_PORT *)port);255}256257int ossl_quic_port_get_rx_short_dcid_len(const QUIC_PORT *port)258{259return port->rx_short_dcid_len;260}261262int ossl_quic_port_get_tx_init_dcid_len(const QUIC_PORT *port)263{264return port->tx_init_dcid_len;265}266267size_t ossl_quic_port_get_num_incoming_channels(const QUIC_PORT *port)268{269return ossl_list_incoming_ch_num(&port->incoming_channel_list);270}271272/*273* QUIC Port: Network BIO Configuration274* ====================================275*/276277/* Determines whether we can support a given poll descriptor. */278static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)279{280if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0) {281ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);282return 0;283}284285return 1;286}287288BIO *ossl_quic_port_get_net_rbio(QUIC_PORT *port)289{290return port->net_rbio;291}292293BIO *ossl_quic_port_get_net_wbio(QUIC_PORT *port)294{295return port->net_wbio;296}297298static int port_update_poll_desc(QUIC_PORT *port, BIO *net_bio, int for_write)299{300BIO_POLL_DESCRIPTOR d = {0};301302if (net_bio == NULL303|| (!for_write && !BIO_get_rpoll_descriptor(net_bio, &d))304|| (for_write && !BIO_get_wpoll_descriptor(net_bio, &d)))305/* Non-pollable BIO */306d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;307308if (!validate_poll_descriptor(&d))309return 0;310311/*312* TODO(QUIC MULTIPORT): We currently only support one port per313* engine/domain. This is necessitated because QUIC_REACTOR only supports a314* single pollable currently. In the future, once complete polling315* infrastructure has been implemented, this limitation can be removed.316*317* For now, just update the descriptor on the engine's reactor as we are318* guaranteed to be the only port under it.319*/320if (for_write)321ossl_quic_reactor_set_poll_w(&port->engine->rtor, &d);322else323ossl_quic_reactor_set_poll_r(&port->engine->rtor, &d);324325return 1;326}327328int ossl_quic_port_update_poll_descriptors(QUIC_PORT *port, int force)329{330int ok = 1;331332if (!force && !port->bio_changed)333return 0;334335if (!port_update_poll_desc(port, port->net_rbio, /*for_write=*/0))336ok = 0;337338if (!port_update_poll_desc(port, port->net_wbio, /*for_write=*/1))339ok = 0;340341port->bio_changed = 0;342return ok;343}344345/*346* We need to determine our addressing mode. There are basically two ways we can347* use L4 addresses:348*349* - Addressed mode, in which our BIO_sendmmsg calls have destination350* addresses attached to them which we expect the underlying network BIO to351* handle;352*353* - Unaddressed mode, in which the BIO provided to us on the network side354* neither provides us with L4 addresses nor is capable of honouring ones we355* provide. We don't know where the QUIC traffic we send ends up exactly and356* trust the application to know what it is doing.357*358* Addressed mode is preferred because it enables support for connection359* migration, multipath, etc. in the future. Addressed mode is automatically360* enabled if we are using e.g. BIO_s_datagram, with or without BIO_s_connect.361*362* If we are passed a BIO_s_dgram_pair (or some custom BIO) we may have to use363* unaddressed mode unless that BIO supports capability flags indicating it can364* provide and honour L4 addresses.365*366* Our strategy for determining address mode is simple: we probe the underlying367* network BIOs for their capabilities. If the network BIOs support what we368* need, we use addressed mode. Otherwise, we use unaddressed mode.369*370* If addressed mode is chosen, we require an initial peer address to be set. If371* this is not set, we fail. If unaddressed mode is used, we do not require372* this, as such an address is superfluous, though it can be set if desired.373*/374static void port_update_addressing_mode(QUIC_PORT *port)375{376long rcaps = 0, wcaps = 0;377378if (port->net_rbio != NULL)379rcaps = BIO_dgram_get_effective_caps(port->net_rbio);380381if (port->net_wbio != NULL)382wcaps = BIO_dgram_get_effective_caps(port->net_wbio);383384port->addressed_mode_r = ((rcaps & BIO_DGRAM_CAP_PROVIDES_SRC_ADDR) != 0);385port->addressed_mode_w = ((wcaps & BIO_DGRAM_CAP_HANDLES_DST_ADDR) != 0);386port->bio_changed = 1;387}388389int ossl_quic_port_is_addressed_r(const QUIC_PORT *port)390{391return port->addressed_mode_r;392}393394int ossl_quic_port_is_addressed_w(const QUIC_PORT *port)395{396return port->addressed_mode_w;397}398399int ossl_quic_port_is_addressed(const QUIC_PORT *port)400{401return ossl_quic_port_is_addressed_r(port) && ossl_quic_port_is_addressed_w(port);402}403404/*405* QUIC_PORT does not ref any BIO it is provided with, nor is any ref406* transferred to it. The caller (e.g., QUIC_CONNECTION) is responsible for407* ensuring the BIO lasts until the channel is freed or the BIO is switched out408* for another BIO by a subsequent successful call to this function.409*/410int ossl_quic_port_set_net_rbio(QUIC_PORT *port, BIO *net_rbio)411{412if (port->net_rbio == net_rbio)413return 1;414415if (!port_update_poll_desc(port, net_rbio, /*for_write=*/0))416return 0;417418ossl_quic_demux_set_bio(port->demux, net_rbio);419port->net_rbio = net_rbio;420port_update_addressing_mode(port);421return 1;422}423424int ossl_quic_port_set_net_wbio(QUIC_PORT *port, BIO *net_wbio)425{426QUIC_CHANNEL *ch;427428if (port->net_wbio == net_wbio)429return 1;430431if (!port_update_poll_desc(port, net_wbio, /*for_write=*/1))432return 0;433434OSSL_LIST_FOREACH(ch, ch, &port->channel_list)435ossl_qtx_set_bio(ch->qtx, net_wbio);436437port->net_wbio = net_wbio;438port_update_addressing_mode(port);439return 1;440}441442SSL_CTX *ossl_quic_port_get_channel_ctx(QUIC_PORT *port)443{444return port->channel_ctx;445}446447/*448* QUIC Port: Channel Lifecycle449* ============================450*/451452static SSL *port_new_handshake_layer(QUIC_PORT *port, QUIC_CHANNEL *ch)453{454SSL *tls = NULL;455SSL_CONNECTION *tls_conn = NULL;456SSL *user_ssl = NULL;457QUIC_CONNECTION *qc = NULL;458QUIC_LISTENER *ql = NULL;459460/*461* It only makes sense to call this function if we know how to associate462* the handshake layer we are about to create with some user_ssl object.463*/464if (!ossl_assert(port->get_conn_user_ssl != NULL))465return NULL;466user_ssl = port->get_conn_user_ssl(ch, port->user_ssl_arg);467if (user_ssl == NULL)468return NULL;469qc = (QUIC_CONNECTION *)user_ssl;470ql = (QUIC_LISTENER *)port->user_ssl_arg;471472/*473* We expect the user_ssl to be newly created so it must not have an474* existing qc->tls475*/476if (!ossl_assert(qc->tls == NULL)) {477SSL_free(user_ssl);478return NULL;479}480481tls = ossl_ssl_connection_new_int(port->channel_ctx, user_ssl, TLS_method());482qc->tls = tls;483if (tls == NULL || (tls_conn = SSL_CONNECTION_FROM_SSL(tls)) == NULL) {484SSL_free(user_ssl);485return NULL;486}487488if (ql != NULL && ql->obj.ssl.ctx->new_pending_conn_cb != NULL)489if (!ql->obj.ssl.ctx->new_pending_conn_cb(ql->obj.ssl.ctx, user_ssl,490ql->obj.ssl.ctx->new_pending_conn_arg)) {491SSL_free(user_ssl);492return NULL;493}494495/* Override the user_ssl of the inner connection. */496tls_conn->s3.flags |= TLS1_FLAGS_QUIC | TLS1_FLAGS_QUIC_INTERNAL;497498/* Restrict options derived from the SSL_CTX. */499tls_conn->options &= OSSL_QUIC_PERMITTED_OPTIONS_CONN;500tls_conn->pha_enabled = 0;501return tls;502}503504static QUIC_CHANNEL *port_make_channel(QUIC_PORT *port, SSL *tls, OSSL_QRX *qrx,505int is_server, int is_tserver)506{507QUIC_CHANNEL_ARGS args = {0};508QUIC_CHANNEL *ch;509510args.port = port;511args.is_server = is_server;512args.lcidm = port->lcidm;513args.srtm = port->srtm;514args.qrx = qrx;515args.is_tserver_ch = is_tserver;516517/*518* Creating a a new channel is made a bit tricky here as there is a519* bit of a circular dependency. Initalizing a channel requires that520* the ch->tls and optionally the qlog_title be configured prior to521* initalization, but we need the channel at least partially configured522* to create the new handshake layer, so we have to do this in a few steps.523*/524525/*526* start by allocation and provisioning as much of the channel as we can527*/528ch = ossl_quic_channel_alloc(&args);529if (ch == NULL)530return NULL;531532/*533* Fixup the channel tls connection here before we init the channel534*/535ch->tls = (tls != NULL) ? tls : port_new_handshake_layer(port, ch);536537if (ch->tls == NULL) {538OPENSSL_free(ch);539return NULL;540}541542#ifndef OPENSSL_NO_QLOG543/*544* If we're using qlog, make sure the tls get further configured properly545*/546ch->use_qlog = 1;547if (ch->tls->ctx->qlog_title != NULL) {548if ((ch->qlog_title = OPENSSL_strdup(ch->tls->ctx->qlog_title)) == NULL) {549OPENSSL_free(ch);550return NULL;551}552}553#endif554555/*556* And finally init the channel struct557*/558if (!ossl_quic_channel_init(ch)) {559OPENSSL_free(ch);560return NULL;561}562563ossl_qtx_set_bio(ch->qtx, port->net_wbio);564return ch;565}566567QUIC_CHANNEL *ossl_quic_port_create_outgoing(QUIC_PORT *port, SSL *tls)568{569return port_make_channel(port, tls, NULL, /* is_server= */ 0,570/* is_tserver= */ 0);571}572573QUIC_CHANNEL *ossl_quic_port_create_incoming(QUIC_PORT *port, SSL *tls)574{575QUIC_CHANNEL *ch;576577assert(port->tserver_ch == NULL);578579/*580* pass -1 for qrx to indicate port will create qrx581* later in port_default_packet_handler() when calling port_bind_channel().582*/583ch = port_make_channel(port, tls, NULL, /* is_server= */ 1,584/* is_tserver_ch */ 1);585port->tserver_ch = ch;586port->allow_incoming = 1;587return ch;588}589590QUIC_CHANNEL *ossl_quic_port_pop_incoming(QUIC_PORT *port)591{592QUIC_CHANNEL *ch;593594ch = ossl_list_incoming_ch_head(&port->incoming_channel_list);595if (ch == NULL)596return NULL;597598ossl_list_incoming_ch_remove(&port->incoming_channel_list, ch);599return ch;600}601602int ossl_quic_port_have_incoming(QUIC_PORT *port)603{604return ossl_list_incoming_ch_head(&port->incoming_channel_list) != NULL;605}606607void ossl_quic_port_drop_incoming(QUIC_PORT *port)608{609QUIC_CHANNEL *ch;610SSL *tls;611SSL *user_ssl;612SSL_CONNECTION *sc;613614for (;;) {615ch = ossl_quic_port_pop_incoming(port);616if (ch == NULL)617break;618619tls = ossl_quic_channel_get0_tls(ch);620/*621* The user ssl may or may not have been created via the622* get_conn_user_ssl callback in the QUIC stack. The623* differentiation being if the user_ssl pointer and tls pointer624* are different. If they are, then the user_ssl needs freeing here625* which sends us through ossl_quic_free, which then drops the actual626* ch->tls ref and frees the channel627*/628sc = SSL_CONNECTION_FROM_SSL(tls);629if (sc == NULL)630break;631632user_ssl = SSL_CONNECTION_GET_USER_SSL(sc);633if (user_ssl == tls) {634ossl_quic_channel_free(ch);635SSL_free(tls);636} else {637SSL_free(user_ssl);638}639}640}641642void ossl_quic_port_set_allow_incoming(QUIC_PORT *port, int allow_incoming)643{644port->allow_incoming = allow_incoming;645}646647/*648* QUIC Port: Ticker-Mutator649* =========================650*/651652/*653* Tick function for this port. This does everything related to network I/O for654* this port's network BIOs, and services child channels.655*/656void ossl_quic_port_subtick(QUIC_PORT *port, QUIC_TICK_RESULT *res,657uint32_t flags)658{659QUIC_CHANNEL *ch;660661res->net_read_desired = ossl_quic_port_is_running(port);662res->net_write_desired = 0;663res->notify_other_threads = 0;664res->tick_deadline = ossl_time_infinite();665666if (!port->engine->inhibit_tick) {667/* Handle any incoming data from network. */668if (ossl_quic_port_is_running(port))669port_rx_pre(port);670671/* Iterate through all channels and service them. */672OSSL_LIST_FOREACH(ch, ch, &port->channel_list) {673QUIC_TICK_RESULT subr = {0};674675ossl_quic_channel_subtick(ch, &subr, flags);676ossl_quic_tick_result_merge_into(res, &subr);677}678}679}680681/* Process incoming datagrams, if any. */682static void port_rx_pre(QUIC_PORT *port)683{684int ret;685686/*687* Originally, this check (don't RX before we have sent anything if we are688* not a server, because there can't be anything) was just intended as a689* minor optimisation. However, it is actually required on Windows, and690* removing this check will cause Windows to break.691*692* The reason is that under Win32, recvfrom() does not work on a UDP socket693* which has not had bind() called (???). However, calling sendto() will694* automatically bind an unbound UDP socket. Therefore, if we call a Winsock695* recv-type function before calling a Winsock send-type function, that call696* will fail with WSAEINVAL, which we will regard as a permanent network697* error.698*699* Therefore, this check is essential as we do not require our API users to700* bind a socket first when using the API in client mode.701*/702if (!port->allow_incoming && !port->have_sent_any_pkt)703return;704705/*706* Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams707* to the appropriate QRX instances.708*/709ret = ossl_quic_demux_pump(port->demux);710if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)711/*712* We don't care about transient failure, but permanent failure means we713* should tear down the port. All connections skip straight to the714* Terminated state as there is no point trying to send CONNECTION_CLOSE715* frames if the network BIO is not operating correctly.716*/717ossl_quic_port_raise_net_error(port, NULL);718}719720/*721* Handles an incoming connection request and potentially decides to make a722* connection from it. If a new connection is made, the new channel is written723* to *new_ch.724*/725static void port_bind_channel(QUIC_PORT *port, const BIO_ADDR *peer,726const QUIC_CONN_ID *scid, const QUIC_CONN_ID *dcid,727const QUIC_CONN_ID *odcid, OSSL_QRX *qrx,728QUIC_CHANNEL **new_ch)729{730QUIC_CHANNEL *ch;731732/*733* If we're running with a simulated tserver, it will already have734* a dummy channel created, use that instead735*/736if (port->tserver_ch != NULL) {737ch = port->tserver_ch;738port->tserver_ch = NULL;739ossl_quic_channel_bind_qrx(ch, qrx);740ossl_qrx_set_msg_callback(ch->qrx, ch->msg_callback,741ch->msg_callback_ssl);742ossl_qrx_set_msg_callback_arg(ch->qrx, ch->msg_callback_arg);743} else {744ch = port_make_channel(port, NULL, qrx, /* is_server= */ 1,745/* is_tserver */ 0);746}747748if (ch == NULL)749return;750751/*752* If we didn't provide a qrx here that means we need to set our initial753* secret here, since we just created a qrx754* Normally its not needed, as the initial secret gets added when we send755* our first server hello, but if we get a huge client hello, crossing756* multiple datagrams, we don't have a chance to do that, and datagrams757* after the first won't get decoded properly, for lack of secrets758*/759if (qrx == NULL)760if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,761ch->port->engine->propq,762dcid, /* is_server */ 1,763ch->qrx, NULL))764return;765766if (odcid->id_len != 0) {767/*768* If we have an odcid, then we went through server address validation769* and as such, this channel need not conform to the 3x validation cap770* See RFC 9000 s. 8.1771*/772ossl_quic_tx_packetiser_set_validated(ch->txp);773if (!ossl_quic_bind_channel(ch, peer, scid, dcid, odcid)) {774ossl_quic_channel_free(ch);775return;776}777} else {778/*779* No odcid means we didn't do server validation, so we need to780* generate a cid via ossl_quic_channel_on_new_conn781*/782if (!ossl_quic_channel_on_new_conn(ch, peer, scid, dcid)) {783ossl_quic_channel_free(ch);784return;785}786}787788ossl_list_incoming_ch_insert_tail(&port->incoming_channel_list, ch);789*new_ch = ch;790}791792static int port_try_handle_stateless_reset(QUIC_PORT *port, const QUIC_URXE *e)793{794size_t i;795const unsigned char *data = ossl_quic_urxe_data(e);796void *opaque = NULL;797798/*799* Perform some fast and cheap checks for a packet not being a stateless800* reset token. RFC 9000 s. 10.3 specifies this layout for stateless801* reset packets:802*803* Stateless Reset {804* Fixed Bits (2) = 1,805* Unpredictable Bits (38..),806* Stateless Reset Token (128),807* }808*809* It also specifies:810* However, endpoints MUST treat any packet ending in a valid811* stateless reset token as a Stateless Reset, as other QUIC812* versions might allow the use of a long header.813*814* We can rapidly check for the minimum length and that the first pair815* of bits in the first byte are 01 or 11.816*817* The function returns 1 if it is a stateless reset packet, 0 if it isn't818* and -1 if an error was encountered.819*/820if (e->data_len < QUIC_STATELESS_RESET_TOKEN_LEN + 5821|| (0100 & *data) != 0100)822return 0;823824for (i = 0;; ++i) {825if (!ossl_quic_srtm_lookup(port->srtm,826(QUIC_STATELESS_RESET_TOKEN *)(data + e->data_len827- sizeof(QUIC_STATELESS_RESET_TOKEN)),828i, &opaque, NULL))829break;830831assert(opaque != NULL);832ossl_quic_channel_on_stateless_reset((QUIC_CHANNEL *)opaque);833}834835return i > 0;836}837838static void cleanup_validation_token(QUIC_VALIDATION_TOKEN *token)839{840OPENSSL_free(token->remote_addr);841}842843/**844* @brief Generates a validation token for a RETRY/NEW_TOKEN packet.845*846*847* @param peer Address of the client peer receiving the packet.848* @param odcid DCID of the connection attempt.849* @param rscid Retry source connection ID of the connection attempt.850* @param token Address of token to fill data.851*852* @return 1 if validation token is filled successfully, 0 otherwise.853*/854static int generate_token(BIO_ADDR *peer, QUIC_CONN_ID odcid,855QUIC_CONN_ID rscid, QUIC_VALIDATION_TOKEN *token,856int is_retry)857{858token->is_retry = is_retry;859token->timestamp = ossl_time_now();860token->remote_addr = NULL;861token->odcid = odcid;862token->rscid = rscid;863864if (!BIO_ADDR_rawaddress(peer, NULL, &token->remote_addr_len)865|| token->remote_addr_len == 0866|| (token->remote_addr = OPENSSL_malloc(token->remote_addr_len)) == NULL867|| !BIO_ADDR_rawaddress(peer, token->remote_addr,868&token->remote_addr_len)) {869cleanup_validation_token(token);870return 0;871}872873return 1;874}875876/**877* @brief Marshals a validation token into a new buffer.878*879* |buffer| should already be allocated and at least MARSHALLED_TOKEN_MAX_LEN880* bytes long. Stores the length of data stored in |buffer| in |buffer_len|.881*882* @param token Validation token.883* @param buffer Address to store the marshalled token.884* @param buffer_len Size of data stored in |buffer|.885*/886static int marshal_validation_token(QUIC_VALIDATION_TOKEN *token,887unsigned char *buffer, size_t *buffer_len)888{889WPACKET wpkt = {0};890BUF_MEM *buf_mem = BUF_MEM_new();891892if (buffer == NULL || buf_mem == NULL893|| (token->is_retry != 0 && token->is_retry != 1)) {894BUF_MEM_free(buf_mem);895return 0;896}897898if (!WPACKET_init(&wpkt, buf_mem)899|| !WPACKET_memset(&wpkt, token->is_retry, 1)900|| !WPACKET_memcpy(&wpkt, &token->timestamp,901sizeof(token->timestamp))902|| (token->is_retry903&& (!WPACKET_sub_memcpy_u8(&wpkt, &token->odcid.id,904token->odcid.id_len)905|| !WPACKET_sub_memcpy_u8(&wpkt, &token->rscid.id,906token->rscid.id_len)))907|| !WPACKET_sub_memcpy_u8(&wpkt, token->remote_addr, token->remote_addr_len)908|| !WPACKET_get_total_written(&wpkt, buffer_len)909|| *buffer_len > MARSHALLED_TOKEN_MAX_LEN910|| !WPACKET_finish(&wpkt)) {911WPACKET_cleanup(&wpkt);912BUF_MEM_free(buf_mem);913return 0;914}915916memcpy(buffer, buf_mem->data, *buffer_len);917BUF_MEM_free(buf_mem);918return 1;919}920921/**922* @brief Encrypts a validation token using AES-256-GCM923*924* @param port The QUIC port containing the encryption key925* @param plaintext The data to encrypt926* @param pt_len Length of the plaintext927* @param ciphertext Buffer to receive encrypted data. If NULL, ct_len will be928* set to the required buffer size and function returns929* immediately.930* @param ct_len Pointer to size_t that will receive the ciphertext length.931* This also includes bytes for QUIC_RETRY_INTEGRITY_TAG_LEN.932*933* @return 1 on success, 0 on failure934*935* The ciphertext format is:936* [EVP_GCM_IV_LEN bytes IV][encrypted data][EVP_GCM_TAG_LEN bytes tag]937*/938static int encrypt_validation_token(const QUIC_PORT *port,939const unsigned char *plaintext,940size_t pt_len,941unsigned char *ciphertext,942size_t *ct_len)943{944int iv_len, len, ret = 0;945size_t tag_len;946unsigned char *iv = ciphertext, *data, *tag;947948if ((tag_len = EVP_CIPHER_CTX_get_tag_length(port->token_ctx)) == 0949|| (iv_len = EVP_CIPHER_CTX_get_iv_length(port->token_ctx)) <= 0)950goto err;951952*ct_len = iv_len + pt_len + tag_len + QUIC_RETRY_INTEGRITY_TAG_LEN;953if (ciphertext == NULL) {954ret = 1;955goto err;956}957958data = ciphertext + iv_len;959tag = data + pt_len;960961if (!RAND_bytes_ex(port->engine->libctx, ciphertext, iv_len, 0)962|| !EVP_EncryptInit_ex(port->token_ctx, NULL, NULL, NULL, iv)963|| !EVP_EncryptUpdate(port->token_ctx, data, &len, plaintext, pt_len)964|| !EVP_EncryptFinal_ex(port->token_ctx, data + pt_len, &len)965|| !EVP_CIPHER_CTX_ctrl(port->token_ctx, EVP_CTRL_GCM_GET_TAG, tag_len, tag))966goto err;967968ret = 1;969err:970return ret;971}972973/**974* @brief Decrypts a validation token using AES-256-GCM975*976* @param port The QUIC port containing the decryption key977* @param ciphertext The encrypted data (including IV and tag)978* @param ct_len Length of the ciphertext979* @param plaintext Buffer to receive decrypted data. If NULL, pt_len will be980* set to the required buffer size.981* @param pt_len Pointer to size_t that will receive the plaintext length982*983* @return 1 on success, 0 on failure984*985* Expected ciphertext format:986* [EVP_GCM_IV_LEN bytes IV][encrypted data][EVP_GCM_TAG_LEN bytes tag]987*/988static int decrypt_validation_token(const QUIC_PORT *port,989const unsigned char *ciphertext,990size_t ct_len,991unsigned char *plaintext,992size_t *pt_len)993{994int iv_len, len = 0, ret = 0;995size_t tag_len;996const unsigned char *iv = ciphertext, *data, *tag;997998if ((tag_len = EVP_CIPHER_CTX_get_tag_length(port->token_ctx)) == 0999|| (iv_len = EVP_CIPHER_CTX_get_iv_length(port->token_ctx)) <= 0)1000goto err;10011002/* Prevent decryption of a buffer that is not within reasonable bounds */1003if (ct_len < (iv_len + tag_len) || ct_len > ENCRYPTED_TOKEN_MAX_LEN)1004goto err;10051006*pt_len = ct_len - iv_len - tag_len;1007if (plaintext == NULL) {1008ret = 1;1009goto err;1010}10111012data = ciphertext + iv_len;1013tag = ciphertext + ct_len - tag_len;10141015if (!EVP_DecryptInit_ex(port->token_ctx, NULL, NULL, NULL, iv)1016|| !EVP_DecryptUpdate(port->token_ctx, plaintext, &len, data,1017ct_len - iv_len - tag_len)1018|| !EVP_CIPHER_CTX_ctrl(port->token_ctx, EVP_CTRL_GCM_SET_TAG, tag_len,1019(void *)tag)1020|| !EVP_DecryptFinal_ex(port->token_ctx, plaintext + len, &len))1021goto err;10221023ret = 1;10241025err:1026return ret;1027}10281029/**1030* @brief Parses contents of a buffer into a validation token.1031*1032* VALIDATION_TOKEN should already be initalized. Does some basic sanity checks.1033*1034* @param token Validation token to fill data in.1035* @param buf Buffer of previously marshaled validation token.1036* @param buf_len Length of |buf|.1037*/1038static int parse_validation_token(QUIC_VALIDATION_TOKEN *token,1039const unsigned char *buf, size_t buf_len)1040{1041PACKET pkt, subpkt;10421043if (buf == NULL || token == NULL)1044return 0;10451046token->remote_addr = NULL;10471048if (!PACKET_buf_init(&pkt, buf, buf_len)1049|| !PACKET_copy_bytes(&pkt, &token->is_retry, sizeof(token->is_retry))1050|| !(token->is_retry == 0 || token->is_retry == 1)1051|| !PACKET_copy_bytes(&pkt, (unsigned char *)&token->timestamp,1052sizeof(token->timestamp))1053|| (token->is_retry1054&& (!PACKET_get_length_prefixed_1(&pkt, &subpkt)1055|| (token->odcid.id_len = (unsigned char)PACKET_remaining(&subpkt))1056> QUIC_MAX_CONN_ID_LEN1057|| !PACKET_copy_bytes(&subpkt,1058(unsigned char *)&token->odcid.id,1059token->odcid.id_len)1060|| !PACKET_get_length_prefixed_1(&pkt, &subpkt)1061|| (token->rscid.id_len = (unsigned char)PACKET_remaining(&subpkt))1062> QUIC_MAX_CONN_ID_LEN1063|| !PACKET_copy_bytes(&subpkt, (unsigned char *)&token->rscid.id,1064token->rscid.id_len)))1065|| !PACKET_get_length_prefixed_1(&pkt, &subpkt)1066|| (token->remote_addr_len = PACKET_remaining(&subpkt)) == 01067|| (token->remote_addr = OPENSSL_malloc(token->remote_addr_len)) == NULL1068|| !PACKET_copy_bytes(&subpkt, token->remote_addr, token->remote_addr_len)1069|| PACKET_remaining(&pkt) != 0) {1070cleanup_validation_token(token);1071return 0;1072}10731074return 1;1075}10761077/**1078* @brief Sends a QUIC Retry packet to a client.1079*1080* This function constructs and sends a Retry packet to the specified client1081* using the provided connection header information. The Retry packet1082* includes a generated validation token and a new connection ID, following1083* the QUIC protocol specifications for connection establishment.1084*1085* @param port Pointer to the QUIC port from which to send the packet.1086* @param peer Address of the client peer receiving the packet.1087* @param client_hdr Header of the client's initial packet, containing1088* connection IDs and other relevant information.1089*1090* This function performs the following steps:1091* - Generates a validation token for the client.1092* - Sets the destination and source connection IDs.1093* - Calculates the integrity tag and sets the token length.1094* - Encodes and sends the packet via the BIO network interface.1095*1096* Error handling is included for failures in CID generation, encoding, and1097* network transmiss1098*/1099static void port_send_retry(QUIC_PORT *port,1100BIO_ADDR *peer,1101QUIC_PKT_HDR *client_hdr)1102{1103BIO_MSG msg[1];1104/*1105* Buffer is used for both marshalling the token as well as for the RETRY1106* packet. The size of buffer should not be less than1107* MARSHALLED_TOKEN_MAX_LEN.1108*/1109unsigned char buffer[512];1110unsigned char ct_buf[ENCRYPTED_TOKEN_MAX_LEN];1111WPACKET wpkt;1112size_t written, token_buf_len, ct_len;1113QUIC_PKT_HDR hdr = {0};1114QUIC_VALIDATION_TOKEN token = {0};1115int ok;11161117if (!ossl_assert(sizeof(buffer) >= MARSHALLED_TOKEN_MAX_LEN))1118return;1119/*1120* 17.2.5.1 Sending a Retry packet1121* dst ConnId is src ConnId we got from client1122* src ConnId comes from local conn ID manager1123*/1124memset(&hdr, 0, sizeof(QUIC_PKT_HDR));1125hdr.dst_conn_id = client_hdr->src_conn_id;1126/*1127* this is the random connection ID, we expect client is1128* going to send the ID with next INITIAL packet which1129* will also come with token we generate here.1130*/1131ok = ossl_quic_lcidm_get_unused_cid(port->lcidm, &hdr.src_conn_id);1132if (ok == 0)1133goto err;11341135memset(&token, 0, sizeof(QUIC_VALIDATION_TOKEN));11361137/* Generate retry validation token */1138if (!generate_token(peer, client_hdr->dst_conn_id,1139hdr.src_conn_id, &token, 1)1140|| !marshal_validation_token(&token, buffer, &token_buf_len)1141|| !encrypt_validation_token(port, buffer, token_buf_len, NULL,1142&ct_len)1143|| ct_len > ENCRYPTED_TOKEN_MAX_LEN1144|| !encrypt_validation_token(port, buffer, token_buf_len, ct_buf,1145&ct_len)1146|| !ossl_assert(ct_len >= QUIC_RETRY_INTEGRITY_TAG_LEN))1147goto err;11481149hdr.dst_conn_id = client_hdr->src_conn_id;1150hdr.type = QUIC_PKT_TYPE_RETRY;1151hdr.fixed = 1;1152hdr.version = 1;1153hdr.len = ct_len;1154hdr.data = ct_buf;1155ok = ossl_quic_calculate_retry_integrity_tag(port->engine->libctx,1156port->engine->propq, &hdr,1157&client_hdr->dst_conn_id,1158ct_buf + ct_len1159- QUIC_RETRY_INTEGRITY_TAG_LEN);1160if (ok == 0)1161goto err;11621163hdr.token = hdr.data;1164hdr.token_len = hdr.len;11651166msg[0].data = buffer;1167msg[0].peer = peer;1168msg[0].local = NULL;1169msg[0].flags = 0;11701171ok = WPACKET_init_static_len(&wpkt, buffer, sizeof(buffer), 0);1172if (ok == 0)1173goto err;11741175ok = ossl_quic_wire_encode_pkt_hdr(&wpkt, client_hdr->dst_conn_id.id_len,1176&hdr, NULL);1177if (ok == 0)1178goto err;11791180ok = WPACKET_get_total_written(&wpkt, &msg[0].data_len);1181if (ok == 0)1182goto err;11831184ok = WPACKET_finish(&wpkt);1185if (ok == 0)1186goto err;11871188/*1189* TODO(QUIC FUTURE) need to retry this in the event it return EAGAIN1190* on a non-blocking BIO1191*/1192if (!BIO_sendmmsg(port->net_wbio, msg, sizeof(BIO_MSG), 1, 0, &written))1193ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,1194"port retry send failed due to network BIO I/O error");11951196err:1197cleanup_validation_token(&token);1198}11991200/**1201* @brief Sends a QUIC Version Negotiation packet to the specified peer.1202*1203* This function constructs and sends a Version Negotiation packet using1204* the connection IDs from the client's initial packet header. The1205* Version Negotiation packet indicates support for QUIC version 1.1206*1207* @param port Pointer to the QUIC_PORT structure representing the port1208* context used for network communication.1209* @param peer Pointer to the BIO_ADDR structure specifying the address1210* of the peer to which the Version Negotiation packet1211* will be sent.1212* @param client_hdr Pointer to the QUIC_PKT_HDR structure containing the1213* client's packet header used to extract connection IDs.1214*1215* @note The function will raise an error if sending the message fails.1216*/1217static void port_send_version_negotiation(QUIC_PORT *port, BIO_ADDR *peer,1218QUIC_PKT_HDR *client_hdr)1219{1220BIO_MSG msg[1];1221unsigned char buffer[1024];1222QUIC_PKT_HDR hdr;1223WPACKET wpkt;1224uint32_t supported_versions[1];1225size_t written;1226size_t i;12271228memset(&hdr, 0, sizeof(QUIC_PKT_HDR));1229/*1230* Reverse the source and dst conn ids1231*/1232hdr.dst_conn_id = client_hdr->src_conn_id;1233hdr.src_conn_id = client_hdr->dst_conn_id;12341235/*1236* This is our list of supported protocol versions1237* Currently only QUIC_VERSION_11238*/1239supported_versions[0] = QUIC_VERSION_1;12401241/*1242* Fill out the header fields1243* Note: Version negotiation packets, must, unlike1244* other packet types have a version of 01245*/1246hdr.type = QUIC_PKT_TYPE_VERSION_NEG;1247hdr.version = 0;1248hdr.token = 0;1249hdr.token_len = 0;1250hdr.len = sizeof(supported_versions);1251hdr.data = (unsigned char *)supported_versions;12521253msg[0].data = buffer;1254msg[0].peer = peer;1255msg[0].local = NULL;1256msg[0].flags = 0;12571258if (!WPACKET_init_static_len(&wpkt, buffer, sizeof(buffer), 0))1259return;12601261if (!ossl_quic_wire_encode_pkt_hdr(&wpkt, client_hdr->dst_conn_id.id_len,1262&hdr, NULL))1263return;12641265/*1266* Add the array of supported versions to the end of the packet1267*/1268for (i = 0; i < OSSL_NELEM(supported_versions); i++) {1269if (!WPACKET_put_bytes_u32(&wpkt, supported_versions[i]))1270return;1271}12721273if (!WPACKET_get_total_written(&wpkt, &msg[0].data_len))1274return;12751276if (!WPACKET_finish(&wpkt))1277return;12781279/*1280* Send it back to the client attempting to connect1281* TODO(QUIC FUTURE): Need to handle the EAGAIN case here, if the1282* BIO_sendmmsg call falls in a retryable manner1283*/1284if (!BIO_sendmmsg(port->net_wbio, msg, sizeof(BIO_MSG), 1, 0, &written))1285ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,1286"port version negotiation send failed");1287}12881289/**1290* @brief defintions of token lifetimes1291*1292* RETRY tokens are only valid for 10 seconds1293* NEW_TOKEN tokens have a lifetime of 3600 sec (1 hour)1294*/12951296#define RETRY_LIFETIME 101297#define NEW_TOKEN_LIFETIME 36001298/**1299* @brief Validates a received token in a QUIC packet header.1300*1301* This function checks the validity of a token contained in the provided1302* QUIC packet header (`QUIC_PKT_HDR *hdr`). The validation process involves1303* verifying that the token matches an expected format and value. If the1304* token is from a RETRY packet, the function extracts the original connection1305* ID (ODCID)/original source connection ID (SCID) and stores it in the provided1306* parameters. If the token is from a NEW_TOKEN packet, the values will be1307* derived instead.1308*1309* @param hdr Pointer to the QUIC packet header containing the token.1310* @param port Pointer to the QUIC port from which to send the packet.1311* @param peer Address of the client peer receiving the packet.1312* @param odcid Pointer to the connection ID structure to store the ODCID if the1313* token is valid.1314* @param scid Pointer to the connection ID structure to store the SCID if the1315* token is valid.1316*1317* @return 1 if the token is valid and ODCID/SCID are successfully set.1318* 0 otherwise.1319*1320* The function performs the following checks:1321* - Token length meets the required minimum.1322* - Buffer matches expected format.1323* - Peer address matches previous connection address.1324* - Token has not expired. Currently set to 10 seconds for tokens from RETRY1325* packets and 60 minutes for tokens from NEW_TOKEN packets. This may be1326* configurable in the future.1327*/1328static int port_validate_token(QUIC_PKT_HDR *hdr, QUIC_PORT *port,1329BIO_ADDR *peer, QUIC_CONN_ID *odcid,1330QUIC_CONN_ID *scid, uint8_t *gen_new_token)1331{1332int ret = 0;1333QUIC_VALIDATION_TOKEN token = { 0 };1334uint64_t time_diff;1335size_t remote_addr_len, dec_token_len;1336unsigned char *remote_addr = NULL, dec_token[MARSHALLED_TOKEN_MAX_LEN];1337OSSL_TIME now = ossl_time_now();13381339*gen_new_token = 0;13401341if (!decrypt_validation_token(port, hdr->token, hdr->token_len, NULL,1342&dec_token_len)1343|| dec_token_len > MARSHALLED_TOKEN_MAX_LEN1344|| !decrypt_validation_token(port, hdr->token, hdr->token_len,1345dec_token, &dec_token_len)1346|| !parse_validation_token(&token, dec_token, dec_token_len))1347goto err;13481349/*1350* Validate token timestamp. Current time should not be before the token1351* timestamp.1352*/1353if (ossl_time_compare(now, token.timestamp) < 0)1354goto err;1355time_diff = ossl_time2seconds(ossl_time_abs_difference(token.timestamp,1356now));1357if ((token.is_retry && time_diff > RETRY_LIFETIME)1358|| (!token.is_retry && time_diff > NEW_TOKEN_LIFETIME))1359goto err;13601361/* Validate remote address */1362if (!BIO_ADDR_rawaddress(peer, NULL, &remote_addr_len)1363|| remote_addr_len != token.remote_addr_len1364|| (remote_addr = OPENSSL_malloc(remote_addr_len)) == NULL1365|| !BIO_ADDR_rawaddress(peer, remote_addr, &remote_addr_len)1366|| memcmp(remote_addr, token.remote_addr, remote_addr_len) != 0)1367goto err;13681369/*1370* Set ODCID and SCID. If the token is from a RETRY packet, retrieve both1371* from the token. Otherwise, generate a new ODCID and use the header's1372* source connection ID for SCID.1373*/1374if (token.is_retry) {1375/*1376* We're parsing a packet header before its gone through AEAD validation1377* here, so there is a chance we are dealing with corrupted data. Make1378* Sure the dcid encoded in the token matches the headers dcid to1379* mitigate that.1380* TODO(QUIC FUTURE): Consider handling AEAD validation at the port1381* level rather than the QRX/channel level to eliminate the need for1382* this.1383*/1384if (token.rscid.id_len != hdr->dst_conn_id.id_len1385|| memcmp(&token.rscid.id, &hdr->dst_conn_id.id,1386token.rscid.id_len) != 0)1387goto err;1388*odcid = token.odcid;1389*scid = token.rscid;1390} else {1391if (!ossl_quic_lcidm_get_unused_cid(port->lcidm, odcid))1392goto err;1393*scid = hdr->src_conn_id;1394}13951396/*1397* Determine if we need to send a NEW_TOKEN frame1398* If we validated a retry token, we should always1399* send a NEW_TOKEN frame to the client1400*1401* If however, we validated a NEW_TOKEN, which may be1402* reused multiple times, only send a NEW_TOKEN frame1403* if the existing received token has less than 10% of its lifetime1404* remaining. This prevents us from constantly sending1405* NEW_TOKEN frames on every connection when not needed1406*/1407if (token.is_retry) {1408*gen_new_token = 1;1409} else {1410if (time_diff > ((NEW_TOKEN_LIFETIME * 9) / 10))1411*gen_new_token = 1;1412}14131414ret = 1;1415err:1416cleanup_validation_token(&token);1417OPENSSL_free(remote_addr);1418return ret;1419}14201421static void generate_new_token(QUIC_CHANNEL *ch, BIO_ADDR *peer)1422{1423QUIC_CONN_ID rscid = { 0 };1424QUIC_VALIDATION_TOKEN token;1425unsigned char buffer[ENCRYPTED_TOKEN_MAX_LEN];1426unsigned char *ct_buf;1427size_t ct_len;1428size_t token_buf_len = 0;14291430/* Clients never send a NEW_TOKEN */1431if (!ch->is_server)1432return;14331434ct_buf = OPENSSL_zalloc(ENCRYPTED_TOKEN_MAX_LEN);1435if (ct_buf == NULL)1436return;14371438/*1439* NEW_TOKEN tokens may be used for multiple subsequent connections1440* within their timeout period, so don't reserve an rscid here1441* like we do for retry tokens, instead, just fill it with random1442* data, as we won't use it anyway1443*/1444rscid.id_len = 8;1445if (!RAND_bytes_ex(ch->port->engine->libctx, rscid.id, 8, 0)) {1446OPENSSL_free(ct_buf);1447return;1448}14491450memset(&token, 0, sizeof(QUIC_VALIDATION_TOKEN));14511452if (!generate_token(peer, ch->init_dcid, rscid, &token, 0)1453|| !marshal_validation_token(&token, buffer, &token_buf_len)1454|| !encrypt_validation_token(ch->port, buffer, token_buf_len, NULL,1455&ct_len)1456|| ct_len > ENCRYPTED_TOKEN_MAX_LEN1457|| !encrypt_validation_token(ch->port, buffer, token_buf_len, ct_buf,1458&ct_len)1459|| !ossl_assert(ct_len >= QUIC_RETRY_INTEGRITY_TAG_LEN)) {1460OPENSSL_free(ct_buf);1461cleanup_validation_token(&token);1462return;1463}14641465ch->pending_new_token = ct_buf;1466ch->pending_new_token_len = ct_len;14671468cleanup_validation_token(&token);1469}14701471/*1472* This is called by the demux when we get a packet not destined for any known1473* DCID.1474*/1475static void port_default_packet_handler(QUIC_URXE *e, void *arg,1476const QUIC_CONN_ID *dcid)1477{1478QUIC_PORT *port = arg;1479PACKET pkt;1480QUIC_PKT_HDR hdr;1481QUIC_CHANNEL *ch = NULL, *new_ch = NULL;1482QUIC_CONN_ID odcid, scid;1483uint8_t gen_new_token = 0;1484OSSL_QRX *qrx = NULL;1485OSSL_QRX *qrx_src = NULL;1486OSSL_QRX_ARGS qrx_args = {0};1487uint64_t cause_flags = 0;1488OSSL_QRX_PKT *qrx_pkt = NULL;14891490/* Don't handle anything if we are no longer running. */1491if (!ossl_quic_port_is_running(port))1492goto undesirable;14931494if (port_try_handle_stateless_reset(port, e))1495goto undesirable;14961497if (dcid != NULL1498&& ossl_quic_lcidm_lookup(port->lcidm, dcid, NULL,1499(void **)&ch)) {1500assert(ch != NULL);1501ossl_quic_channel_inject(ch, e);1502return;1503}15041505/*1506* If we have an incoming packet which doesn't match any existing connection1507* we assume this is an attempt to make a new connection.1508*/1509if (!port->allow_incoming)1510goto undesirable;15111512/*1513* We have got a packet for an unknown DCID. This might be an attempt to1514* open a new connection.1515*/1516if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)1517goto undesirable;15181519if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))1520goto undesirable;15211522/*1523* We set short_conn_id_len to SIZE_MAX here which will cause the decode1524* operation to fail if we get a 1-RTT packet. This is fine since we only1525* care about Initial packets.1526*/1527if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL,1528&cause_flags)) {1529/*1530* If we fail due to a bad version, we know the packet up to the version1531* number was decoded, and we use it below to send a version1532* negotiation packet1533*/1534if ((cause_flags & QUIC_PKT_HDR_DECODE_BAD_VERSION) == 0)1535goto undesirable;1536}15371538switch (hdr.version) {1539case QUIC_VERSION_1:1540break;15411542case QUIC_VERSION_NONE:1543default:15441545/*1546* If we get here, then we have a bogus version, and might need1547* to send a version negotiation packet. According to1548* RFC 9000 s. 6 and 14.1, we only do so however, if the UDP datagram1549* is a minimum of 1200 bytes in size1550*/1551if (e->data_len < 1200)1552goto undesirable;15531554/*1555* If we don't get a supported version, respond with a ver1556* negotiation packet, and discard1557* TODO(QUIC FUTURE): Rate limit the reception of these1558*/1559port_send_version_negotiation(port, &e->peer, &hdr);1560goto undesirable;1561}15621563/*1564* We only care about Initial packets which might be trying to establish a1565* connection.1566*/1567if (hdr.type != QUIC_PKT_TYPE_INITIAL)1568goto undesirable;15691570odcid.id_len = 0;15711572/*1573* Create qrx now so we can check integrity of packet1574* which does not belong to any channel.1575*/1576qrx_args.libctx = port->engine->libctx;1577qrx_args.demux = port->demux;1578qrx_args.short_conn_id_len = dcid->id_len;1579qrx_args.max_deferred = 32;1580qrx = ossl_qrx_new(&qrx_args);1581if (qrx == NULL)1582goto undesirable;15831584/*1585* Derive secrets for qrx only.1586*/1587if (!ossl_quic_provide_initial_secret(port->engine->libctx,1588port->engine->propq,1589&hdr.dst_conn_id,1590/* is_server */ 1,1591qrx, NULL))1592goto undesirable;15931594if (ossl_qrx_validate_initial_packet(qrx, e, (const QUIC_CONN_ID *)dcid) == 0)1595goto undesirable;15961597if (port->validate_addr == 0) {1598/*1599* Forget qrx, because it becomes (almost) useless here. We must let1600* channel to create a new QRX for connection ID server chooses. The1601* validation keys for new DCID will be derived by1602* ossl_quic_channel_on_new_conn() when we will be creating channel.1603* See RFC 9000 section 7.2 negotiating connection id to better1604* understand what's going on here.1605*1606* Did we say qrx is almost useless? Why? Because qrx remembers packets1607* we just validated. Those packets must be injected to channel we are1608* going to create. We use qrx_src alias so we can read packets from1609* qrx and inject them to channel.1610*/1611qrx_src = qrx;1612qrx = NULL;1613}1614/*1615* TODO(QUIC FUTURE): there should be some logic similar to accounting half-open1616* states in TCP. If we reach certain threshold, then we want to1617* validate clients.1618*/1619if (port->validate_addr == 1 && hdr.token == NULL) {1620port_send_retry(port, &e->peer, &hdr);1621goto undesirable;1622}16231624/*1625* Note, even if we don't enforce the sending of retry frames for1626* server address validation, we may still get a token if we sent1627* a NEW_TOKEN frame during a prior connection, which we should still1628* validate here1629*/1630if (hdr.token != NULL1631&& port_validate_token(&hdr, port, &e->peer,1632&odcid, &scid,1633&gen_new_token) == 0) {1634/*1635* RFC 9000 s 8.1.31636* When a server receives an Initial packet with an address1637* validation token, it MUST attempt to validate the token,1638* unless it has already completed address validation.1639* If the token is invalid, then the server SHOULD proceed as1640* if the client did not have a validated address,1641* including potentially sending a Retry packet1642* Note: If address validation is disabled, just act like1643* the request is valid1644*/1645if (port->validate_addr == 1) {1646/*1647* Again: we should consider saving initial encryption level1648* secrets to token here to save some CPU cycles.1649*/1650port_send_retry(port, &e->peer, &hdr);1651goto undesirable;1652}16531654/*1655* client is under amplification limit, until it completes1656* handshake.1657*1658* forget qrx so channel can create a new one1659* with valid initial encryption level keys.1660*/1661qrx_src = qrx;1662qrx = NULL;1663}16641665port_bind_channel(port, &e->peer, &scid, &hdr.dst_conn_id,1666&odcid, qrx, &new_ch);16671668/*1669* if packet validates it gets moved to channel, we've just bound1670* to port.1671*/1672if (new_ch == NULL)1673goto undesirable;16741675/*1676* Generate a token for sending in a later NEW_TOKEN frame1677*/1678if (gen_new_token == 1)1679generate_new_token(new_ch, &e->peer);16801681if (qrx != NULL) {1682/*1683* The qrx belongs to channel now, so don't free it.1684*/1685qrx = NULL;1686} else {1687/*1688* We still need to salvage packets from almost forgotten qrx1689* and pass them to channel.1690*/1691while (ossl_qrx_read_pkt(qrx_src, &qrx_pkt) == 1)1692ossl_quic_channel_inject_pkt(new_ch, qrx_pkt);1693ossl_qrx_update_pn_space(qrx_src, new_ch->qrx);1694}16951696/*1697* If function reaches this place, then packet got validated in1698* ossl_qrx_validate_initial_packet(). Keep in mind the function1699* ossl_qrx_validate_initial_packet() decrypts the packet to validate it.1700* If packet validation was successful (and it was because we are here),1701* then the function puts the packet to qrx->rx_pending. We must not call1702* ossl_qrx_inject_urxe() here now, because we don't want to insert1703* the packet to qrx->urx_pending which keeps packet waiting for decryption.1704*1705* We are going to call ossl_quic_demux_release_urxe() to dispose buffer1706* which still holds encrypted data.1707*/17081709undesirable:1710ossl_qrx_free(qrx);1711ossl_qrx_free(qrx_src);1712ossl_quic_demux_release_urxe(port->demux, e);1713}17141715void ossl_quic_port_raise_net_error(QUIC_PORT *port,1716QUIC_CHANNEL *triggering_ch)1717{1718QUIC_CHANNEL *ch;17191720if (!ossl_quic_port_is_running(port))1721return;17221723/*1724* Immediately capture any triggering error on the error stack, with a1725* cover error.1726*/1727ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,1728"port failed due to network BIO I/O error");1729OSSL_ERR_STATE_save(port->err_state);17301731port_transition_failed(port);17321733/* Give the triggering channel (if any) the first notification. */1734if (triggering_ch != NULL)1735ossl_quic_channel_raise_net_error(triggering_ch);17361737OSSL_LIST_FOREACH(ch, ch, &port->channel_list)1738if (ch != triggering_ch)1739ossl_quic_channel_raise_net_error(ch);1740}17411742void ossl_quic_port_restore_err_state(const QUIC_PORT *port)1743{1744ERR_clear_error();1745OSSL_ERR_STATE_restore(port->err_state);1746}174717481749