]> git.ipfire.org Git - thirdparty/openssl.git/blame - ssl/quic/quic_channel.c
VMS knows POSIX threads too!
[thirdparty/openssl.git] / ssl / quic / quic_channel.c
CommitLineData
f538b421
HL
1/*
2 * Copyright 2022 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_channel.h"
11#include "internal/quic_error.h"
12#include "internal/quic_rx_depack.h"
13#include "../ssl_local.h"
14#include "quic_channel_local.h"
15#include <openssl/rand.h>
16
b1b06da2
HL
17/*
18 * NOTE: While this channel implementation currently has basic server support,
19 * this functionality has been implemented for internal testing purposes and is
20 * not suitable for network use. In particular, it does not implement address
21 * validation, anti-amplification or retry logic.
22 *
23 * TODO(QUIC): Implement address validation and anti-amplification
24 * TODO(QUIC): Implement retry logic
25 */
26
f538b421
HL
27#define INIT_DCID_LEN 8
28#define INIT_CRYPTO_BUF_LEN 8192
29#define INIT_APP_BUF_LEN 8192
30
3bf4dc8c 31static void ch_rx_pre(QUIC_CHANNEL *ch);
f538b421
HL
32static int ch_rx(QUIC_CHANNEL *ch);
33static int ch_tx(QUIC_CHANNEL *ch);
34static void ch_tick(QUIC_TICK_RESULT *res, void *arg);
35static void ch_rx_handle_packet(QUIC_CHANNEL *ch);
36static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch);
37static int ch_retry(QUIC_CHANNEL *ch,
38 const unsigned char *retry_token,
39 size_t retry_token_len,
40 const QUIC_CONN_ID *retry_scid);
41static void ch_cleanup(QUIC_CHANNEL *ch);
42static int ch_generate_transport_params(QUIC_CHANNEL *ch);
43static int ch_on_transport_params(const unsigned char *params,
44 size_t params_len,
45 void *arg);
46static int ch_on_handshake_alert(void *arg, unsigned char alert_code);
47static int ch_on_handshake_complete(void *arg);
48static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
49 uint32_t suite_id, EVP_MD *md,
50 const unsigned char *secret,
51 size_t secret_len,
52 void *arg);
53static int ch_on_crypto_recv(unsigned char *buf, size_t buf_len,
54 size_t *bytes_read, void *arg);
55static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
56static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
57 size_t *consumed, void *arg);
58static OSSL_TIME get_time(void *arg);
59static uint64_t get_stream_limit(int uni, void *arg);
60static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg);
61static int ch_retry(QUIC_CHANNEL *ch,
62 const unsigned char *retry_token,
63 size_t retry_token_len,
64 const QUIC_CONN_ID *retry_scid);
65static void ch_update_idle(QUIC_CHANNEL *ch);
66static int ch_discard_el(QUIC_CHANNEL *ch,
67 uint32_t enc_level);
68static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
69static void ch_update_idle(QUIC_CHANNEL *ch);
df15e990 70static void ch_raise_net_error(QUIC_CHANNEL *ch);
f538b421
HL
71static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
72static void ch_start_terminating(QUIC_CHANNEL *ch,
df15e990
HL
73 const QUIC_TERMINATE_CAUSE *tcause,
74 int force_immediate);
b1b06da2
HL
75static void ch_default_packet_handler(QUIC_URXE *e, void *arg);
76static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
77 const QUIC_CONN_ID *peer_scid,
78 const QUIC_CONN_ID *peer_dcid);
f538b421
HL
79
80static int gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid)
81{
82 if (len > QUIC_MAX_CONN_ID_LEN)
83 return 0;
84
85 cid->id_len = (unsigned char)len;
86
87 if (RAND_bytes_ex(libctx, cid->id, len, len * 8) != 1) {
88 cid->id_len = 0;
89 return 0;
90 }
91
92 return 1;
93}
94
95/*
96 * QUIC Channel Initialization and Teardown
97 * ========================================
98 */
99static int ch_init(QUIC_CHANNEL *ch)
100{
101 OSSL_QUIC_TX_PACKETISER_ARGS txp_args = {0};
102 OSSL_QTX_ARGS qtx_args = {0};
103 OSSL_QRX_ARGS qrx_args = {0};
2723d705 104 QUIC_TLS_ARGS tls_args = {0};
f538b421 105 uint32_t pn_space;
b1b06da2 106 size_t rx_short_cid_len = ch->is_server ? INIT_DCID_LEN : 0;
f538b421 107
b1b06da2
HL
108 /* For clients, generate our initial DCID. */
109 if (!ch->is_server
110 && !gen_rand_conn_id(ch->libctx, INIT_DCID_LEN, &ch->init_dcid))
f538b421
HL
111 goto err;
112
113 /* We plug in a network write BIO to the QTX later when we get one. */
114 qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN;
115 ch->rx_max_udp_payload_size = qtx_args.mdpl;
116
117 ch->qtx = ossl_qtx_new(&qtx_args);
118 if (ch->qtx == NULL)
119 goto err;
120
121 ch->txpim = ossl_quic_txpim_new();
122 if (ch->txpim == NULL)
123 goto err;
124
125 ch->cfq = ossl_quic_cfq_new();
126 if (ch->cfq == NULL)
127 goto err;
128
129 if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
130 goto err;
131
132 if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
133 2 * 1024 * 1024,
134 10 * 1024 * 1024,
135 get_time, NULL))
136 goto err;
137
138 if (!ossl_statm_init(&ch->statm))
139 goto err;
140
141 ch->have_statm = 1;
142 ch->cc_method = &ossl_cc_dummy_method;
143 if ((ch->cc_data = ch->cc_method->new(NULL, NULL, NULL)) == NULL)
144 goto err;
145
146 if ((ch->ackm = ossl_ackm_new(get_time, NULL, &ch->statm,
147 ch->cc_method, ch->cc_data)) == NULL)
148 goto err;
149
150 if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch))
151 goto err;
152
153 ch->have_qsm = 1;
154
155 /* We use a zero-length SCID. */
156 txp_args.cur_dcid = ch->init_dcid;
157 txp_args.ack_delay_exponent = 3;
158 txp_args.qtx = ch->qtx;
159 txp_args.txpim = ch->txpim;
160 txp_args.cfq = ch->cfq;
161 txp_args.ackm = ch->ackm;
162 txp_args.qsm = &ch->qsm;
163 txp_args.conn_txfc = &ch->conn_txfc;
164 txp_args.conn_rxfc = &ch->conn_rxfc;
165 txp_args.cc_method = ch->cc_method;
166 txp_args.cc_data = ch->cc_data;
167 txp_args.now = get_time;
168 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
169 ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_BUF_LEN);
170 if (ch->crypto_send[pn_space] == NULL)
171 goto err;
172
173 txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
174 }
175
176 ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
177 if (ch->txp == NULL)
178 goto err;
179
b1b06da2
HL
180 if ((ch->demux = ossl_quic_demux_new(/*BIO=*/NULL,
181 /*Short CID Len=*/rx_short_cid_len,
d7668ff2 182 get_time, NULL)) == NULL)
f538b421
HL
183 goto err;
184
b1b06da2
HL
185 /*
186 * If we are a server, setup our handler for packets not corresponding to
187 * any known DCID on our end. This is for handling clients establishing new
188 * connections.
189 */
190 if (ch->is_server)
191 ossl_quic_demux_set_default_handler(ch->demux,
192 ch_default_packet_handler,
193 ch);
194
f538b421 195 qrx_args.demux = ch->demux;
b1b06da2 196 qrx_args.short_conn_id_len = rx_short_cid_len;
f538b421
HL
197 qrx_args.max_deferred = 32;
198
199 if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
200 goto err;
201
202 if (!ossl_qrx_set_early_validation_cb(ch->qrx,
203 rx_early_validate,
204 ch))
205 goto err;
206
b1b06da2 207 if (!ch->is_server && !ossl_qrx_add_dst_conn_id(ch->qrx, &txp_args.cur_scid))
f538b421
HL
208 goto err;
209
210 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
211 ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL);
212 if (ch->crypto_recv[pn_space] == NULL)
213 goto err;
214 }
215
216 if ((ch->stream0 = ossl_quic_stream_map_alloc(&ch->qsm, 0,
217 QUIC_STREAM_INITIATOR_CLIENT
218 | QUIC_STREAM_DIR_BIDI)) == NULL)
219 goto err;
220
221 if ((ch->stream0->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL)
222 goto err;
223
224 if ((ch->stream0->rstream = ossl_quic_rstream_new(NULL, NULL)) == NULL)
225 goto err;
226
227 if (!ossl_quic_txfc_init(&ch->stream0->txfc, &ch->conn_txfc))
228 goto err;
229
230 if (!ossl_quic_rxfc_init(&ch->stream0->rxfc, &ch->conn_rxfc,
231 1 * 1024 * 1024,
232 5 * 1024 * 1024,
233 get_time, NULL))
234 goto err;
235
2723d705
MC
236 /* Plug in the TLS handshake layer. */
237 tls_args.s = ch->tls;
238 tls_args.crypto_send_cb = ch_on_crypto_send;
239 tls_args.crypto_send_cb_arg = ch;
240 tls_args.crypto_recv_cb = ch_on_crypto_recv;
241 tls_args.crypto_recv_cb_arg = ch;
242 tls_args.yield_secret_cb = ch_on_handshake_yield_secret;
243 tls_args.yield_secret_cb_arg = ch;
244 tls_args.got_transport_params_cb = ch_on_transport_params;
245 tls_args.got_transport_params_cb_arg= ch;
246 tls_args.handshake_complete_cb = ch_on_handshake_complete;
247 tls_args.handshake_complete_cb_arg = ch;
248 tls_args.alert_cb = ch_on_handshake_alert;
249 tls_args.alert_cb_arg = ch;
250 tls_args.is_server = ch->is_server;
251
252 if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
f538b421
HL
253 goto err;
254
255 /*
256 * Determine the QUIC Transport Parameters and serialize the transport
257 * parameters block. (For servers, we do this later as we must defer
258 * generation until we have received the client's transport parameters.)
259 */
260 if (!ch->is_server && !ch_generate_transport_params(ch))
261 goto err;
262
263 ch->rx_max_ack_delay = QUIC_DEFAULT_MAX_ACK_DELAY;
264 ch->rx_ack_delay_exp = QUIC_DEFAULT_ACK_DELAY_EXP;
265 ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
266 ch->max_idle_timeout = QUIC_DEFAULT_IDLE_TIMEOUT;
267 ch->tx_enc_level = QUIC_ENC_LEVEL_INITIAL;
45ecfc9b 268 ch->rx_enc_level = QUIC_ENC_LEVEL_INITIAL;
f538b421
HL
269 ch_update_idle(ch);
270 ossl_quic_reactor_init(&ch->rtor, ch_tick, ch,
271 ch_determine_next_tick_deadline(ch));
272 return 1;
273
274err:
275 ch_cleanup(ch);
276 return 0;
277}
278
279static void ch_cleanup(QUIC_CHANNEL *ch)
280{
281 uint32_t pn_space;
282
283 if (ch->ackm != NULL)
284 for (pn_space = QUIC_PN_SPACE_INITIAL;
285 pn_space < QUIC_PN_SPACE_NUM;
286 ++pn_space)
287 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
288
289 ossl_quic_tx_packetiser_free(ch->txp);
290 ossl_quic_txpim_free(ch->txpim);
291 ossl_quic_cfq_free(ch->cfq);
292 ossl_qtx_free(ch->qtx);
293 if (ch->cc_data != NULL)
294 ch->cc_method->free(ch->cc_data);
295 if (ch->have_statm)
296 ossl_statm_destroy(&ch->statm);
297 ossl_ackm_free(ch->ackm);
298
299 if (ch->stream0 != NULL) {
300 assert(ch->have_qsm);
301 ossl_quic_stream_map_release(&ch->qsm, ch->stream0); /* frees sstream */
302 }
303
304 if (ch->have_qsm)
305 ossl_quic_stream_map_cleanup(&ch->qsm);
306
307 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
308 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
309 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
310 }
311
312 ossl_qrx_pkt_release(ch->qrx_pkt);
313 ch->qrx_pkt = NULL;
314
2723d705 315 ossl_quic_tls_free(ch->qtls);
f538b421
HL
316 ossl_qrx_free(ch->qrx);
317 ossl_quic_demux_free(ch->demux);
318 OPENSSL_free(ch->local_transport_params);
f538b421
HL
319}
320
321QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
322{
323 QUIC_CHANNEL *ch = NULL;
324
325 if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
326 return NULL;
327
328 ch->libctx = args->libctx;
329 ch->propq = args->propq;
330 ch->is_server = args->is_server;
2723d705 331 ch->tls = args->tls;
f538b421
HL
332
333 if (!ch_init(ch)) {
334 OPENSSL_free(ch);
335 return NULL;
336 }
337
338 return ch;
339}
340
341void ossl_quic_channel_free(QUIC_CHANNEL *ch)
342{
343 if (ch == NULL)
344 return;
345
346 ch_cleanup(ch);
347 OPENSSL_free(ch);
348}
349
14e31409
MC
350/* Set mutator callbacks for test framework support */
351int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch,
352 ossl_mutate_packet_cb mutatecb,
353 ossl_finish_mutate_cb finishmutatecb,
354 void *mutatearg)
355{
356 if (ch->qtx == NULL)
357 return 0;
358
359 ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
360 return 1;
361}
362
f538b421
HL
363int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
364{
365 *peer_addr = ch->cur_peer_addr;
366 return 1;
367}
368
369int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
370{
371 ch->cur_peer_addr = *peer_addr;
372 return 1;
373}
374
375QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
376{
377 return &ch->rtor;
378}
379
380QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
381{
382 return &ch->qsm;
383}
384
385OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
386{
387 return &ch->statm;
388}
389
390QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
391 uint64_t stream_id)
392{
393 return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
394}
395
396int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
397{
398 return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
399}
400
c12e1113 401int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
f538b421 402{
149a8e6c 403 if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING
c12e1113 404 || ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING)
149a8e6c 405 return 1;
c12e1113 406
149a8e6c 407 return 0;
f538b421
HL
408}
409
c12e1113 410int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
f538b421 411{
c12e1113 412 if (ch->state == QUIC_CHANNEL_STATE_TERMINATED)
149a8e6c 413 return 1;
c12e1113 414
149a8e6c 415 return 0;
f538b421
HL
416}
417
c12e1113
MC
418int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
419{
420 return ossl_quic_channel_is_terminating(ch)
421 || ossl_quic_channel_is_terminated(ch);
422}
423
424QUIC_TERMINATE_CAUSE ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
f538b421 425{
c12e1113 426 return ch->terminate_cause;
f538b421
HL
427}
428
429int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
430{
431 return ch->handshake_complete;
432}
433
ce8f20b6
MC
434int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
435{
436 return ch->handshake_confirmed;
437}
438
f538b421
HL
439/*
440 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
441 * ================================================================
442 */
443
444/* Used by various components. */
445static OSSL_TIME get_time(void *arg)
446{
447 return ossl_time_now();
448}
449
450/* Used by QSM. */
451static uint64_t get_stream_limit(int uni, void *arg)
452{
453 QUIC_CHANNEL *ch = arg;
454
455 return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
456}
457
458/*
459 * Called by QRX to determine if a packet is potentially invalid before trying
460 * to decrypt it.
461 */
462static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg)
463{
464 QUIC_CHANNEL *ch = arg;
465
466 /* Potential duplicates should not be processed. */
467 if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
468 return 0;
469
470 return 1;
471}
472
473/*
474 * QUIC Channel: Handshake Layer Event Handling
475 * ============================================
476 */
477static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
478 size_t *consumed, void *arg)
479{
480 int ret;
481 QUIC_CHANNEL *ch = arg;
482 uint32_t enc_level = ch->tx_enc_level;
483 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
484 QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
485
486 if (!ossl_assert(sstream != NULL))
487 return 0;
488
489 ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
490 return ret;
491}
492
493static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
494{
495 size_t avail = 0;
496 int is_fin = 0;
497
498 if (rstream == NULL)
499 return 1;
500
501 if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
502 return 0;
503
504 return avail == 0;
505}
506
507static int ch_on_crypto_recv(unsigned char *buf, size_t buf_len,
508 size_t *bytes_read, void *arg)
509{
510 QUIC_CHANNEL *ch = arg;
511 QUIC_RSTREAM *rstream;
512 int is_fin = 0; /* crypto stream is never finished, so we don't use this */
513 uint32_t i;
514
515 /*
516 * After we move to a later EL we must not allow our peer to send any new
517 * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
518 * are allowed.
519 *
520 * In practice we will only move to a new EL when we have consumed all bytes
521 * which should be sent on the crypto stream at a previous EL. For example,
522 * the Handshake EL should not be provisioned until we have completely
523 * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
524 * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
525 * given EL is available we simply ensure we have not received any further
526 * bytes at a lower EL.
527 */
45ecfc9b 528 for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
f538b421
HL
529 if (i != QUIC_ENC_LEVEL_0RTT &&
530 !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
531 /* Protocol violation (RFC 9001 s. 4.1.3) */
532 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
533 OSSL_QUIC_FRAME_TYPE_CRYPTO,
534 "crypto stream data in wrong EL");
535 return 0;
536 }
537
45ecfc9b 538 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
f538b421
HL
539 if (rstream == NULL)
540 return 0;
541
542 return ossl_quic_rstream_read(rstream, buf, buf_len, bytes_read,
543 &is_fin);
544}
545
546static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
547 uint32_t suite_id, EVP_MD *md,
548 const unsigned char *secret,
549 size_t secret_len,
550 void *arg)
551{
552 QUIC_CHANNEL *ch = arg;
553 uint32_t i;
554
555 if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
556 /* Invalid EL. */
557 return 0;
558
f538b421
HL
559
560 if (direction) {
561 /* TX */
45ecfc9b
MC
562 if (enc_level <= ch->tx_enc_level)
563 /*
9f0ade7c
HL
564 * Does not make sense for us to try and provision an EL we have already
565 * attained.
566 */
45ecfc9b
MC
567 return 0;
568
f538b421
HL
569 if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
570 suite_id, md,
571 secret, secret_len))
572 return 0;
573
574 ch->tx_enc_level = enc_level;
575 } else {
576 /* RX */
45ecfc9b
MC
577 if (enc_level <= ch->rx_enc_level)
578 /*
9f0ade7c
HL
579 * Does not make sense for us to try and provision an EL we have already
580 * attained.
581 */
45ecfc9b
MC
582 return 0;
583
584 /*
9f0ade7c
HL
585 * Ensure all crypto streams for previous ELs are now empty of available
586 * data.
587 */
45ecfc9b 588 for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
e28f512f 589 if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
45ecfc9b
MC
590 /* Protocol violation (RFC 9001 s. 4.1.3) */
591 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
592 OSSL_QUIC_FRAME_TYPE_CRYPTO,
593 "crypto stream data in wrong EL");
594 return 0;
595 }
596
f538b421
HL
597 if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
598 suite_id, md,
599 secret, secret_len))
600 return 0;
92282a17
HL
601
602 ch->have_new_rx_secret = 1;
45ecfc9b 603 ch->rx_enc_level = enc_level;
f538b421
HL
604 }
605
606 return 1;
607}
608
609static int ch_on_handshake_complete(void *arg)
610{
611 QUIC_CHANNEL *ch = arg;
612
e28f512f 613 if (!ossl_assert(!ch->handshake_complete))
f538b421
HL
614 return 0; /* this should not happen twice */
615
616 if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
617 return 0;
618
62d0da12 619 if (!ch->got_remote_transport_params) {
f538b421
HL
620 /*
621 * Was not a valid QUIC handshake if we did not get valid transport
622 * params.
623 */
62d0da12
MC
624 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
625 OSSL_QUIC_FRAME_TYPE_CRYPTO,
626 "no transport parameters received");
f538b421 627 return 0;
62d0da12 628 }
f538b421
HL
629
630 /* Don't need transport parameters anymore. */
631 OPENSSL_free(ch->local_transport_params);
632 ch->local_transport_params = NULL;
633
634 /* Tell TXP the handshake is complete. */
635 ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
636
637 ch->handshake_complete = 1;
b1b06da2
HL
638
639 if (ch->is_server) {
640 /*
641 * On the server, the handshake is confirmed as soon as it is complete.
642 */
643 ossl_quic_channel_on_handshake_confirmed(ch);
644
645 ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
646 }
647
f538b421
HL
648 return 1;
649}
650
651static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
652{
653 QUIC_CHANNEL *ch = arg;
654
655 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_ERR_BEGIN + alert_code,
656 0, "handshake alert");
657 return 1;
658}
659
660/*
661 * QUIC Channel: Transport Parameter Handling
662 * ==========================================
663 */
664
665/*
666 * Called by handshake layer when we receive QUIC Transport Parameters from the
667 * peer. Note that these are not authenticated until the handshake is marked
668 * as complete.
669 */
3c567a52
HL
670#define TP_REASON_SERVER_ONLY(x) \
671 x " may not be sent by a client"
672#define TP_REASON_DUP(x) \
673 x " appears multiple times"
674#define TP_REASON_MALFORMED(x) \
675 x " is malformed"
676#define TP_REASON_EXPECTED_VALUE(x) \
677 x " does not match expected value"
678#define TP_REASON_NOT_RETRY(x) \
679 x " sent when not performing a retry"
680#define TP_REASON_REQUIRED(x) \
681 x " was not sent but is required"
682
f538b421
HL
683static int ch_on_transport_params(const unsigned char *params,
684 size_t params_len,
685 void *arg)
686{
687 QUIC_CHANNEL *ch = arg;
688 PACKET pkt;
689 uint64_t id, v;
690 size_t len;
691 const unsigned char *body;
692 int got_orig_dcid = 0;
693 int got_initial_scid = 0;
694 int got_retry_scid = 0;
695 int got_initial_max_data = 0;
696 int got_initial_max_stream_data_bidi_local = 0;
697 int got_initial_max_stream_data_bidi_remote = 0;
698 int got_initial_max_stream_data_uni = 0;
699 int got_initial_max_streams_bidi = 0;
700 int got_initial_max_streams_uni = 0;
701 int got_ack_delay_exp = 0;
702 int got_max_ack_delay = 0;
703 int got_max_udp_payload_size = 0;
704 int got_max_idle_timeout = 0;
705 int got_active_conn_id_limit = 0;
706 QUIC_CONN_ID cid;
3c567a52 707 const char *reason = "bad transport parameter";
f538b421
HL
708
709 if (ch->got_remote_transport_params)
710 goto malformed;
711
712 if (!PACKET_buf_init(&pkt, params, params_len))
713 return 0;
714
715 while (PACKET_remaining(&pkt) > 0) {
716 if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
717 goto malformed;
718
719 switch (id) {
75b2920a 720 case QUIC_TPARAM_ORIG_DCID:
3c567a52
HL
721 if (got_orig_dcid) {
722 reason = TP_REASON_DUP("ORIG_DCID");
723 goto malformed;
724 }
725
726 if (ch->is_server) {
727 reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
75b2920a 728 goto malformed;
3c567a52 729 }
75b2920a 730
3c567a52
HL
731 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
732 reason = TP_REASON_MALFORMED("ORIG_DCID");
75b2920a 733 goto malformed;
3c567a52 734 }
75b2920a
HL
735
736 /* Must match our initial DCID. */
3c567a52
HL
737 if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
738 reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
75b2920a 739 goto malformed;
3c567a52 740 }
75b2920a
HL
741
742 got_orig_dcid = 1;
743 break;
744
745 case QUIC_TPARAM_RETRY_SCID:
3c567a52
HL
746 if (ch->is_server) {
747 reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
748 goto malformed;
749 }
750
751 if (got_retry_scid) {
752 reason = TP_REASON_DUP("RETRY_SCID");
75b2920a 753 goto malformed;
3c567a52
HL
754 }
755
756 if (!ch->doing_retry) {
757 reason = TP_REASON_NOT_RETRY("RETRY_SCID");
758 goto malformed;
759 }
75b2920a 760
3c567a52
HL
761 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
762 reason = TP_REASON_MALFORMED("RETRY_SCID");
75b2920a 763 goto malformed;
3c567a52 764 }
75b2920a
HL
765
766 /* Must match Retry packet SCID. */
3c567a52
HL
767 if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
768 reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
75b2920a 769 goto malformed;
3c567a52 770 }
75b2920a
HL
771
772 got_retry_scid = 1;
773 break;
774
775 case QUIC_TPARAM_INITIAL_SCID:
3c567a52 776 if (got_initial_scid) {
75b2920a 777 /* must not appear more than once */
3c567a52 778 reason = TP_REASON_DUP("INITIAL_SCID");
75b2920a 779 goto malformed;
3c567a52 780 }
75b2920a 781
3c567a52
HL
782 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
783 reason = TP_REASON_MALFORMED("INITIAL_SCID");
75b2920a 784 goto malformed;
3c567a52 785 }
75b2920a
HL
786
787 /* Must match SCID of first Initial packet from server. */
3c567a52
HL
788 if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
789 reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
75b2920a 790 goto malformed;
3c567a52 791 }
75b2920a
HL
792
793 got_initial_scid = 1;
794 break;
795
796 case QUIC_TPARAM_INITIAL_MAX_DATA:
3c567a52 797 if (got_initial_max_data) {
75b2920a 798 /* must not appear more than once */
3c567a52 799 reason = TP_REASON_DUP("INITIAL_MAX_DATA");
75b2920a 800 goto malformed;
3c567a52 801 }
75b2920a 802
3c567a52
HL
803 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
804 reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
75b2920a 805 goto malformed;
3c567a52 806 }
75b2920a
HL
807
808 ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
809 got_initial_max_data = 1;
810 break;
811
812 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
3c567a52 813 if (got_initial_max_stream_data_bidi_local) {
75b2920a 814 /* must not appear more than once */
3c567a52 815 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
75b2920a 816 goto malformed;
3c567a52 817 }
75b2920a 818
3c567a52
HL
819 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
820 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
75b2920a 821 goto malformed;
3c567a52 822 }
f538b421
HL
823
824 /*
75b2920a
HL
825 * This is correct; the BIDI_LOCAL TP governs streams created by
826 * the endpoint which sends the TP, i.e., our peer.
f538b421 827 */
75b2920a
HL
828 ch->init_max_stream_data_bidi_remote = v;
829 got_initial_max_stream_data_bidi_local = 1;
830 break;
831
832 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
3c567a52 833 if (got_initial_max_stream_data_bidi_remote) {
75b2920a 834 /* must not appear more than once */
3c567a52 835 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
75b2920a 836 goto malformed;
3c567a52 837 }
75b2920a 838
3c567a52
HL
839 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
840 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
75b2920a 841 goto malformed;
3c567a52 842 }
75b2920a
HL
843
844 /*
845 * This is correct; the BIDI_REMOTE TP governs streams created
846 * by the endpoint which receives the TP, i.e., us.
847 */
848 ch->init_max_stream_data_bidi_local = v;
849
850 /* Apply to stream 0. */
851 ossl_quic_txfc_bump_cwm(&ch->stream0->txfc, v);
852 got_initial_max_stream_data_bidi_remote = 1;
853 break;
854
855 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
3c567a52 856 if (got_initial_max_stream_data_uni) {
75b2920a 857 /* must not appear more than once */
3c567a52 858 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
75b2920a 859 goto malformed;
3c567a52 860 }
75b2920a 861
3c567a52
HL
862 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
863 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
75b2920a 864 goto malformed;
3c567a52 865 }
75b2920a
HL
866
867 ch->init_max_stream_data_uni_remote = v;
868 got_initial_max_stream_data_uni = 1;
869 break;
870
871 case QUIC_TPARAM_ACK_DELAY_EXP:
3c567a52 872 if (got_ack_delay_exp) {
75b2920a 873 /* must not appear more than once */
3c567a52 874 reason = TP_REASON_DUP("ACK_DELAY_EXP");
75b2920a 875 goto malformed;
3c567a52 876 }
75b2920a
HL
877
878 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
3c567a52
HL
879 || v > QUIC_MAX_ACK_DELAY_EXP) {
880 reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
75b2920a 881 goto malformed;
3c567a52 882 }
75b2920a
HL
883
884 ch->rx_ack_delay_exp = (unsigned char)v;
885 got_ack_delay_exp = 1;
886 break;
887
888 case QUIC_TPARAM_MAX_ACK_DELAY:
3c567a52 889 if (got_max_ack_delay) {
75b2920a 890 /* must not appear more than once */
3c567a52 891 reason = TP_REASON_DUP("MAX_ACK_DELAY");
75b2920a 892 return 0;
3c567a52 893 }
75b2920a
HL
894
895 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
3c567a52
HL
896 || v >= (((uint64_t)1) << 14)) {
897 reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
75b2920a 898 goto malformed;
3c567a52 899 }
75b2920a
HL
900
901 ch->rx_max_ack_delay = v;
902 got_max_ack_delay = 1;
903 break;
904
905 case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
3c567a52 906 if (got_initial_max_streams_bidi) {
75b2920a 907 /* must not appear more than once */
3c567a52 908 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
75b2920a 909 return 0;
3c567a52 910 }
75b2920a
HL
911
912 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
3c567a52
HL
913 || v > (((uint64_t)1) << 60)) {
914 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
75b2920a 915 goto malformed;
3c567a52 916 }
75b2920a
HL
917
918 assert(ch->max_local_streams_bidi == 0);
919 ch->max_local_streams_bidi = v;
920 got_initial_max_streams_bidi = 1;
921 break;
922
923 case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
3c567a52 924 if (got_initial_max_streams_uni) {
75b2920a 925 /* must not appear more than once */
3c567a52 926 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
75b2920a 927 goto malformed;
3c567a52 928 }
75b2920a
HL
929
930 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
3c567a52
HL
931 || v > (((uint64_t)1) << 60)) {
932 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
75b2920a 933 goto malformed;
3c567a52 934 }
75b2920a
HL
935
936 assert(ch->max_local_streams_uni == 0);
937 ch->max_local_streams_uni = v;
938 got_initial_max_streams_uni = 1;
939 break;
940
941 case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
3c567a52 942 if (got_max_idle_timeout) {
75b2920a 943 /* must not appear more than once */
3c567a52 944 reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
75b2920a 945 goto malformed;
3c567a52 946 }
75b2920a 947
3c567a52
HL
948 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
949 reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
75b2920a 950 goto malformed;
3c567a52 951 }
75b2920a
HL
952
953 if (v < ch->max_idle_timeout)
954 ch->max_idle_timeout = v;
955
956 ch_update_idle(ch);
957 got_max_idle_timeout = 1;
958 break;
f538b421 959
75b2920a 960 case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
3c567a52 961 if (got_max_udp_payload_size) {
75b2920a 962 /* must not appear more than once */
3c567a52 963 reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
75b2920a 964 goto malformed;
3c567a52 965 }
f538b421 966
75b2920a 967 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
3c567a52
HL
968 || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
969 reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
75b2920a 970 goto malformed;
3c567a52 971 }
75b2920a
HL
972
973 ch->rx_max_udp_payload_size = v;
974 got_max_udp_payload_size = 1;
975 break;
976
977 case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
3c567a52 978 if (got_active_conn_id_limit) {
75b2920a 979 /* must not appear more than once */
3c567a52 980 reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
75b2920a 981 goto malformed;
3c567a52 982 }
75b2920a
HL
983
984 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
3c567a52
HL
985 || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
986 reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
75b2920a 987 goto malformed;
3c567a52 988 }
75b2920a
HL
989
990 ch->rx_active_conn_id_limit = v;
991 got_active_conn_id_limit = 1;
992 break;
993
3c567a52
HL
994 case QUIC_TPARAM_STATELESS_RESET_TOKEN:
995 /* TODO(QUIC): Handle stateless reset tokens. */
996 /*
997 * We ignore these for now, but we must ensure a client doesn't
998 * send them.
999 */
1000 if (ch->is_server) {
1001 reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
1002 goto malformed;
1003 }
1004
1005 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1006 if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
1007 reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
1008 goto malformed;
1009 }
1010
1011 break;
1012
1013 case QUIC_TPARAM_PREFERRED_ADDR:
1014 /* TODO(QUIC): Handle preferred address. */
1015 if (ch->is_server) {
1016 reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
1017 goto malformed;
1018 }
1019
1020 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1021 if (body == NULL) {
1022 reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
1023 goto malformed;
1024 }
1025
1026 break;
75b2920a
HL
1027
1028 case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
1029 /* We do not currently handle migration, so nothing to do. */
1030 default:
1031 /* Skip over and ignore. */
1032 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
1033 &len);
1034 if (body == NULL)
1035 goto malformed;
1036
1037 break;
f538b421
HL
1038 }
1039 }
1040
3c567a52
HL
1041 if (!got_initial_scid) {
1042 reason = TP_REASON_REQUIRED("INITIAL_SCID");
f538b421 1043 goto malformed;
3c567a52
HL
1044 }
1045
1046 if (!ch->is_server) {
1047 if (!got_orig_dcid) {
1048 reason = TP_REASON_REQUIRED("ORIG_DCID");
1049 goto malformed;
1050 }
1051
1052 if (ch->doing_retry && !got_retry_scid) {
1053 reason = TP_REASON_REQUIRED("RETRY_SCID");
1054 goto malformed;
1055 }
1056 }
f538b421
HL
1057
1058 ch->got_remote_transport_params = 1;
1059
1060 if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
1061 || got_initial_max_streams_bidi || got_initial_max_streams_uni)
1062 /* If FC credit was bumped, we may now be able to send. */
1063 ossl_quic_stream_map_update_state(&ch->qsm, ch->stream0);
1064
1065 /* If we are a server, we now generate our own transport parameters. */
1066 if (ch->is_server && !ch_generate_transport_params(ch)) {
1067 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1068 "internal error");
1069 return 0;
1070 }
1071
1072 return 1;
1073
1074malformed:
1075 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
3c567a52 1076 0, reason);
f538b421
HL
1077 return 0;
1078}
1079
1080/*
1081 * Called when we want to generate transport parameters. This is called
1082 * immediately at instantiation time for a client and after we receive the
1083 * client's transport parameters for a server.
1084 */
1085static int ch_generate_transport_params(QUIC_CHANNEL *ch)
1086{
1087 int ok = 0;
1088 BUF_MEM *buf_mem = NULL;
1089 WPACKET wpkt;
1090 int wpkt_valid = 0;
1091 size_t buf_len = 0;
1092
1093 if (ch->local_transport_params != NULL)
1094 goto err;
1095
1096 if ((buf_mem = BUF_MEM_new()) == NULL)
1097 goto err;
1098
1099 if (!WPACKET_init(&wpkt, buf_mem))
1100 goto err;
1101
1102 wpkt_valid = 1;
1103
1104 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
1105 NULL, 0) == NULL)
1106 goto err;
1107
3c567a52
HL
1108 if (ch->is_server) {
1109 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
1110 &ch->init_dcid))
1111 goto err;
1112
1113 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1114 &ch->cur_local_dcid))
1115 goto err;
1116 } else {
1117 /* Client always uses an empty SCID. */
1118 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1119 NULL, 0) == NULL)
1120 goto err;
1121 }
f538b421
HL
1122
1123 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
1124 ch->max_idle_timeout))
1125 goto err;
1126
1127 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
1128 QUIC_MIN_INITIAL_DGRAM_LEN))
1129 goto err;
1130
1131 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
1132 4))
1133 goto err;
1134
1135 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
1136 ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
1137 goto err;
1138
1139 /*
1140 * We actually want the default CWM for a new RXFC, but here we just use
1141 * stream0 as a representative specimen. TODO(QUIC): revisit this when we
1142 * support multiple streams.
1143 */
1144 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1145 ossl_quic_rxfc_get_cwm(&ch->stream0->rxfc)))
1146 goto err;
1147
1148 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1149 ossl_quic_rxfc_get_cwm(&ch->stream0->rxfc)))
1150 goto err;
1151
1152 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
1153 ossl_quic_rxfc_get_cwm(&ch->stream0->rxfc)))
1154 goto err;
1155
1156 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
3c567a52 1157 ch->is_server ? 1 : 0))
f538b421
HL
1158 goto err;
1159
1160 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
1161 0))
1162 goto err;
1163
1164 if (!WPACKET_get_total_written(&wpkt, &buf_len))
1165 goto err;
1166
1167 ch->local_transport_params = (unsigned char *)buf_mem->data;
1168 buf_mem->data = NULL;
1169
1170 if (!WPACKET_finish(&wpkt))
1171 goto err;
1172
1173 wpkt_valid = 0;
1174
2723d705 1175 if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
f538b421
HL
1176 buf_len))
1177 goto err;
1178
1179 ok = 1;
1180err:
1181 if (wpkt_valid)
1182 WPACKET_cleanup(&wpkt);
1183 BUF_MEM_free(buf_mem);
1184 return ok;
1185}
1186
1187/*
1188 * QUIC Channel: Ticker-Mutator
1189 * ============================
1190 */
1191
1192/*
1193 * The central ticker function called by the reactor. This does everything, or
1194 * at least everything network I/O related. Best effort - not allowed to fail
1195 * "loudly".
1196 */
1197static void ch_tick(QUIC_TICK_RESULT *res, void *arg)
1198{
1199 OSSL_TIME now, deadline;
1200 QUIC_CHANNEL *ch = arg;
1201
1202 /*
1203 * When we tick the QUIC connection, we do everything we need to do
1204 * periodically. In order, we:
1205 *
1206 * - handle any incoming data from the network;
1207 * - handle any timer events which are due to fire (ACKM, etc.)
1208 * - write any data to the network due to be sent, to the extent
1209 * possible;
1210 * - determine the time at which we should next be ticked.
1211 */
1212
1213 /* If we are in the TERMINATED state, there is nothing to do. */
c12e1113 1214 if (ossl_quic_channel_is_terminated(ch)) {
b639475a
HL
1215 res->net_read_desired = 0;
1216 res->net_write_desired = 0;
1217 res->tick_deadline = ossl_time_infinite();
f538b421
HL
1218 return;
1219 }
1220
1221 /*
1222 * If we are in the TERMINATING state, check if the terminating timer has
1223 * expired.
1224 */
c12e1113 1225 if (ossl_quic_channel_is_terminating(ch)) {
f538b421
HL
1226 now = ossl_time_now();
1227
1228 if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
1229 ch_on_terminating_timeout(ch);
b639475a
HL
1230 res->net_read_desired = 0;
1231 res->net_write_desired = 0;
1232 res->tick_deadline = ossl_time_infinite();
f538b421
HL
1233 return; /* abort normal processing, nothing to do */
1234 }
1235 }
1236
3bf4dc8c
HL
1237 /* Handle any incoming data from network. */
1238 ch_rx_pre(ch);
1239
4e64437a 1240 do {
3bf4dc8c 1241 /* Process queued incoming packets. */
4e64437a 1242 ch_rx(ch);
f538b421 1243
4e64437a
HL
1244 /*
1245 * Allow the handshake layer to check for any new incoming data and generate
1246 * new outgoing data.
1247 */
92282a17 1248 ch->have_new_rx_secret = 0;
2723d705 1249 ossl_quic_tls_tick(ch->qtls);
4e64437a
HL
1250
1251 /*
1252 * If the handshake layer gave us a new secret, we need to do RX again
1253 * because packets that were not previously processable and were
1254 * deferred might now be processable.
9f0ade7c
HL
1255 *
1256 * TODO(QUIC): Consider handling this in the yield_secret callback.
4e64437a 1257 */
92282a17 1258 } while (ch->have_new_rx_secret);
f538b421
HL
1259
1260 /*
1261 * Handle any timer events which are due to fire; namely, the loss detection
1262 * deadline and the idle timeout.
1263 *
1264 * ACKM ACK generation deadline is polled by TXP, so we don't need to handle
1265 * it here.
1266 */
1267 now = ossl_time_now();
1268 if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
1269 /*
1270 * Idle timeout differs from normal protocol violation because we do not
1271 * send a CONN_CLOSE frame; go straight to TERMINATED.
1272 */
1273 ch_on_idle_timeout(ch);
b639475a
HL
1274 res->net_read_desired = 0;
1275 res->net_write_desired = 0;
1276 res->tick_deadline = ossl_time_infinite();
f538b421
HL
1277 return;
1278 }
1279
1280 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1281 if (!ossl_time_is_zero(deadline) && ossl_time_compare(now, deadline) >= 0)
1282 ossl_ackm_on_timeout(ch->ackm);
1283
1284 /* Write any data to the network due to be sent. */
1285 ch_tx(ch);
1286
1287 /* Determine the time at which we should next be ticked. */
1288 res->tick_deadline = ch_determine_next_tick_deadline(ch);
1289
df15e990
HL
1290 /*
1291 * Always process network input unless we are now terminated.
1292 * Although we had not terminated at the beginning of this tick, network
1293 * errors in ch_rx_pre() or ch_tx() may have caused us to transition to the
1294 * Terminated state.
1295 */
c12e1113 1296 res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
f538b421
HL
1297
1298 /* We want to write to the network if we have any in our queue. */
b639475a 1299 res->net_write_desired
c12e1113 1300 = (!ossl_quic_channel_is_terminated(ch)
df15e990 1301 && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
f538b421
HL
1302}
1303
3bf4dc8c
HL
1304/* Process incoming datagrams, if any. */
1305static void ch_rx_pre(QUIC_CHANNEL *ch)
1306{
df15e990
HL
1307 int ret;
1308
b1b06da2 1309 if (!ch->is_server && !ch->have_sent_any_pkt)
3bf4dc8c
HL
1310 return;
1311
1312 /*
1313 * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
1314 * to the appropriate QRX instance.
1315 */
df15e990
HL
1316 ret = ossl_quic_demux_pump(ch->demux);
1317 if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
1318 /*
1319 * We don't care about transient failure, but permanent failure means we
1320 * should tear down the connection as though a protocol violation
1321 * occurred. Skip straight to the Terminating state as there is no point
1322 * trying to send CONNECTION_CLOSE frames if the network BIO is not
1323 * operating correctly.
1324 */
1325 ch_raise_net_error(ch);
3bf4dc8c
HL
1326}
1327
1328/* Process queued incoming packets and handle frames, if any. */
f538b421
HL
1329static int ch_rx(QUIC_CHANNEL *ch)
1330{
1331 int handled_any = 0;
1332
b1b06da2 1333 if (!ch->is_server && !ch->have_sent_any_pkt)
f538b421
HL
1334 /*
1335 * We have not sent anything yet, therefore there is no need to check
75b2920a 1336 * for incoming data.
f538b421
HL
1337 */
1338 return 1;
1339
f538b421
HL
1340 for (;;) {
1341 assert(ch->qrx_pkt == NULL);
1342
1343 if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
1344 break;
1345
1346 if (!handled_any)
1347 ch_update_idle(ch);
1348
1349 ch_rx_handle_packet(ch); /* best effort */
1350
1351 /*
1352 * Regardless of the outcome of frame handling, unref the packet.
1353 * This will free the packet unless something added another
1354 * reference to it during frame processing.
1355 */
1356 ossl_qrx_pkt_release(ch->qrx_pkt);
1357 ch->qrx_pkt = NULL;
1358
1359 handled_any = 1;
1360 }
1361
1362 /*
1363 * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
1364 * process one or more incoming packets.
1365 */
1366 if (handled_any && ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING)
1367 ch->conn_close_queued = 1;
1368
1369 return 1;
1370}
1371
1372/* Handles the packet currently in ch->qrx_pkt->hdr. */
1373static void ch_rx_handle_packet(QUIC_CHANNEL *ch)
1374{
1375 uint32_t enc_level;
1376
1377 assert(ch->qrx_pkt != NULL);
1378
1379 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
1380 if (!ch->have_received_enc_pkt) {
1381 ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
1382 ch->have_received_enc_pkt = 1;
1383
1384 /*
1385 * We change to using the SCID in the first Initial packet as the
1386 * DCID.
1387 */
1388 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
1389 }
1390
1391 enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
1392 if ((ch->el_discarded & (1U << enc_level)) != 0)
1393 /* Do not process packets from ELs we have already discarded. */
1394 return;
1395 }
1396
1397 /* Handle incoming packet. */
1398 switch (ch->qrx_pkt->hdr->type) {
75b2920a 1399 case QUIC_PKT_TYPE_RETRY:
b1b06da2 1400 if (ch->doing_retry || ch->is_server)
75b2920a
HL
1401 /*
1402 * It is not allowed to ask a client to do a retry more than
b1b06da2 1403 * once. Clients may not send retries.
75b2920a
HL
1404 */
1405 return;
f538b421 1406
75b2920a
HL
1407 if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
1408 /* Packets with zero-length Retry Tokens are invalid. */
1409 return;
f538b421 1410
75b2920a
HL
1411 /*
1412 * TODO(QUIC): Theoretically this should probably be in the QRX.
1413 * However because validation is dependent on context (namely the
1414 * client's initial DCID) we can't do this cleanly. In the future we
1415 * should probably add a callback to the QRX to let it call us (via
1416 * the DEMUX) and ask us about the correct original DCID, rather
1417 * than allow the QRX to emit a potentially malformed packet to the
1418 * upper layers. However, special casing this will do for now.
1419 */
1420 if (!ossl_quic_validate_retry_integrity_tag(ch->libctx,
1421 ch->propq,
1422 ch->qrx_pkt->hdr,
1423 &ch->init_dcid))
1424 /* Malformed retry packet, ignore. */
1425 return;
f538b421 1426
75b2920a
HL
1427 ch_retry(ch, ch->qrx_pkt->hdr->data,
1428 ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
1429 &ch->qrx_pkt->hdr->src_conn_id);
1430 break;
f538b421 1431
75b2920a 1432 case QUIC_PKT_TYPE_0RTT:
b1b06da2
HL
1433 if (!ch->is_server)
1434 /* Clients should never receive 0-RTT packets. */
1435 return;
1436
1437 /*
1438 * TODO(QUIC): Implement 0-RTT on the server side. We currently do
1439 * not need to implement this as a client can only do 0-RTT if we
1440 * have given it permission to in a previous session.
1441 */
75b2920a
HL
1442 break;
1443
b1b06da2
HL
1444 case QUIC_PKT_TYPE_INITIAL:
1445 case QUIC_PKT_TYPE_HANDSHAKE:
1446 case QUIC_PKT_TYPE_1RTT:
75b2920a
HL
1447 if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
1448 /*
1449 * We automatically drop INITIAL EL keys when first successfully
1450 * decrypting a HANDSHAKE packet, as per the RFC.
1451 */
1452 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
1453
1454 /* This packet contains frames, pass to the RXDP. */
1455 ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
1456 break;
b1b06da2
HL
1457
1458 default:
1459 assert(0);
1460 break;
1461 }
1462}
1463
1464/*
1465 * This is called by the demux when we get a packet not destined for any known
1466 * DCID.
1467 */
1468static void ch_default_packet_handler(QUIC_URXE *e, void *arg)
1469{
1470 QUIC_CHANNEL *ch = arg;
1471 PACKET pkt;
1472 QUIC_PKT_HDR hdr;
1473
1474 if (!ossl_assert(ch->is_server))
1475 goto undesirable;
1476
1477 /*
1478 * We only support one connection to our server currently, so if we already
1479 * started one, ignore any new connection attempts.
1480 */
1481 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1482 goto undesirable;
1483
1484 /*
1485 * We have got a packet for an unknown DCID. This might be an attempt to
1486 * open a new connection.
1487 */
1488 if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
1489 goto undesirable;
1490
1491 if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
091f532e 1492 goto err;
b1b06da2
HL
1493
1494 /*
1495 * We set short_conn_id_len to SIZE_MAX here which will cause the decode
1496 * operation to fail if we get a 1-RTT packet. This is fine since we only
1497 * care about Initial packets.
1498 */
1499 if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, &hdr, NULL))
1500 goto undesirable;
1501
1502 switch (hdr.version) {
1503 case QUIC_VERSION_1:
1504 break;
1505
1506 case QUIC_VERSION_NONE:
1507 default:
1508 /* Unknown version or proactive version negotiation request, bail. */
1509 /* TODO(QUIC): Handle version negotiation on server side */
1510 goto undesirable;
f538b421 1511 }
b1b06da2
HL
1512
1513 /*
1514 * We only care about Initial packets which might be trying to establish a
1515 * connection.
1516 */
1517 if (hdr.type != QUIC_PKT_TYPE_INITIAL)
1518 goto undesirable;
1519
1520 /*
1521 * Assume this is a valid attempt to initiate a connection.
1522 *
1523 * We do not register the DCID in the initial packet we received and that
1524 * DCID is not actually used again, thus after provisioning the correct
1525 * Initial keys derived from it (which is done in the call below) we pass
1526 * the received packet directly to the QRX so that it can process it as a
1527 * one-time thing, instead of going through the usual DEMUX DCID-based
1528 * routing.
1529 */
1530 if (!ch_server_on_new_conn(ch, &e->peer,
1531 &hdr.src_conn_id,
1532 &hdr.dst_conn_id))
091f532e 1533 goto err;
b1b06da2
HL
1534
1535 ossl_qrx_inject_urxe(ch->qrx, e);
1536 return;
1537
091f532e
HL
1538err:
1539 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1540 "internal error");
b1b06da2
HL
1541undesirable:
1542 ossl_quic_demux_release_urxe(ch->demux, e);
f538b421
HL
1543}
1544
1545/* Try to generate packets and if possible, flush them to the network. */
1546static int ch_tx(QUIC_CHANNEL *ch)
1547{
1548 if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING) {
1549 /*
1550 * While closing, only send CONN_CLOSE if we've received more traffic
1551 * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
1552 * future calls to it generate CONN_CLOSE frames, so otherwise we would
1553 * just constantly generate CONN_CLOSE frames.
1554 */
1555 if (!ch->conn_close_queued)
1556 return 0;
1557
1558 ch->conn_close_queued = 0;
1559 }
1560
1561 /*
1562 * Send a packet, if we need to. Best effort. The TXP consults the CC and
1563 * applies any limitations imposed by it, so we don't need to do it here.
1564 *
1565 * Best effort. In particular if TXP fails for some reason we should still
1566 * flush any queued packets which we already generated.
1567 */
df15e990
HL
1568 switch (ossl_quic_tx_packetiser_generate(ch->txp,
1569 TX_PACKETISER_ARCHETYPE_NORMAL)) {
1570 case TX_PACKETISER_RES_SENT_PKT:
1571 ch->have_sent_any_pkt = 1; /* Packet was sent */
1572 break;
1573 case TX_PACKETISER_RES_NO_PKT:
1574 break; /* No packet was sent */
1575 default:
1576 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1577 "internal error");
1578 break; /* Internal failure (e.g. allocation, assertion) */
1579 }
1580
1581 /* Flush packets to network. */
1582 switch (ossl_qtx_flush_net(ch->qtx)) {
1583 case QTX_FLUSH_NET_RES_OK:
1584 case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
1585 /* Best effort, done for now. */
1586 break;
1587
1588 case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
1589 default:
1590 /* Permanent underlying network BIO, start terminating. */
1591 ch_raise_net_error(ch);
1592 break;
1593 }
f538b421 1594
f538b421
HL
1595 return 1;
1596}
1597
1598/* Determine next tick deadline. */
1599static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
1600{
1601 OSSL_TIME deadline;
1602 uint32_t pn_space;
1603
c12e1113 1604 if (ossl_quic_channel_is_terminated(ch))
df15e990
HL
1605 return ossl_time_infinite();
1606
f538b421
HL
1607 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1608 if (ossl_time_is_zero(deadline))
1609 deadline = ossl_time_infinite();
1610
1611 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
1612 deadline = ossl_time_min(deadline,
1613 ossl_ackm_get_ack_deadline(ch->ackm, pn_space));
1614
1615 /* When will CC let us send more? */
1616 if (ossl_quic_tx_packetiser_has_pending(ch->txp, TX_PACKETISER_ARCHETYPE_NORMAL,
1617 TX_PACKETISER_BYPASS_CC))
1618 deadline = ossl_time_min(deadline,
1619 ch->cc_method->get_next_credit_time(ch->cc_data));
1620
1621 /* Is the terminating timer armed? */
c12e1113 1622 if (ossl_quic_channel_is_terminating(ch))
f538b421
HL
1623 deadline = ossl_time_min(deadline,
1624 ch->terminate_deadline);
1625 else if (!ossl_time_is_infinite(ch->idle_deadline))
1626 deadline = ossl_time_min(deadline,
1627 ch->idle_deadline);
1628
1629 return deadline;
1630}
1631
1632/*
1633 * QUIC Channel: Network BIO Configuration
1634 * =======================================
1635 */
1636
1637/* Determines whether we can support a given poll descriptor. */
1638static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
1639{
1640 if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0)
1641 return 0;
1642
1643 return 1;
1644}
1645
1646BIO *ossl_quic_channel_get_net_rbio(QUIC_CHANNEL *ch)
1647{
1648 return ch->net_rbio;
1649}
1650
1651BIO *ossl_quic_channel_get_net_wbio(QUIC_CHANNEL *ch)
1652{
1653 return ch->net_wbio;
1654}
1655
d1ac77b1
HL
1656/*
1657 * QUIC_CHANNEL does not ref any BIO it is provided with, nor is any ref
1658 * transferred to it. The caller (i.e., QUIC_CONNECTION) is responsible for
1659 * ensuring the BIO lasts until the channel is freed or the BIO is switched out
1660 * for another BIO by a subsequent successful call to this function.
1661 */
1662int ossl_quic_channel_set_net_rbio(QUIC_CHANNEL *ch, BIO *net_rbio)
f538b421
HL
1663{
1664 BIO_POLL_DESCRIPTOR d = {0};
1665
1666 if (ch->net_rbio == net_rbio)
1667 return 1;
1668
1669 if (net_rbio != NULL) {
1670 if (!BIO_get_rpoll_descriptor(net_rbio, &d))
1671 /* Non-pollable BIO */
1672 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1673
1674 if (!validate_poll_descriptor(&d))
1675 return 0;
1676 }
1677
1678 ossl_quic_reactor_set_poll_r(&ch->rtor, &d);
f538b421
HL
1679 ossl_quic_demux_set_bio(ch->demux, net_rbio);
1680 ch->net_rbio = net_rbio;
1681 return 1;
1682}
1683
d1ac77b1 1684int ossl_quic_channel_set_net_wbio(QUIC_CHANNEL *ch, BIO *net_wbio)
f538b421
HL
1685{
1686 BIO_POLL_DESCRIPTOR d = {0};
1687
1688 if (ch->net_wbio == net_wbio)
1689 return 1;
1690
1691 if (net_wbio != NULL) {
1692 if (!BIO_get_wpoll_descriptor(net_wbio, &d))
1693 /* Non-pollable BIO */
1694 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1695
1696 if (!validate_poll_descriptor(&d))
1697 return 0;
1698 }
1699
1700 ossl_quic_reactor_set_poll_w(&ch->rtor, &d);
f538b421
HL
1701 ossl_qtx_set_bio(ch->qtx, net_wbio);
1702 ch->net_wbio = net_wbio;
1703 return 1;
1704}
1705
1706/*
1707 * QUIC Channel: Lifecycle Events
1708 * ==============================
1709 */
f538b421
HL
1710int ossl_quic_channel_start(QUIC_CHANNEL *ch)
1711{
b1b06da2
HL
1712 if (ch->is_server)
1713 /*
1714 * This is not used by the server. The server moves to active
1715 * automatically on receiving an incoming connection.
1716 */
1717 return 0;
1718
f538b421
HL
1719 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1720 /* Calls to connect are idempotent */
1721 return 1;
1722
1723 /* Inform QTX of peer address. */
1724 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
1725 return 0;
1726
1727 /* Plug in secrets for the Initial EL. */
1728 if (!ossl_quic_provide_initial_secret(ch->libctx,
1729 ch->propq,
1730 &ch->init_dcid,
091f532e 1731 ch->is_server,
f538b421
HL
1732 ch->qrx, ch->qtx))
1733 return 0;
1734
1735 /* Change state. */
1736 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
1737 ch->doing_proactive_ver_neg = 0; /* not currently supported */
1738
1739 /* Handshake layer: start (e.g. send CH). */
2723d705 1740 if (!ossl_quic_tls_tick(ch->qtls))
f538b421
HL
1741 return 0;
1742
1743 ossl_quic_reactor_tick(&ch->rtor); /* best effort */
1744 return 1;
1745}
1746
1747/* Start a locally initiated connection shutdown. */
e8043229 1748void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code)
f538b421
HL
1749{
1750 QUIC_TERMINATE_CAUSE tcause = {0};
1751
c12e1113 1752 if (ossl_quic_channel_is_term_any(ch))
f538b421
HL
1753 return;
1754
e8043229
HL
1755 tcause.app = 1;
1756 tcause.error_code = app_error_code;
df15e990 1757 ch_start_terminating(ch, &tcause, 0);
f538b421
HL
1758}
1759
1760static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
1761{
1762 OPENSSL_free((unsigned char *)buf);
1763}
1764
1765/* Called when a server asks us to do a retry. */
1766static int ch_retry(QUIC_CHANNEL *ch,
1767 const unsigned char *retry_token,
1768 size_t retry_token_len,
1769 const QUIC_CONN_ID *retry_scid)
1770{
1771 void *buf;
1772
1773 /* We change to using the SCID in the Retry packet as the DCID. */
1774 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
1775 return 0;
1776
1777 /*
1778 * Now we retry. We will release the Retry packet immediately, so copy
1779 * the token.
1780 */
e28f512f 1781 if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
f538b421
HL
1782 return 0;
1783
f538b421
HL
1784 ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf, retry_token_len,
1785 free_token, NULL);
1786
1787 ch->retry_scid = *retry_scid;
1788 ch->doing_retry = 1;
1789
1790 /*
1791 * We need to stimulate the Initial EL to generate the first CRYPTO frame
1792 * again. We can do this most cleanly by simply forcing the ACKM to consider
1793 * the first Initial packet as lost, which it effectively was as the server
1794 * hasn't processed it. This also maintains the desired behaviour with e.g.
1795 * PNs not resetting and so on.
1796 *
1797 * The PN we used initially is always zero, because QUIC does not allow
1798 * repeated retries.
1799 */
1800 if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
1801 /*PN=*/0))
1802 return 0;
1803
1804 /*
1805 * Plug in new secrets for the Initial EL. This is the only time we change
1806 * the secrets for an EL after we already provisioned it.
1807 */
1808 if (!ossl_quic_provide_initial_secret(ch->libctx,
1809 ch->propq,
1810 &ch->retry_scid,
1811 /*is_server=*/0,
1812 ch->qrx, ch->qtx))
1813 return 0;
1814
1815 return 1;
1816}
1817
1818/* Called when an EL is to be discarded. */
1819static int ch_discard_el(QUIC_CHANNEL *ch,
1820 uint32_t enc_level)
1821{
1822 if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
1823 return 0;
1824
1825 if ((ch->el_discarded & (1U << enc_level)) != 0)
1826 /* Already done. */
1827 return 1;
1828
1829 /* Best effort for all of these. */
1830 ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
1831 ossl_qrx_discard_enc_level(ch->qrx, enc_level);
1832 ossl_qtx_discard_enc_level(ch->qtx, enc_level);
1833
1834 if (enc_level != QUIC_ENC_LEVEL_0RTT) {
1835 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1836
1837 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
1838
1839 /* We should still have crypto streams at this point. */
79534440
HL
1840 if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
1841 || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
1842 return 0;
f538b421
HL
1843
1844 /* Get rid of the crypto stream state for the EL. */
1845 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
1846 ch->crypto_send[pn_space] = NULL;
1847
1848 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
1849 ch->crypto_recv[pn_space] = NULL;
1850 }
1851
1852 ch->el_discarded |= (1U << enc_level);
1853 return 1;
1854}
1855
1856/* Intended to be called by the RXDP. */
1857int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
1858{
1859 if (ch->handshake_confirmed)
1860 return 1;
1861
1862 if (!ch->handshake_complete) {
1863 /*
1864 * Does not make sense for handshake to be confirmed before it is
1865 * completed.
1866 */
1867 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
1868 OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
1869 "handshake cannot be confirmed "
1870 "before it is completed");
1871 return 0;
1872 }
1873
1874 ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
1875 ch->handshake_confirmed = 1;
1876 return 1;
1877}
1878
1879/*
1880 * Master function used when we want to start tearing down a connection:
1881 *
1882 * - If the connection is still IDLE we can go straight to TERMINATED;
1883 *
1884 * - If we are already TERMINATED this is a no-op.
1885 *
1886 * - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
9bbc5b54 1887 * from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
f538b421
HL
1888 *
1889 * - If we are TERMINATING - DRAINING, we remain here until the terminating
1890 * timer expires.
1891 *
1892 * - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
1893 * if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
1894 * that we are considered to have caused a termination if we sent the first
1895 * CONNECTION_CLOSE frame, even if it is caused by a peer protocol
1896 * violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
1897 * TERMINATING - DRAINING.
1898 *
1899 * We record the termination cause structure passed on the first call only.
1900 * Any successive calls have their termination cause data discarded;
1901 * once we start sending a CONNECTION_CLOSE frame, we don't change the details
1902 * in it.
1903 */
1904static void ch_start_terminating(QUIC_CHANNEL *ch,
df15e990
HL
1905 const QUIC_TERMINATE_CAUSE *tcause,
1906 int force_immediate)
f538b421
HL
1907{
1908 switch (ch->state) {
75b2920a
HL
1909 default:
1910 case QUIC_CHANNEL_STATE_IDLE:
1911 ch->terminate_cause = *tcause;
1912 ch_on_terminating_timeout(ch);
1913 break;
1914
1915 case QUIC_CHANNEL_STATE_ACTIVE:
75b2920a 1916 ch->terminate_cause = *tcause;
df15e990
HL
1917
1918 if (!force_immediate) {
1919 ch->state = tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
1920 : QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
1921 ch->terminate_deadline
1922 = ossl_time_add(ossl_time_now(),
1923 ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
1924 3));
1925
1926 if (!tcause->remote) {
1927 OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
1928
1929 /* best effort */
1930 f.error_code = ch->terminate_cause.error_code;
1931 f.frame_type = ch->terminate_cause.frame_type;
1932 f.is_app = ch->terminate_cause.app;
1933 ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
1934 ch->conn_close_queued = 1;
1935 }
1936 } else {
1937 ch_on_terminating_timeout(ch);
75b2920a
HL
1938 }
1939 break;
f538b421 1940
75b2920a 1941 case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
df15e990
HL
1942 if (force_immediate)
1943 ch_on_terminating_timeout(ch);
1944 else if (tcause->remote)
75b2920a 1945 ch->state = QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
f538b421 1946
75b2920a 1947 break;
f538b421 1948
75b2920a 1949 case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
df15e990
HL
1950 /*
1951 * Other than in the force-immediate case, we remain here until the
1952 * timout expires.
1953 */
1954 if (force_immediate)
1955 ch_on_terminating_timeout(ch);
1956
75b2920a 1957 break;
f538b421 1958
75b2920a
HL
1959 case QUIC_CHANNEL_STATE_TERMINATED:
1960 /* No-op. */
1961 break;
f538b421
HL
1962 }
1963}
1964
1965/* For RXDP use. */
1966void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
1967 OSSL_QUIC_FRAME_CONN_CLOSE *f)
1968{
1969 QUIC_TERMINATE_CAUSE tcause = {0};
1970
1971 if (!ossl_quic_channel_is_active(ch))
1972 return;
1973
1974 tcause.remote = 1;
1975 tcause.app = f->is_app;
1976 tcause.error_code = f->error_code;
1977 tcause.frame_type = f->frame_type;
1978
df15e990
HL
1979 ch_start_terminating(ch, &tcause, 0);
1980}
1981
1982static void ch_raise_net_error(QUIC_CHANNEL *ch)
1983{
1984 QUIC_TERMINATE_CAUSE tcause = {0};
1985
1986 tcause.error_code = QUIC_ERR_INTERNAL_ERROR;
1987
1988 /*
1989 * Skip Terminating state and go directly to Terminated, no point trying to
1990 * send CONNECTION_CLOSE if we cannot communicate.
1991 */
1992 ch_start_terminating(ch, &tcause, 1);
f538b421
HL
1993}
1994
1995void ossl_quic_channel_raise_protocol_error(QUIC_CHANNEL *ch,
1996 uint64_t error_code,
1997 uint64_t frame_type,
1998 const char *reason)
1999{
2000 QUIC_TERMINATE_CAUSE tcause = {0};
2001
2002 tcause.error_code = error_code;
2003 tcause.frame_type = frame_type;
2004
df15e990 2005 ch_start_terminating(ch, &tcause, 0);
f538b421
HL
2006}
2007
2008/*
2009 * Called once the terminating timer expires, meaning we move from TERMINATING
2010 * to TERMINATED.
2011 */
2012static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
2013{
2014 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2015}
2016
2017/*
2018 * Updates our idle deadline. Called when an event happens which should bump the
2019 * idle timeout.
2020 */
2021static void ch_update_idle(QUIC_CHANNEL *ch)
2022{
2023 if (ch->max_idle_timeout == 0)
2024 ch->idle_deadline = ossl_time_infinite();
2025 else
2026 ch->idle_deadline = ossl_time_add(ossl_time_now(),
2027 ossl_ms2time(ch->max_idle_timeout));
2028}
2029
2030/* Called when the idle timeout expires. */
2031static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
2032{
2033 /*
2034 * Idle timeout does not have an error code associated with it because a
2035 * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
2036 * TERMINATED anyway.
2037 */
2038 ch->terminate_cause.app = 0;
2039 ch->terminate_cause.error_code = UINT64_MAX;
2040 ch->terminate_cause.frame_type = 0;
2041
2042 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2043}
b1b06da2
HL
2044
2045/* Called when we, as a server, get a new incoming connection. */
2046static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
2047 const QUIC_CONN_ID *peer_scid,
2048 const QUIC_CONN_ID *peer_dcid)
2049{
2050 if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
2051 return 0;
2052
2053 /* Generate a SCID we will use for the connection. */
2054 if (!gen_rand_conn_id(ch->libctx, INIT_DCID_LEN,
2055 &ch->cur_local_dcid))
2056 return 0;
2057
2058 /* Note our newly learnt peer address and CIDs. */
2059 ch->cur_peer_addr = *peer;
2060 ch->init_dcid = *peer_dcid;
2061 ch->cur_remote_dcid = *peer_scid;
2062
2063 /* Inform QTX of peer address. */
2064 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2065 return 0;
2066
2067 /* Inform TXP of desired CIDs. */
2068 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
2069 return 0;
2070
2071 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_dcid))
2072 return 0;
2073
2074 /* Plug in secrets for the Initial EL. */
2075 if (!ossl_quic_provide_initial_secret(ch->libctx,
2076 ch->propq,
2077 &ch->init_dcid,
2078 /*is_server=*/1,
2079 ch->qrx, ch->qtx))
2080 return 0;
2081
2082 /* Register our local DCID in the DEMUX. */
2083 if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_dcid))
2084 return 0;
2085
2086 /* Change state. */
2087 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
2088 ch->doing_proactive_ver_neg = 0; /* not currently supported */
2089 return 1;
2090}
d03fe5de
MC
2091
2092SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)
2093{
2094 return ch->tls;
2095}