QUIC APL: Implement SSL_poll backend
[openssl.git] / include / internal / quic_record_rx.h
1 /*
2  * Copyright 2022-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 #ifndef OSSL_QUIC_RECORD_RX_H
11 # define OSSL_QUIC_RECORD_RX_H
12
13 # include <openssl/ssl.h>
14 # include "internal/quic_wire_pkt.h"
15 # include "internal/quic_types.h"
16 # include "internal/quic_predef.h"
17 # include "internal/quic_record_util.h"
18 # include "internal/quic_demux.h"
19
20 # ifndef OPENSSL_NO_QUIC
21
22 /*
23  * QUIC Record Layer - RX
24  * ======================
25  */
26 typedef struct ossl_qrx_st OSSL_QRX;
27
28 typedef struct ossl_qrx_args_st {
29     OSSL_LIB_CTX   *libctx;
30     const char     *propq;
31
32     /* Demux which owns the URXEs passed to us. */
33     QUIC_DEMUX     *demux;
34
35     /* Length of connection IDs used in short-header packets in bytes. */
36     size_t          short_conn_id_len;
37
38     /*
39      * Maximum number of deferred datagrams buffered at any one time.
40      * Suggested value: 32.
41      */
42     size_t          max_deferred;
43
44     /* Initial reference PN used for RX. */
45     QUIC_PN         init_largest_pn[QUIC_PN_SPACE_NUM];
46
47     /* Initial key phase. For debugging use only; always 0 in real use. */
48     unsigned char   init_key_phase_bit;
49 } OSSL_QRX_ARGS;
50
51 /* Instantiates a new QRX. */
52 OSSL_QRX *ossl_qrx_new(const OSSL_QRX_ARGS *args);
53
54 /*
55  * Frees the QRX. All packets obtained using ossl_qrx_read_pkt must already
56  * have been released by calling ossl_qrx_release_pkt.
57  *
58  * You do not need to call ossl_qrx_remove_dst_conn_id first; this function will
59  * unregister the QRX from the demuxer for all registered destination connection
60  * IDs (DCIDs) automatically.
61  */
62 void ossl_qrx_free(OSSL_QRX *qrx);
63
64 /* Setters for the msg_callback and msg_callback_arg */
65 void ossl_qrx_set_msg_callback(OSSL_QRX *qrx, ossl_msg_cb msg_callback,
66                                SSL *msg_callback_ssl);
67 void ossl_qrx_set_msg_callback_arg(OSSL_QRX *qrx,
68                                    void *msg_callback_arg);
69
70 /*
71  * Secret Management
72  * =================
73  *
74  * A QRX has several encryption levels (Initial, Handshake, 0-RTT, 1-RTT) and
75  * two directions (RX, TX). At any given time, key material is managed for each
76  * (EL, RX/TX) combination.
77  *
78  * Broadly, for a given (EL, RX/TX), the following state machine is applicable:
79  *
80  *   WAITING_FOR_KEYS --[Provide]--> HAVE_KEYS --[Discard]--> | DISCARDED |
81  *         \-------------------------------------[Discard]--> |           |
82  *
83  * To transition the RX side of an EL from WAITING_FOR_KEYS to HAVE_KEYS, call
84  * ossl_qrx_provide_secret (for the INITIAL EL, use of
85  * ossl_quic_provide_initial_secret is recommended).
86  *
87  * Once keys have been provisioned for an EL, you call
88  * ossl_qrx_discard_enc_level to transition the EL to the DISCARDED state. You
89  * can also call this function to transition directly to the DISCARDED state
90  * even before any keys have been provisioned for that EL.
91  *
92  * The DISCARDED state is terminal for a given EL; you cannot provide a secret
93  * again for that EL after reaching it.
94  *
95  * Incoming packets cannot be processed and decrypted if they target an EL
96  * not in the HAVE_KEYS state. However, there is a distinction between
97  * the WAITING_FOR_KEYS and DISCARDED states:
98  *
99  *   - In the WAITING_FOR_KEYS state, the QRX assumes keys for the given
100  *     EL will eventually arrive. Therefore, if it receives any packet
101  *     for an EL in this state, it buffers it and tries to process it
102  *     again once the EL reaches HAVE_KEYS.
103  *
104  *   - In the DISCARDED state, the QRX assumes no keys for the given
105  *     EL will ever arrive again. If it receives any packet for an EL
106  *     in this state, it is simply discarded.
107  *
108  * If the user wishes to instantiate a new QRX to replace an old one for
109  * whatever reason, for example to take over for an already established QUIC
110  * connection, it is important that all ELs no longer being used (i.e., INITIAL,
111  * 0-RTT, 1-RTT) are transitioned to the DISCARDED state. Otherwise, the QRX
112  * will assume that keys for these ELs will arrive in future, and will buffer
113  * any received packets for those ELs perpetually. This can be done by calling
114  * ossl_qrx_discard_enc_level for all non-1-RTT ELs immediately after
115  * instantiating the QRX.
116  *
117  * The INITIAL EL is not setup automatically when the QRX is instantiated. This
118  * allows the caller to instead discard it immediately after instantiation of
119  * the QRX if it is not needed, for example if the QRX is being instantiated to
120  * take over handling of an existing connection which has already passed the
121  * INITIAL phase. This avoids the unnecessary derivation of INITIAL keys where
122  * they are not needed. In the ordinary case, ossl_quic_provide_initial_secret
123  * should be called immediately after instantiation.
124  */
125
126 /*
127  * Provides a secret to the QRX, which arises due to an encryption level change.
128  * enc_level is a QUIC_ENC_LEVEL_* value. To initialise the INITIAL encryption
129  * level, it is recommended to use ossl_quic_provide_initial_secret instead.
130  *
131  * You should seek to call this function for a given EL before packets of that
132  * EL arrive and are processed by the QRX. However, if packets have already
133  * arrived for a given EL, the QRX will defer processing of them and perform
134  * processing of them when this function is eventually called for the EL in
135  * question.
136  *
137  * suite_id is a QRL_SUITE_* value which determines the AEAD function used for
138  * the QRX.
139  *
140  * The secret passed is used directly to derive the "quic key", "quic iv" and
141  * "quic hp" values.
142  *
143  * secret_len is the length of the secret buffer in bytes. The buffer must be
144  * sized correctly to the chosen suite, else the function fails.
145  *
146  * This function can only be called once for a given EL, except for the INITIAL
147  * EL, which can need rekeying when a connection retry occurs. Subsequent calls
148  * for non-INITIAL ELs fail, as do calls made after a corresponding call to
149  * ossl_qrx_discard_enc_level for that EL. The secret for a non-INITIAL EL
150  * cannot be changed after it is set because QUIC has no facility for
151  * introducing additional key material after an EL is setup. QUIC key updates
152  * are managed semi-automatically by the QRX but do require some caller handling
153  * (see below).
154  *
155  * md is for internal use and should be NULL.
156  *
157  * Returns 1 on success or 0 on failure.
158  */
159 int ossl_qrx_provide_secret(OSSL_QRX              *qrx,
160                             uint32_t               enc_level,
161                             uint32_t               suite_id,
162                             EVP_MD                *md,
163                             const unsigned char   *secret,
164                             size_t                 secret_len);
165
166 /*
167  * Informs the QRX that it can now discard key material for a given EL. The QRX
168  * will no longer be able to process incoming packets received at that
169  * encryption level. This function is idempotent and succeeds if the EL has
170  * already been discarded.
171  *
172  * Returns 1 on success and 0 on failure.
173  */
174 int ossl_qrx_discard_enc_level(OSSL_QRX *qrx, uint32_t enc_level);
175
176 /*
177  * Packet Reception
178  * ================
179  */
180
181 /* Information about a received packet. */
182 struct ossl_qrx_pkt_st {
183     /*
184      * Points to a logical representation of the decoded QUIC packet header. The
185      * data and len fields point to the decrypted QUIC payload (i.e., to a
186      * sequence of zero or more (potentially malformed) frames to be decoded).
187      */
188     QUIC_PKT_HDR       *hdr;
189
190     /*
191      * Address the packet was received from. If this is not available for this
192      * packet, this field is NULL (but this can only occur for manually injected
193      * packets).
194      */
195     const BIO_ADDR     *peer;
196
197     /*
198      * Local address the packet was sent to. If this is not available for this
199      * packet, this field is NULL.
200      */
201     const BIO_ADDR     *local;
202
203     /*
204      * This is the length of the datagram which contained this packet. Note that
205      * the datagram may have contained other packets than this. The intended use
206      * for this is so that the user can enforce minimum datagram sizes (e.g. for
207      * datagrams containing INITIAL packets), as required by RFC 9000.
208      */
209     size_t              datagram_len;
210
211     /* The PN which was decoded for the packet, if the packet has a PN field. */
212     QUIC_PN             pn;
213
214     /*
215      * Time the packet was received, or ossl_time_zero() if the demuxer is not
216      * using a now() function.
217      */
218     OSSL_TIME           time;
219
220     /* The QRX which was used to receive the packet. */
221     OSSL_QRX            *qrx;
222
223     /*
224      * The key epoch the packet was received with. Always 0 for non-1-RTT
225      * packets.
226      */
227     uint64_t            key_epoch;
228
229     /*
230      * This monotonically increases with each datagram received.
231      * It is for diagnostic use only.
232      */
233     uint64_t            datagram_id;
234 };
235
236 /*
237  * Tries to read a new decrypted packet from the QRX.
238  *
239  * On success, *pkt points to a OSSL_QRX_PKT structure. The structure should be
240  * freed when no longer needed by calling ossl_qrx_pkt_release(). The structure
241  * is refcounted; to gain extra references, call ossl_qrx_pkt_up_ref(). This
242  * will cause a corresponding number of calls to ossl_qrx_pkt_release() to be
243  * ignored.
244  *
245  * The resources referenced by (*pkt)->hdr, (*pkt)->hdr->data and (*pkt)->peer
246  * have the same lifetime as *pkt.
247  *
248  * Returns 1 on success and 0 on failure.
249  */
250 int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT **pkt);
251
252 /*
253  * Decrement the reference count for the given packet and frees it if the
254  * reference count drops to zero. No-op if pkt is NULL.
255  */
256 void ossl_qrx_pkt_release(OSSL_QRX_PKT *pkt);
257
258 /* Increments the reference count for the given packet. */
259 void ossl_qrx_pkt_up_ref(OSSL_QRX_PKT *pkt);
260
261 /*
262  * Returns 1 if there are any already processed (i.e. decrypted) packets waiting
263  * to be read from the QRX.
264  */
265 int ossl_qrx_processed_read_pending(OSSL_QRX *qrx);
266
267 /*
268  * Returns 1 if there are any unprocessed (i.e. not yet decrypted) packets
269  * waiting to be processed by the QRX. These may or may not result in
270  * successfully decrypted packets once processed. This indicates whether
271  * unprocessed data is buffered by the QRX, not whether any data is available in
272  * a kernel socket buffer.
273  */
274 int ossl_qrx_unprocessed_read_pending(OSSL_QRX *qrx);
275
276 /*
277  * Returns the number of UDP payload bytes received from the network so far
278  * since the last time this counter was cleared. If clear is 1, clears the
279  * counter and returns the old value.
280  *
281  * The intended use of this is to allow callers to determine how much credit to
282  * add to their anti-amplification budgets. This is reported separately instead
283  * of in the OSSL_QRX_PKT structure so that a caller can apply
284  * anti-amplification credit as soon as a datagram is received, before it has
285  * necessarily read all processed packets contained within that datagram from
286  * the QRX.
287  */
288 uint64_t ossl_qrx_get_bytes_received(OSSL_QRX *qrx, int clear);
289
290 /*
291  * Sets a callback which is called when a packet is received and being validated
292  * before being queued in the read queue. This is called after packet body
293  * decryption and authentication to prevent exposing side channels. pn_space is
294  * a QUIC_PN_SPACE_* value denoting which PN space the PN belongs to.
295  *
296  * If this callback returns 1, processing continues normally.
297  * If this callback returns 0, the packet is discarded.
298  *
299  * Other packets in the same datagram will still be processed where possible.
300  *
301  * The callback is optional and can be unset by passing NULL for cb.
302  * cb_arg is an opaque value passed to cb.
303  */
304 typedef int (ossl_qrx_late_validation_cb)(QUIC_PN pn, int pn_space,
305                                           void *arg);
306
307 int ossl_qrx_set_late_validation_cb(OSSL_QRX *qrx,
308                                     ossl_qrx_late_validation_cb *cb,
309                                     void *cb_arg);
310
311 /*
312  * Forcibly injects a URXE which has been issued by the DEMUX into the QRX for
313  * processing. This can be used to pass a received datagram to the QRX if it
314  * would not be correctly routed to the QRX via standard DCID-based routing; for
315  * example, when handling an incoming Initial packet which is attempting to
316  * establish a new connection.
317  */
318 void ossl_qrx_inject_urxe(OSSL_QRX *qrx, QUIC_URXE *e);
319
320 /*
321  * Decryption of 1-RTT packets must be explicitly enabled by calling this
322  * function. This is to comply with the requirement that we not process 1-RTT
323  * packets until the handshake is complete, even if we already have 1-RTT
324  * secrets. Even if a 1-RTT secret is provisioned for the QRX, incoming 1-RTT
325  * packets will be handled as though no key is available until this function is
326  * called. Calling this function will then requeue any such deferred packets for
327  * processing.
328  */
329 void ossl_qrx_allow_1rtt_processing(OSSL_QRX *qrx);
330
331 /*
332  * Key Update (RX)
333  * ===============
334  *
335  * Key update on the RX side is a largely but not entirely automatic process.
336  *
337  * Key update is initially triggered by receiving a 1-RTT packet with a
338  * different Key Phase value. This could be caused by an attacker in the network
339  * flipping random bits, therefore such a key update is tentative until the
340  * packet payload is successfully decrypted and authenticated by the AEAD with
341  * the 'next' keys. These 'next' keys then become the 'current' keys and the
342  * 'current' keys then become the 'previous' keys. The 'previous' keys must be
343  * kept around temporarily as some packets may still be in flight in the network
344  * encrypted with the old keys. If the old Key Phase value is X and the new Key
345  * Phase Value is Y (where obviously X != Y), this creates an ambiguity as any
346  * new packet received with a KP of X could either be an attempt to initiate yet
347  * another key update right after the last one, or an old packet encrypted
348  * before the key update.
349  *
350  * RFC 9001 provides some guidance on handling this issue:
351  *
352  *   Strategy 1:
353  *      Three keys, disambiguation using packet numbers
354  *
355  *      "A recovered PN that is lower than any PN from the current KP uses the
356  *       previous packet protection keys; a recovered PN that is higher than any
357  *       PN from the current KP requires use of the next packet protection
358  *       keys."
359  *
360  *   Strategy 2:
361  *      Two keys and a timer
362  *
363  *      "Alternatively, endpoints can retain only two sets of packet protection
364  *       keys, swapping previous keys for next after enough time has passed to
365  *       allow for reordering in the network. In this case, the KP bit alone can
366  *       be used to select keys."
367  *
368  * Strategy 2 is more efficient (we can keep fewer cipher contexts around) and
369  * should cover all actually possible network conditions. It also allows a delay
370  * after we make the 'next' keys our 'current' keys before we generate new
371  * 'next' keys, which allows us to mitigate against malicious peers who try to
372  * initiate an excessive number of key updates.
373  *
374  * We therefore model the following state machine:
375  *
376  *
377  *                               PROVISIONED
378  *                     _______________________________
379  *                    |                               |
380  *   UNPROVISIONED  --|---->  NORMAL  <----------\    |------>  DISCARDED
381  *                    |          |               |    |
382  *                    |          |               |    |
383  *                    |          v               |    |
384  *                    |      UPDATING            |    |
385  *                    |          |               |    |
386  *                    |          |               |    |
387  *                    |          v               |    |
388  *                    |       COOLDOWN           |    |
389  *                    |          |               |    |
390  *                    |          |               |    |
391  *                    |          \---------------|    |
392  *                    |_______________________________|
393  *
394  *
395  * The RX starts (once a secret has been provisioned) in the NORMAL state. In
396  * the NORMAL state, the current expected value of the Key Phase bit is
397  * recorded. When a flipped Key Phase bit is detected, the RX attempts to
398  * decrypt and authenticate the received packet with the 'next' keys rather than
399  * the 'current' keys. If (and only if) this authentication is successful, we
400  * move to the UPDATING state. (An attacker in the network could flip
401  * the Key Phase bit randomly, so it is essential we do nothing until AEAD
402  * authentication is complete.)
403  *
404  * In the UPDATING state, we know a key update is occurring and record
405  * the new Key Phase bit value as the newly current value, but we still keep the
406  * old keys around so that we can still process any packets which were still in
407  * flight when the key update was initiated. In the UPDATING state, a
408  * Key Phase bit value different to the current expected value is treated not as
409  * the initiation of another key update, but a reference to our old keys.
410  *
411  * Eventually we will be reasonably sure we are not going to receive any more
412  * packets with the old keys. At this point, we can transition to the COOLDOWN
413  * state. This transition occurs automatically after a certain amount of time;
414  * RFC 9001 recommends it be the PTO interval, which relates to our RTT to the
415  * peer. The duration also SHOULD NOT exceed three times the PTO to assist with
416  * maintaining PFS.
417  *
418  * In the COOLDOWN phase, the old keys have been securely erased and only one
419  * set of keys can be used: the current keys. If a packet is received with a Key
420  * Phase bit value different to the current Key Phase Bit value, this is treated
421  * as a request for a Key Update, but this request is ignored and the packet is
422  * treated as malformed. We do this to allow mitigation against malicious peers
423  * trying to initiate an excessive number of Key Updates. The timeout for the
424  * transition from UPDATING to COOLDOWN is recommended as adequate for
425  * this purpose in itself by the RFC, so the normal additional timeout value for
426  * the transition from COOLDOWN to normal is zero (immediate transition).
427  *
428  * A summary of each state:
429  *
430  *                 Epoch  Exp KP  Uses Keys KS0    KS1    If Non-Expected KP Bit
431  *                 -----  ------  --------- ------ -----  ----------------------
432  *      NORMAL         0  0       Keyset 0  Gen 0  Gen 1  → UPDATING
433  *      UPDATING       1  1       Keyset 1  Gen 0  Gen 1  Use Keyset 0
434  *      COOLDOWN       1  1       Keyset 1  Erased Gen 1  Ignore Packet (*)
435  *
436  *      NORMAL         1  1       Keyset 1  Gen 2  Gen 1  → UPDATING
437  *      UPDATING       2  0       Keyset 0  Gen 2  Gen 1  Use Keyset 1
438  *      COOLDOWN       2  0       Keyset 0  Gen 2  Erased Ignore Packet (*)
439  *
440  * (*) Actually implemented by attempting to decrypt the packet with the
441  *     wrong keys (which ultimately has the same outcome), as recommended
442  *     by RFC 9001 to avoid creating timing channels.
443  *
444  * Note that the key material for the next key generation ("key epoch") is
445  * always kept in the NORMAL state (necessary to avoid side-channel attacks).
446  * This material is derived during the transition from COOLDOWN to NORMAL.
447  *
448  * Note that when a peer initiates a Key Update, we MUST also initiate a Key
449  * Update as per the RFC. The caller is responsible for detecting this condition
450  * and making the necessary calls to the TX side by detecting changes to the
451  * return value of ossl_qrx_get_key_epoch().
452  *
453  * The above states (NORMAL, UPDATING, COOLDOWN) can themselves be
454  * considered substates of the PROVISIONED state. Providing a secret to the QRX
455  * for an EL transitions from UNPROVISIONED, the initial state, to PROVISIONED
456  * (NORMAL). Dropping key material for an EL transitions from whatever the
457  * current substate of the PROVISIONED state is to the DISCARDED state, which is
458  * the terminal state.
459  *
460  * Note that non-1RTT ELs cannot undergo key update, therefore a non-1RTT EL is
461  * always in the NORMAL substate if it is in the PROVISIONED state.
462  */
463
464 /*
465  * Return the current RX key epoch for the 1-RTT encryption level. This is
466  * initially zero and is incremented by one for every Key Update successfully
467  * signalled by the peer. If the 1-RTT EL has not yet been provisioned or has
468  * been discarded, returns UINT64_MAX.
469  *
470  * A necessary implication of this API is that the least significant bit of the
471  * returned value corresponds to the currently expected Key Phase bit, though
472  * callers are not anticipated to have any need of this information.
473  *
474  * It is not possible for the returned value to overflow, as a QUIC connection
475  * cannot support more than 2**62 packet numbers, and a connection must be
476  * terminated if this limit is reached.
477  *
478  * The caller should use this function to detect when the key epoch has changed
479  * and use it to initiate a key update on the TX side.
480  *
481  * The value returned by this function increments specifically at the transition
482  * from the NORMAL to the UPDATING state discussed above.
483  */
484 uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx);
485
486 /*
487  * Sets an optional callback which will be called when the key epoch changes.
488  *
489  * The callback is optional and can be unset by passing NULL for cb.
490  * cb_arg is an opaque value passed to cb. pn is the PN of the packet.
491  * Since key update is only supported for 1-RTT packets, the PN is always
492  * in the Application Data PN space.
493 */
494 typedef void (ossl_qrx_key_update_cb)(QUIC_PN pn, void *arg);
495
496 int ossl_qrx_set_key_update_cb(OSSL_QRX *qrx,
497                                ossl_qrx_key_update_cb *cb, void *cb_arg);
498
499 /*
500  * Relates to the 1-RTT encryption level. The caller should call this after the
501  * UPDATING state is reached, after a timeout to be determined by the caller.
502  *
503  * This transitions from the UPDATING state to the COOLDOWN state (if
504  * still in the UPDATING state). If normal is 1, then transitions from
505  * the COOLDOWN state to the NORMAL state. Both transitions can be performed at
506  * once if desired.
507  *
508  * If in the normal state, or if in the COOLDOWN state and normal is 0, this is
509  * a no-op and returns 1. Returns 0 if the 1-RTT EL has not been provisioned or
510  * has been dropped.
511  *
512  * It is essential that the caller call this within a few PTO intervals of a key
513  * update occurring (as detected by the caller in a call to
514  * ossl_qrx_key_get_key_epoch()), as otherwise the peer will not be able to
515  * perform a Key Update ever again.
516  */
517 int ossl_qrx_key_update_timeout(OSSL_QRX *qrx, int normal);
518
519
520 /*
521  * Key Expiration
522  * ==============
523  */
524
525 /*
526  * Returns the number of seemingly forged packets which have been received by
527  * the QRX. If this value reaches the value returned by
528  * ossl_qrx_get_max_epoch_forged_pkt_count() for a given EL, all further
529  * received encrypted packets for that EL will be discarded without processing.
530  *
531  * Note that the forged packet limit is for the connection lifetime, thus it is
532  * not reset by a key update. It is suggested that the caller terminate the
533  * connection a reasonable margin before the limit is reached. However, the
534  * exact limit imposed does vary by EL due to the possibility that different ELs
535  * use different AEADs.
536  */
537 uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX *qrx);
538
539 /*
540  * Returns the maximum number of forged packets which the record layer will
541  * permit to be verified using this QRX instance.
542  */
543 uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX *qrx,
544                                            uint32_t enc_level);
545
546 # endif
547
548 #endif