482f696e11bbdb67114cad2ab4fa185ee6abf9c9
[openssl.git] / ssl / quic / quic_port.c
1 /*
2  * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/quic_port.h"
11 #include "internal/quic_channel.h"
12 #include "internal/quic_lcidm.h"
13 #include "internal/quic_srtm.h"
14 #include "quic_port_local.h"
15 #include "quic_channel_local.h"
16 #include "../ssl_local.h"
17
18 /*
19  * QUIC Port Structure
20  * ===================
21  */
22 #define INIT_DCID_LEN                   8
23
24 static int port_init(QUIC_PORT *port);
25 static void port_cleanup(QUIC_PORT *port);
26 static OSSL_TIME get_time(void *arg);
27 static void port_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags);
28 static void port_default_packet_handler(QUIC_URXE *e, void *arg,
29                                         const QUIC_CONN_ID *dcid);
30 static void port_rx_pre(QUIC_PORT *port);
31
32 DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL);
33
34 QUIC_PORT *ossl_quic_port_new(const QUIC_PORT_ARGS *args)
35 {
36     QUIC_PORT *port;
37
38     if ((port = OPENSSL_zalloc(sizeof(QUIC_PORT))) == NULL)
39         return NULL;
40
41     port->libctx        = args->libctx;
42     port->propq         = args->propq;
43     port->mutex         = args->mutex;
44     port->now_cb        = args->now_cb;
45     port->now_cb_arg    = args->now_cb_arg;
46     port->channel_ctx   = args->channel_ctx;
47     port->is_multi_conn = args->is_multi_conn;
48
49     if (!port_init(port)) {
50         OPENSSL_free(port);
51         return NULL;
52     }
53
54     return port;
55 }
56
57 void ossl_quic_port_free(QUIC_PORT *port)
58 {
59     if (port == NULL)
60         return;
61
62     port_cleanup(port);
63     OPENSSL_free(port);
64 }
65
66 static int port_init(QUIC_PORT *port)
67 {
68     size_t rx_short_dcid_len = (port->is_multi_conn ? INIT_DCID_LEN : 0);
69
70     if (port->channel_ctx == NULL)
71         goto err;
72
73     if ((port->demux = ossl_quic_demux_new(/*BIO=*/NULL,
74                                            /*Short CID Len=*/rx_short_dcid_len,
75                                            get_time, port)) == NULL)
76         goto err;
77
78     ossl_quic_demux_set_default_handler(port->demux,
79                                         port_default_packet_handler,
80                                         port);
81
82     if ((port->srtm = ossl_quic_srtm_new(port->libctx, port->propq)) == NULL)
83         goto err;
84
85     if ((port->lcidm = ossl_quic_lcidm_new(port->libctx, rx_short_dcid_len)) == NULL)
86         goto err;
87
88     ossl_quic_reactor_init(&port->rtor, port_tick, port, ossl_time_zero());
89     port->rx_short_dcid_len = (unsigned char)rx_short_dcid_len;
90     port->tx_init_dcid_len  = INIT_DCID_LEN;
91     return 1;
92
93 err:
94     port_cleanup(port);
95     return 0;
96 }
97
98 static void port_cleanup(QUIC_PORT *port)
99 {
100     assert(ossl_list_ch_num(&port->channel_list) == 0);
101
102     ossl_quic_demux_free(port->demux);
103     port->demux = NULL;
104
105     ossl_quic_srtm_free(port->srtm);
106     port->srtm = NULL;
107
108     ossl_quic_lcidm_free(port->lcidm);
109     port->lcidm = NULL;
110 }
111
112 QUIC_REACTOR *ossl_quic_port_get0_reactor(QUIC_PORT *port)
113 {
114     return &port->rtor;
115 }
116
117 QUIC_DEMUX *ossl_quic_port_get0_demux(QUIC_PORT *port)
118 {
119     return port->demux;
120 }
121
122 CRYPTO_MUTEX *ossl_quic_port_get0_mutex(QUIC_PORT *port)
123 {
124     return port->mutex;
125 }
126
127 OSSL_TIME ossl_quic_port_get_time(QUIC_PORT *port)
128 {
129     if (port->now_cb == NULL)
130         return ossl_time_now();
131
132     return port->now_cb(port->now_cb_arg);
133 }
134
135 static OSSL_TIME get_time(void *port)
136 {
137     return ossl_quic_port_get_time(port);
138 }
139
140 int ossl_quic_port_get_rx_short_dcid_len(const QUIC_PORT *port)
141 {
142     return port->rx_short_dcid_len;
143 }
144
145 int ossl_quic_port_get_tx_init_dcid_len(const QUIC_PORT *port)
146 {
147     return port->tx_init_dcid_len;
148 }
149
150 /*
151  * QUIC Port: Network BIO Configuration
152  * ====================================
153  */
154
155 /* Determines whether we can support a given poll descriptor. */
156 static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
157 {
158     if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0) {
159         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
160         return 0;
161     }
162
163     return 1;
164 }
165
166 BIO *ossl_quic_port_get_net_rbio(QUIC_PORT *port)
167 {
168     return port->net_rbio;
169 }
170
171 BIO *ossl_quic_port_get_net_wbio(QUIC_PORT *port)
172 {
173     return port->net_wbio;
174 }
175
176 static int port_update_poll_desc(QUIC_PORT *port, BIO *net_bio, int for_write)
177 {
178     BIO_POLL_DESCRIPTOR d = {0};
179
180     if (net_bio == NULL
181         || (!for_write && !BIO_get_rpoll_descriptor(net_bio, &d))
182         || (for_write && !BIO_get_wpoll_descriptor(net_bio, &d)))
183         /* Non-pollable BIO */
184         d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
185
186     if (!validate_poll_descriptor(&d))
187         return 0;
188
189     if (for_write)
190         ossl_quic_reactor_set_poll_w(&port->rtor, &d);
191     else
192         ossl_quic_reactor_set_poll_r(&port->rtor, &d);
193
194     return 1;
195 }
196
197 int ossl_quic_port_update_poll_descriptors(QUIC_PORT *port)
198 {
199     int ok = 1;
200
201     if (!port_update_poll_desc(port, port->net_rbio, /*for_write=*/0))
202         ok = 0;
203
204     if (!port_update_poll_desc(port, port->net_wbio, /*for_write=*/1))
205         ok = 0;
206
207     return ok;
208 }
209
210 /*
211  * QUIC_PORT does not ref any BIO it is provided with, nor is any ref
212  * transferred to it. The caller (e.g., QUIC_CONNECTION) is responsible for
213  * ensuring the BIO lasts until the channel is freed or the BIO is switched out
214  * for another BIO by a subsequent successful call to this function.
215  */
216 int ossl_quic_port_set_net_rbio(QUIC_PORT *port, BIO *net_rbio)
217 {
218     if (port->net_rbio == net_rbio)
219         return 1;
220
221     if (!port_update_poll_desc(port, net_rbio, /*for_write=*/0))
222         return 0;
223
224     ossl_quic_demux_set_bio(port->demux, net_rbio);
225     port->net_rbio = net_rbio;
226     return 1;
227 }
228
229 int ossl_quic_port_set_net_wbio(QUIC_PORT *port, BIO *net_wbio)
230 {
231     QUIC_CHANNEL *ch;
232
233     if (port->net_wbio == net_wbio)
234         return 1;
235
236     if (!port_update_poll_desc(port, net_wbio, /*for_write=*/1))
237         return 0;
238
239     LIST_FOREACH(ch, ch, &port->channel_list)
240         ossl_qtx_set_bio(ch->qtx, net_wbio);
241
242     port->net_wbio = net_wbio;
243     return 1;
244 }
245
246 /*
247  * QUIC Port: Channel Lifecycle
248  * ============================
249  */
250
251 static SSL *port_new_handshake_layer(QUIC_PORT *port)
252 {
253     SSL *tls = NULL;
254     SSL_CONNECTION *tls_conn = NULL;
255
256     tls = ossl_ssl_connection_new_int(port->channel_ctx, TLS_method());
257     if (tls == NULL || (tls_conn = SSL_CONNECTION_FROM_SSL(tls)) == NULL)
258         return NULL;
259
260     /* Override the user_ssl of the inner connection. */
261     tls_conn->s3.flags      |= TLS1_FLAGS_QUIC;
262
263     /* Restrict options derived from the SSL_CTX. */
264     tls_conn->options       &= OSSL_QUIC_PERMITTED_OPTIONS_CONN;
265     tls_conn->pha_enabled   = 0;
266     return tls;
267 }
268
269 static QUIC_CHANNEL *port_make_channel(QUIC_PORT *port, SSL *tls, int is_server)
270 {
271     QUIC_CHANNEL_ARGS args = {0};
272     QUIC_CHANNEL *ch;
273
274     args.port       = port;
275     args.is_server  = is_server;
276     args.tls        = (tls != NULL ? tls : port_new_handshake_layer(port));
277     args.lcidm      = port->lcidm;
278     args.srtm       = port->srtm;
279     if (args.tls == NULL)
280         return NULL;
281
282     ch = ossl_quic_channel_new(&args);
283     if (ch == NULL) {
284         if (tls == NULL)
285             SSL_free(args.tls);
286
287         return NULL;
288     }
289
290     return ch;
291 }
292
293 QUIC_CHANNEL *ossl_quic_port_create_outgoing(QUIC_PORT *port, SSL *tls)
294 {
295     return port_make_channel(port, tls, /*is_server=*/0);
296 }
297
298 QUIC_CHANNEL *ossl_quic_port_create_incoming(QUIC_PORT *port, SSL *tls)
299 {
300     QUIC_CHANNEL *ch;
301
302     assert(port->tserver_ch == NULL);
303
304     ch = port_make_channel(port, tls, /*is_server=*/1);
305     port->tserver_ch = ch;
306     return ch;
307 }
308
309 /*
310  * QUIC Port: Ticker-Mutator
311  * =========================
312  */
313
314 /*
315  * The central ticker function called by the reactor. This does everything, or
316  * at least everything network I/O related. Best effort - not allowed to fail
317  * "loudly".
318  */
319 static void port_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags)
320 {
321     QUIC_PORT *port = arg;
322     QUIC_CHANNEL *ch;
323
324     res->net_read_desired   = 0;
325     res->net_write_desired  = 0;
326     res->tick_deadline      = ossl_time_infinite();
327
328     if (!port->inhibit_tick) {
329         /* Handle any incoming data from network. */
330         port_rx_pre(port);
331
332         /* Iterate through all channels and service them. */
333         LIST_FOREACH(ch, ch, &port->channel_list) {
334             QUIC_TICK_RESULT subr = {0};
335
336             ossl_quic_channel_subtick(ch, &subr, flags);
337             ossl_quic_tick_result_merge_into(res, &subr);
338         }
339     }
340 }
341
342 /* Process incoming datagrams, if any. */
343 static void port_rx_pre(QUIC_PORT *port)
344 {
345     int ret;
346
347     // TODO !have_sent_any_pkt
348
349     /*
350      * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
351      * to the appropriate QRX instances.
352      */
353     ret = ossl_quic_demux_pump(port->demux);
354     if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
355         /*
356          * We don't care about transient failure, but permanent failure means we
357          * should tear down the port. All connections skip straight to the
358          * Terminated state as there is no point trying to send CONNECTION_CLOSE
359          * frames if the network BIO is not operating correctly.
360          */
361         ossl_quic_port_raise_net_error(port);
362 }
363
364 /*
365  * Handles an incoming connection request and potentially decides to make a
366  * connection from it. If a new connection is made, the new channel is written
367  * to *new_ch.
368  */
369 static void port_on_new_conn(QUIC_PORT *port, const BIO_ADDR *peer,
370                              const QUIC_CONN_ID *scid,
371                              const QUIC_CONN_ID *dcid,
372                              QUIC_CHANNEL **new_ch)
373 {
374     if (port->tserver_ch != NULL) {
375         /* Specially assign to existing channel */
376         if (!ossl_quic_channel_on_new_conn(port->tserver_ch, peer, scid, dcid))
377             return;
378
379         *new_ch = port->tserver_ch;
380         port->tserver_ch = NULL;
381         return;
382     }
383 }
384
385 static int port_try_handle_stateless_reset(QUIC_PORT *port, const QUIC_URXE *e)
386 {
387     size_t i;
388     const unsigned char *data = ossl_quic_urxe_data(e);
389     void *opaque = NULL;
390
391     /*
392      * Perform some fast and cheap checks for a packet not being a stateless
393      * reset token.  RFC 9000 s. 10.3 specifies this layout for stateless
394      * reset packets:
395      *
396      *  Stateless Reset {
397      *      Fixed Bits (2) = 1,
398      *      Unpredictable Bits (38..),
399      *      Stateless Reset Token (128),
400      *  }
401      *
402      * It also specifies:
403      *      However, endpoints MUST treat any packet ending in a valid
404      *      stateless reset token as a Stateless Reset, as other QUIC
405      *      versions might allow the use of a long header.
406      *
407      * We can rapidly check for the minimum length and that the first pair
408      * of bits in the first byte are 01 or 11.
409      *
410      * The function returns 1 if it is a stateless reset packet, 0 if it isn't
411      * and -1 if an error was encountered.
412      */
413     if (e->data_len < QUIC_STATELESS_RESET_TOKEN_LEN + 5
414         || (0100 & *data) != 0100)
415         return 0;
416
417     for (i = 0;; ++i) {
418         if (!ossl_quic_srtm_lookup(port->srtm,
419                                    (QUIC_STATELESS_RESET_TOKEN *)(data + e->data_len
420                                        - sizeof(QUIC_STATELESS_RESET_TOKEN)),
421                                    i, &opaque, NULL))
422             break;
423
424         assert(opaque != NULL);
425         ossl_quic_channel_on_stateless_reset((QUIC_CHANNEL *)opaque);
426     }
427
428     return i > 0;
429 }
430
431 /*
432  * This is called by the demux when we get a packet not destined for any known
433  * DCID.
434  */
435 static void port_default_packet_handler(QUIC_URXE *e, void *arg,
436                                         const QUIC_CONN_ID *dcid)
437 {
438     QUIC_PORT *port = arg;
439     PACKET pkt;
440     QUIC_PKT_HDR hdr;
441     QUIC_CHANNEL *ch = NULL, *new_ch = NULL;
442
443     if (dcid != NULL
444         && ossl_quic_lcidm_lookup(port->lcidm, dcid, NULL,
445                                   (void **)&ch)) {
446         assert(ch != NULL);
447         ossl_quic_channel_inject(ch, e);
448         return;
449     }
450
451     if (port_try_handle_stateless_reset(port, e))
452         goto undesirable;
453
454     // TODO review this
455     if (port->tserver_ch == NULL)
456         goto undesirable;
457
458     // TODO allow_incoming
459     //if (!ossl_assert(ch->is_server))
460     //    goto undesirable;
461
462     //TODO if (ch->state != QUIC_CHANNEL_STATE_IDLE)
463     //    goto undesirable;
464
465     /*
466      * We have got a packet for an unknown DCID. This might be an attempt to
467      * open a new connection.
468      */
469     if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
470         goto undesirable;
471
472     if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
473         goto undesirable;
474
475     /*
476      * We set short_conn_id_len to SIZE_MAX here which will cause the decode
477      * operation to fail if we get a 1-RTT packet. This is fine since we only
478      * care about Initial packets.
479      */
480     if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL))
481         goto undesirable;
482
483     switch (hdr.version) {
484         case QUIC_VERSION_1:
485             break;
486
487         case QUIC_VERSION_NONE:
488         default:
489             /* Unknown version or proactive version negotiation request, bail. */
490             /* TODO(QUIC SERVER): Handle version negotiation on server side */
491             goto undesirable;
492     }
493
494     /*
495      * We only care about Initial packets which might be trying to establish a
496      * connection.
497      */
498     if (hdr.type != QUIC_PKT_TYPE_INITIAL)
499         goto undesirable;
500
501     /*
502      * Try to process this as a valid attempt to initiate a connection.
503      *
504      * We do not register the DCID in the Initial packet we received as
505      * that DCID is not actually used again, thus after provisioning
506      * the new connection and associated Initial keys, we inject the
507      * received packet directly to the new channel's QRX so that it can
508      * process it as a one-time thing, instead of going through the usual
509      * DEMUX DCID-based routing.
510      */
511     port_on_new_conn(port, &e->peer, &hdr.src_conn_id, &hdr.dst_conn_id,
512                      &new_ch);
513     if (new_ch != NULL)
514         ossl_qrx_inject_urxe(new_ch->qrx, e);
515
516     return;
517
518 undesirable:
519     ossl_quic_demux_release_urxe(port->demux, e);
520 }
521
522 void ossl_quic_port_set_inhibit_tick(QUIC_PORT *port, int inhibit)
523 {
524     port->inhibit_tick = (inhibit != 0);
525 }
526
527 void ossl_quic_port_raise_net_error(QUIC_PORT *port)
528 {
529     QUIC_CHANNEL *ch;
530
531     // TODO fsm
532
533     LIST_FOREACH(ch, ch, &port->channel_list)
534         ossl_quic_channel_raise_net_error(ch);
535 }