Coverage Report

Created: 2025-12-14 06:48

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