Coverage Report

Created: 2026-05-30 06:56

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