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