QUIC APL: Implement SSL_poll backend
[openssl.git] / include / internal / quic_record_tx.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_TX_H
11 # define OSSL_QUIC_RECORD_TX_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/qlog.h"
19
20 # ifndef OPENSSL_NO_QUIC
21
22 /*
23  * QUIC Record Layer - TX
24  * ======================
25  */
26 typedef struct ossl_qtx_iovec_st {
27     const unsigned char    *buf;
28     size_t                  buf_len;
29 } OSSL_QTX_IOVEC;
30
31 typedef struct ossl_qtx_st OSSL_QTX;
32
33 typedef int (*ossl_mutate_packet_cb)(const QUIC_PKT_HDR *hdrin,
34                                      const OSSL_QTX_IOVEC *iovecin, size_t numin,
35                                      QUIC_PKT_HDR **hdrout,
36                                      const OSSL_QTX_IOVEC **iovecout,
37                                      size_t *numout,
38                                      void *arg);
39
40 typedef void (*ossl_finish_mutate_cb)(void *arg);
41
42 typedef struct ossl_qtx_args_st {
43     OSSL_LIB_CTX   *libctx;
44     const char     *propq;
45
46     /* BIO to transmit to. */
47     BIO            *bio;
48
49     /* Maximum datagram payload length (MDPL) for TX purposes. */
50     size_t          mdpl;
51
52     /* QLOG instance to use, or NULL. */
53     QLOG           *qlog;
54 } OSSL_QTX_ARGS;
55
56 /* Instantiates a new QTX. */
57 OSSL_QTX *ossl_qtx_new(const OSSL_QTX_ARGS *args);
58
59 /* Frees the QTX. */
60 void ossl_qtx_free(OSSL_QTX *qtx);
61
62 /* Set mutator callbacks for test framework support */
63 void ossl_qtx_set_mutator(OSSL_QTX *qtx, ossl_mutate_packet_cb mutatecb,
64                           ossl_finish_mutate_cb finishmutatecb, void *mutatearg);
65
66 /* Setters for the msg_callback and the msg_callback_arg */
67 void ossl_qtx_set_msg_callback(OSSL_QTX *qtx, ossl_msg_cb msg_callback,
68                                SSL *msg_callback_ssl);
69 void ossl_qtx_set_msg_callback_arg(OSSL_QTX *qtx, void *msg_callback_arg);
70
71 /* Change QLOG instance in use after instantiation. */
72 void ossl_qtx_set0_qlog(OSSL_QTX *qtx, QLOG *qlog);
73
74 /*
75  * Secret Management
76  * -----------------
77  */
78
79 /*
80  * Provides a secret to the QTX, which arises due to an encryption level change.
81  * enc_level is a QUIC_ENC_LEVEL_* value.
82  *
83  * This function can be used to initialise the INITIAL encryption level, but you
84  * should not do so directly; see the utility function
85  * ossl_qrl_provide_initial_secret() instead, which can initialise the INITIAL
86  * encryption level of a QRX and QTX simultaneously without duplicating certain
87  * key derivation steps.
88  *
89  * You must call this function for a given EL before transmitting packets at
90  * that EL using this QTX, otherwise ossl_qtx_write_pkt will fail.
91  *
92  * suite_id is a QRL_SUITE_* value which determines the AEAD function used for
93  * the QTX.
94  *
95  * The secret passed is used directly to derive the "quic key", "quic iv" and
96  * "quic hp" values.
97  *
98  * secret_len is the length of the secret buffer in bytes. The buffer must be
99  * sized correctly to the chosen suite, else the function fails.
100  *
101  * This function can only be called once for a given EL, except for the INITIAL
102  * EL, as the INITIAL EL can need to be rekeyed if connection retry occurs.
103  * Subsequent calls for non-INITIAL ELs fail. Calls made after a corresponding
104  * call to ossl_qtx_discard_enc_level for a given EL also fail, including for
105  * the INITIAL EL. The secret for a non-INITIAL EL cannot be changed after it is
106  * set because QUIC has no facility for introducing additional key material
107  * after an EL is setup. (QUIC key updates generate new keys from existing key
108  * material and do not introduce new entropy into a connection's key material.)
109  *
110  * Returns 1 on success or 0 on failure.
111  */
112 int ossl_qtx_provide_secret(OSSL_QTX              *qtx,
113                             uint32_t               enc_level,
114                             uint32_t               suite_id,
115                             EVP_MD                *md,
116                             const unsigned char   *secret,
117                             size_t                 secret_len);
118
119 /*
120  * Informs the QTX that it can now discard key material for a given EL. The QTX
121  * will no longer be able to generate packets at that EL. This function is
122  * idempotent and succeeds if the EL has already been discarded.
123  *
124  * Returns 1 on success and 0 on failure.
125  */
126 int ossl_qtx_discard_enc_level(OSSL_QTX *qtx, uint32_t enc_level);
127
128 /* Returns 1 if the given encryption level is provisioned. */
129 int ossl_qtx_is_enc_level_provisioned(OSSL_QTX *qtx, uint32_t enc_level);
130
131 /*
132  * Given the value ciphertext_len representing an encrypted packet payload
133  * length in bytes, determines how many plaintext bytes it will decrypt to.
134  * Returns 0 if the specified EL is not provisioned or ciphertext_len is too
135  * small. The result is written to *plaintext_len.
136  */
137 int ossl_qtx_calculate_plaintext_payload_len(OSSL_QTX *qtx, uint32_t enc_level,
138                                              size_t ciphertext_len,
139                                              size_t *plaintext_len);
140
141 /*
142  * Given the value plaintext_len represented a plaintext packet payload length
143  * in bytes, determines how many ciphertext bytes it will encrypt to. The value
144  * output does not include packet headers. Returns 0 if the specified EL is not
145  * provisioned. The result is written to *ciphertext_len.
146  */
147 int ossl_qtx_calculate_ciphertext_payload_len(OSSL_QTX *qtx, uint32_t enc_level,
148                                               size_t plaintext_len,
149                                               size_t *ciphertext_len);
150
151 uint32_t ossl_qrl_get_suite_cipher_tag_len(uint32_t suite_id);
152
153
154 /*
155  * Packet Transmission
156  * -------------------
157  */
158
159 struct ossl_qtx_pkt_st {
160     /* Logical packet header to be serialized. */
161     QUIC_PKT_HDR               *hdr;
162
163     /*
164      * iovecs expressing the logical packet payload buffer. Zero-length entries
165      * are permitted.
166      */
167     const OSSL_QTX_IOVEC       *iovec;
168     size_t                      num_iovec;
169
170     /* Destination address. Will be passed through to the BIO if non-NULL. */
171     const BIO_ADDR             *peer;
172
173     /*
174      * Local address (optional). Specify as non-NULL only if TX BIO
175      * has local address support enabled.
176      */
177     const BIO_ADDR             *local;
178
179     /*
180      * Logical PN. Used for encryption. This will automatically be encoded to
181      * hdr->pn, which need not be initialized.
182      */
183     QUIC_PN                     pn;
184
185     /* Packet flags. Zero or more OSSL_QTX_PKT_FLAG_* values. */
186     uint32_t                    flags;
187 };
188
189 /*
190  * More packets will be written which should be coalesced into a single
191  * datagram; do not send this packet yet. To use this, set this flag for all
192  * packets but the final packet in a datagram, then send the final packet
193  * without this flag set.
194  *
195  * This flag is not a guarantee and the QTX may transmit immediately anyway if
196  * it is not possible to fit any more packets in the current datagram.
197  *
198  * If the caller change its mind and needs to cause a packet queued with
199  * COALESCE after having passed it to this function but without writing another
200  * packet, it should call ossl_qtx_flush_pkt().
201  */
202 #define OSSL_QTX_PKT_FLAG_COALESCE       (1U << 0)
203
204 /*
205  * Writes a packet.
206  *
207  * *pkt need be valid only for the duration of the call to this function.
208  *
209  * pkt->hdr->data and pkt->hdr->len are unused. The payload buffer is specified
210  * via an array of OSSL_QTX_IOVEC structures. The API is designed to support
211  * single-copy transmission; data is copied from the iovecs as it is encrypted
212  * into an internal staging buffer for transmission.
213  *
214  * The function may modify and clobber pkt->hdr->data, pkt->hdr->len,
215  * pkt->hdr->key_phase and pkt->hdr->pn for its own internal use. No other
216  * fields of pkt or pkt->hdr will be modified.
217  *
218  * It is the callers responsibility to determine how long the PN field in the
219  * encoded packet should be by setting pkt->hdr->pn_len. This function takes
220  * care of the PN encoding. Set pkt->pn to the desired PN.
221  *
222  * Note that 1-RTT packets do not have a DCID Length field, therefore the DCID
223  * length must be understood contextually. This function assumes the caller
224  * knows what it is doing and will serialize a DCID of whatever length is given.
225  * It is the caller's responsibility to ensure it uses a consistent DCID length
226  * for communication with any given set of remote peers.
227  *
228  * The packet is queued regardless of whether it is able to be sent immediately.
229  * This enables packets to be batched and sent at once on systems which support
230  * system calls to send multiple datagrams in a single system call (see
231  * BIO_sendmmsg). To flush queued datagrams to the network, see
232  * ossl_qtx_flush_net().
233  *
234  * Returns 1 on success or 0 on failure.
235  */
236 int ossl_qtx_write_pkt(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt);
237
238 /*
239  * Finish any incomplete datagrams for transmission which were flagged for
240  * coalescing. If there is no current coalescing datagram, this is a no-op.
241  */
242 void ossl_qtx_finish_dgram(OSSL_QTX *qtx);
243
244 /*
245  * (Attempt to) flush any datagrams which are queued for transmission. Note that
246  * this does not cancel coalescing; call ossl_qtx_finish_dgram() first if that
247  * is desired. The queue is drained into the OS's sockets as much as possible.
248  * To determine if there is still data to be sent after calling this function,
249  * use ossl_qtx_get_queue_len_bytes().
250  *
251  * Returns one of the following values:
252  *
253  *   QTX_FLUSH_NET_RES_OK
254  *      Either no packets are currently queued for transmission,
255  *      or at least one packet was successfully submitted.
256  *
257  *   QTX_FLUSH_NET_RES_TRANSIENT_FAIL
258  *      The underlying network write BIO indicated a transient error
259  *      (e.g. buffers full).
260  *
261  *   QTX_FLUSH_NET_RES_PERMANENT_FAIL
262  *      Internal error (e.g. assertion or allocation error)
263  *      or the underlying network write BIO indicated a non-transient
264  *      error.
265  */
266 #define QTX_FLUSH_NET_RES_OK                1
267 #define QTX_FLUSH_NET_RES_TRANSIENT_FAIL    (-1)
268 #define QTX_FLUSH_NET_RES_PERMANENT_FAIL    (-2)
269
270 int ossl_qtx_flush_net(OSSL_QTX *qtx);
271
272 /*
273  * Diagnostic function. If there is any datagram pending transmission, pops it
274  * and writes the details of the datagram as they would have been passed to
275  * *msg. Returns 1, or 0 if there are no datagrams pending. For test use only.
276  */
277 int ossl_qtx_pop_net(OSSL_QTX *qtx, BIO_MSG *msg);
278
279 /* Returns number of datagrams which are fully-formed but not yet sent. */
280 size_t ossl_qtx_get_queue_len_datagrams(OSSL_QTX *qtx);
281
282 /*
283  * Returns number of payload bytes across all datagrams which are fully-formed
284  * but not yet sent. Does not count any incomplete coalescing datagram.
285  */
286 size_t ossl_qtx_get_queue_len_bytes(OSSL_QTX *qtx);
287
288 /*
289  * Returns number of bytes in the current coalescing datagram, or 0 if there is
290  * no current coalescing datagram. Returns 0 after a call to
291  * ossl_qtx_finish_dgram().
292  */
293 size_t ossl_qtx_get_cur_dgram_len_bytes(OSSL_QTX *qtx);
294
295 /*
296  * Returns number of queued coalesced packets which have not been put into a
297  * datagram yet. If this is non-zero, ossl_qtx_flush_pkt() needs to be called.
298  */
299 size_t ossl_qtx_get_unflushed_pkt_count(OSSL_QTX *qtx);
300
301 /*
302  * Change the BIO being used by the QTX. May be NULL if actual transmission is
303  * not currently required. Does not up-ref the BIO; the caller is responsible
304  * for ensuring the lifetime of the BIO exceeds the lifetime of the QTX.
305  */
306 void ossl_qtx_set_bio(OSSL_QTX *qtx, BIO *bio);
307
308 /* Changes the MDPL. */
309 int ossl_qtx_set_mdpl(OSSL_QTX *qtx, size_t mdpl);
310
311 /* Retrieves the current MDPL. */
312 size_t ossl_qtx_get_mdpl(OSSL_QTX *qtx);
313
314
315 /*
316  * Key Update
317  * ----------
318  *
319  * For additional discussion of key update considerations, see QRX header file.
320  */
321
322 /*
323  * Triggers a key update. The key update will be started by inverting the Key
324  * Phase bit of the next packet transmitted; no key update occurs until the next
325  * packet is transmitted. Thus, this function should generally be called
326  * immediately before queueing the next packet.
327  *
328  * There are substantial requirements imposed by RFC 9001 on under what
329  * circumstances a key update can be initiated. The caller is responsible for
330  * meeting most of these requirements. For example, this function cannot be
331  * called too soon after a previous key update has occurred. Key updates also
332  * cannot be initiated until the 1-RTT encryption level is reached.
333  *
334  * As a sanity check, this function will fail and return 0 if the non-1RTT
335  * encryption levels have not yet been dropped.
336  *
337  * The caller may decide itself to initiate a key update, but it also MUST
338  * initiate a key update where it detects that the peer has initiated a key
339  * update. The caller is responsible for initiating a TX key update by calling
340  * this function in this circumstance; thus, the caller is responsible for
341  * coupling the RX and TX QUIC record layers in this way.
342  */
343 int ossl_qtx_trigger_key_update(OSSL_QTX *qtx);
344
345
346 /*
347  * Key Expiration
348  * --------------
349  */
350
351 /*
352  * Returns the number of packets which have been encrypted for transmission with
353  * the current set of TX keys (the current "TX key epoch"). Reset to zero after
354  * a key update and incremented for each packet queued. If enc_level is not
355  * valid or relates to an EL which is not currently available, returns
356  * UINT64_MAX.
357  */
358 uint64_t ossl_qtx_get_cur_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level);
359
360 /*
361  * Returns the maximum number of packets which the record layer will permit to
362  * be encrypted using the current set of TX keys. If this limit is reached (that
363  * is, if the counter returned by ossl_qrx_tx_get_cur_epoch_pkt_count() reaches
364  * this value), as a safety measure, the QTX will not permit any further packets
365  * to be queued. All calls to ossl_qrx_write_pkt that try to send packets of a
366  * kind which need to be encrypted will fail. It is not possible to recover from
367  * this condition and the QTX must then be destroyed; therefore, callers should
368  * ensure they always trigger a key update well in advance of reaching this
369  * limit.
370  *
371  * The value returned by this function is based on the ciphersuite configured
372  * for the given encryption level. If keys have not been provisioned for the
373  * specified enc_level or the enc_level argument is invalid, this function
374  * returns UINT64_MAX, which is not a valid value. Note that it is not possible
375  * to perform a key update at any encryption level other than 1-RTT, therefore
376  * if this limit is reached at earlier encryption levels (which should not be
377  * possible) the connection must be terminated. Since this condition precludes
378  * the transmission of further packets, the only possible signalling of such an
379  * error condition to a peer is a Stateless Reset packet.
380  */
381 uint64_t ossl_qtx_get_max_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level);
382
383 /*
384  * Get the 1-RTT EL key epoch number for the QTX. This is intended for
385  * diagnostic purposes. Returns 0 if 1-RTT EL is not provisioned yet.
386  */
387 uint64_t ossl_qtx_get_key_epoch(OSSL_QTX *qtx);
388
389 # endif
390
391 #endif