0de384de454e877741bec8e158797d4d710c1a53
[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 "quic_engine_local.h"
17 #include "../ssl_local.h"
18
19 /*
20  * QUIC Port Structure
21  * ===================
22  */
23 #define INIT_DCID_LEN                   8
24
25 static int port_init(QUIC_PORT *port);
26 static void port_cleanup(QUIC_PORT *port);
27 static OSSL_TIME get_time(void *arg);
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 DEFINE_LIST_OF_IMPL(port, QUIC_PORT);
34
35 QUIC_PORT *ossl_quic_port_new(const QUIC_PORT_ARGS *args)
36 {
37     QUIC_PORT *port;
38
39     if ((port = OPENSSL_zalloc(sizeof(QUIC_PORT))) == NULL)
40         return NULL;
41
42     port->engine        = args->engine;
43     port->channel_ctx   = args->channel_ctx;
44     port->is_multi_conn = args->is_multi_conn;
45
46     if (!port_init(port)) {
47         OPENSSL_free(port);
48         return NULL;
49     }
50
51     return port;
52 }
53
54 void ossl_quic_port_free(QUIC_PORT *port)
55 {
56     if (port == NULL)
57         return;
58
59     port_cleanup(port);
60     OPENSSL_free(port);
61 }
62
63 static int port_init(QUIC_PORT *port)
64 {
65     size_t rx_short_dcid_len = (port->is_multi_conn ? INIT_DCID_LEN : 0);
66
67     if (port->engine == NULL || port->channel_ctx == NULL)
68         goto err;
69
70     if ((port->err_state = OSSL_ERR_STATE_new()) == 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->engine->libctx,
83                                          port->engine->propq)) == NULL)
84         goto err;
85
86     if ((port->lcidm = ossl_quic_lcidm_new(port->engine->libctx,
87                                            rx_short_dcid_len)) == NULL)
88         goto err;
89
90     port->rx_short_dcid_len = (unsigned char)rx_short_dcid_len;
91     port->tx_init_dcid_len  = INIT_DCID_LEN;
92     port->state             = QUIC_PORT_STATE_RUNNING;
93
94     ossl_list_port_insert_tail(&port->engine->port_list, port);
95     port->on_engine_list    = 1;
96     return 1;
97
98 err:
99     port_cleanup(port);
100     return 0;
101 }
102
103 static void port_cleanup(QUIC_PORT *port)
104 {
105     assert(ossl_list_ch_num(&port->channel_list) == 0);
106
107     ossl_quic_demux_free(port->demux);
108     port->demux = NULL;
109
110     ossl_quic_srtm_free(port->srtm);
111     port->srtm = NULL;
112
113     ossl_quic_lcidm_free(port->lcidm);
114     port->lcidm = NULL;
115
116     OSSL_ERR_STATE_free(port->err_state);
117     port->err_state = NULL;
118
119     if (port->on_engine_list) {
120         ossl_list_port_remove(&port->engine->port_list, port);
121         port->on_engine_list = 0;
122     }
123 }
124
125 static void port_transition_failed(QUIC_PORT *port)
126 {
127     if (port->state == QUIC_PORT_STATE_FAILED)
128         return;
129
130     port->state = QUIC_PORT_STATE_FAILED;
131 }
132
133 int ossl_quic_port_is_running(const QUIC_PORT *port)
134 {
135     return port->state == QUIC_PORT_STATE_RUNNING;
136 }
137
138 QUIC_ENGINE *ossl_quic_port_get0_engine(QUIC_PORT *port)
139 {
140     return port->engine;
141 }
142
143 QUIC_REACTOR *ossl_quic_port_get0_reactor(QUIC_PORT *port)
144 {
145     return ossl_quic_engine_get0_reactor(port->engine);
146 }
147
148 QUIC_DEMUX *ossl_quic_port_get0_demux(QUIC_PORT *port)
149 {
150     return port->demux;
151 }
152
153 CRYPTO_MUTEX *ossl_quic_port_get0_mutex(QUIC_PORT *port)
154 {
155     return ossl_quic_engine_get0_mutex(port->engine);
156 }
157
158 OSSL_TIME ossl_quic_port_get_time(QUIC_PORT *port)
159 {
160     return ossl_quic_engine_get_time(port->engine);
161 }
162
163 static OSSL_TIME get_time(void *port)
164 {
165     return ossl_quic_port_get_time((QUIC_PORT *)port);
166 }
167
168 int ossl_quic_port_get_rx_short_dcid_len(const QUIC_PORT *port)
169 {
170     return port->rx_short_dcid_len;
171 }
172
173 int ossl_quic_port_get_tx_init_dcid_len(const QUIC_PORT *port)
174 {
175     return port->tx_init_dcid_len;
176 }
177
178 /*
179  * QUIC Port: Network BIO Configuration
180  * ====================================
181  */
182
183 /* Determines whether we can support a given poll descriptor. */
184 static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
185 {
186     if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0) {
187         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
188         return 0;
189     }
190
191     return 1;
192 }
193
194 BIO *ossl_quic_port_get_net_rbio(QUIC_PORT *port)
195 {
196     return port->net_rbio;
197 }
198
199 BIO *ossl_quic_port_get_net_wbio(QUIC_PORT *port)
200 {
201     return port->net_wbio;
202 }
203
204 static int port_update_poll_desc(QUIC_PORT *port, BIO *net_bio, int for_write)
205 {
206     BIO_POLL_DESCRIPTOR d = {0};
207
208     if (net_bio == NULL
209         || (!for_write && !BIO_get_rpoll_descriptor(net_bio, &d))
210         || (for_write && !BIO_get_wpoll_descriptor(net_bio, &d)))
211         /* Non-pollable BIO */
212         d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
213
214     if (!validate_poll_descriptor(&d))
215         return 0;
216
217     /*
218      * TODO(QUIC MULTIPORT): We currently only support one port per
219      * engine/domain. This is necessitated because QUIC_REACTOR only supports a
220      * single pollable currently. In the future, once complete polling
221      * infrastructure has been implemented, this limitation can be removed.
222      *
223      * For now, just update the descriptor on the the engine's reactor as we are
224      * guaranteed to be the only port under it.
225      */
226     if (for_write)
227         ossl_quic_reactor_set_poll_w(&port->engine->rtor, &d);
228     else
229         ossl_quic_reactor_set_poll_r(&port->engine->rtor, &d);
230
231     return 1;
232 }
233
234 int ossl_quic_port_update_poll_descriptors(QUIC_PORT *port)
235 {
236     int ok = 1;
237
238     if (!port_update_poll_desc(port, port->net_rbio, /*for_write=*/0))
239         ok = 0;
240
241     if (!port_update_poll_desc(port, port->net_wbio, /*for_write=*/1))
242         ok = 0;
243
244     return ok;
245 }
246
247 /*
248  * QUIC_PORT does not ref any BIO it is provided with, nor is any ref
249  * transferred to it. The caller (e.g., QUIC_CONNECTION) is responsible for
250  * ensuring the BIO lasts until the channel is freed or the BIO is switched out
251  * for another BIO by a subsequent successful call to this function.
252  */
253 int ossl_quic_port_set_net_rbio(QUIC_PORT *port, BIO *net_rbio)
254 {
255     if (port->net_rbio == net_rbio)
256         return 1;
257
258     if (!port_update_poll_desc(port, net_rbio, /*for_write=*/0))
259         return 0;
260
261     ossl_quic_demux_set_bio(port->demux, net_rbio);
262     port->net_rbio = net_rbio;
263     return 1;
264 }
265
266 int ossl_quic_port_set_net_wbio(QUIC_PORT *port, BIO *net_wbio)
267 {
268     QUIC_CHANNEL *ch;
269
270     if (port->net_wbio == net_wbio)
271         return 1;
272
273     if (!port_update_poll_desc(port, net_wbio, /*for_write=*/1))
274         return 0;
275
276     LIST_FOREACH(ch, ch, &port->channel_list)
277         ossl_qtx_set_bio(ch->qtx, net_wbio);
278
279     port->net_wbio = net_wbio;
280     return 1;
281 }
282
283 /*
284  * QUIC Port: Channel Lifecycle
285  * ============================
286  */
287
288 static SSL *port_new_handshake_layer(QUIC_PORT *port)
289 {
290     SSL *tls = NULL;
291     SSL_CONNECTION *tls_conn = NULL;
292
293     tls = ossl_ssl_connection_new_int(port->channel_ctx, TLS_method());
294     if (tls == NULL || (tls_conn = SSL_CONNECTION_FROM_SSL(tls)) == NULL)
295         return NULL;
296
297     /* Override the user_ssl of the inner connection. */
298     tls_conn->s3.flags      |= TLS1_FLAGS_QUIC;
299
300     /* Restrict options derived from the SSL_CTX. */
301     tls_conn->options       &= OSSL_QUIC_PERMITTED_OPTIONS_CONN;
302     tls_conn->pha_enabled   = 0;
303     return tls;
304 }
305
306 static QUIC_CHANNEL *port_make_channel(QUIC_PORT *port, SSL *tls, int is_server)
307 {
308     QUIC_CHANNEL_ARGS args = {0};
309     QUIC_CHANNEL *ch;
310
311     args.port       = port;
312     args.is_server  = is_server;
313     args.tls        = (tls != NULL ? tls : port_new_handshake_layer(port));
314     args.lcidm      = port->lcidm;
315     args.srtm       = port->srtm;
316     if (args.tls == NULL)
317         return NULL;
318
319     ch = ossl_quic_channel_new(&args);
320     if (ch == NULL) {
321         if (tls == NULL)
322             SSL_free(args.tls);
323
324         return NULL;
325     }
326
327     return ch;
328 }
329
330 QUIC_CHANNEL *ossl_quic_port_create_outgoing(QUIC_PORT *port, SSL *tls)
331 {
332     return port_make_channel(port, tls, /*is_server=*/0);
333 }
334
335 QUIC_CHANNEL *ossl_quic_port_create_incoming(QUIC_PORT *port, SSL *tls)
336 {
337     QUIC_CHANNEL *ch;
338
339     assert(port->tserver_ch == NULL);
340
341     ch = port_make_channel(port, tls, /*is_server=*/1);
342     port->tserver_ch = ch;
343     port->is_server  = 1;
344     return ch;
345 }
346
347 /*
348  * QUIC Port: Ticker-Mutator
349  * =========================
350  */
351
352 /*
353  * Tick function for this port. This does everything related to network I/O for
354  * this port's network BIOs, and services child channels.
355  */
356 void ossl_quic_port_subtick(QUIC_PORT *port, QUIC_TICK_RESULT *res,
357                             uint32_t flags)
358 {
359     QUIC_CHANNEL *ch;
360
361     res->net_read_desired   = 0;
362     res->net_write_desired  = 0;
363     res->tick_deadline      = ossl_time_infinite();
364
365     if (!port->engine->inhibit_tick) {
366         /* Handle any incoming data from network. */
367         if (ossl_quic_port_is_running(port))
368             port_rx_pre(port);
369
370         /* Iterate through all channels and service them. */
371         LIST_FOREACH(ch, ch, &port->channel_list) {
372             QUIC_TICK_RESULT subr = {0};
373
374             ossl_quic_channel_subtick(ch, &subr, flags);
375             ossl_quic_tick_result_merge_into(res, &subr);
376         }
377     }
378 }
379
380 /* Process incoming datagrams, if any. */
381 static void port_rx_pre(QUIC_PORT *port)
382 {
383     int ret;
384
385     /*
386      * Originally, this check (don't RX before we have sent anything if we are
387      * not a server, because there can't be anything) was just intended as a
388      * minor optimisation. However, it is actually required on Windows, and
389      * removing this check will cause Windows to break.
390      *
391      * The reason is that under Win32, recvfrom() does not work on a UDP socket
392      * which has not had bind() called (???). However, calling sendto() will
393      * automatically bind an unbound UDP socket. Therefore, if we call a Winsock
394      * recv-type function before calling a Winsock send-type function, that call
395      * will fail with WSAEINVAL, which we will regard as a permanent network
396      * error.
397      *
398      * Therefore, this check is essential as we do not require our API users to
399      * bind a socket first when using the API in client mode.
400      */
401     if (!port->is_server && !port->have_sent_any_pkt)
402         return;
403
404     /*
405      * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
406      * to the appropriate QRX instances.
407      */
408     ret = ossl_quic_demux_pump(port->demux);
409     if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
410         /*
411          * We don't care about transient failure, but permanent failure means we
412          * should tear down the port. All connections skip straight to the
413          * Terminated state as there is no point trying to send CONNECTION_CLOSE
414          * frames if the network BIO is not operating correctly.
415          */
416         ossl_quic_port_raise_net_error(port, NULL);
417 }
418
419 /*
420  * Handles an incoming connection request and potentially decides to make a
421  * connection from it. If a new connection is made, the new channel is written
422  * to *new_ch.
423  */
424 static void port_on_new_conn(QUIC_PORT *port, const BIO_ADDR *peer,
425                              const QUIC_CONN_ID *scid,
426                              const QUIC_CONN_ID *dcid,
427                              QUIC_CHANNEL **new_ch)
428 {
429     if (port->tserver_ch != NULL) {
430         /* Specially assign to existing channel */
431         if (!ossl_quic_channel_on_new_conn(port->tserver_ch, peer, scid, dcid))
432             return;
433
434         *new_ch = port->tserver_ch;
435         port->tserver_ch = NULL;
436         return;
437     }
438 }
439
440 static int port_try_handle_stateless_reset(QUIC_PORT *port, const QUIC_URXE *e)
441 {
442     size_t i;
443     const unsigned char *data = ossl_quic_urxe_data(e);
444     void *opaque = NULL;
445
446     /*
447      * Perform some fast and cheap checks for a packet not being a stateless
448      * reset token.  RFC 9000 s. 10.3 specifies this layout for stateless
449      * reset packets:
450      *
451      *  Stateless Reset {
452      *      Fixed Bits (2) = 1,
453      *      Unpredictable Bits (38..),
454      *      Stateless Reset Token (128),
455      *  }
456      *
457      * It also specifies:
458      *      However, endpoints MUST treat any packet ending in a valid
459      *      stateless reset token as a Stateless Reset, as other QUIC
460      *      versions might allow the use of a long header.
461      *
462      * We can rapidly check for the minimum length and that the first pair
463      * of bits in the first byte are 01 or 11.
464      *
465      * The function returns 1 if it is a stateless reset packet, 0 if it isn't
466      * and -1 if an error was encountered.
467      */
468     if (e->data_len < QUIC_STATELESS_RESET_TOKEN_LEN + 5
469         || (0100 & *data) != 0100)
470         return 0;
471
472     for (i = 0;; ++i) {
473         if (!ossl_quic_srtm_lookup(port->srtm,
474                                    (QUIC_STATELESS_RESET_TOKEN *)(data + e->data_len
475                                    - sizeof(QUIC_STATELESS_RESET_TOKEN)),
476                                    i, &opaque, NULL))
477             break;
478
479         assert(opaque != NULL);
480         ossl_quic_channel_on_stateless_reset((QUIC_CHANNEL *)opaque);
481     }
482
483     return i > 0;
484 }
485
486 /*
487  * This is called by the demux when we get a packet not destined for any known
488  * DCID.
489  */
490 static void port_default_packet_handler(QUIC_URXE *e, void *arg,
491                                         const QUIC_CONN_ID *dcid)
492 {
493     QUIC_PORT *port = arg;
494     PACKET pkt;
495     QUIC_PKT_HDR hdr;
496     QUIC_CHANNEL *ch = NULL, *new_ch = NULL;
497
498     /* Don't handle anything if we are no longer running. */
499     if (!ossl_quic_port_is_running(port))
500         goto undesirable;
501
502     if (port_try_handle_stateless_reset(port, e))
503         goto undesirable;
504
505     if (dcid != NULL
506         && ossl_quic_lcidm_lookup(port->lcidm, dcid, NULL,
507                                   (void **)&ch)) {
508         assert(ch != NULL);
509         ossl_quic_channel_inject(ch, e);
510         return;
511     }
512
513     /*
514      * If we have an incoming packet which doesn't match any existing connection
515      * we assume this is an attempt to make a new connection. Currently we
516      * require our caller to have precreated a latent 'incoming' channel via
517      * TSERVER which then gets turned into the new connection.
518      *
519      * TODO(QUIC SERVER): In the future we will construct channels dynamically
520      * in this case.
521      */
522     if (port->tserver_ch == NULL)
523         goto undesirable;
524
525     /*
526      * We have got a packet for an unknown DCID. This might be an attempt to
527      * open a new connection.
528      */
529     if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
530         goto undesirable;
531
532     if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
533         goto undesirable;
534
535     /*
536      * We set short_conn_id_len to SIZE_MAX here which will cause the decode
537      * operation to fail if we get a 1-RTT packet. This is fine since we only
538      * care about Initial packets.
539      */
540     if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL))
541         goto undesirable;
542
543     switch (hdr.version) {
544         case QUIC_VERSION_1:
545             break;
546
547         case QUIC_VERSION_NONE:
548         default:
549             /* Unknown version or proactive version negotiation request, bail. */
550             /* TODO(QUIC SERVER): Handle version negotiation on server side */
551             goto undesirable;
552     }
553
554     /*
555      * We only care about Initial packets which might be trying to establish a
556      * connection.
557      */
558     if (hdr.type != QUIC_PKT_TYPE_INITIAL)
559         goto undesirable;
560
561     /*
562      * Try to process this as a valid attempt to initiate a connection.
563      *
564      * The channel will do all the LCID registration needed, but as an
565      * optimization inject this packet directly into the channel's QRX for
566      * processing without going through the DEMUX again.
567      */
568     port_on_new_conn(port, &e->peer, &hdr.src_conn_id, &hdr.dst_conn_id,
569                      &new_ch);
570     if (new_ch != NULL)
571         ossl_qrx_inject_urxe(new_ch->qrx, e);
572
573     return;
574
575 undesirable:
576     ossl_quic_demux_release_urxe(port->demux, e);
577 }
578
579 void ossl_quic_port_raise_net_error(QUIC_PORT *port,
580                                     QUIC_CHANNEL *triggering_ch)
581 {
582     QUIC_CHANNEL *ch;
583
584     if (!ossl_quic_port_is_running(port))
585         return;
586
587     /*
588      * Immediately capture any triggering error on the error stack, with a
589      * cover error.
590      */
591     ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR,
592                    "port failed due to network BIO I/O error");
593     OSSL_ERR_STATE_save(port->err_state);
594
595     port_transition_failed(port);
596
597     /* Give the triggering channel (if any) the first notification. */
598     if (triggering_ch != NULL)
599         ossl_quic_channel_raise_net_error(triggering_ch);
600
601     LIST_FOREACH(ch, ch, &port->channel_list)
602         if (ch != triggering_ch)
603             ossl_quic_channel_raise_net_error(ch);
604 }
605
606 void ossl_quic_port_restore_err_state(const QUIC_PORT *port)
607 {
608     ERR_clear_error();
609     OSSL_ERR_STATE_restore(port->err_state);
610 }