Coverage Report

Created: 2026-05-24 07:14

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