Home | History | Annotate | Line # | Download | only in quic
      1 /*
      2  * Copyright 2023-2026 The OpenSSL Project Authors. All Rights Reserved.
      3  *
      4  * Licensed under the Apache License 2.0 (the "License").  You may not use
      5  * this file except in compliance with the License.  You can obtain a copy
      6  * in the file LICENSE in the source distribution or at
      7  * https://www.openssl.org/source/license.html
      8  */
      9 
     10 #include "internal/quic_port.h"
     11 #include "internal/quic_channel.h"
     12 #include "internal/quic_lcidm.h"
     13 #include "internal/quic_srtm.h"
     14 #include "internal/quic_txp.h"
     15 #include "internal/ssl_unwrap.h"
     16 #include "quic_port_local.h"
     17 #include "quic_channel_local.h"
     18 #include "quic_engine_local.h"
     19 #include "quic_local.h"
     20 #include "../ssl_local.h"
     21 #include <openssl/rand.h>
     22 
     23 /*
     24  * QUIC Port Structure
     25  * ===================
     26  */
     27 #define INIT_DCID_LEN 8
     28 
     29 static int port_init(QUIC_PORT *port);
     30 static void port_cleanup(QUIC_PORT *port);
     31 static OSSL_TIME get_time(void *arg);
     32 static void port_default_packet_handler(QUIC_URXE *e, void *arg,
     33     const QUIC_CONN_ID *dcid);
     34 static void port_rx_pre(QUIC_PORT *port);
     35 
     36 /**
     37  * @struct validation_token
     38  * @brief Represents a validation token for secure connection handling.
     39  *
     40  * This struct is used to store information related to a validation token.
     41  *
     42  * @var validation_token::is_retry
     43  * True iff this validation token is for a token sent in a RETRY packet.
     44  * Otherwise, this token is from a NEW_TOKEN_packet. Iff this value is true,
     45  * then ODCID and RSCID are set.
     46  *
     47  * @var validation_token::timestamp
     48  * Time that the validation token was minted.
     49  *
     50  * @var validation_token::odcid
     51  * An original connection ID (`QUIC_CONN_ID`) used to identify the QUIC
     52  * connection. This ID helps associate the token with a specific connection.
     53  * This will only be valid for validation tokens from RETRY packets.
     54  *
     55  * @var validation_token::rscid
     56  * DCID that the client will use as the DCID of the subsequent initial packet
     57  * i.e the "new" DCID.
     58  * This will only be valid for validation tokens from RETRY packets.
     59  *
     60  * @var validation_token::remote_addr_len
     61  * Length of the following character array.
     62  *
     63  * @var validation_token::remote_addr
     64  * A character array holding the raw address of the client requesting the
     65  * connection.
     66  */
     67 typedef struct validation_token {
     68     OSSL_TIME timestamp;
     69     QUIC_CONN_ID odcid;
     70     QUIC_CONN_ID rscid;
     71     size_t remote_addr_len;
     72     unsigned char *remote_addr;
     73     unsigned char is_retry;
     74 } QUIC_VALIDATION_TOKEN;
     75 
     76 /*
     77  * Maximum length of a marshalled validation token.
     78  *
     79  * - timestamp is 8 bytes
     80  * - odcid and rscid are maximally 42 bytes in total
     81  * - remote_addr_len is a size_t (8 bytes)
     82  * - remote_addr is in the worst case 110 bytes (in the case of using a
     83  *   maximally sized AF_UNIX socket)
     84  * - is_retry is a single byte
     85  */
     86 #define MARSHALLED_TOKEN_MAX_LEN 169
     87 
     88 /*
     89  * Maximum length of an encrypted marshalled validation token.
     90  *
     91  * This will include the size of the marshalled validation token plus a 16 byte
     92  * tag and a 12 byte IV, so in total 197 bytes.
     93  */
     94 #define ENCRYPTED_TOKEN_MAX_LEN (MARSHALLED_TOKEN_MAX_LEN + 16 + 12)
     95 
     96 DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL);
     97 DEFINE_LIST_OF_IMPL(incoming_ch, QUIC_CHANNEL);
     98 DEFINE_LIST_OF_IMPL(port, QUIC_PORT);
     99 
    100 QUIC_PORT *ossl_quic_port_new(const QUIC_PORT_ARGS *args)
    101 {
    102     QUIC_PORT *port;
    103 
    104     if ((port = OPENSSL_zalloc(sizeof(QUIC_PORT))) == NULL)
    105         return NULL;
    106 
    107     port->engine = args->engine;
    108     port->channel_ctx = args->channel_ctx;
    109     port->is_multi_conn = args->is_multi_conn;
    110     port->validate_addr = args->do_addr_validation;
    111     port->get_conn_user_ssl = args->get_conn_user_ssl;
    112     port->user_ssl_arg = args->user_ssl_arg;
    113 
    114     if (!port_init(port)) {
    115         OPENSSL_free(port);
    116         return NULL;
    117     }
    118 
    119     return port;
    120 }
    121 
    122 void ossl_quic_port_free(QUIC_PORT *port)
    123 {
    124     if (port == NULL)
    125         return;
    126 
    127     port_cleanup(port);
    128     OPENSSL_free(port);
    129 }
    130 
    131 static int port_init(QUIC_PORT *port)
    132 {
    133     size_t rx_short_dcid_len = (port->is_multi_conn ? INIT_DCID_LEN : 0);
    134     int key_len;
    135     EVP_CIPHER *cipher = NULL;
    136     unsigned char *token_key = NULL;
    137     int ret = 0;
    138 
    139     if (port->engine == NULL || port->channel_ctx == NULL)
    140         goto err;
    141 
    142     if ((port->err_state = OSSL_ERR_STATE_new()) == NULL)
    143         goto err;
    144 
    145     if ((port->demux = ossl_quic_demux_new(/*BIO=*/NULL,
    146              /*Short CID Len=*/rx_short_dcid_len,
    147              get_time, port))
    148         == NULL)
    149         goto err;
    150 
    151     ossl_quic_demux_set_default_handler(port->demux,
    152         port_default_packet_handler,
    153         port);
    154 
    155     if ((port->srtm = ossl_quic_srtm_new(port->engine->libctx,
    156              port->engine->propq))
    157         == NULL)
    158         goto err;
    159 
    160     if ((port->lcidm = ossl_quic_lcidm_new(port->engine->libctx,
    161              rx_short_dcid_len))
    162         == NULL)
    163         goto err;
    164 
    165     port->rx_short_dcid_len = (unsigned char)rx_short_dcid_len;
    166     port->tx_init_dcid_len = INIT_DCID_LEN;
    167     port->state = QUIC_PORT_STATE_RUNNING;
    168 
    169     ossl_list_port_insert_tail(&port->engine->port_list, port);
    170     port->on_engine_list = 1;
    171     port->bio_changed = 1;
    172 
    173     /* Generate random key for token encryption */
    174     if ((port->token_ctx = EVP_CIPHER_CTX_new()) == NULL
    175         || (cipher = EVP_CIPHER_fetch(port->engine->libctx,
    176                 "AES-256-GCM", NULL))
    177             == NULL
    178         || !EVP_EncryptInit_ex(port->token_ctx, cipher, NULL, NULL, NULL)
    179         || (key_len = EVP_CIPHER_CTX_get_key_length(port->token_ctx)) <= 0
    180         || (token_key = OPENSSL_malloc(key_len)) == NULL
    181         || !RAND_bytes_ex(port->engine->libctx, token_key, key_len, 0)
    182         || !EVP_EncryptInit_ex(port->token_ctx, NULL, NULL, token_key, NULL))
    183         goto err;
    184 
    185     ret = 1;
    186 err:
    187     EVP_CIPHER_free(cipher);
    188     OPENSSL_free(token_key);
    189     if (!ret)
    190         port_cleanup(port);
    191     return ret;
    192 }
    193 
    194 static void port_cleanup(QUIC_PORT *port)
    195 {
    196     assert(ossl_list_ch_num(&port->channel_list) == 0);
    197 
    198     ossl_quic_demux_free(port->demux);
    199     port->demux = NULL;
    200 
    201     ossl_quic_srtm_free(port->srtm);
    202     port->srtm = NULL;
    203 
    204     ossl_quic_lcidm_free(port->lcidm);
    205     port->lcidm = NULL;
    206 
    207     OSSL_ERR_STATE_free(port->err_state);
    208     port->err_state = NULL;
    209 
    210     if (port->on_engine_list) {
    211         ossl_list_port_remove(&port->engine->port_list, port);
    212         port->on_engine_list = 0;
    213     }
    214 
    215     EVP_CIPHER_CTX_free(port->token_ctx);
    216     port->token_ctx = NULL;
    217 }
    218 
    219 static void port_transition_failed(QUIC_PORT *port)
    220 {
    221     if (port->state == QUIC_PORT_STATE_FAILED)
    222         return;
    223 
    224     port->state = QUIC_PORT_STATE_FAILED;
    225 }
    226 
    227 int ossl_quic_port_is_running(const QUIC_PORT *port)
    228 {
    229     return port->state == QUIC_PORT_STATE_RUNNING;
    230 }
    231 
    232 QUIC_ENGINE *ossl_quic_port_get0_engine(QUIC_PORT *port)
    233 {
    234     return port->engine;
    235 }
    236 
    237 QUIC_REACTOR *ossl_quic_port_get0_reactor(QUIC_PORT *port)
    238 {
    239     return ossl_quic_engine_get0_reactor(port->engine);
    240 }
    241 
    242 QUIC_DEMUX *ossl_quic_port_get0_demux(QUIC_PORT *port)
    243 {
    244     return port->demux;
    245 }
    246 
    247 CRYPTO_MUTEX *ossl_quic_port_get0_mutex(QUIC_PORT *port)
    248 {
    249     return ossl_quic_engine_get0_mutex(port->engine);
    250 }
    251 
    252 OSSL_TIME ossl_quic_port_get_time(QUIC_PORT *port)
    253 {
    254     return ossl_quic_engine_get_time(port->engine);
    255 }
    256 
    257 static OSSL_TIME get_time(void *port)
    258 {
    259     return ossl_quic_port_get_time((QUIC_PORT *)port);
    260 }
    261 
    262 int ossl_quic_port_get_rx_short_dcid_len(const QUIC_PORT *port)
    263 {
    264     return port->rx_short_dcid_len;
    265 }
    266 
    267 int ossl_quic_port_get_tx_init_dcid_len(const QUIC_PORT *port)
    268 {
    269     return port->tx_init_dcid_len;
    270 }
    271 
    272 size_t ossl_quic_port_get_num_incoming_channels(const QUIC_PORT *port)
    273 {
    274     return ossl_list_incoming_ch_num(&port->incoming_channel_list);
    275 }
    276 
    277 /*
    278  * QUIC Port: Network BIO Configuration
    279  * ====================================
    280  */
    281 
    282 /* Determines whether we can support a given poll descriptor. */
    283 static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
    284 {
    285     if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0) {
    286         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
    287         return 0;
    288     }
    289 
    290     return 1;
    291 }
    292 
    293 BIO *ossl_quic_port_get_net_rbio(QUIC_PORT *port)
    294 {
    295     return port->net_rbio;
    296 }
    297 
    298 BIO *ossl_quic_port_get_net_wbio(QUIC_PORT *port)
    299 {
    300     return port->net_wbio;
    301 }
    302 
    303 static int port_update_poll_desc(QUIC_PORT *port, BIO *net_bio, int for_write)
    304 {
    305     BIO_POLL_DESCRIPTOR d = { 0 };
    306 
    307     if (net_bio == NULL
    308         || (!for_write && !BIO_get_rpoll_descriptor(net_bio, &d))
    309         || (for_write && !BIO_get_wpoll_descriptor(net_bio, &d)))
    310         /* Non-pollable BIO */
    311         d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
    312 
    313     if (!validate_poll_descriptor(&d))
    314         return 0;
    315 
    316     /*
    317      * TODO(QUIC MULTIPORT): We currently only support one port per
    318      * engine/domain. This is necessitated because QUIC_REACTOR only supports a
    319      * single pollable currently. In the future, once complete polling
    320      * infrastructure has been implemented, this limitation can be removed.
    321      *
    322      * For now, just update the descriptor on the engine's reactor as we are
    323      * guaranteed to be the only port under it.
    324      */
    325     if (for_write)
    326         ossl_quic_reactor_set_poll_w(&port->engine->rtor, &d);
    327     else
    328         ossl_quic_reactor_set_poll_r(&port->engine->rtor, &d);
    329 
    330     return 1;
    331 }
    332 
    333 int ossl_quic_port_update_poll_descriptors(QUIC_PORT *port, int force)
    334 {
    335     int ok = 1;
    336 
    337     if (!force && !port->bio_changed)
    338         return 0;
    339 
    340     if (!port_update_poll_desc(port, port->net_rbio, /*for_write=*/0))
    341         ok = 0;
    342 
    343     if (!port_update_poll_desc(port, port->net_wbio, /*for_write=*/1))
    344         ok = 0;
    345 
    346     port->bio_changed = 0;
    347     return ok;
    348 }
    349 
    350 /*
    351  * We need to determine our addressing mode. There are basically two ways we can
    352  * use L4 addresses:
    353  *
    354  *   - Addressed mode, in which our BIO_sendmmsg calls have destination
    355  *     addresses attached to them which we expect the underlying network BIO to
    356  *     handle;
    357  *
    358  *   - Unaddressed mode, in which the BIO provided to us on the network side
    359  *     neither provides us with L4 addresses nor is capable of honouring ones we
    360  *     provide. We don't know where the QUIC traffic we send ends up exactly and
    361  *     trust the application to know what it is doing.
    362  *
    363  * Addressed mode is preferred because it enables support for connection
    364  * migration, multipath, etc. in the future. Addressed mode is automatically
    365  * enabled if we are using e.g. BIO_s_datagram, with or without BIO_s_connect.
    366  *
    367  * If we are passed a BIO_s_dgram_pair (or some custom BIO) we may have to use
    368  * unaddressed mode unless that BIO supports capability flags indicating it can
    369  * provide and honour L4 addresses.
    370  *
    371  * Our strategy for determining address mode is simple: we probe the underlying
    372  * network BIOs for their capabilities. If the network BIOs support what we
    373  * need, we use addressed mode. Otherwise, we use unaddressed mode.
    374  *
    375  * If addressed mode is chosen, we require an initial peer address to be set. If
    376  * this is not set, we fail. If unaddressed mode is used, we do not require
    377  * this, as such an address is superfluous, though it can be set if desired.
    378  */
    379 static void port_update_addressing_mode(QUIC_PORT *port)
    380 {
    381     long rcaps = 0, wcaps = 0;
    382 
    383     if (port->net_rbio != NULL)
    384         rcaps = BIO_dgram_get_effective_caps(port->net_rbio);
    385 
    386     if (port->net_wbio != NULL)
    387         wcaps = BIO_dgram_get_effective_caps(port->net_wbio);
    388 
    389     port->addressed_mode_r = ((rcaps & BIO_DGRAM_CAP_PROVIDES_SRC_ADDR) != 0);
    390     port->addressed_mode_w = ((wcaps & BIO_DGRAM_CAP_HANDLES_DST_ADDR) != 0);
    391     port->bio_changed = 1;
    392 }
    393 
    394 int ossl_quic_port_is_addressed_r(const QUIC_PORT *port)
    395 {
    396     return port->addressed_mode_r;
    397 }
    398 
    399 int ossl_quic_port_is_addressed_w(const QUIC_PORT *port)
    400 {
    401     return port->addressed_mode_w;
    402 }
    403 
    404 int ossl_quic_port_is_addressed(const QUIC_PORT *port)
    405 {
    406     return ossl_quic_port_is_addressed_r(port) && ossl_quic_port_is_addressed_w(port);
    407 }
    408 
    409 /*
    410  * QUIC_PORT does not ref any BIO it is provided with, nor is any ref
    411  * transferred to it. The caller (e.g., QUIC_CONNECTION) is responsible for
    412  * ensuring the BIO lasts until the channel is freed or the BIO is switched out
    413  * for another BIO by a subsequent successful call to this function.
    414  */
    415 int ossl_quic_port_set_net_rbio(QUIC_PORT *port, BIO *net_rbio)
    416 {
    417     if (port->net_rbio == net_rbio)
    418         return 1;
    419 
    420     if (!port_update_poll_desc(port, net_rbio, /*for_write=*/0))
    421         return 0;
    422 
    423     ossl_quic_demux_set_bio(port->demux, net_rbio);
    424     port->net_rbio = net_rbio;
    425     port_update_addressing_mode(port);
    426     return 1;
    427 }
    428 
    429 int ossl_quic_port_set_net_wbio(QUIC_PORT *port, BIO *net_wbio)
    430 {
    431     QUIC_CHANNEL *ch;
    432 
    433     if (port->net_wbio == net_wbio)
    434         return 1;
    435 
    436     if (!port_update_poll_desc(port, net_wbio, /*for_write=*/1))
    437         return 0;
    438 
    439     OSSL_LIST_FOREACH(ch, ch, &port->channel_list)
    440     ossl_qtx_set_bio(ch->qtx, net_wbio);
    441 
    442     port->net_wbio = net_wbio;
    443     port_update_addressing_mode(port);
    444     return 1;
    445 }
    446 
    447 SSL_CTX *ossl_quic_port_get_channel_ctx(QUIC_PORT *port)
    448 {
    449     return port->channel_ctx;
    450 }
    451 
    452 /*
    453  * QUIC Port: Channel Lifecycle
    454  * ============================
    455  */
    456 
    457 static SSL *port_new_handshake_layer(QUIC_PORT *port, QUIC_CHANNEL *ch)
    458 {
    459     SSL *tls = NULL;
    460     SSL_CONNECTION *tls_conn = NULL;
    461     SSL *user_ssl = NULL;
    462     QUIC_CONNECTION *qc = NULL;
    463     QUIC_LISTENER *ql = NULL;
    464 
    465     /*
    466      * It only makes sense to call this function if we know how to associate
    467      * the handshake layer we are about to create with some user_ssl object.
    468      */
    469     if (!ossl_assert(port->get_conn_user_ssl != NULL))
    470         return NULL;
    471     user_ssl = port->get_conn_user_ssl(ch, port->user_ssl_arg);
    472     if (user_ssl == NULL)
    473         return NULL;
    474     qc = (QUIC_CONNECTION *)user_ssl;
    475     ql = (QUIC_LISTENER *)port->user_ssl_arg;
    476 
    477     /*
    478      * We expect the user_ssl to be newly created so it must not have an
    479      * existing qc->tls
    480      */
    481     if (!ossl_assert(qc->tls == NULL)) {
    482         SSL_free(user_ssl);
    483         return NULL;
    484     }
    485 
    486     tls = ossl_ssl_connection_new_int(port->channel_ctx, user_ssl, TLS_method());
    487     qc->tls = tls;
    488     if (tls == NULL || (tls_conn = SSL_CONNECTION_FROM_SSL(tls)) == NULL) {
    489         SSL_free(user_ssl);
    490         return NULL;
    491     }
    492 
    493     if (ql != NULL && ql->obj.ssl.ctx->new_pending_conn_cb != NULL)
    494         if (!ql->obj.ssl.ctx->new_pending_conn_cb(ql->obj.ssl.ctx, user_ssl,
    495                 ql->obj.ssl.ctx->new_pending_conn_arg)) {
    496             SSL_free(user_ssl);
    497             return NULL;
    498         }
    499 
    500     /* Override the user_ssl of the inner connection. */
    501     tls_conn->s3.flags |= TLS1_FLAGS_QUIC | TLS1_FLAGS_QUIC_INTERNAL;
    502 
    503     /* Restrict options derived from the SSL_CTX. */
    504     tls_conn->options &= OSSL_QUIC_PERMITTED_OPTIONS_CONN;
    505     tls_conn->pha_enabled = 0;
    506     return tls;
    507 }
    508 
    509 static QUIC_CHANNEL *port_make_channel(QUIC_PORT *port, SSL *tls, OSSL_QRX *qrx,
    510     int is_server, int is_tserver)
    511 {
    512     QUIC_CHANNEL_ARGS args = { 0 };
    513     QUIC_CHANNEL *ch;
    514 
    515     args.port = port;
    516     args.is_server = is_server;
    517     args.lcidm = port->lcidm;
    518     args.srtm = port->srtm;
    519     args.qrx = qrx;
    520     args.is_tserver_ch = is_tserver;
    521 
    522     /*
    523      * Creating a a new channel is made a bit tricky here as there is a
    524      * bit of a circular dependency.  Initializing a channel requires that
    525      * the ch->tls and optionally the qlog_title be configured prior to
    526      * initialization, but we need the channel at least partially configured
    527      * to create the new handshake layer, so we have to do this in a few steps.
    528      */
    529 
    530     /*
    531      * start by allocation and provisioning as much of the channel as we can
    532      */
    533     ch = ossl_quic_channel_alloc(&args);
    534     if (ch == NULL)
    535         return NULL;
    536 
    537     /*
    538      * Fixup the channel tls connection here before we init the channel
    539      */
    540     ch->tls = (tls != NULL) ? tls : port_new_handshake_layer(port, ch);
    541 
    542     if (ch->tls == NULL) {
    543         OPENSSL_free(ch);
    544         return NULL;
    545     }
    546 
    547 #ifndef OPENSSL_NO_QLOG
    548     /*
    549      * If we're using qlog, make sure the tls get further configured properly
    550      */
    551     ch->use_qlog = 1;
    552     if (ch->tls != NULL && ch->tls->ctx->qlog_title != NULL) {
    553         OPENSSL_free(ch->qlog_title);
    554         if ((ch->qlog_title = OPENSSL_strdup(ch->tls->ctx->qlog_title)) == NULL) {
    555             ossl_quic_channel_free(ch);
    556             return NULL;
    557         }
    558     }
    559 #endif
    560 
    561     /*
    562      * And finally init the channel struct
    563      */
    564     if (!ossl_quic_channel_init(ch)) {
    565         OPENSSL_free(ch);
    566         return NULL;
    567     }
    568 
    569     ossl_qtx_set_bio(ch->qtx, port->net_wbio);
    570     return ch;
    571 }
    572 
    573 QUIC_CHANNEL *ossl_quic_port_create_outgoing(QUIC_PORT *port, SSL *tls)
    574 {
    575     return port_make_channel(port, tls, NULL, /* is_server= */ 0,
    576         /* is_tserver= */ 0);
    577 }
    578 
    579 QUIC_CHANNEL *ossl_quic_port_create_incoming(QUIC_PORT *port, SSL *tls)
    580 {
    581     QUIC_CHANNEL *ch;
    582 
    583     assert(port->tserver_ch == NULL);
    584 
    585     /*
    586      * pass -1 for qrx to indicate port will create qrx
    587      * later in port_default_packet_handler() when calling port_bind_channel().
    588      */
    589     ch = port_make_channel(port, tls, NULL, /* is_server= */ 1,
    590         /* is_tserver_ch */ 1);
    591     port->tserver_ch = ch;
    592     port->allow_incoming = 1;
    593     return ch;
    594 }
    595 
    596 QUIC_CHANNEL *ossl_quic_port_pop_incoming(QUIC_PORT *port)
    597 {
    598     QUIC_CHANNEL *ch;
    599 
    600     ch = ossl_list_incoming_ch_head(&port->incoming_channel_list);
    601     if (ch == NULL)
    602         return NULL;
    603 
    604     ossl_list_incoming_ch_remove(&port->incoming_channel_list, ch);
    605     return ch;
    606 }
    607 
    608 int ossl_quic_port_have_incoming(QUIC_PORT *port)
    609 {
    610     return ossl_list_incoming_ch_head(&port->incoming_channel_list) != NULL;
    611 }
    612 
    613 void ossl_quic_port_drop_incoming(QUIC_PORT *port)
    614 {
    615     QUIC_CHANNEL *ch;
    616     SSL *tls;
    617     SSL *user_ssl;
    618     SSL_CONNECTION *sc;
    619 
    620     for (;;) {
    621         ch = ossl_quic_port_pop_incoming(port);
    622         if (ch == NULL)
    623             break;
    624 
    625         tls = ossl_quic_channel_get0_tls(ch);
    626         /*
    627          * The user ssl may or may not have been created via the
    628          * get_conn_user_ssl callback in the QUIC stack.  The
    629          * differentiation being if the user_ssl pointer and tls pointer
    630          * are different.  If they are, then the user_ssl needs freeing here
    631          * which sends us through ossl_quic_free, which then drops the actual
    632          * ch->tls ref and frees the channel
    633          */
    634         sc = SSL_CONNECTION_FROM_SSL(tls);
    635         if (sc == NULL)
    636             break;
    637 
    638         user_ssl = SSL_CONNECTION_GET_USER_SSL(sc);
    639         if (user_ssl == tls) {
    640             ossl_quic_channel_free(ch);
    641             SSL_free(tls);
    642         } else {
    643             SSL_free(user_ssl);
    644         }
    645     }
    646 }
    647 
    648 void ossl_quic_port_set_allow_incoming(QUIC_PORT *port, int allow_incoming)
    649 {
    650     port->allow_incoming = allow_incoming;
    651 }
    652 
    653 /*
    654  * QUIC Port: Ticker-Mutator
    655  * =========================
    656  */
    657 
    658 /*
    659  * Tick function for this port. This does everything related to network I/O for
    660  * this port's network BIOs, and services child channels.
    661  */
    662 void ossl_quic_port_subtick(QUIC_PORT *port, QUIC_TICK_RESULT *res,
    663     uint32_t flags)
    664 {
    665     QUIC_CHANNEL *ch;
    666 
    667     res->net_read_desired = ossl_quic_port_is_running(port);
    668     res->net_write_desired = 0;
    669     res->notify_other_threads = 0;
    670     res->tick_deadline = ossl_time_infinite();
    671 
    672     if (!port->engine->inhibit_tick) {
    673         /* Handle any incoming data from network. */
    674         if (ossl_quic_port_is_running(port))
    675             port_rx_pre(port);
    676 
    677         /* Iterate through all channels and service them. */
    678         OSSL_LIST_FOREACH(ch, ch, &port->channel_list)
    679         {
    680             QUIC_TICK_RESULT subr = { 0 };
    681 
    682             ossl_quic_channel_subtick(ch, &subr, flags);
    683             ossl_quic_tick_result_merge_into(res, &subr);
    684         }
    685     }
    686 }
    687 
    688 /* Process incoming datagrams, if any. */
    689 static void port_rx_pre(QUIC_PORT *port)
    690 {
    691     int ret;
    692 
    693     /*
    694      * Originally, this check (don't RX before we have sent anything if we are
    695      * not a server, because there can't be anything) was just intended as a
    696      * minor optimisation. However, it is actually required on Windows, and
    697      * removing this check will cause Windows to break.
    698      *
    699      * The reason is that under Win32, recvfrom() does not work on a UDP socket
    700      * which has not had bind() called (???). However, calling sendto() will
    701      * automatically bind an unbound UDP socket. Therefore, if we call a Winsock
    702      * recv-type function before calling a Winsock send-type function, that call
    703      * will fail with WSAEINVAL, which we will regard as a permanent network
    704      * error.
    705      *
    706      * Therefore, this check is essential as we do not require our API users to
    707      * bind a socket first when using the API in client mode.
    708      */
    709     if (!port->allow_incoming && !port->have_sent_any_pkt)
    710         return;
    711 
    712     /*
    713      * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
    714      * to the appropriate QRX instances.
    715      */
    716     ret = ossl_quic_demux_pump(port->demux);
    717     if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
    718         /*
    719          * We don't care about transient failure, but permanent failure means we
    720          * should tear down the port. All connections skip straight to the
    721          * Terminated state as there is no point trying to send CONNECTION_CLOSE
    722          * frames if the network BIO is not operating correctly.
    723          */
    724         ossl_quic_port_raise_net_error(port, NULL);
    725 }
    726 
    727 /*
    728  * Handles an incoming connection request and potentially decides to make a
    729  * connection from it. If a new connection is made, the new channel is written
    730  * to *new_ch.
    731  */
    732 static void port_bind_channel(QUIC_PORT *port, const BIO_ADDR *peer,
    733     const QUIC_CONN_ID *dcid,
    734     const QUIC_CONN_ID *odcid, OSSL_QRX *qrx,
    735     QUIC_CHANNEL **new_ch)
    736 {
    737     QUIC_CHANNEL *ch;
    738 
    739     /*
    740      * If we're running with a simulated tserver, it will already have
    741      * a dummy channel created, use that instead
    742      */
    743     if (port->tserver_ch != NULL) {
    744         ch = port->tserver_ch;
    745         port->tserver_ch = NULL;
    746         ossl_quic_channel_bind_qrx(ch, qrx);
    747         ossl_qrx_set_msg_callback(ch->qrx, ch->msg_callback,
    748             ch->msg_callback_ssl);
    749         ossl_qrx_set_msg_callback_arg(ch->qrx, ch->msg_callback_arg);
    750     } else {
    751         ch = port_make_channel(port, NULL, qrx, /* is_server= */ 1,
    752             /* is_tserver */ 0);
    753     }
    754 
    755     if (ch == NULL)
    756         return;
    757 
    758     /*
    759      * If we didn't provide a qrx here that means we need to set our initial
    760      * secret here, since we just created a qrx
    761      * Normally its not needed, as the initial secret gets added when we send
    762      * our first server hello, but if we get a huge client hello, crossing
    763      * multiple datagrams, we don't have a chance to do that, and datagrams
    764      * after the first won't get decoded properly, for lack of secrets
    765      */
    766     if (qrx == NULL)
    767         if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,
    768                 ch->port->engine->propq,
    769                 dcid, /* is_server */ 1,
    770                 ch->qrx, NULL)) {
    771             ossl_quic_channel_free(ch);
    772             return;
    773         }
    774 
    775     if (odcid->id_len != 0) {
    776         /*
    777          * If we have an odcid, then we went through server address validation
    778          * and as such, this channel need not conform to the 3x validation cap
    779          * See RFC 9000 s. 8.1
    780          */
    781         ossl_quic_tx_packetiser_set_validated(ch->txp);
    782         if (!ossl_quic_bind_channel(ch, peer, dcid, odcid)) {
    783             ossl_quic_channel_free(ch);
    784             return;
    785         }
    786     } else {
    787         /*
    788          * No odcid means we didn't do server validation, so we need to
    789          * generate a cid via ossl_quic_channel_on_new_conn
    790          */
    791         if (!ossl_quic_channel_on_new_conn(ch, peer, dcid)) {
    792             ossl_quic_channel_free(ch);
    793             return;
    794         }
    795     }
    796 
    797     ossl_list_incoming_ch_insert_tail(&port->incoming_channel_list, ch);
    798     *new_ch = ch;
    799 }
    800 
    801 static int port_try_handle_stateless_reset(QUIC_PORT *port, const QUIC_URXE *e)
    802 {
    803     size_t i;
    804     const unsigned char *data = ossl_quic_urxe_data(e);
    805     void *opaque = NULL;
    806 
    807     /*
    808      * Perform some fast and cheap checks for a packet not being a stateless
    809      * reset token.  RFC 9000 s. 10.3 specifies this layout for stateless
    810      * reset packets:
    811      *
    812      *  Stateless Reset {
    813      *      Fixed Bits (2) = 1,
    814      *      Unpredictable Bits (38..),
    815      *      Stateless Reset Token (128),
    816      *  }
    817      *
    818      * It also specifies:
    819      *      However, endpoints MUST treat any packet ending in a valid
    820      *      stateless reset token as a Stateless Reset, as other QUIC
    821      *      versions might allow the use of a long header.
    822      *
    823      * We can rapidly check for the minimum length and that the first pair
    824      * of bits in the first byte are 01 or 11.
    825      *
    826      * The function returns 1 if it is a stateless reset packet, 0 if it isn't
    827      * and -1 if an error was encountered.
    828      */
    829     if (e->data_len < QUIC_STATELESS_RESET_TOKEN_LEN + 5
    830         || (0100 & *data) != 0100)
    831         return 0;
    832 
    833     for (i = 0;; ++i) {
    834         if (!ossl_quic_srtm_lookup(port->srtm,
    835                 (QUIC_STATELESS_RESET_TOKEN *)(data + e->data_len
    836                     - sizeof(QUIC_STATELESS_RESET_TOKEN)),
    837                 i, &opaque, NULL))
    838             break;
    839 
    840         assert(opaque != NULL);
    841         ossl_quic_channel_on_stateless_reset((QUIC_CHANNEL *)opaque);
    842     }
    843 
    844     return i > 0;
    845 }
    846 
    847 static void cleanup_validation_token(QUIC_VALIDATION_TOKEN *token)
    848 {
    849     OPENSSL_free(token->remote_addr);
    850 }
    851 
    852 /**
    853  * @brief Generates a validation token for a RETRY/NEW_TOKEN packet.
    854  *
    855  *
    856  * @param peer  Address of the client peer receiving the packet.
    857  * @param odcid DCID of the connection attempt.
    858  * @param rscid Retry source connection ID of the connection attempt.
    859  * @param token Address of token to fill data.
    860  *
    861  * @return 1 if validation token is filled successfully, 0 otherwise.
    862  */
    863 static int generate_token(BIO_ADDR *peer, QUIC_CONN_ID odcid,
    864     QUIC_CONN_ID rscid, QUIC_VALIDATION_TOKEN *token,
    865     int is_retry)
    866 {
    867     token->is_retry = is_retry;
    868     token->timestamp = ossl_time_now();
    869     token->remote_addr = NULL;
    870     token->odcid = odcid;
    871     token->rscid = rscid;
    872 
    873     if (!BIO_ADDR_rawaddress(peer, NULL, &token->remote_addr_len)
    874         || token->remote_addr_len == 0
    875         || (token->remote_addr = OPENSSL_malloc(token->remote_addr_len)) == NULL
    876         || !BIO_ADDR_rawaddress(peer, token->remote_addr,
    877             &token->remote_addr_len)) {
    878         cleanup_validation_token(token);
    879         return 0;
    880     }
    881 
    882     return 1;
    883 }
    884 
    885 /**
    886  * @brief Marshals a validation token into a new buffer.
    887  *
    888  * |buffer| should already be allocated and at least MARSHALLED_TOKEN_MAX_LEN
    889  * bytes long. Stores the length of data stored in |buffer| in |buffer_len|.
    890  *
    891  * @param token      Validation token.
    892  * @param buffer     Address to store the marshalled token.
    893  * @param buffer_len Size of data stored in |buffer|.
    894  */
    895 static int marshal_validation_token(QUIC_VALIDATION_TOKEN *token,
    896     unsigned char *buffer, size_t *buffer_len)
    897 {
    898     WPACKET wpkt = { 0 };
    899     BUF_MEM *buf_mem = BUF_MEM_new();
    900 
    901     if (buffer == NULL || buf_mem == NULL
    902         || (token->is_retry != 0 && token->is_retry != 1)) {
    903         BUF_MEM_free(buf_mem);
    904         return 0;
    905     }
    906 
    907     if (!WPACKET_init(&wpkt, buf_mem)
    908         || !WPACKET_memset(&wpkt, token->is_retry, 1)
    909         || !WPACKET_memcpy(&wpkt, &token->timestamp,
    910             sizeof(token->timestamp))
    911         || (token->is_retry
    912             && (!WPACKET_sub_memcpy_u8(&wpkt, &token->odcid.id,
    913                     token->odcid.id_len)
    914                 || !WPACKET_sub_memcpy_u8(&wpkt, &token->rscid.id,
    915                     token->rscid.id_len)))
    916         || !WPACKET_sub_memcpy_u8(&wpkt, token->remote_addr, token->remote_addr_len)
    917         || !WPACKET_get_total_written(&wpkt, buffer_len)
    918         || *buffer_len > MARSHALLED_TOKEN_MAX_LEN
    919         || !WPACKET_finish(&wpkt)) {
    920         WPACKET_cleanup(&wpkt);
    921         BUF_MEM_free(buf_mem);
    922         return 0;
    923     }
    924 
    925     memcpy(buffer, buf_mem->data, *buffer_len);
    926     BUF_MEM_free(buf_mem);
    927     return 1;
    928 }
    929 
    930 /**
    931  * @brief Encrypts a validation token using AES-256-GCM
    932  *
    933  * @param port       The QUIC port containing the encryption key
    934  * @param plaintext  The data to encrypt
    935  * @param pt_len     Length of the plaintext
    936  * @param ciphertext Buffer to receive encrypted data. If NULL, ct_len will be
    937  *                   set to the required buffer size and function returns
    938  *                   immediately.
    939  * @param ct_len     Pointer to size_t that will receive the ciphertext length.
    940  *                   This also includes bytes for QUIC_RETRY_INTEGRITY_TAG_LEN.
    941  *
    942  * @return 1 on success, 0 on failure
    943  *
    944  * The ciphertext format is:
    945  * [EVP_GCM_IV_LEN bytes IV][encrypted data][EVP_GCM_TAG_LEN bytes tag]
    946  */
    947 static int encrypt_validation_token(const QUIC_PORT *port,
    948     const unsigned char *plaintext,
    949     size_t pt_len,
    950     unsigned char *ciphertext,
    951     size_t *ct_len)
    952 {
    953     int iv_len, len, ret = 0;
    954     size_t tag_len;
    955     unsigned char *iv = ciphertext, *data, *tag;
    956 
    957     if ((tag_len = EVP_CIPHER_CTX_get_tag_length(port->token_ctx)) == 0
    958         || (iv_len = EVP_CIPHER_CTX_get_iv_length(port->token_ctx)) <= 0)
    959         goto err;
    960 
    961     *ct_len = iv_len + pt_len + tag_len + QUIC_RETRY_INTEGRITY_TAG_LEN;
    962     if (ciphertext == NULL) {
    963         ret = 1;
    964         goto err;
    965     }
    966 
    967     data = ciphertext + iv_len;
    968     tag = data + pt_len;
    969 
    970     if (!RAND_bytes_ex(port->engine->libctx, ciphertext, iv_len, 0)
    971         || !EVP_EncryptInit_ex(port->token_ctx, NULL, NULL, NULL, iv)
    972         || !EVP_EncryptUpdate(port->token_ctx, data, &len, plaintext, pt_len)
    973         || !EVP_EncryptFinal_ex(port->token_ctx, data + pt_len, &len)
    974         || !EVP_CIPHER_CTX_ctrl(port->token_ctx, EVP_CTRL_GCM_GET_TAG, tag_len, tag))
    975         goto err;
    976 
    977     ret = 1;
    978 err:
    979     return ret;
    980 }
    981 
    982 /**
    983  * @brief Decrypts a validation token using AES-256-GCM
    984  *
    985  * @param port       The QUIC port containing the decryption key
    986  * @param ciphertext The encrypted data (including IV and tag)
    987  * @param ct_len     Length of the ciphertext
    988  * @param plaintext  Buffer to receive decrypted data. If NULL, pt_len will be
    989  *                   set to the required buffer size.
    990  * @param pt_len     Pointer to size_t that will receive the plaintext length
    991  *
    992  * @return 1 on success, 0 on failure
    993  *
    994  * Expected ciphertext format:
    995  * [EVP_GCM_IV_LEN bytes IV][encrypted data][EVP_GCM_TAG_LEN bytes tag]
    996  */
    997 static int decrypt_validation_token(const QUIC_PORT *port,
    998     const unsigned char *ciphertext,
    999     size_t ct_len,
   1000     unsigned char *plaintext,
   1001     size_t *pt_len)
   1002 {
   1003     int iv_len, len = 0, ret = 0;
   1004     size_t tag_len;
   1005     const unsigned char *iv = ciphertext, *data, *tag;
   1006 
   1007     if ((tag_len = EVP_CIPHER_CTX_get_tag_length(port->token_ctx)) == 0
   1008         || (iv_len = EVP_CIPHER_CTX_get_iv_length(port->token_ctx)) <= 0)
   1009         goto err;
   1010 
   1011     /* Prevent decryption of a buffer that is not within reasonable bounds */
   1012     if (ct_len < (iv_len + tag_len) || ct_len > ENCRYPTED_TOKEN_MAX_LEN)
   1013         goto err;
   1014 
   1015     *pt_len = ct_len - iv_len - tag_len;
   1016     if (plaintext == NULL) {
   1017         ret = 1;
   1018         goto err;
   1019     }
   1020 
   1021     data = ciphertext + iv_len;
   1022     tag = ciphertext + ct_len - tag_len;
   1023 
   1024     if (!EVP_DecryptInit_ex(port->token_ctx, NULL, NULL, NULL, iv)
   1025         || !EVP_DecryptUpdate(port->token_ctx, plaintext, &len, data,
   1026             ct_len - iv_len - tag_len)
   1027         || !EVP_CIPHER_CTX_ctrl(port->token_ctx, EVP_CTRL_GCM_SET_TAG, tag_len,
   1028             (void *)tag)
   1029         || !EVP_DecryptFinal_ex(port->token_ctx, plaintext + len, &len))
   1030         goto err;
   1031 
   1032     ret = 1;
   1033 
   1034 err:
   1035     return ret;
   1036 }
   1037 
   1038 /**
   1039  * @brief Parses contents of a buffer into a validation token.
   1040  *
   1041  * VALIDATION_TOKEN should already be initialized. Does some basic sanity checks.
   1042  *
   1043  * @param token   Validation token to fill data in.
   1044  * @param buf     Buffer of previously marshaled validation token.
   1045  * @param buf_len Length of |buf|.
   1046  */
   1047 static int parse_validation_token(QUIC_VALIDATION_TOKEN *token,
   1048     const unsigned char *buf, size_t buf_len)
   1049 {
   1050     PACKET pkt, subpkt;
   1051 
   1052     if (buf == NULL || token == NULL)
   1053         return 0;
   1054 
   1055     token->remote_addr = NULL;
   1056 
   1057     if (!PACKET_buf_init(&pkt, buf, buf_len)
   1058         || !PACKET_copy_bytes(&pkt, &token->is_retry, sizeof(token->is_retry))
   1059         || !(token->is_retry == 0 || token->is_retry == 1)
   1060         || !PACKET_copy_bytes(&pkt, (unsigned char *)&token->timestamp,
   1061             sizeof(token->timestamp))
   1062         || (token->is_retry
   1063             && (!PACKET_get_length_prefixed_1(&pkt, &subpkt)
   1064                 || (token->odcid.id_len = (unsigned char)PACKET_remaining(&subpkt))
   1065                     > QUIC_MAX_CONN_ID_LEN
   1066                 || !PACKET_copy_bytes(&subpkt,
   1067                     (unsigned char *)&token->odcid.id,
   1068                     token->odcid.id_len)
   1069                 || !PACKET_get_length_prefixed_1(&pkt, &subpkt)
   1070                 || (token->rscid.id_len = (unsigned char)PACKET_remaining(&subpkt))
   1071                     > QUIC_MAX_CONN_ID_LEN
   1072                 || !PACKET_copy_bytes(&subpkt, (unsigned char *)&token->rscid.id,
   1073                     token->rscid.id_len)))
   1074         || !PACKET_get_length_prefixed_1(&pkt, &subpkt)
   1075         || (token->remote_addr_len = PACKET_remaining(&subpkt)) == 0
   1076         || (token->remote_addr = OPENSSL_malloc(token->remote_addr_len)) == NULL
   1077         || !PACKET_copy_bytes(&subpkt, token->remote_addr, token->remote_addr_len)
   1078         || PACKET_remaining(&pkt) != 0) {
   1079         cleanup_validation_token(token);
   1080         return 0;
   1081     }
   1082 
   1083     return 1;
   1084 }
   1085 
   1086 /**
   1087  * @brief Sends a QUIC Retry packet to a client.
   1088  *
   1089  * This function constructs and sends a Retry packet to the specified client
   1090  * using the provided connection header information. The Retry packet
   1091  * includes a generated validation token and a new connection ID, following
   1092  * the QUIC protocol specifications for connection establishment.
   1093  *
   1094  * @param port        Pointer to the QUIC port from which to send the packet.
   1095  * @param peer        Address of the client peer receiving the packet.
   1096  * @param client_hdr  Header of the client's initial packet, containing
   1097  *                    connection IDs and other relevant information.
   1098  *
   1099  * This function performs the following steps:
   1100  * - Generates a validation token for the client.
   1101  * - Sets the destination and source connection IDs.
   1102  * - Calculates the integrity tag and sets the token length.
   1103  * - Encodes and sends the packet via the BIO network interface.
   1104  *
   1105  * Error handling is included for failures in CID generation, encoding, and
   1106  * network transmiss
   1107  */
   1108 static void port_send_retry(QUIC_PORT *port,
   1109     BIO_ADDR *peer,
   1110     QUIC_PKT_HDR *client_hdr)
   1111 {
   1112     BIO_MSG msg[1];
   1113     /*
   1114      * Buffer is used for both marshalling the token as well as for the RETRY
   1115      * packet. The size of buffer should not be less than
   1116      * MARSHALLED_TOKEN_MAX_LEN.
   1117      */
   1118     unsigned char buffer[512];
   1119     unsigned char ct_buf[ENCRYPTED_TOKEN_MAX_LEN];
   1120     WPACKET wpkt;
   1121     size_t written, token_buf_len, ct_len;
   1122     QUIC_PKT_HDR hdr = { 0 };
   1123     QUIC_VALIDATION_TOKEN token = { 0 };
   1124     int ok;
   1125 
   1126     if (!ossl_assert(sizeof(buffer) >= MARSHALLED_TOKEN_MAX_LEN))
   1127         return;
   1128     /*
   1129      * 17.2.5.1 Sending a Retry packet
   1130      *   dst ConnId is src ConnId we got from client
   1131      *   src ConnId comes from local conn ID manager
   1132      */
   1133     memset(&hdr, 0, sizeof(QUIC_PKT_HDR));
   1134     hdr.dst_conn_id = client_hdr->src_conn_id;
   1135     /*
   1136      * this is the random connection ID, we expect client is
   1137      * going to send the ID with next INITIAL packet which
   1138      * will also come with token we generate here.
   1139      */
   1140     ok = ossl_quic_lcidm_get_unused_cid(port->lcidm, &hdr.src_conn_id);
   1141     if (ok == 0)
   1142         goto err;
   1143 
   1144     memset(&token, 0, sizeof(QUIC_VALIDATION_TOKEN));
   1145 
   1146     /* Generate retry validation token */
   1147     if (!generate_token(peer, client_hdr->dst_conn_id,
   1148             hdr.src_conn_id, &token, 1)
   1149         || !marshal_validation_token(&token, buffer, &token_buf_len)
   1150         || !encrypt_validation_token(port, buffer, token_buf_len, NULL,
   1151             &ct_len)
   1152         || ct_len > ENCRYPTED_TOKEN_MAX_LEN
   1153         || !encrypt_validation_token(port, buffer, token_buf_len, ct_buf,
   1154             &ct_len)
   1155         || !ossl_assert(ct_len >= QUIC_RETRY_INTEGRITY_TAG_LEN))
   1156         goto err;
   1157 
   1158     hdr.dst_conn_id = client_hdr->src_conn_id;
   1159     hdr.type = QUIC_PKT_TYPE_RETRY;
   1160     hdr.fixed = 1;
   1161     hdr.version = 1;
   1162     hdr.len = ct_len;
   1163     hdr.data = ct_buf;
   1164     ok = ossl_quic_calculate_retry_integrity_tag(port->engine->libctx,
   1165         port->engine->propq, &hdr,
   1166         &client_hdr->dst_conn_id,
   1167         ct_buf + ct_len
   1168             - QUIC_RETRY_INTEGRITY_TAG_LEN);
   1169     if (ok == 0)
   1170         goto err;
   1171 
   1172     hdr.token = hdr.data;
   1173     hdr.token_len = hdr.len;
   1174 
   1175     msg[0].data = buffer;
   1176     msg[0].peer = peer;
   1177     msg[0].local = NULL;
   1178     msg[0].flags = 0;
   1179 
   1180     ok = WPACKET_init_static_len(&wpkt, buffer, sizeof(buffer), 0);
   1181     if (ok == 0)
   1182         goto err;
   1183 
   1184     ok = ossl_quic_wire_encode_pkt_hdr(&wpkt, client_hdr->dst_conn_id.id_len,
   1185         &hdr, NULL);
   1186     if (ok == 0)
   1187         goto err;
   1188 
   1189     ok = WPACKET_get_total_written(&wpkt, &msg[0].data_len);
   1190     if (ok == 0)
   1191         goto err;
   1192 
   1193     ok = WPACKET_finish(&wpkt);
   1194     if (ok == 0)
   1195         goto err;
   1196 
   1197     /*
   1198      * TODO(QUIC FUTURE) need to retry this in the event it return EAGAIN
   1199      * on a non-blocking BIO
   1200      */
   1201     if (!BIO_sendmmsg(port->net_wbio, msg, sizeof(BIO_MSG), 1, 0, &written))
   1202         ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,
   1203             "port retry send failed due to network BIO I/O error");
   1204 
   1205 err:
   1206     cleanup_validation_token(&token);
   1207 }
   1208 
   1209 /**
   1210  * @brief Sends a QUIC Version Negotiation packet to the specified peer.
   1211  *
   1212  * This function constructs and sends a Version Negotiation packet using
   1213  * the connection IDs from the client's initial packet header. The
   1214  * Version Negotiation packet indicates support for QUIC version 1.
   1215  *
   1216  * @param port      Pointer to the QUIC_PORT structure representing the port
   1217  *                  context used for network communication.
   1218  * @param peer      Pointer to the BIO_ADDR structure specifying the address
   1219  *                  of the peer to which the Version Negotiation packet
   1220  *                  will be sent.
   1221  * @param client_hdr Pointer to the QUIC_PKT_HDR structure containing the
   1222  *                  client's packet header used to extract connection IDs.
   1223  *
   1224  * @note The function will raise an error if sending the message fails.
   1225  */
   1226 static void port_send_version_negotiation(QUIC_PORT *port, BIO_ADDR *peer,
   1227     QUIC_PKT_HDR *client_hdr)
   1228 {
   1229     BIO_MSG msg[1];
   1230     unsigned char buffer[1024];
   1231     QUIC_PKT_HDR hdr;
   1232     WPACKET wpkt;
   1233     uint32_t supported_versions[1];
   1234     size_t written;
   1235     size_t i;
   1236 
   1237     memset(&hdr, 0, sizeof(QUIC_PKT_HDR));
   1238     /*
   1239      * Reverse the source and dst conn ids
   1240      */
   1241     hdr.dst_conn_id = client_hdr->src_conn_id;
   1242     hdr.src_conn_id = client_hdr->dst_conn_id;
   1243 
   1244     /*
   1245      * This is our list of supported protocol versions
   1246      * Currently only QUIC_VERSION_1
   1247      */
   1248     supported_versions[0] = QUIC_VERSION_1;
   1249 
   1250     /*
   1251      * Fill out the header fields
   1252      * Note: Version negotiation packets, must, unlike
   1253      * other packet types have a version of 0
   1254      */
   1255     hdr.type = QUIC_PKT_TYPE_VERSION_NEG;
   1256     hdr.version = 0;
   1257     hdr.token = 0;
   1258     hdr.token_len = 0;
   1259     hdr.len = sizeof(supported_versions);
   1260     hdr.data = (unsigned char *)supported_versions;
   1261 
   1262     msg[0].data = buffer;
   1263     msg[0].peer = peer;
   1264     msg[0].local = NULL;
   1265     msg[0].flags = 0;
   1266 
   1267     if (!WPACKET_init_static_len(&wpkt, buffer, sizeof(buffer), 0))
   1268         return;
   1269 
   1270     if (!ossl_quic_wire_encode_pkt_hdr(&wpkt, client_hdr->dst_conn_id.id_len,
   1271             &hdr, NULL))
   1272         return;
   1273 
   1274     /*
   1275      * Add the array of supported versions to the end of the packet
   1276      */
   1277     for (i = 0; i < OSSL_NELEM(supported_versions); i++) {
   1278         if (!WPACKET_put_bytes_u32(&wpkt, supported_versions[i]))
   1279             return;
   1280     }
   1281 
   1282     if (!WPACKET_get_total_written(&wpkt, &msg[0].data_len))
   1283         return;
   1284 
   1285     if (!WPACKET_finish(&wpkt))
   1286         return;
   1287 
   1288     /*
   1289      * Send it back to the client attempting to connect
   1290      * TODO(QUIC FUTURE): Need to handle the EAGAIN case here, if the
   1291      * BIO_sendmmsg call falls in a retryable manner
   1292      */
   1293     if (!BIO_sendmmsg(port->net_wbio, msg, sizeof(BIO_MSG), 1, 0, &written))
   1294         ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,
   1295             "port version negotiation send failed");
   1296 }
   1297 
   1298 /**
   1299  * @brief definitions of token lifetimes
   1300  *
   1301  * RETRY tokens are only valid for 10 seconds
   1302  * NEW_TOKEN tokens have a lifetime of 3600 sec (1 hour)
   1303  */
   1304 
   1305 #define RETRY_LIFETIME 10
   1306 #define NEW_TOKEN_LIFETIME 3600
   1307 /**
   1308  * @brief Validates a received token in a QUIC packet header.
   1309  *
   1310  * This function checks the validity of a token contained in the provided
   1311  * QUIC packet header (`QUIC_PKT_HDR *hdr`). The validation process involves
   1312  * verifying that the token matches an expected format and value. If the
   1313  * token is from a RETRY packet, the function extracts the original connection
   1314  * ID (ODCID)/original source connection ID (SCID) and stores it in the provided
   1315  * parameters. If the token is from a NEW_TOKEN packet, the values will be
   1316  * derived instead.
   1317  *
   1318  * @param hdr   Pointer to the QUIC packet header containing the token.
   1319  * @param port  Pointer to the QUIC port from which to send the packet.
   1320  * @param peer  Address of the client peer receiving the packet.
   1321  * @param odcid Pointer to the connection ID structure to store the ODCID if the
   1322  *              token is valid.
   1323  * @param scid  Pointer to the connection ID structure to store the SCID if the
   1324  *              token is valid.
   1325  *
   1326  * @return      1 if the token is valid and ODCID/SCID are successfully set.
   1327  *              0 otherwise.
   1328  *
   1329  * The function performs the following checks:
   1330  * - Token length meets the required minimum.
   1331  * - Buffer matches expected format.
   1332  * - Peer address matches previous connection address.
   1333  * - Token has not expired. Currently set to 10 seconds for tokens from RETRY
   1334  *   packets and 60 minutes for tokens from NEW_TOKEN packets. This may be
   1335  *   configurable in the future.
   1336  */
   1337 static int port_validate_token(QUIC_PKT_HDR *hdr, QUIC_PORT *port,
   1338     BIO_ADDR *peer, QUIC_CONN_ID *odcid, uint8_t *gen_new_token)
   1339 {
   1340     int ret = 0;
   1341     QUIC_VALIDATION_TOKEN token = { 0 };
   1342     uint64_t time_diff;
   1343     size_t remote_addr_len, dec_token_len;
   1344     unsigned char *remote_addr = NULL, dec_token[MARSHALLED_TOKEN_MAX_LEN];
   1345     OSSL_TIME now = ossl_time_now();
   1346 
   1347     *gen_new_token = 0;
   1348 
   1349     if (!decrypt_validation_token(port, hdr->token, hdr->token_len, NULL,
   1350             &dec_token_len)
   1351         || dec_token_len > MARSHALLED_TOKEN_MAX_LEN
   1352         || !decrypt_validation_token(port, hdr->token, hdr->token_len,
   1353             dec_token, &dec_token_len)
   1354         || !parse_validation_token(&token, dec_token, dec_token_len))
   1355         goto err;
   1356 
   1357     /*
   1358      * Validate token timestamp. Current time should not be before the token
   1359      * timestamp.
   1360      */
   1361     if (ossl_time_compare(now, token.timestamp) < 0)
   1362         goto err;
   1363     time_diff = ossl_time2seconds(ossl_time_abs_difference(token.timestamp,
   1364         now));
   1365     if ((token.is_retry && time_diff > RETRY_LIFETIME)
   1366         || (!token.is_retry && time_diff > NEW_TOKEN_LIFETIME))
   1367         goto err;
   1368 
   1369     /* Validate remote address */
   1370     if (!BIO_ADDR_rawaddress(peer, NULL, &remote_addr_len)
   1371         || remote_addr_len != token.remote_addr_len
   1372         || (remote_addr = OPENSSL_malloc(remote_addr_len)) == NULL
   1373         || !BIO_ADDR_rawaddress(peer, remote_addr, &remote_addr_len)
   1374         || memcmp(remote_addr, token.remote_addr, remote_addr_len) != 0)
   1375         goto err;
   1376 
   1377     /*
   1378      * Set ODCID and SCID. If the token is from a RETRY packet, retrieve both
   1379      * from the token. Otherwise, generate a new ODCID and use the header's
   1380      * source connection ID for SCID.
   1381      */
   1382     if (token.is_retry) {
   1383         /*
   1384          * We're parsing a packet header before its gone through AEAD validation
   1385          * here, so there is a chance we are dealing with corrupted data. Make
   1386          * Sure the dcid encoded in the token matches the headers dcid to
   1387          * mitigate that.
   1388          * TODO(QUIC FUTURE): Consider handling AEAD validation at the port
   1389          * level rather than the QRX/channel level to eliminate the need for
   1390          * this.
   1391          */
   1392         if (token.rscid.id_len != hdr->dst_conn_id.id_len
   1393             || memcmp(&token.rscid.id, &hdr->dst_conn_id.id,
   1394                    token.rscid.id_len)
   1395                 != 0)
   1396             goto err;
   1397         *odcid = token.odcid;
   1398     } else {
   1399         if (!ossl_quic_lcidm_get_unused_cid(port->lcidm, odcid))
   1400             goto err;
   1401     }
   1402 
   1403     /*
   1404      * Determine if we need to send a NEW_TOKEN frame
   1405      * If we validated a retry token, we should always
   1406      * send a NEW_TOKEN frame to the client
   1407      *
   1408      * If however, we validated a NEW_TOKEN, which may be
   1409      * reused multiple times, only send a NEW_TOKEN frame
   1410      * if the existing received token has less than 10% of its lifetime
   1411      * remaining.  This prevents us from constantly sending
   1412      * NEW_TOKEN frames on every connection when not needed
   1413      */
   1414     if (token.is_retry) {
   1415         *gen_new_token = 1;
   1416     } else {
   1417         if (time_diff > ((NEW_TOKEN_LIFETIME * 9) / 10))
   1418             *gen_new_token = 1;
   1419     }
   1420 
   1421     ret = 1;
   1422 err:
   1423     cleanup_validation_token(&token);
   1424     OPENSSL_free(remote_addr);
   1425     return ret;
   1426 }
   1427 
   1428 static void generate_new_token(QUIC_CHANNEL *ch, BIO_ADDR *peer)
   1429 {
   1430     QUIC_CONN_ID rscid = { 0 };
   1431     QUIC_VALIDATION_TOKEN token;
   1432     unsigned char buffer[ENCRYPTED_TOKEN_MAX_LEN];
   1433     unsigned char *ct_buf;
   1434     size_t ct_len;
   1435     size_t token_buf_len = 0;
   1436 
   1437     /* Clients never send a NEW_TOKEN */
   1438     if (!ch->is_server)
   1439         return;
   1440 
   1441     ct_buf = OPENSSL_zalloc(ENCRYPTED_TOKEN_MAX_LEN);
   1442     if (ct_buf == NULL)
   1443         return;
   1444 
   1445     /*
   1446      * NEW_TOKEN tokens may be used for multiple subsequent connections
   1447      * within their timeout period, so don't reserve an rscid here
   1448      * like we do for retry tokens, instead, just fill it with random
   1449      * data, as we won't use it anyway
   1450      */
   1451     rscid.id_len = 8;
   1452     if (!RAND_bytes_ex(ch->port->engine->libctx, rscid.id, 8, 0)) {
   1453         OPENSSL_free(ct_buf);
   1454         return;
   1455     }
   1456 
   1457     memset(&token, 0, sizeof(QUIC_VALIDATION_TOKEN));
   1458 
   1459     if (!generate_token(peer, ch->init_dcid, rscid, &token, 0)
   1460         || !marshal_validation_token(&token, buffer, &token_buf_len)
   1461         || !encrypt_validation_token(ch->port, buffer, token_buf_len, NULL,
   1462             &ct_len)
   1463         || ct_len > ENCRYPTED_TOKEN_MAX_LEN
   1464         || !encrypt_validation_token(ch->port, buffer, token_buf_len, ct_buf,
   1465             &ct_len)
   1466         || !ossl_assert(ct_len >= QUIC_RETRY_INTEGRITY_TAG_LEN)) {
   1467         OPENSSL_free(ct_buf);
   1468         cleanup_validation_token(&token);
   1469         return;
   1470     }
   1471 
   1472     ch->pending_new_token = ct_buf;
   1473     ch->pending_new_token_len = ct_len;
   1474 
   1475     cleanup_validation_token(&token);
   1476 }
   1477 
   1478 /*
   1479  * This is called by the demux when we get a packet not destined for any known
   1480  * DCID.
   1481  */
   1482 static void port_default_packet_handler(QUIC_URXE *e, void *arg,
   1483     const QUIC_CONN_ID *dcid)
   1484 {
   1485     QUIC_PORT *port = arg;
   1486     PACKET pkt;
   1487     QUIC_PKT_HDR hdr;
   1488     QUIC_CHANNEL *ch = NULL, *new_ch = NULL;
   1489     QUIC_CONN_ID odcid;
   1490     uint8_t gen_new_token = 0;
   1491     OSSL_QRX *qrx = NULL;
   1492     OSSL_QRX *qrx_src = NULL;
   1493     OSSL_QRX_ARGS qrx_args = { 0 };
   1494     uint64_t cause_flags = 0;
   1495     OSSL_QRX_PKT *qrx_pkt = NULL;
   1496 
   1497     /* Don't handle anything if we are no longer running. */
   1498     if (!ossl_quic_port_is_running(port))
   1499         goto undesirable;
   1500 
   1501     if (port_try_handle_stateless_reset(port, e))
   1502         goto undesirable;
   1503 
   1504     if (dcid != NULL
   1505         && ossl_quic_lcidm_lookup(port->lcidm, dcid, NULL,
   1506             (void **)&ch)) {
   1507         assert(ch != NULL);
   1508         ossl_quic_channel_inject(ch, e);
   1509         return;
   1510     }
   1511 
   1512     /*
   1513      * If we have an incoming packet which doesn't match any existing connection
   1514      * we assume this is an attempt to make a new connection.
   1515      */
   1516     if (!port->allow_incoming)
   1517         goto undesirable;
   1518 
   1519     /*
   1520      * packet without destination connection id is invalid/corrupted here.
   1521      * stop wasting CPU cycles now.
   1522      */
   1523     if (dcid == NULL)
   1524         goto undesirable;
   1525 
   1526     /*
   1527      * We have got a packet for an unknown DCID. This might be an attempt to
   1528      * open a new connection.
   1529      */
   1530     if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
   1531         goto undesirable;
   1532 
   1533     if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
   1534         goto undesirable;
   1535 
   1536     /*
   1537      * We set short_conn_id_len to SIZE_MAX here which will cause the decode
   1538      * operation to fail if we get a 1-RTT packet. This is fine since we only
   1539      * care about Initial packets.
   1540      */
   1541     if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL,
   1542             &cause_flags)) {
   1543         /*
   1544          * If we fail due to a bad version, we know the packet up to the version
   1545          * number was decoded, and we use it below to send a version
   1546          * negotiation packet
   1547          */
   1548         if ((cause_flags & QUIC_PKT_HDR_DECODE_BAD_VERSION) == 0)
   1549             goto undesirable;
   1550     }
   1551 
   1552     switch (hdr.version) {
   1553     case QUIC_VERSION_1:
   1554         break;
   1555 
   1556     case QUIC_VERSION_NONE:
   1557     default:
   1558 
   1559         /*
   1560          * If we get here, then we have a bogus version, and might need
   1561          * to send a version negotiation packet.  According to
   1562          * RFC 9000 s. 6 and 14.1, we only do so however, if the UDP datagram
   1563          * is a minimum of 1200 bytes in size
   1564          */
   1565         if (e->data_len < 1200)
   1566             goto undesirable;
   1567 
   1568         /*
   1569          * If we don't get a supported version, respond with a ver
   1570          * negotiation packet, and discard
   1571          * TODO(QUIC FUTURE): Rate limit the reception of these
   1572          */
   1573         port_send_version_negotiation(port, &e->peer, &hdr);
   1574         goto undesirable;
   1575     }
   1576 
   1577     /*
   1578      * We only care about Initial packets which might be trying to establish a
   1579      * connection.
   1580      */
   1581     if (hdr.type != QUIC_PKT_TYPE_INITIAL)
   1582         goto undesirable;
   1583 
   1584     odcid.id_len = 0;
   1585 
   1586     /*
   1587      * Create qrx now so we can check integrity of packet
   1588      * which does not belong to any channel.
   1589      */
   1590     qrx_args.libctx = port->engine->libctx;
   1591     qrx_args.demux = port->demux;
   1592     qrx_args.short_conn_id_len = dcid->id_len;
   1593     qrx_args.max_deferred = 32;
   1594     qrx = ossl_qrx_new(&qrx_args);
   1595     if (qrx == NULL)
   1596         goto undesirable;
   1597 
   1598     /*
   1599      * Derive secrets for qrx only.
   1600      */
   1601     if (!ossl_quic_provide_initial_secret(port->engine->libctx,
   1602             port->engine->propq,
   1603             &hdr.dst_conn_id,
   1604             /* is_server */ 1,
   1605             qrx, NULL))
   1606         goto undesirable;
   1607 
   1608     if (ossl_qrx_validate_initial_packet(qrx, e, (const QUIC_CONN_ID *)dcid) == 0)
   1609         goto undesirable;
   1610 
   1611     if (port->validate_addr == 0) {
   1612         /*
   1613          * Forget qrx, because it becomes (almost) useless here. We must let
   1614          * channel to create a new QRX for connection ID server chooses. The
   1615          * validation keys for new DCID will be derived by
   1616          * ossl_quic_channel_on_new_conn() when we will be creating channel.
   1617          * See RFC 9000 section 7.2 negotiating connection id to better
   1618          * understand what's going on here.
   1619          *
   1620          * Did we say qrx is almost useless? Why? Because qrx remembers packets
   1621          * we just validated. Those packets must be injected to channel we are
   1622          * going to create. We use qrx_src alias so we can read packets from
   1623          * qrx and inject them to channel.
   1624          */
   1625         qrx_src = qrx;
   1626         qrx = NULL;
   1627     }
   1628     /*
   1629      * TODO(QUIC FUTURE): there should be some logic similar to accounting half-open
   1630      * states in TCP. If we reach certain threshold, then we want to
   1631      * validate clients.
   1632      */
   1633     if (port->validate_addr == 1 && hdr.token == NULL) {
   1634         port_send_retry(port, &e->peer, &hdr);
   1635         goto undesirable;
   1636     }
   1637 
   1638     /*
   1639      * Note, even if we don't enforce the sending of retry frames for
   1640      * server address validation, we may still get a token if we sent
   1641      * a NEW_TOKEN frame during a prior connection, which we should still
   1642      * validate here
   1643      */
   1644     if (hdr.token != NULL
   1645         && port_validate_token(&hdr, port, &e->peer,
   1646                &odcid, &gen_new_token)
   1647             == 0) {
   1648         /*
   1649          * RFC 9000 s 8.1.3
   1650          * When a server receives an Initial packet with an address
   1651          * validation token, it MUST attempt to validate the token,
   1652          * unless it has already completed address validation.
   1653          * If the token is invalid, then the server SHOULD proceed as
   1654          * if the client did not have a validated address,
   1655          * including potentially sending a Retry packet
   1656          * Note: If address validation is disabled, just act like
   1657          * the request is valid
   1658          */
   1659         if (port->validate_addr == 1) {
   1660             /*
   1661              * Again: we should consider saving initial encryption level
   1662              * secrets to token here to save some CPU cycles.
   1663              */
   1664             port_send_retry(port, &e->peer, &hdr);
   1665             goto undesirable;
   1666         }
   1667 
   1668         /*
   1669          * client is under amplification limit, until it completes
   1670          * handshake.
   1671          *
   1672          * forget qrx so channel can create a new one
   1673          * with valid initial encryption level keys.
   1674          */
   1675         if (qrx != NULL) {
   1676             qrx_src = qrx;
   1677             qrx = NULL;
   1678         }
   1679     }
   1680 
   1681     port_bind_channel(port, &e->peer, &hdr.dst_conn_id,
   1682         &odcid, qrx, &new_ch);
   1683 
   1684     /*
   1685      * if packet validates it gets moved to channel, we've just bound
   1686      * to port.
   1687      */
   1688     if (new_ch == NULL)
   1689         goto undesirable;
   1690 
   1691     /*
   1692      * Generate a token for sending in a later NEW_TOKEN frame
   1693      */
   1694     if (gen_new_token == 1)
   1695         generate_new_token(new_ch, &e->peer);
   1696 
   1697     if (qrx != NULL) {
   1698         /*
   1699          * The qrx belongs to channel now, so don't free it.
   1700          */
   1701         qrx = NULL;
   1702     } else {
   1703         /*
   1704          * We still need to salvage packets from almost forgotten qrx
   1705          * and pass them to channel.
   1706          */
   1707         while (ossl_qrx_read_pkt(qrx_src, &qrx_pkt) == 1)
   1708             ossl_quic_channel_inject_pkt(new_ch, qrx_pkt);
   1709         ossl_qrx_update_pn_space(qrx_src, new_ch->qrx);
   1710     }
   1711 
   1712     /*
   1713      * If function reaches this place, then packet got validated in
   1714      * ossl_qrx_validate_initial_packet(). Keep in mind the function
   1715      * ossl_qrx_validate_initial_packet() decrypts the packet to validate it.
   1716      * If packet validation was successful (and it was because we are here),
   1717      * then the function puts the packet to qrx->rx_pending. We must not call
   1718      * ossl_qrx_inject_urxe() here now, because we don't want to insert
   1719      * the packet to qrx->urx_pending which keeps packet waiting for decryption.
   1720      *
   1721      * We are going to call ossl_quic_demux_release_urxe() to dispose buffer
   1722      * which still holds encrypted data.
   1723      */
   1724 
   1725 undesirable:
   1726     ossl_qrx_free(qrx);
   1727     ossl_qrx_free(qrx_src);
   1728     ossl_quic_demux_release_urxe(port->demux, e);
   1729 }
   1730 
   1731 void ossl_quic_port_raise_net_error(QUIC_PORT *port,
   1732     QUIC_CHANNEL *triggering_ch)
   1733 {
   1734     QUIC_CHANNEL *ch;
   1735 
   1736     if (!ossl_quic_port_is_running(port))
   1737         return;
   1738 
   1739     /*
   1740      * Immediately capture any triggering error on the error stack, with a
   1741      * cover error.
   1742      */
   1743     ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,
   1744         "port failed due to network BIO I/O error");
   1745     OSSL_ERR_STATE_save(port->err_state);
   1746 
   1747     port_transition_failed(port);
   1748 
   1749     /* Give the triggering channel (if any) the first notification. */
   1750     if (triggering_ch != NULL)
   1751         ossl_quic_channel_raise_net_error(triggering_ch);
   1752 
   1753     OSSL_LIST_FOREACH(ch, ch, &port->channel_list)
   1754     if (ch != triggering_ch)
   1755         ossl_quic_channel_raise_net_error(ch);
   1756 }
   1757 
   1758 void ossl_quic_port_restore_err_state(const QUIC_PORT *port)
   1759 {
   1760     ERR_clear_error();
   1761     OSSL_ERR_STATE_restore(port->err_state);
   1762 }
   1763