Coverage Report

Created: 2025-08-28 07:07

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