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