Coverage Report

Created: 2026-10-28 06:28

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