Coverage Report

Created: 2026-09-12 06:55

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