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