Coverage Report

Created: 2026-09-12 06:55

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