QUIC Record Layer (Refactor and TX Side)

Reviewed-by: Paul Dale <pauli@openssl.org>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/18949)
This commit is contained in:
Hugo Landau
2022-08-11 11:24:57 +01:00
committed by Tomas Mraz
parent ec279ac211
commit 1957148384
14 changed files with 3201 additions and 1115 deletions
+12 -11
View File
@@ -21,15 +21,16 @@
* The QUIC connection demuxer is the entity responsible for receiving datagrams
* from the network via a datagram BIO. It parses packet headers to determine
* each packet's destination connection ID (DCID) and hands off processing of
* the packet to the correct QUIC Record Layer (QRL)'s RX side.
* the packet to the correct QUIC Record Layer (QRL)'s RX side (known as the
* QRX).
*
* A QRL is instantiated per QUIC connection and contains the cryptographic
* A QRX is instantiated per QUIC connection and contains the cryptographic
* resources needed to decrypt QUIC packets for that connection. Received
* datagrams are passed from the demuxer to the QRL via a callback registered
* for a specific DCID by the QRL; thus the demuxer has no specific knowledge of
* the QRL and is not coupled to it.
* datagrams are passed from the demuxer to the QRX via a callback registered
* for a specific DCID by the QRX; thus the demuxer has no specific knowledge of
* the QRX and is not coupled to it.
*
* A connection may have multiple connection IDs associated with it; a QRL
* A connection may have multiple connection IDs associated with it; a QRX
* handles this simply by registering multiple connection IDs with the demuxer
* via multiple register calls.
*
@@ -49,12 +50,12 @@
* packets, however, this is not the demuxer's concern. QUIC prohibits different
* packets in the same datagram from containing different DCIDs; the demuxer
* only considers the DCID of the first packet in a datagram when deciding how
* to route a received datagram, and it is the responsibility of the QRL to
* to route a received datagram, and it is the responsibility of the QRX to
* enforce this rule. Packets other than the first packet in a datagram are not
* examined by the demuxer, and the demuxer does not perform validation of
* packet headers other than to the minimum extent necessary to extract the
* DCID; further parsing and validation of packet headers is the responsibility
* of the QRL.
* of the QRX.
*
* Rather than defining an opaque interface, the URXE structure internals
* are exposed. Since the demuxer is only exposed to other parts of the QUIC
@@ -62,10 +63,10 @@
* advantages:
*
* - Fields in the URXE can be allocated to support requirements in other
* components, like the QRL, which would otherwise have to allocate extra
* components, like the QRX, which would otherwise have to allocate extra
* memory corresponding to each URXE.
*
* - Other components, like the QRL, can keep the URXE in queues of its own
* - Other components, like the QRX, can keep the URXE in queues of its own
* when it is not being managed by the demuxer.
*
* URX Queue Structure
@@ -99,7 +100,7 @@ struct quic_urxe_st {
/*
* Bitfields per packet. processed indicates the packet has been processed
* and must not be processed again, hpr_removed indicates header protection
* has already been removed. Used by QRL only; not used by the demuxer.
* has already been removed. Used by QRX only; not used by the demuxer.
*/
uint64_t processed, hpr_removed;
-311
View File
@@ -1,311 +0,0 @@
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_QUIC_RECORD_H
# define OSSL_QUIC_RECORD_H
# include <openssl/ssl.h>
# include "internal/quic_wire_pkt.h"
# include "internal/quic_types.h"
# include "internal/quic_record_util.h"
# include "internal/quic_demux.h"
/*
* QUIC Record Layer
* =================
*/
typedef struct ossl_qrl_st OSSL_QRL;
typedef struct ossl_qrl_args_st {
OSSL_LIB_CTX *libctx;
const char *propq;
/* Demux to receive datagrams from. */
QUIC_DEMUX *rx_demux;
/* Length of connection IDs used in short-header packets in bytes. */
size_t short_conn_id_len;
/* Initial reference PN used for RX. */
QUIC_PN rx_init_largest_pn[QUIC_PN_SPACE_NUM];
} OSSL_QRL_ARGS;
/* Instantiates a new QRL. */
OSSL_QRL *ossl_qrl_new(const OSSL_QRL_ARGS *args);
/*
* Frees the QRL. All packets obtained using ossl_qrl_read_pkt must already
* have been released by calling ossl_qrl_release_pkt.
*
* You do not need to call ossl_qrl_remove_dst_conn_id first; this function will
* unregister the QRL from the demuxer for all registered destination connection
* IDs (DCIDs) automatically.
*/
void ossl_qrl_free(OSSL_QRL *qrl);
/*
* DCID Management
* ===============
*/
/*
* Adds a given DCID to the QRL. The QRL will register the DCID with the demuxer
* so that incoming packets with that DCID are passed to the given QRL. Multiple
* DCIDs may be associated with a QRL at any one time. You will need to add at
* least one DCID after instantiating the QRL. A zero-length DCID is a valid
* input to this function. This function fails if the DCID is already
* registered.
*
* Returns 1 on success or 0 on error.
*/
int ossl_qrl_add_dst_conn_id(OSSL_QRL *qrl,
const QUIC_CONN_ID *dst_conn_id);
/*
* Remove a DCID previously registered with ossl_qrl_add_dst_conn_id. The DCID
* is unregistered from the demuxer. Fails if the DCID is not registered with
* the demuxer.
*
* Returns 1 on success or 0 on error.
*/
int ossl_qrl_remove_dst_conn_id(OSSL_QRL *qrl,
const QUIC_CONN_ID *dst_conn_id);
/*
* Secret Management
* =================
*
* A QRL has several encryption levels (Initial, Handshake, 0-RTT, 1-RTT) and
* two directions (RX, TX). At any given time, key material is managed for each
* (EL, RX/TX) combination.
*
* Broadly, for a given (EL, RX/TX), the following state machine is applicable:
*
* WAITING_FOR_KEYS --[Provide]--> HAVE_KEYS --[Discard]--> | DISCARDED |
* \-------------------------------------[Discard]--> | |
*
* To transition the RX side of an EL from WAITING_FOR_KEYS to HAVE_KEYS, call
* ossl_qrl_provide_rx_secret (or for the INITIAL EL,
* ossl_qrl_provide_rx_secret_initial).
*
* Once keys have been provisioned for an EL, you call
* ossl_qrl_discard_enc_level to transition the EL to the DISCARDED state. You
* can also call this function to transition directly to the DISCARDED state
* even before any keys have been provisioned for that EL.
*
* The DISCARDED state is terminal for a given EL; you cannot provide a secret
* again for that EL after reaching it.
*
* Incoming packets cannot be processed and decrypted if they target an EL
* not in the HAVE_KEYS state. However, there is a distinction between
* the WAITING_FOR_KEYS and DISCARDED states:
*
* - In the WAITING_FOR_KEYS state, the QRL assumes keys for the given
* EL will eventually arrive. Therefore, if it receives any packet
* for an EL in this state, it buffers it and tries to process it
* again once the EL reaches HAVE_KEYS.
*
* - In the DISCARDED state, the QRL assumes no keys for the given
* EL will ever arrive again. If it receives any packet for an EL
* in this state, it is simply discarded.
*
* If the user wishes to instantiate a new QRL to replace an old one for
* whatever reason, for example to take over for an already established QUIC
* connection, it is important that all ELs no longer being used (i.e., INITIAL,
* 0-RTT, 1-RTT) are transitioned to the DISCARDED state. Otherwise, the QRL
* will assume that keys for these ELs will arrive in future, and will buffer
* any received packets for those ELs perpetually. This can be done by calling
* ossl_qrl_discard_enc_level for all non-1-RTT ELs immediately after
* instantiating the QRL.
*
* The INITIAL EL is not setup automatically when the QRL is instantiated. This
* allows the caller to instead discard it immediately after instantiation of
* the QRL if it is not needed, for example if the QRL is being instantiated to
* take over handling of an existing connection which has already passed the
* INITIAL phase. This avoids the unnecessary derivation of INITIAL keys where
* they are not needed. In the ordinary case, ossl_qrl_provide_rx_secret_initial
* should be called immediately after instantiation.
*/
/*
* A QUIC client sends its first INITIAL packet with a random DCID, which is
* used to compute the secret used for INITIAL packet encryption. This function
* must be called to provide the DCID used for INITIAL packet secret computation
* before the QRL can process any INITIAL response packets.
*
* It is possible to use the QRL without ever calling this, for example if there
* is no desire to handle INITIAL packets (e.g. if the QRL is instantiated to
* succeed a previous QRL and handle a connection which is already established.)
* However, in this case you should make sure you call
* ossl_qrl_discard_enc_level (see above).
*
* Returns 1 on success or 0 on error.
*/
int ossl_qrl_provide_rx_secret_initial(OSSL_QRL *qrl,
const QUIC_CONN_ID *dst_conn_id);
/*
* Provides a secret to the QRL, which arises due to an encryption level change.
* enc_level is a QUIC_ENC_LEVEL_* value. This function cannot be used to
* initialise the INITIAL encryption level; see
* ossl_qrl_provide_rx_secret_initial instead.
*
* You should seek to call this function for a given EL before packets of that
* EL arrive and are processed by the QRL. However, if packets have already
* arrived for a given EL, the QRL will defer processing of them and perform
* processing of them when this function is eventually called for the EL in
* question.
*
* suite_id is a QRL_SUITE_* value which determines the AEAD function used for
* the QRL.
*
* The secret passed is used directly to derive the "quic key", "quic iv" and
* "quic hp" values.
*
* secret_len is the length of the secret buffer in bytes. The buffer must be
* sized correctly to the chosen suite, else the function fails.
*
* This function can only be called once for a given EL. Subsequent calls fail,
* as do calls made after a corresponding call to ossl_qrl_discard_enc_level for
* that EL. The secret for a EL cannot be changed after it is set because QUIC
* has no facility for introducing additional key material after an EL is setup.
* QUIC key updates are managed automatically by the QRL and do not require user
* intervention.
*
* Returns 1 on success or 0 on failure.
*/
int ossl_qrl_provide_rx_secret(OSSL_QRL *qrl,
uint32_t enc_level,
uint32_t suite_id,
const unsigned char *secret,
size_t secret_len);
/*
* Informs the QRL that it can now discard key material for a given EL. The QRL
* will no longer be able to process incoming packets received at that
* encryption level. This function is idempotent and succeeds if the EL has
* already been discarded.
*
* Returns 1 on success and 0 on failure.
*/
int ossl_qrl_discard_enc_level(OSSL_QRL *qrl, uint32_t enc_level);
/*
* Packet Reception
* ================
*/
/* Information about a received packet. */
typedef struct ossl_qrl_rx_pkt_st {
/* Opaque handle to be passed to ossl_qrl_release_pkt. */
void *handle;
/*
* Points to a logical representation of the decoded QUIC packet header. The
* data and len fields point to the decrypted QUIC payload (i.e., to a
* sequence of zero or more (potentially malformed) frames to be decoded).
*/
QUIC_PKT_HDR *hdr;
/*
* Address the packet was received from. If this is not available for this
* packet, this field is NULL (but this can only occur for manually injected
* packets).
*/
const BIO_ADDR *peer;
/*
* Local address the packet was sent to. If this is not available for this
* packet, this field is NULL.
*/
const BIO_ADDR *local;
/*
* This is the length of the datagram which contained this packet. Note that
* the datagram may have contained other packets than this. The intended use
* for this is so that the user can enforce minimum datagram sizes (e.g. for
* datagrams containing INITIAL packets), as required by RFC 9000.
*/
size_t datagram_len;
} OSSL_QRL_RX_PKT;
/*
* Tries to read a new decrypted packet from the QRL.
*
* On success, all fields of *pkt are filled and 1 is returned.
* Else, returns 0.
*
* The resources referenced by pkt->hdr, pkt->data and pkt->peer will remain
* allocated at least until the user frees them by calling ossl_qrl_release_pkt,
* which must be called once you are done with the packet.
*/
int ossl_qrl_read_pkt(OSSL_QRL *qrl, OSSL_QRL_RX_PKT *pkt);
/*
* Release the resources pointed to by an OSSL_QRL_RX_PKT returned by
* ossl_qrl_read_pkt. Pass the opaque value pkt->handle returned in the
* structure.
*/
void ossl_qrl_release_pkt(OSSL_QRL *qrl, void *handle);
/*
* Returns 1 if there are any already processed (i.e. decrypted) packets waiting
* to be read from the QRL.
*/
int ossl_qrl_processed_read_pending(OSSL_QRL *qrl);
/*
* Returns 1 if there arre any unprocessed (i.e. not yet decrypted) packets
* waiting to be processed by the QRL. These may or may not result in
* successfully decrypted packets once processed. This indicates whether
* unprocessed data is buffered by the QRL, not whether any data is available in
* a kernel socket buffer.
*/
int ossl_qrl_unprocessed_read_pending(OSSL_QRL *qrl);
/*
* Returns the number of UDP payload bytes received from the network so far
* since the last time this counter was cleared. If clear is 1, clears the
* counter and returns the old value.
*
* The intended use of this is to allow callers to determine how much credit to
* add to their anti-amplification budgets. This is reported separately instead
* of in the OSSL_QRL_RX_PKT structure so that a caller can apply
* anti-amplification credit as soon as a datagram is received, before it has
* necessarily read all processed packets contained within that datagram from
* the QRL.
*/
uint64_t ossl_qrl_get_bytes_received(OSSL_QRL *qrl, int clear);
/*
* Sets a callback which is called when a packet is received and being
* validated before being queued in the read queue. This is called before packet
* body decryption. pn_space is a QUIC_PN_SPACE_* value denoting which PN space
* the PN belongs to.
*
* If this callback returns 1, processing continues normally.
* If this callback returns 0, the packet is discarded.
*
* Other packets in the same datagram will still be processed where possible.
*
* The intended use for this function is to allow early validation of whether
* a PN is a potential duplicate before spending CPU time decrypting the
* packet payload.
*
* The callback is optional and can be unset by passing NULL for cb.
* cb_arg is an opaque value passed to cb.
*/
typedef int (ossl_qrl_early_rx_validation_cb)(QUIC_PN pn, int pn_space,
void *arg);
int ossl_qrl_set_early_rx_validation_cb(OSSL_QRL *qrl,
ossl_qrl_early_rx_validation_cb *cb,
void *cb_arg);
#endif
+488
View File
@@ -0,0 +1,488 @@
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_QUIC_RECORD_RX_H
# define OSSL_QUIC_RECORD_RX_H
# include <openssl/ssl.h>
# include "internal/quic_wire_pkt.h"
# include "internal/quic_types.h"
# include "internal/quic_record_util.h"
# include "internal/quic_demux.h"
/*
* QUIC Record Layer - RX
* ======================
*/
typedef struct ossl_qrx_st OSSL_QRX;
typedef struct ossl_qrx_args_st {
OSSL_LIB_CTX *libctx;
const char *propq;
/* Demux to receive datagrams from. */
QUIC_DEMUX *demux;
/* Length of connection IDs used in short-header packets in bytes. */
size_t short_conn_id_len;
/* Initial reference PN used for RX. */
QUIC_PN init_largest_pn[QUIC_PN_SPACE_NUM];
} OSSL_QRX_ARGS;
/* Instantiates a new QRX. */
OSSL_QRX *ossl_qrx_new(const OSSL_QRX_ARGS *args);
/*
* Frees the QRX. All packets obtained using ossl_qrx_read_pkt must already
* have been released by calling ossl_qrx_release_pkt.
*
* You do not need to call ossl_qrx_remove_dst_conn_id first; this function will
* unregister the QRX from the demuxer for all registered destination connection
* IDs (DCIDs) automatically.
*/
void ossl_qrx_free(OSSL_QRX *qrx);
/*
* DCID Management
* ===============
*/
/*
* Adds a given DCID to the QRX. The QRX will register the DCID with the demuxer
* so that incoming packets with that DCID are passed to the given QRX. Multiple
* DCIDs may be associated with a QRX at any one time. You will need to add at
* least one DCID after instantiating the QRX. A zero-length DCID is a valid
* input to this function. This function fails if the DCID is already
* registered.
*
* Returns 1 on success or 0 on error.
*/
int ossl_qrx_add_dst_conn_id(OSSL_QRX *qrx,
const QUIC_CONN_ID *dst_conn_id);
/*
* Remove a DCID previously registered with ossl_qrx_add_dst_conn_id. The DCID
* is unregistered from the demuxer. Fails if the DCID is not registered with
* the demuxer.
*
* Returns 1 on success or 0 on error.
*/
int ossl_qrx_remove_dst_conn_id(OSSL_QRX *qrx,
const QUIC_CONN_ID *dst_conn_id);
/*
* Secret Management
* =================
*
* A QRX has several encryption levels (Initial, Handshake, 0-RTT, 1-RTT) and
* two directions (RX, TX). At any given time, key material is managed for each
* (EL, RX/TX) combination.
*
* Broadly, for a given (EL, RX/TX), the following state machine is applicable:
*
* WAITING_FOR_KEYS --[Provide]--> HAVE_KEYS --[Discard]--> | DISCARDED |
* \-------------------------------------[Discard]--> | |
*
* To transition the RX side of an EL from WAITING_FOR_KEYS to HAVE_KEYS, call
* ossl_qrx_provide_secret (for the INITIAL EL, use of
* ossl_qrl_provide_initial_secret is recommended).
*
* Once keys have been provisioned for an EL, you call
* ossl_qrx_discard_enc_level to transition the EL to the DISCARDED state. You
* can also call this function to transition directly to the DISCARDED state
* even before any keys have been provisioned for that EL.
*
* The DISCARDED state is terminal for a given EL; you cannot provide a secret
* again for that EL after reaching it.
*
* Incoming packets cannot be processed and decrypted if they target an EL
* not in the HAVE_KEYS state. However, there is a distinction between
* the WAITING_FOR_KEYS and DISCARDED states:
*
* - In the WAITING_FOR_KEYS state, the QRX assumes keys for the given
* EL will eventually arrive. Therefore, if it receives any packet
* for an EL in this state, it buffers it and tries to process it
* again once the EL reaches HAVE_KEYS.
*
* - In the DISCARDED state, the QRX assumes no keys for the given
* EL will ever arrive again. If it receives any packet for an EL
* in this state, it is simply discarded.
*
* If the user wishes to instantiate a new QRX to replace an old one for
* whatever reason, for example to take over for an already established QUIC
* connection, it is important that all ELs no longer being used (i.e., INITIAL,
* 0-RTT, 1-RTT) are transitioned to the DISCARDED state. Otherwise, the QRX
* will assume that keys for these ELs will arrive in future, and will buffer
* any received packets for those ELs perpetually. This can be done by calling
* ossl_qrx_discard_enc_level for all non-1-RTT ELs immediately after
* instantiating the QRX.
*
* The INITIAL EL is not setup automatically when the QRX is instantiated. This
* allows the caller to instead discard it immediately after instantiation of
* the QRX if it is not needed, for example if the QRX is being instantiated to
* take over handling of an existing connection which has already passed the
* INITIAL phase. This avoids the unnecessary derivation of INITIAL keys where
* they are not needed. In the ordinary case, ossl_qrx_provide_secret_initial
* should be called immediately after instantiation.
*/
/*
* Provides a secret to the QRX, which arises due to an encryption level change.
* enc_level is a QUIC_ENC_LEVEL_* value. To initialise the INITIAL encryption
* level, it is recommended to use ossl_qrl_provide_initial_secret instead.
*
* You should seek to call this function for a given EL before packets of that
* EL arrive and are processed by the QRX. However, if packets have already
* arrived for a given EL, the QRX will defer processing of them and perform
* processing of them when this function is eventually called for the EL in
* question.
*
* suite_id is a QRX_SUITE_* value which determines the AEAD function used for
* the QRX.
*
* The secret passed is used directly to derive the "quic key", "quic iv" and
* "quic hp" values.
*
* secret_len is the length of the secret buffer in bytes. The buffer must be
* sized correctly to the chosen suite, else the function fails.
*
* This function can only be called once for a given EL. Subsequent calls fail,
* as do calls made after a corresponding call to ossl_qrx_discard_enc_level for
* that EL. The secret for a EL cannot be changed after it is set because QUIC
* has no facility for introducing additional key material after an EL is setup.
* QUIC key updates are managed automatically by the QRX and do not require user
* intervention.
*
* md is for internal use and should be NULL.
*
* Returns 1 on success or 0 on failure.
*/
int ossl_qrx_provide_secret(OSSL_QRX *qrx,
uint32_t enc_level,
uint32_t suite_id,
EVP_MD *md,
const unsigned char *secret,
size_t secret_len);
/*
* Informs the QRX that it can now discard key material for a given EL. The QRX
* will no longer be able to process incoming packets received at that
* encryption level. This function is idempotent and succeeds if the EL has
* already been discarded.
*
* Returns 1 on success and 0 on failure.
*/
int ossl_qrx_discard_enc_level(OSSL_QRX *qrx, uint32_t enc_level);
/*
* Packet Reception
* ================
*/
/* Information about a received packet. */
typedef struct ossl_qrx_pkt_st {
/* Opaque handle to be passed to ossl_qrx_release_pkt. */
void *handle;
/*
* Points to a logical representation of the decoded QUIC packet header. The
* data and len fields point to the decrypted QUIC payload (i.e., to a
* sequence of zero or more (potentially malformed) frames to be decoded).
*/
QUIC_PKT_HDR *hdr;
/*
* Address the packet was received from. If this is not available for this
* packet, this field is NULL (but this can only occur for manually injected
* packets).
*/
const BIO_ADDR *peer;
/*
* Local address the packet was sent to. If this is not available for this
* packet, this field is NULL.
*/
const BIO_ADDR *local;
/*
* This is the length of the datagram which contained this packet. Note that
* the datagram may have contained other packets than this. The intended use
* for this is so that the user can enforce minimum datagram sizes (e.g. for
* datagrams containing INITIAL packets), as required by RFC 9000.
*/
size_t datagram_len;
} OSSL_QRX_PKT;
/*
* Tries to read a new decrypted packet from the QRX.
*
* On success, all fields of *pkt are filled and 1 is returned.
* Else, returns 0.
*
* The resources referenced by pkt->hdr, pkt->data and pkt->peer will remain
* allocated at least until the user frees them by calling ossl_qrx_release_pkt,
* which must be called once you are done with the packet.
*/
int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT *pkt);
/*
* Release the resources pointed to by an OSSL_QRX_PKT returned by
* ossl_qrx_read_pkt. Pass the opaque value pkt->handle returned in the
* structure.
*/
void ossl_qrx_release_pkt(OSSL_QRX *qrx, void *handle);
/*
* Returns 1 if there are any already processed (i.e. decrypted) packets waiting
* to be read from the QRX.
*/
int ossl_qrx_processed_read_pending(OSSL_QRX *qrx);
/*
* Returns 1 if there arre any unprocessed (i.e. not yet decrypted) packets
* waiting to be processed by the QRX. These may or may not result in
* successfully decrypted packets once processed. This indicates whether
* unprocessed data is buffered by the QRX, not whether any data is available in
* a kernel socket buffer.
*/
int ossl_qrx_unprocessed_read_pending(OSSL_QRX *qrx);
/*
* Returns the number of UDP payload bytes received from the network so far
* since the last time this counter was cleared. If clear is 1, clears the
* counter and returns the old value.
*
* The intended use of this is to allow callers to determine how much credit to
* add to their anti-amplification budgets. This is reported separately instead
* of in the OSSL_QRX_PKT structure so that a caller can apply
* anti-amplification credit as soon as a datagram is received, before it has
* necessarily read all processed packets contained within that datagram from
* the QRX.
*/
uint64_t ossl_qrx_get_bytes_received(OSSL_QRX *qrx, int clear);
/*
* Sets a callback which is called when a packet is received and being
* validated before being queued in the read queue. This is called before packet
* body decryption. pn_space is a QUIC_PN_SPACE_* value denoting which PN space
* the PN belongs to.
*
* If this callback returns 1, processing continues normally.
* If this callback returns 0, the packet is discarded.
*
* Other packets in the same datagram will still be processed where possible.
*
* The intended use for this function is to allow early validation of whether
* a PN is a potential duplicate before spending CPU time decrypting the
* packet payload.
*
* The callback is optional and can be unset by passing NULL for cb.
* cb_arg is an opaque value passed to cb.
*/
typedef int (ossl_qrx_early_validation_cb)(QUIC_PN pn, int pn_space,
void *arg);
int ossl_qrx_set_early_validation_cb(OSSL_QRX *qrx,
ossl_qrx_early_validation_cb *cb,
void *cb_arg);
/*
* Key Update (RX)
* ===============
*
* Key update on the RX side is a largely but not entirely automatic process.
*
* Key update is initially triggered by receiving a 1-RTT packet with a
* different Key Phase value. This could be caused by an attacker in the network
* flipping random bits, therefore such a key update is tentative until the
* packet payload is successfully decrypted and authenticated by the AEAD with
* the 'next' keys. These 'next' keys then become the 'current' keys and the
* 'current' keys then become the 'previous' keys. The 'previous' keys must be
* kept around temporarily as some packets may still be in flight in the network
* encrypted with the old keys. If the old Key Phase value is X and the new Key
* Phase Value is Y (where obviously X != Y), this creates an ambiguity as any
* new packet received with a KP of X could either be an attempt to initiate yet
* another key update right after the last one, or an old packet encrypted
* before the key update.
*
* RFC 9001 provides some guidance on handling this issue:
*
* Strategy 1:
* Three keys, disambiguation using packet numbers
*
* "A recovered PN that is lower than any PN from the current KP uses the
* previous packet protection keys; a recovered PN that is higher than any
* PN from the current KP requires use of the next packet protection
* keys."
*
* Strategy 2:
* Two keys and a timer
*
* "Alternatively, endpoints can retain only two sets of packet protection
* neys, swapping previous keys for next after enough time has passed to
* allow for reordering in the network. In this case, the KP bit alone can
* be used to select keys."
*
* Strategy 2 is more efficient (we can keep fewer cipher contexts around) and
* should cover all actually possible network conditions. It also allows a delay
* after we make the 'next' keys our 'current' keys before we generate new
* 'next' keys, which allows us to mitigate against malicious peers who try to
* initiate an excessive number of key updates.
*
* We therefore model the following state machine:
*
*
* PROVISIONED
* _______________________________
* | |
* UNPROVISIONED --|----> NORMAL <----------\ |------> DROPPED
* | | | |
* | | | |
* | v | |
* | UPDATE_CONFIRMED | |
* | | | |
* | | | |
* | v | |
* | COOLDOWN | |
* | | | |
* | | | |
* | \---------------| |
* |_______________________________|
*
*
* The RX starts (once a secret has been provisioned) in the NORMAL state. In
* the NORMAL state, the current expected value of the Key Phase bit is
* recorded. When a flipped Key Phase bit is detected, the RX attempts to
* decrypt and authenticate the received packet with the 'next' keys rather than
* the 'current' keys. If (and only if) this authentication is successful, we
* move to the UPDATE_CONFIRMED state. (An attacker in the network could flip
* the Key Phase bit randomly, so it is essential we do nothing until AEAD
* authentication is complete.)
*
* In the UPDATE_CONFIRMED state, we know a key update is occurring and record
* the new Key Phase bit value as the newly current value, but we still keep the
* old keys around so that we can still process any packets which were still in
* flight when the key update was initiated. In the UPDATE_CONFIRMED state, a
* Key Phase bit value different to the current expected value is treated not as
* the initiation of another key update, but a reference to our old keys.
*
* Eventually we will be reasonably sure we are not going to receive any more
* packets with the old keys. At this point, we can transition to the COOLDOWN
* state. This transition occurs automatically after a certain amount of time;
* RFC 9001 recommends it be the PTO interval, which relates to our RTT to the
* peer. The duration also SHOULD NOT exceed three times the PTO to assist with
* maintaining PFS.
*
* In the COOLDOWN phase, the old keys have been securely erased and only one
* set of keys can be used: the current keys. If a packet is received with a Key
* Phase bit value different to the current Key Phase Bit value, this is treated
* as a request for a Key Update, but this request is ignored and the packet is
* treated as malformed. We do this to allow mitigation against malicious peers
* trying to initiate an excessive number of Key Updates. The timeout for the
* transition from UPDATE_CONFIRMED to COOLDOWN is recommended as adequate for
* this purpose in itself by the RFC, so the normal additional timeout value for
* the transition from COOLDOWN to normal is zero (immediate transition).
*
* A summary of each state:
*
* Exp KP Uses Keys KS0 KS1 If Non-Expected KP Bit
* ------ --------- ------ ----- ----------------------
* NORMAL 0 Keyset 0 Gen 0 Gen 1 → UPDATE_CONFIRMED
* UPDATE_CONFIRMED 1 Keyset 1 Gen 0 Gen 1 Use Keyset 0
* COOLDOWN 1 Keyset 1 Erased Gen 1 Ignore Packet
*
* NORMAL 1 Keyset 1 Gen 2 Gen 1 → UPDATE_CONFIRMED
* UPDATE_CONFIRMED 0 Keyset 0 Gen 2 Gen 1 Use Keyset 1
* COOLDOWN 0 Keyset 0 Gen 2 Erased Ignore Packet
*
* Note that the key material for the next key generation ("key epoch") is
* always kept in the NORMAL state (necessary to avoid side-channel attacks).
* This material is derived during the transition from COOLDOWN to NORMAL.
*
* Note that when a peer initiates a Key Update, we MUST also initiate a Key
* Update as per the RFC. The caller is responsible for detecting this condition
* and making the necessary calls to the TX side by detecting changes to the
* return value of ossl_qrx_get_key_epoch().
*
* The above states (NORMAL, UPDATE_CONFIRMED, COOLDOWN) can themselves be
* considered substates of the PROVISIONED state. Providing a secret to the QRX
* for an EL transitions from UNPROVISIONED, the initial state, to PROVISIONED
* (NORMAL). Dropping key material for an EL transitions from whatever the
* current substate of the PROVISIONED state is to the DROPPED state, which is
* the terminal state.
*
* Note that non-1RTT ELs cannot undergo key update, therefore a non-1RT EL is
* always in the NORMAL substate if it is in the PROVISIONED state.
*/
/*
* Return the current RX key epoch. This is initially zero and is incremented by
* one for every Key Update successfully signalled by the peer.
*
* A necessary implication of this API is that the least significant bit of the
* returned value corresponds to the currently expected Key Phase bit, though
* callers are not anticipated to have any need of this information.
*
* It is not possible for the returned value to overflow, as a QUIC connection
* cannot support more than 2**62 packet numbers, and a connection must be
* terminated if this limit is reached.
*
* The caller should use this function to detect when the key epoch has changed
* and use it to initiate a key update on the TX side.
*
* The value returned by this function increments specifically at the transition
* from the NORMAL to the UPDATE_CONFIRMED state discussed above.
*/
uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx);
/*
* The caller should call this after the UPDATE_CONFIRMED state is reached,
* after a timeout to be determined by the caller.
*
* This transitions from the UPDATE_CONFIRMED state to the COOLDOWN state (if
* still in the UPDATE_CONFIRMED state). If normal is 1, then transitions from
* the COOLDOWN state to the NORMAL state. Both transitions can be performed at
* once if desired.
*
* If in the normal state, or if in the COOLDOWN state and normal is 0, this is
* a no-op and returns 1.
*
* It is essential that the caller call this within a few PTO intervals of a key
* update occurring (as detected by the caller in a call to
* ossl_qrx_key_get_key_epoch()), as otherwise the peer will not be able to
* perform a Key Update ever again.
*/
int ossl_qrx_key_update_timeout(OSSL_QRX *qrx, int normal);
/*
* Key Expiration
* ==============
*/
/*
* Returns the number of seemingly forged packets which have been received by
* the QRX. If this value reaches the value returned by
* ossl_qrx_get_max_epoch_forged_pkt_count(), all further received encrypted
* packets will be discarded without processing; thus, callers should trigger a
* key update on the TX side (which will cause the peer to trigger a key update
* on our RX side) well before this occurs.
*/
uint64_t ossl_qrx_get_cur_epoch_forged_pkt_count(OSSL_QRX *qrx,
uint32_t enc_level);
/*
* Returns the maximum number of forged packets which the record layer
* will permit to be verified using the current set of RX keys.
*/
uint64_t ossl_qrx_get_max_epoch_forged_pkt_count(OSSL_QRX *qrx,
uint32_t enc_level);
#endif
+293
View File
@@ -0,0 +1,293 @@
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_QUIC_RECORD_TX_H
# define OSSL_QUIC_RECORD_TX_H
# include <openssl/ssl.h>
# include "internal/quic_wire_pkt.h"
# include "internal/quic_types.h"
# include "internal/quic_record_util.h"
/*
* QUIC Record Layer - TX
* ======================
*/
typedef struct ossl_qtx_st OSSL_QTX;
typedef struct ossl_qtx_args_st {
OSSL_LIB_CTX *libctx;
const char *propq;
/* BIO to transmit to. */
BIO *bio;
/* Maximum datagram payload length (MDPL) for TX purposes. */
size_t mdpl;
} OSSL_QTX_ARGS;
/* Instantiates a new QTX. */
OSSL_QTX *ossl_qtx_new(const OSSL_QTX_ARGS *args);
/* Frees the QTX. */
void ossl_qtx_free(OSSL_QTX *qtx);
/*
* Secret Management
* -----------------
*/
/*
* Provides a secret to the QTX, which arises due to an encryption level change.
* enc_level is a QUIC_ENC_LEVEL_* value.
*
* This function can be used to initialise the INITIAL encryption level, but you
* should not do so directly; see the utility function
* ossl_qrl_provide_initial_secret() instead, which can initialise the INITIAL
* encryption level of a QRX and QTX simultaneously without duplicating certain
* key derivation steps.
*
* You must call this function for a given EL before transmitting packets at
* that EL using this QTX, otherwise ossl_qtx_write_pkt will fail.
*
* suite_id is a QRL_SUITE_* value which determines the AEAD function used for
* the QTX.
*
* The secret passed is used directly to derive the "quic key", "quic iv" and
* "quic hp" values.
*
* secret_len is the length of the secret buffer in bytes. The buffer must be
* sized correctly to the chosen suite, else the function fails.
*
* This function can only be called once for a given EL. Subsequent calls fail,
* as do calls made after a corresponding call to ossl_qtx_discard_enc_level for
* that EL. The secret for a EL cannot be changed after it is set because QUIC
* has no facility for introducing additional key material after an EL is setup.
* (QUIC key updates generate new keys from existing key material and do not
* introduce new entropy into a connection's key material.)
*
* Returns 1 on success or 0 on failure.
*/
int ossl_qtx_provide_secret(OSSL_QTX *qtx,
uint32_t enc_level,
uint32_t suite_id,
EVP_MD *md,
const unsigned char *secret,
size_t secret_len);
/*
* Informs the QTX that it can now discard key material for a given EL. The QTX
* will no longer be able to generate packets at that EL. This function is
* idempotent and succeeds if the EL has already been discarded.
*
* Returns 1 on success and 0 on failure.
*/
int ossl_qtx_discard_enc_level(OSSL_QTX *qtx, uint32_t enc_level);
/*
* Packet Transmission
* -------------------
*/
typedef struct ossl_qtx_iovec_st {
const unsigned char *buf;
size_t buf_len;
} OSSL_QTX_IOVEC;
typedef struct ossl_qtx_pkt_st {
/* Logical packet header to be serialized. */
QUIC_PKT_HDR *hdr;
/*
* iovecs expressing the logical packet payload buffer. Zero-length entries
* are permitted.
*/
const OSSL_QTX_IOVEC *iovec;
size_t num_iovec;
/* Destination address. Will be passed through to the BIO if non-NULL. */
const BIO_ADDR *peer;
/*
* Local address (optional). Specify as non-NULL only if TX BIO
* has local address support enabled.
*/
const BIO_ADDR *local;
/*
* Logical PN. Used for encryption. This will automatically be encoded to
* hdr->pn, which need not be initialized.
*/
QUIC_PN pn;
/* Packet flags. Zero or more OSSL_QTX_PKT_FLAG_* values. */
uint32_t flags;
} OSSL_QTX_PKT;
/*
* More packets will be written which should be coalesced into a single
* datagram; do not send this packet yet. To use this, set this flag for all
* packets but the final packet in a datagram, then send the final packet
* without this flag set.
*
* This flag is not a guarantee and the QTX may transmit immediately anyway if
* it is not possible to fit any more packets in the current datagram.
*
* If the caller change its mind and needs to cause a packet queued with
* COALESCE after having passed it to this function but without writing another
* packet, it should call ossl_qtx_flush_pkt().
*/
#define OSSL_QTX_PKT_FLAG_COALESCE (1U << 0)
/*
* Writes a packet.
*
* *pkt need be valid only for the duration of the call to this function.
*
* pkt->hdr->data and pkt->hdr->len are unused. The payload buffer is specified
* via an array of OSSL_QTX_IOVEC structures. The API is designed to support
* single-copy transmission; data is copied from the iovecs as it is encrypted
* into an internal staging buffer for transmission.
*
* The function may modify and clobber pkt->hdr->data, pkt->hdr->len,
* pkt->hdr->key_phase and pkt->hdr->pn for its own internal use. No other
* fields of pkt or pkt->hdr will be modified.
*
* It is the callers responsibility to determine how long the PN field in the
* encoded packet should be by setting pkt->hdr->pn_len. This function takes
* care of the PN encoding. Set pkt->pn to the desired PN.
*
* The packet is queued regardless of whether it is able to be sent immediately.
* Returns 1 on success or 0 on failure.
*/
int ossl_qtx_write_pkt(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt);
/*
* Finish any incomplete datagrams for transmission which were flagged for
* coalescing. If there is no current coalescing datagram, this is a no-op.
*/
void ossl_qtx_finish_dgram(OSSL_QTX *qtx);
/*
* (Attempt to) flush any datagrams which are queued for transmission. Note that
* this does not cancel coalescing; call ossl_qtx_finish_dgram() first if that
* is desired. The queue is drained into the OS's sockets as much as possible.
* To determine if there is still data to be sent after calling this function,
* use ossl_qtx_get_queue_len_bytes().
*/
void ossl_qtx_flush_net(OSSL_QTX *qtx);
/*
* Diagnostic function. If there is any datagram pending transmission, pops it
* and writes the details of the datagram as they would have been passed to
* *msg. Returns 1, or 0 if there are no datagrams pending. For test use only.
*/
int ossl_qtx_pop_net(OSSL_QTX *qtx, BIO_MSG *msg);
/* Returns number of datagrams which are fully-formed but not yet sent. */
size_t ossl_qtx_get_queue_len_datagrams(OSSL_QTX *qtx);
/*
* Returns number of payload bytes across all datagrams which are fully-formed
* but not yet sent. Does not count any incomplete coalescing datagram.
*/
size_t ossl_qtx_get_queue_len_bytes(OSSL_QTX *qtx);
/*
* Returns number of bytes in the current coalescing datagram, or 0 if there is
* no current coalescing datagram. Returns 0 after a call to
* ossl_qtx_finish_dgram().
*/
size_t ossl_qtx_get_cur_dgram_len_bytes(OSSL_QTX *qtx);
/*
* Returns number of queued coalesced packets which have not been put into a
* datagram yet. If this is non-zero, ossl_qtx_flush_pkt() needs to be called.
*/
size_t ossl_qtx_get_unflushed_pkt_count(OSSL_QTX *qtx);
/*
* Change the BIO being used by the QTX. May be NULL if actual transmission is
* not currently required.
*/
int ossl_qtx_set1_bio(OSSL_QTX *qtx, BIO *bio);
/* Changes the MDPL. */
int ossl_qtx_set_mdpl(OSSL_QTX *qtx, size_t mdpl);
/*
* Key Update
* ----------
*
* For additional discussion of key update considerations, see QRX header file.
*/
/*
* Triggers a key update. The key update will be started by inverting the Key
* Phase bit of the next packet transmitted; no key update occurs until the next
* packet is transmitted. Thus, this function should generally be called
* immediately before queueing the next packet.
*
* There are substantial requirements imposed by RFC 9001 on under what
* circumstances a key update can be initiated. The caller is responsible for
* meeting most of these requirements. For example, this function cannot be
* called too soon after a previous key update has occurred. Key updates also
* cannot be initiated until the 1-RTT encryption level is reached.
*
* As a sanity check, this function will fail and return 0 if the non-1RTT
* encryption levels have not yet been dropped.
*
* The caller may decide itself to initiate a key update, but it also MUST
* initiate a key update where it detects that the peer has initiated a key
* update. The caller is responsible for initiating a TX key update by calling
* this function in this circumstance; thus, the caller is responsible for
* coupling the RX and TX QUIC record layers in this way.
*/
int ossl_qtx_trigger_key_update(OSSL_QTX *qtx);
/*
* Key Expiration
* --------------
*/
/*
* Returns the number of packets which have been encrypted for transmission with
* the current set of TX keys (the current "TX key epoch"). Reset to zero after
* a key update and incremented for each packet queued. If enc_level is not
* valid or relates to an EL which is not currently available, returns
* UINT64_MAX.
*/
uint64_t ossl_qtx_get_cur_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level);
/*
* Returns the maximum number of packets which the record layer will permit to
* be encrypted using the current set of TX keys. If this limit is reached (that
* is, if the counter returned by ossl_qrx_tx_get_cur_epoch_pkt_count() reaches
* this value), as a safety measure, the QTX will not permit any further packets
* to be queued. All calls to ossl_qrx_write_pkt that try to send packets of a
* kind which need to be encrypted will fail. It is not possible to recover from
* this condition and the QTX must then be destroyed; therefore, callers should
* ensure they always trigger a key update well in advance of reaching this
* limit.
*
* The value returned by this function is based on the ciphersuite configured
* for the given encryption level. If keys have not been provisioned for the
* specified enc_level or the enc_level argument is invalid, this function
* returns UINT64_MAX, which is not a valid value. Note that it is not possible
* to perform a key update at any encryption level other than 1-RTT, therefore
* if this limit is reached at earlier encryption levels (which should not be
* possible) the connection must be terminated. Since this condition precludes
* the transmission of further packets, the only possible signalling of such an
* error condition to a peer is a Stateless Reset packet.
*/
uint64_t ossl_qtx_get_max_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level);
#endif
+50
View File
@@ -11,6 +11,10 @@
# define OSSL_QUIC_RECORD_UTIL_H
# include <openssl/ssl.h>
# include "internal/quic_types.h"
struct ossl_qrx_st;
struct ossl_qtx_st;
/*
* QUIC Key Derivation Utilities
@@ -25,6 +29,40 @@ int ossl_quic_hkdf_extract(OSSL_LIB_CTX *libctx,
const unsigned char *ikm, size_t ikm_len,
unsigned char *out, size_t out_len);
/*
* A QUIC client sends its first INITIAL packet with a random DCID, which
* is used to compute the secrets used for INITIAL packet encryption in both
* directions (both client-to-server and server-to-client).
*
* This function performs the necessary DCID-based key derivation, and then
* provides the derived key material for the INITIAL encryption level to a QRX
* instance, a QTX instance, or both.
*
* This function derives the necessary key material and then:
* - if qrx is non-NULL, provides the appropriate secret to it;
* - if qtx is non-NULL, provides the appropriate secret to it.
*
* If both qrx and qtx are NULL, this is a no-op. This function is equivalent to
* making the appropriate calls to ossl_qrx_provide_secret() and
* ossl_qtx_provide_secret().
*
* It is possible to use a QRX or QTX without ever calling this, for example if
* there is no desire to handle INITIAL packets (e.g. if a QRX/QTX is
* instantiated to succeed a previous QRX/QTX and handle a connection which is
* already established). However in this case you should make sure you call
* ossl_qrx_discard_enc_level(); see the header for that function for more
* details. Calling ossl_qtx_discard_enc_level() is not essential but could
* protect against programming errors.
*
* Returns 1 on success or 0 on error.
*/
int ossl_quic_provide_initial_secret(OSSL_LIB_CTX *libctx,
const char *propq,
const QUIC_CONN_ID *dst_conn_id,
int is_server,
struct ossl_qrx_st *qrx,
struct ossl_qtx_st *qtx);
/*
* QUIC Record Layer Ciphersuite Info
* ==================================
@@ -59,4 +97,16 @@ uint32_t ossl_qrl_get_suite_hdr_prot_cipher_id(uint32_t suite_id);
/* Returns header protection key length in bytes or 0 if suite ID is invalid. */
uint32_t ossl_qrl_get_suite_hdr_prot_key_len(uint32_t suite_id);
/*
* Returns maximum number of packets which may be safely encrypted with a suite
* or 0 if suite ID is invalid.
*/
uint64_t ossl_qrl_get_suite_max_pkt(uint32_t suite_id);
/*
* Returns maximum number of RX'd packets which may safely fail AEAD decryption
* for a given suite or 0 if suite ID is invalid.
*/
uint64_t ossl_qrl_get_suite_max_forged_pkt(uint32_t suite_id);
#endif
+31
View File
@@ -25,6 +25,27 @@
# define QUIC_PKT_TYPE_1RTT 5
# define QUIC_PKT_TYPE_VERSION_NEG 6
/*
* Determine encryption level from packet type. Returns QUIC_ENC_LEVEL_NUM if
* the packet is not of a type which is encrypted.
*/
static ossl_inline ossl_unused uint32_t
ossl_quic_pkt_type_to_enc_level(uint32_t pkt_type)
{
switch (pkt_type) {
case QUIC_PKT_TYPE_INITIAL:
return QUIC_ENC_LEVEL_INITIAL;
case QUIC_PKT_TYPE_HANDSHAKE:
return QUIC_ENC_LEVEL_HANDSHAKE;
case QUIC_PKT_TYPE_0RTT:
return QUIC_ENC_LEVEL_0RTT;
case QUIC_PKT_TYPE_1RTT:
return QUIC_ENC_LEVEL_1RTT;
default:
return QUIC_ENC_LEVEL_NUM;
}
}
/*
* Smallest possible QUIC packet size as per RFC (aside from version negotiation
* packets).
@@ -394,6 +415,16 @@ int ossl_quic_wire_get_pkt_hdr_dst_conn_id(const unsigned char *buf,
size_t short_conn_id_len,
QUIC_CONN_ID *dst_conn_id);
/*
* Precisely predicts the encoded length of a packet header structure.
*
* May return 0 if the packet header is not valid, but the fact that this
* function returns non-zero does not guarantee that
* ossl_quic_wire_encode_pkt_hdr() will succeed.
*/
int ossl_quic_wire_get_encoded_pkt_hdr_len(size_t short_conn_id_len,
const QUIC_PKT_HDR *hdr);
/*
* Packet Number Encoding
* ======================
+1 -1
View File
@@ -1,3 +1,3 @@
$LIBSSL=../../libssl
SOURCE[$LIBSSL]=quic_method.c quic_impl.c quic_wire.c quic_ackm.c quic_statm.c cc_dummy.c quic_demux.c quic_record.c quic_record_util.c quic_wire_pkt.c
SOURCE[$LIBSSL]=quic_method.c quic_impl.c quic_wire.c quic_ackm.c quic_statm.c cc_dummy.c quic_demux.c quic_record_rx.c quic_record_tx.c quic_record_util.c quic_record_shared.c quic_wire_pkt.c
File diff suppressed because it is too large Load Diff
+209
View File
@@ -0,0 +1,209 @@
#include "quic_record_shared.h"
#include "internal/quic_record_util.h"
#include "internal/common.h"
#include "../ssl_local.h"
/* Constants used for key derivation in QUIC v1. */
static const unsigned char quic_v1_iv_label[] = {
0x71, 0x75, 0x69, 0x63, 0x20, 0x69, 0x76 /* "quic iv" */
};
static const unsigned char quic_v1_key_label[] = {
0x71, 0x75, 0x69, 0x63, 0x20, 0x6b, 0x65, 0x79 /* "quic key" */
};
static const unsigned char quic_v1_hp_label[] = {
0x71, 0x75, 0x69, 0x63, 0x20, 0x68, 0x70 /* "quic hp" */
};
OSSL_QRL_ENC_LEVEL *ossl_qrl_enc_level_set_get(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
int require_valid)
{
OSSL_QRL_ENC_LEVEL *el;
if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_NUM))
return NULL;
el = &els->el[enc_level];
if (require_valid && (el->cctx == NULL || el->discarded))
return NULL;
return el;
}
int ossl_qrl_enc_level_set_have_el(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
if (el == NULL)
return 0;
if (el->cctx != NULL)
return 1;
if (el->discarded)
return -1;
return 0;
}
/*
* Sets up cryptographic state for a given encryption level and direction by
* deriving "quic iv", "quic key" and "quic hp" values from a given secret.
*
* md is a hash function used for key derivation. If it is NULL, this function
* fetches the necessary hash function itself. If it is non-NULL, this function
* can reuse the caller's reference to a suitable EVP_MD; the EVP_MD provided
* must match the suite.
*
* On success where md is non-NULL, takes ownership of the caller's reference to
* md.
*/
int ossl_qrl_enc_level_set_provide_secret(OSSL_QRL_ENC_LEVEL_SET *els,
OSSL_LIB_CTX *libctx,
const char *propq,
uint32_t enc_level,
uint32_t suite_id,
EVP_MD *md,
const unsigned char *secret,
size_t secret_len)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
unsigned char key[EVP_MAX_KEY_LENGTH], hpr_key[EVP_MAX_KEY_LENGTH];
size_t key_len = 0, hpr_key_len = 0, iv_len = 0;
const char *cipher_name = NULL, *md_name = NULL;
EVP_CIPHER *cipher = NULL;
EVP_CIPHER_CTX *cctx = NULL;
int own_md = 0, have_hpr = 0;
if (el == NULL || el->discarded)
/* Should not be trying to reinitialise an EL which was discarded. */
return 0;
cipher_name = ossl_qrl_get_suite_cipher_name(suite_id);
iv_len = ossl_qrl_get_suite_cipher_iv_len(suite_id);
key_len = ossl_qrl_get_suite_cipher_key_len(suite_id);
hpr_key_len = ossl_qrl_get_suite_hdr_prot_key_len(suite_id);
if (cipher_name == NULL)
return 0;
if (secret_len != ossl_qrl_get_suite_secret_len(suite_id))
return 0;
if (md == NULL) {
md_name = ossl_qrl_get_suite_md_name(suite_id);
if ((md = EVP_MD_fetch(libctx, md_name, propq)) == NULL)
return 0;
own_md = 1;
}
/* Derive "quic iv" key. */
if (!tls13_hkdf_expand_ex(libctx, propq,
md,
secret,
quic_v1_iv_label,
sizeof(quic_v1_iv_label),
NULL, 0,
el->iv, iv_len, 0))
goto err;
/* Derive "quic key" key. */
if (!tls13_hkdf_expand_ex(libctx, propq,
md,
secret,
quic_v1_key_label,
sizeof(quic_v1_key_label),
NULL, 0,
key, key_len, 0))
goto err;
/* Derive "quic hp" key. */
if (!tls13_hkdf_expand_ex(libctx, propq,
md,
secret,
quic_v1_hp_label,
sizeof(quic_v1_hp_label),
NULL, 0,
hpr_key, hpr_key_len, 0))
goto err;
/* Free any old context which is using old keying material. */
if (el->cctx != NULL) {
ossl_quic_hdr_protector_destroy(&el->hpr);
EVP_CIPHER_CTX_free(el->cctx);
el->cctx = NULL;
}
/* Setup header protection context. */
if (!ossl_quic_hdr_protector_init(&el->hpr,
libctx,
propq,
ossl_qrl_get_suite_hdr_prot_cipher_id(suite_id),
hpr_key,
hpr_key_len))
goto err;
have_hpr = 1;
/* Create and initialise cipher context. */
if ((cipher = EVP_CIPHER_fetch(libctx, cipher_name, propq)) == NULL)
goto err;
if (!ossl_assert(iv_len == (size_t)EVP_CIPHER_get_iv_length(cipher))
|| !ossl_assert(key_len == (size_t)EVP_CIPHER_get_key_length(cipher)))
goto err;
if ((cctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
/* IV will be changed on RX/TX so we don't need to use a real value here. */
if (!EVP_CipherInit_ex(cctx, cipher, NULL, key, el->iv, 0))
goto err;
el->suite_id = suite_id;
el->cctx = cctx;
el->md = md;
el->tag_len = ossl_qrl_get_suite_cipher_tag_len(suite_id);
el->op_count = 0;
/* Zeroize intermediate keys. */
OPENSSL_cleanse(key, sizeof(key));
OPENSSL_cleanse(hpr_key, sizeof(hpr_key));
EVP_CIPHER_free(cipher);
return 1;
err:
if (have_hpr)
ossl_quic_hdr_protector_destroy(&el->hpr);
EVP_CIPHER_CTX_free(cctx);
EVP_CIPHER_free(cipher);
if (own_md)
EVP_MD_free(md);
return 0;
}
/* Drops keying material for a given encryption level. */
void ossl_qrl_enc_level_set_discard(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level, int is_final)
{
OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0);
if (el == NULL || el->discarded)
return;
if (el->cctx != NULL) {
ossl_quic_hdr_protector_destroy(&el->hpr);
EVP_CIPHER_CTX_free(el->cctx);
el->cctx = NULL;
EVP_MD_free(el->md);
el->md = NULL;
}
/* Zeroise IV. */
OPENSSL_cleanse(el->iv, sizeof(el->iv));
if (is_final)
el->discarded = 1;
}
+86
View File
@@ -0,0 +1,86 @@
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_QUIC_RECORD_SHARED_H
# define OSSL_QUIC_RECORD_SHARED_H
# include <openssl/ssl.h>
# include "internal/quic_types.h"
# include "internal/quic_wire_pkt.h"
/*
* QUIC Record Layer EL Management Utilities
* =========================================
*
* This defines a structure for managing the cryptographic state at a given
* encryption level, as this functionality is shared between QRX and QTX. For
* QRL use only.
*/
typedef struct ossl_qrl_enc_level_st {
/* Hash function used for key derivation. */
EVP_MD *md;
/* Context used for packet body ciphering. */
EVP_CIPHER_CTX *cctx;
/* IV used to construct nonces used for AEAD packet body ciphering. */
unsigned char iv[EVP_MAX_IV_LENGTH];
/* Have we permanently discarded this encryption level? */
unsigned char discarded;
/* QRL_SUITE_* value. */
uint32_t suite_id;
/* Length of authentication tag. */
uint32_t tag_len;
/*
* Cryptographic context used to apply and remove header protection from
* packet headers.
*/
QUIC_HDR_PROTECTOR hpr;
/* Usage counter. The caller maintains this. */
uint64_t op_count;
} OSSL_QRL_ENC_LEVEL;
typedef struct ossl_qrl_enc_level_set_st {
OSSL_QRL_ENC_LEVEL el[QUIC_ENC_LEVEL_NUM];
} OSSL_QRL_ENC_LEVEL_SET;
/*
* Returns 1 if we have key material for a given encryption level, 0 if we do
* not yet have material and -1 if the EL is discarded.
*/
int ossl_qrl_enc_level_set_have_el(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level);
/*
* Returns EL in a set. If enc_level is not a valid QUIC_ENC_LEVEL_* value,
* returns NULL. If require_valid is 1, returns NULL if the EL is not
* provisioned or has been discarded; otherwise, the returned EL may be
* unprovisioned or discarded.
*/
OSSL_QRL_ENC_LEVEL *ossl_qrl_enc_level_set_get(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
int require_valid);
/* Provide secret to an EL. md may be NULL. */
int ossl_qrl_enc_level_set_provide_secret(OSSL_QRL_ENC_LEVEL_SET *els,
OSSL_LIB_CTX *libctx,
const char *propq,
uint32_t enc_level,
uint32_t suite_id,
EVP_MD *md,
const unsigned char *secret,
size_t secret_len);
/*
* Discard an EL. If is_final is non-zero, no secret can be provided for the EL
* ever again.
*/
void ossl_qrl_enc_level_set_discard(OSSL_QRL_ENC_LEVEL_SET *els,
uint32_t enc_level,
int is_final);
#endif
+906
View File
@@ -0,0 +1,906 @@
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/quic_record_tx.h"
#include "internal/bio_addr.h"
#include "internal/common.h"
#include "quic_record_shared.h"
#include "../ssl_local.h"
/*
* TXE
* ===
* Encrypted packets awaiting transmission are kept in TX Entries (TXEs), which
* are queued in linked lists just like TXEs.
*/
typedef struct txe_st TXE;
struct txe_st {
TXE *prev, *next;
size_t data_len, alloc_len;
/*
* Destination and local addresses, as applicable. Both of these are only
* used if the family is not AF_UNSPEC.
*/
BIO_ADDR peer, local;
/*
* alloc_len allocated bytes (of which data_len bytes are valid) follow this
* structure.
*/
};
static ossl_inline unsigned char *txe_data(const TXE *e)
{
return (unsigned char *)(e + 1);
}
typedef struct txe_list_st {
TXE *head, *tail;
} TXE_LIST;
static void txe_remove(TXE_LIST *l, TXE *e)
{
if (e->prev != NULL)
e->prev->next = e->next;
if (e->next != NULL)
e->next->prev = e->prev;
if (e == l->head)
l->head = e->next;
if (e == l->tail)
l->tail = e->prev;
e->next = e->prev = NULL;
}
static void txe_insert_tail(TXE_LIST *l, TXE *e)
{
if (l->tail == NULL) {
l->head = l->tail = e;
e->next = e->prev = NULL;
return;
}
l->tail->next = e;
e->prev = l->tail;
e->next = NULL;
l->tail = e;
}
/*
* QTX
* ===
*/
/* (Encryption level, direction)-specific state. */
typedef struct ossl_qtx_enc_level_st {
/* Hash function used for key derivation. */
EVP_MD *md;
/* Context used for packet body ciphering. */
EVP_CIPHER_CTX *cctx;
/* IV used to construct nonces used for AEAD packet body ciphering. */
unsigned char iv[EVP_MAX_IV_LENGTH];
/* Have we permanently discarded this encryption level? */
unsigned char discarded;
/* QTX_SUITE_* value. */
uint32_t suite_id;
/* Length of authentication tag. */
uint32_t tag_len;
/*
* Cryptographic context used to apply and remove header protection from
* packet headers.
*/
QUIC_HDR_PROTECTOR hpr;
} OSSL_QTX_ENC_LEVEL;
struct ossl_qtx_st {
OSSL_LIB_CTX *libctx;
const char *propq;
/* Per encryption-level state. */
OSSL_QRL_ENC_LEVEL_SET el_set;
/* TX BIO. */
BIO *bio;
/* TX maximum datagram payload length. */
size_t mdpl;
/*
* List of TXEs which are not currently in use. These are moved to the
* pending list (possibly via tx_cons first) as they are filled.
*/
TXE_LIST free;
/*
* List of TXEs which are filled with completed datagrams ready to be
* transmitted.
*/
TXE_LIST pending;
size_t pending_count; /* items in list */
size_t pending_bytes; /* sum(txe->data_len) in pending */
/*
* TXE which is under construction for coalescing purposes, if any.
* This TXE is neither on the free nor pending list. Once the datagram
* is completed, it is moved to the pending list.
*/
TXE *cons;
size_t cons_count; /* num packets */
};
/* Instantiates a new QTX. */
OSSL_QTX *ossl_qtx_new(const OSSL_QTX_ARGS *args)
{
OSSL_QTX *qtx;
qtx = OPENSSL_zalloc(sizeof(OSSL_QTX));
if (qtx == NULL)
return 0;
if (args->bio != NULL && !BIO_up_ref(args->bio)) {
OPENSSL_free(qtx);
return 0;
}
qtx->libctx = args->libctx;
qtx->propq = args->propq;
qtx->bio = args->bio;
qtx->mdpl = args->mdpl;
return qtx;
}
static void qtx_cleanup_txl(TXE_LIST *l)
{
TXE *e, *enext;
for (e = l->head; e != NULL; e = enext) {
enext = e->next;
OPENSSL_free(e);
}
l->head = l->tail = NULL;
}
/* Frees the QTX. */
void ossl_qtx_free(OSSL_QTX *qtx)
{
uint32_t i;
/* Free TXE queue data. */
qtx_cleanup_txl(&qtx->pending);
qtx_cleanup_txl(&qtx->free);
/* Drop keying material and crypto resources. */
for (i = 0; i < QUIC_ENC_LEVEL_NUM; ++i)
ossl_qrl_enc_level_set_discard(&qtx->el_set, i, 1);
OPENSSL_free(qtx);
}
int ossl_qtx_provide_secret(OSSL_QTX *qtx,
uint32_t enc_level,
uint32_t suite_id,
EVP_MD *md,
const unsigned char *secret,
size_t secret_len)
{
if (enc_level >= QUIC_ENC_LEVEL_NUM)
return 0;
return ossl_qrl_enc_level_set_provide_secret(&qtx->el_set,
qtx->libctx,
qtx->propq,
enc_level,
suite_id,
md,
secret,
secret_len);
}
int ossl_qtx_discard_enc_level(OSSL_QTX *qtx, uint32_t enc_level)
{
if (enc_level >= QUIC_ENC_LEVEL_NUM)
return 0;
ossl_qrl_enc_level_set_discard(&qtx->el_set, enc_level, 1);
return 1;
}
/* Allocate a new TXE. */
static TXE *qtx_alloc_txe(size_t alloc_len)
{
TXE *txe;
if (alloc_len >= SIZE_MAX - sizeof(TXE))
return NULL;
txe = OPENSSL_malloc(sizeof(TXE) + alloc_len);
if (txe == NULL)
return NULL;
txe->prev = txe->next = NULL;
txe->alloc_len = alloc_len;
txe->data_len = 0;
return txe;
}
/*
* Ensures there is at least one TXE in the free list, allocating a new entry
* if necessary. The returned TXE is in the free list; it is not popped.
*
* alloc_len is a hint which may be used to determine the TXE size if allocation
* is necessary. Returns NULL on allocation failure.
*/
static TXE *qtx_ensure_free_txe(OSSL_QTX *qtx, size_t alloc_len)
{
TXE *txe;
if (qtx->free.head != NULL)
return qtx->free.head;
txe = qtx_alloc_txe(alloc_len);
if (txe == NULL)
return NULL;
txe_insert_tail(&qtx->free, txe);
return txe;
}
/*
* Resize the data buffer attached to an TXE to be n bytes in size. The address
* of the TXE might change; the new address is returned, or NULL on failure, in
* which case the original TXE remains valid.
*/
static TXE *qtx_resize_txe(OSSL_QTX *qtx, TXE_LIST *txl, TXE *txe, size_t n)
{
TXE *txe2;
/* Should never happen. */
if (txe == NULL)
return NULL;
if (n >= SIZE_MAX - sizeof(TXE))
return NULL;
/*
* NOTE: We do not clear old memory, although it does contain decrypted
* data.
*/
txe2 = OPENSSL_realloc(txe, sizeof(TXE) + n);
if (txe2 == NULL)
/* original TXE is still in tact unchanged */
return NULL;
if (txl != NULL && txe != txe2) {
if (txl->head == txe)
txl->head = txe2;
if (txl->tail == txe)
txl->tail = txe2;
if (txe->prev != NULL)
txe->prev->next = txe2;
if (txe->next != NULL)
txe->next->prev = txe2;
}
if (qtx->cons == txe)
qtx->cons = txe2;
txe2->alloc_len = n;
return txe2;
}
/*
* Ensure the data buffer attached to an TXE is at least n bytes in size.
* Returns NULL on failure.
*/
static TXE *qtx_reserve_txe(OSSL_QTX *qtx, TXE_LIST *txl,
TXE *txe, size_t n)
{
if (txe->alloc_len >= n)
return txe;
return qtx_resize_txe(qtx, txl, txe, n);
}
/* Move a TXE from pending to free. */
static void qtx_pending_to_free(OSSL_QTX *qtx)
{
TXE *txe = qtx->pending.head;
assert(txe != NULL);
txe_remove(&qtx->pending, txe);
--qtx->pending_count;
qtx->pending_bytes -= txe->data_len;
txe_insert_tail(&qtx->free, txe);
}
/* Add a TXE not currently in any list to the pending list. */
static void qtx_add_to_pending(OSSL_QTX *qtx, TXE *txe)
{
txe_insert_tail(&qtx->pending, txe);
++qtx->pending_count;
qtx->pending_bytes += txe->data_len;
}
struct iovec_cur {
const OSSL_QTX_IOVEC *iovec;
size_t num_iovec, idx, byte_off, bytes_remaining;
};
static size_t iovec_total_bytes(const OSSL_QTX_IOVEC *iovec,
size_t num_iovec)
{
size_t i, l = 0;
for (i = 0; i < num_iovec; ++i)
l += iovec[i].buf_len;
return l;
}
static void iovec_cur_init(struct iovec_cur *cur,
const OSSL_QTX_IOVEC *iovec,
size_t num_iovec)
{
cur->iovec = iovec;
cur->num_iovec = num_iovec;
cur->idx = 0;
cur->byte_off = 0;
cur->bytes_remaining = iovec_total_bytes(iovec, num_iovec);
}
/*
* Get an extent of bytes from the iovec cursor. *buf is set to point to the
* buffer and the number of bytes in length of the buffer is returned. This
* value may be less than the max_buf_len argument. If no more data is
* available, returns 0.
*/
static size_t iovec_cur_get_buffer(struct iovec_cur *cur,
const unsigned char **buf,
size_t max_buf_len)
{
size_t l;
if (max_buf_len == 0) {
*buf = NULL;
return 0;
}
for (;;) {
if (cur->idx >= cur->num_iovec)
return 0;
l = cur->iovec[cur->idx].buf_len - cur->byte_off;
if (l > max_buf_len)
l = max_buf_len;
if (l > 0) {
*buf = cur->iovec[cur->idx].buf + cur->byte_off;
cur->byte_off += l;
cur->bytes_remaining -= l;
return l;
}
/*
* Zero-length iovec entry or we already consumed all of it, try the
* next iovec.
*/
++cur->idx;
cur->byte_off = 0;
}
}
/* Determines the size of the AEAD output given the input size. */
static size_t qtx_inflate_payload_len(OSSL_QTX *qtx, uint32_t enc_level,
size_t plaintext_len)
{
OSSL_QRL_ENC_LEVEL *el
= ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
assert(el != NULL); /* Already checked by caller. */
/*
* We currently only support ciphers with a 1:1 mapping between plaintext
* and ciphertext size, save for authentication tag.
*/
return plaintext_len + ossl_qrl_get_suite_cipher_tag_len(el->suite_id);
}
/* Any other error (including packet being too big for MDPL). */
#define QTX_FAIL_GENERIC (-1)
/*
* Returned where there is insufficient room in the datagram to write the
* packet.
*/
#define QTX_FAIL_INSUFFICIENT_LEN (-2)
static int qtx_write_hdr(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt, TXE *txe,
QUIC_PKT_HDR_PTRS *ptrs)
{
WPACKET wpkt;
size_t l = 0;
if (!WPACKET_init_static_len(&wpkt, txe_data(txe) + txe->data_len,
txe->alloc_len - txe->data_len, 0))
return 0;
if (!ossl_quic_wire_encode_pkt_hdr(&wpkt, pkt->hdr->src_conn_id.id_len,
pkt->hdr, ptrs)
|| !WPACKET_get_total_written(&wpkt, &l)) {
WPACKET_finish(&wpkt);
return 0;
}
txe->data_len += l;
WPACKET_finish(&wpkt);
return 1;
}
static int qtx_encrypt_into_txe(OSSL_QTX *qtx, struct iovec_cur *cur, TXE *txe,
uint32_t enc_level, QUIC_PN pn,
const unsigned char *hdr, size_t hdr_len,
QUIC_PKT_HDR_PTRS *ptrs)
{
int l = 0, l2 = 0;
OSSL_QRL_ENC_LEVEL *el
= ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
unsigned char nonce[EVP_MAX_IV_LENGTH];
size_t nonce_len, i;
/* We should not have been called if we do not have key material. */
if (!ossl_assert(el != NULL))
return 0;
/*
* Have we already encrypted the maximum number of packets using the current
* key?
*/
if (el->op_count >= ossl_qrl_get_suite_max_pkt(el->suite_id))
return 0;
/* Construct nonce (nonce=IV ^ PN). */
nonce_len = EVP_CIPHER_CTX_get_iv_length(el->cctx);
if (!ossl_assert(nonce_len >= sizeof(QUIC_PN)))
return 0;
memcpy(nonce, el->iv, nonce_len);
for (i = 0; i < sizeof(QUIC_PN); ++i)
nonce[nonce_len - i - 1] ^= (unsigned char)(pn >> (i * 8));
/* type and key will already have been setup; feed the IV. */
if (EVP_CipherInit_ex(el->cctx, NULL, NULL, NULL, nonce, /*enc=*/1) != 1)
return 0;
/* Feed AAD data. */
if (EVP_CipherUpdate(el->cctx, NULL, &l, hdr, hdr_len) != 1)
return 0;
/* Encrypt plaintext directly into TXE. */
for (;;) {
const unsigned char *src;
size_t src_len;
src_len = iovec_cur_get_buffer(cur, &src, SIZE_MAX);
if (src_len == 0)
break;
if (EVP_CipherUpdate(el->cctx, txe_data(txe) + txe->data_len,
&l, src, src_len) != 1)
return 0;
assert(l > 0 && src_len == (size_t)l);
txe->data_len += src_len;
}
/* Finalise and get tag. */
if (EVP_CipherFinal_ex(el->cctx, NULL, &l2) != 1)
return 0;
if (EVP_CIPHER_CTX_ctrl(el->cctx, EVP_CTRL_AEAD_GET_TAG,
el->tag_len, txe_data(txe) + txe->data_len) != 1)
return 0;
txe->data_len += el->tag_len;
/* Apply header protection. */
if (!ossl_quic_hdr_protector_encrypt(&el->hpr, ptrs))
return 0;
++el->op_count;
return 1;
}
/*
* Append a packet to the TXE buffer, serializing and encrypting it in the
* process.
*/
static int qtx_write(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt, TXE *txe,
uint32_t enc_level)
{
int ret, needs_encrypt;
size_t hdr_len, pred_hdr_len, payload_len, pkt_len, space_left;
size_t min_len, orig_data_len;
struct iovec_cur cur;
QUIC_PKT_HDR_PTRS ptrs;
unsigned char *hdr_start;
/*
* Determine if the packet needs encryption and the minimum conceivable
* serialization length.
*/
if (pkt->hdr->type == QUIC_PKT_TYPE_RETRY
|| pkt->hdr->type == QUIC_PKT_TYPE_VERSION_NEG) {
needs_encrypt = 0;
min_len = QUIC_MIN_VALID_PKT_LEN;
} else {
needs_encrypt = 1;
min_len = QUIC_MIN_VALID_PKT_LEN_CRYPTO;
}
orig_data_len = txe->data_len;
space_left = txe->alloc_len - txe->data_len;
if (space_left < min_len) {
/* Not even a possibility of it fitting. */
ret = QTX_FAIL_INSUFFICIENT_LEN;
goto err;
}
/* Walk the iovecs to determine actual input payload length. */
iovec_cur_init(&cur, pkt->iovec, pkt->num_iovec);
/* Determine encrypted payload length. */
payload_len = needs_encrypt ? qtx_inflate_payload_len(qtx, enc_level,
cur.bytes_remaining)
: cur.bytes_remaining;
/* Determine header length. */
pkt->hdr->data = NULL;
pkt->hdr->len = payload_len;
pred_hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(pkt->hdr->src_conn_id.id_len,
pkt->hdr);
if (pred_hdr_len == 0) {
ret = QTX_FAIL_GENERIC;
goto err;
}
/* We now definitively know our packet length. */
pkt_len = pred_hdr_len + payload_len;
if (pkt_len > space_left) {
ret = QTX_FAIL_INSUFFICIENT_LEN;
goto err;
}
/* Set some fields in the header we are responsible for. */
pkt->hdr->key_phase = 0; /* TODO */
if (!ossl_quic_wire_encode_pkt_hdr_pn(pkt->pn,
pkt->hdr->pn,
pkt->hdr->pn_len)) {
ret = QTX_FAIL_GENERIC;
goto err;
}
/* Append the header to the TXE. */
hdr_start = txe_data(txe) + txe->data_len;
if (!qtx_write_hdr(qtx, pkt, txe, &ptrs)) {
ret = QTX_FAIL_GENERIC;
goto err;
}
hdr_len = (txe_data(txe) + txe->data_len) - hdr_start;
assert(hdr_len == pred_hdr_len);
if (!needs_encrypt) {
/* Just copy the payload across. */
const unsigned char *src;
size_t src_len;
for (;;) {
/* Buffer length has already been checked above. */
src_len = iovec_cur_get_buffer(&cur, &src, SIZE_MAX);
if (src_len == 0)
break;
memcpy(txe_data(txe) + txe->data_len, src, src_len);
txe->data_len += src_len;
}
} else {
/* Encrypt into TXE. */
if (!qtx_encrypt_into_txe(qtx, &cur, txe, enc_level, pkt->pn,
hdr_start, hdr_len, &ptrs)) {
ret = QTX_FAIL_GENERIC;
goto err;
}
assert(txe->data_len - orig_data_len == pkt_len);
}
return 1;
err:
/*
* Restore original length so we don't leave a half-written packet in the
* TXE.
*/
txe->data_len = orig_data_len;
return ret;
}
static TXE *qtx_ensure_cons(OSSL_QTX *qtx)
{
TXE *txe = qtx->cons;
if (txe != NULL)
return txe;
txe = qtx_ensure_free_txe(qtx, qtx->mdpl);
if (txe == NULL)
return NULL;
txe_remove(&qtx->free, txe);
qtx->cons = txe;
qtx->cons_count = 0;
txe->data_len = 0;
return txe;
}
static int addr_eq(const BIO_ADDR *a, const BIO_ADDR *b)
{
return ((a == NULL || BIO_ADDR_family(a) == AF_UNSPEC)
&& (b == NULL || BIO_ADDR_family(b) == AF_UNSPEC))
|| (a != NULL && b != NULL && memcmp(a, b, sizeof(*a)) == 0);
}
int ossl_qtx_write_pkt(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt)
{
int ret;
int coalescing = (pkt->flags & OSSL_QTX_PKT_FLAG_COALESCE) != 0;
int was_coalescing;
TXE *txe;
uint32_t enc_level;
/* Must have EL configured, must have header. */
if (pkt->hdr == NULL)
return 0;
enc_level = ossl_quic_pkt_type_to_enc_level(pkt->hdr->type);
/* Some packet types must be in a packet all by themselves. */
if (pkt->hdr->type == QUIC_PKT_TYPE_RETRY
|| pkt->hdr->type == QUIC_PKT_TYPE_VERSION_NEG)
ossl_qtx_finish_dgram(qtx);
else if (enc_level >= QUIC_ENC_LEVEL_NUM
|| ossl_qrl_enc_level_set_have_el(&qtx->el_set, enc_level) != 1)
/* All other packet types are encrypted. */
return 0;
was_coalescing = (qtx->cons != NULL && qtx->cons->data_len > 0);
if (was_coalescing)
if (!addr_eq(&qtx->cons->peer, pkt->peer)
|| !addr_eq(&qtx->cons->local, pkt->local)) {
/* Must stop coalescing if addresses have changed */
ossl_qtx_finish_dgram(qtx);
was_coalescing = 0;
}
for (;;) {
/*
* Start a new coalescing session or continue using the existing one and
* serialize/encrypt the packet. We always encrypt packets as soon as
* our caller gives them to us, which relieves the caller of any need to
* keep the plaintext around.
*/
txe = qtx_ensure_cons(qtx);
if (txe == NULL)
return 0; /* allocation failure */
/*
* Ensure TXE has at least MDPL bytes allocated. This should only be
* possible if the MDPL has increased.
*/
if (!qtx_reserve_txe(qtx, NULL, txe, qtx->mdpl))
return 0;
if (!was_coalescing) {
/* Set addresses in TXE. */
if (pkt->peer != NULL)
txe->peer = *pkt->peer;
else
BIO_ADDR_clear(&txe->peer);
if (pkt->local != NULL)
txe->local = *pkt->local;
else
BIO_ADDR_clear(&txe->local);
}
ret = qtx_write(qtx, pkt, txe, enc_level);
if (ret == 1) {
break;
} else if (ret == QTX_FAIL_INSUFFICIENT_LEN) {
if (was_coalescing) {
/*
* We failed due to insufficient length, so end the current
* datagram and try again.
*/
ossl_qtx_finish_dgram(qtx);
was_coalescing = 0;
} else {
/*
* We failed due to insufficient length, but we were not
* coalescing/started with an empty datagram, so any future
* attempt to write this packet must also fail.
*/
return 0;
}
} else {
return 0; /* other error */
}
}
++qtx->cons_count;
/*
* Some packet types cannot have another packet come after them.
*/
if (pkt->hdr->type == QUIC_PKT_TYPE_RETRY
|| pkt->hdr->type == QUIC_PKT_TYPE_VERSION_NEG
|| pkt->hdr->type == QUIC_PKT_TYPE_1RTT)
coalescing = 0;
if (!coalescing)
ossl_qtx_finish_dgram(qtx);
return 1;
}
/*
* Finish any incomplete datagrams for transmission which were flagged for
* coalescing. If there is no current coalescing datagram, this is a no-op.
*/
void ossl_qtx_finish_dgram(OSSL_QTX *qtx)
{
TXE *txe = qtx->cons;
if (txe == NULL)
return;
if (txe->data_len == 0)
/*
* If we did not put anything in the datagram, just move it back to the
* free list.
*/
txe_insert_tail(&qtx->free, txe);
else
qtx_add_to_pending(qtx, txe);
qtx->cons = NULL;
qtx->cons_count = 0;
}
static void txe_to_msg(TXE *txe, BIO_MSG *msg)
{
msg->data = txe_data(txe);
msg->data_len = txe->data_len;
msg->flags = 0;
msg->peer
= BIO_ADDR_family(&txe->peer) != AF_UNSPEC ? &txe->peer : NULL;
msg->local
= BIO_ADDR_family(&txe->local) != AF_UNSPEC ? &txe->local : NULL;
}
#define MAX_MSGS_PER_SEND 32
void ossl_qtx_flush_net(OSSL_QTX *qtx)
{
BIO_MSG msg[MAX_MSGS_PER_SEND];
size_t i;
TXE *txe;
ossl_ssize_t wr;
if (qtx->bio == NULL)
return;
for (;;) {
for (txe = qtx->pending.head, i = 0;
txe != NULL && i < OSSL_NELEM(msg);
txe = txe->next, ++i)
txe_to_msg(txe, &msg[i]);
if (!i)
/* Nothing to send. */
return;
wr = BIO_sendmmsg(qtx->bio, msg, sizeof(BIO_MSG), i, 0);
if (wr <= 0)
/*
* We did not get anything, so further calls will probably not
* succeed either.
*/
break;
/*
* Remove everything which was successfully sent from the pending queue.
*/
for (i = 0; i < (size_t)wr; ++i)
qtx_pending_to_free(qtx);
}
}
int ossl_qtx_pop_net(OSSL_QTX *qtx, BIO_MSG *msg)
{
TXE *txe = qtx->pending.head;
if (txe == NULL)
return 0;
txe_to_msg(txe, msg);
qtx_pending_to_free(qtx);
return 1;
}
int ossl_qtx_set1_bio(OSSL_QTX *qtx, BIO *bio)
{
if (bio != NULL && !BIO_up_ref(bio))
return 0;
BIO_free(qtx->bio);
qtx->bio = bio;
return 1;
}
int ossl_qtx_set_mdpl(OSSL_QTX *qtx, size_t mdpl)
{
qtx->mdpl = mdpl;
return 1;
}
size_t ossl_qtx_get_queue_len_datagrams(OSSL_QTX *qtx)
{
return qtx->pending_count;
}
size_t ossl_qtx_get_queue_len_bytes(OSSL_QTX *qtx)
{
return qtx->pending_bytes;
}
size_t ossl_qtx_get_cur_dgram_len_bytes(OSSL_QTX *qtx)
{
return qtx->cons != NULL ? qtx->cons->data_len : 0;
}
size_t ossl_qtx_get_unflushed_pkt_count(OSSL_QTX *qtx)
{
return qtx->cons_count;
}
uint64_t ossl_qtx_get_cur_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el;
el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
if (el == NULL)
return UINT64_MAX;
return el->op_count;
}
uint64_t ossl_qtx_get_max_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level)
{
OSSL_QRL_ENC_LEVEL *el;
el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
if (el == NULL)
return UINT64_MAX;
return ossl_qrl_get_suite_max_pkt(el->suite_id);
}
+139 -3
View File
@@ -8,7 +8,10 @@
*/
#include "internal/quic_record_util.h"
#include "internal/quic_record_rx.h"
#include "internal/quic_record_tx.h"
#include "internal/quic_wire_pkt.h"
#include "../ssl_local.h"
#include <openssl/kdf.h>
#include <openssl/core_names.h>
@@ -52,6 +55,119 @@ err:
return ret;
}
/* Constants used for key derivation in QUIC v1. */
static const unsigned char quic_client_in_label[] = {
0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x69, 0x6e /* "client in" */
};
static const unsigned char quic_server_in_label[] = {
0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x69, 0x6e /* "server in" */
};
/* Salt used to derive Initial packet protection keys (RFC 9001 Section 5.2). */
static const unsigned char quic_v1_initial_salt[] = {
0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17,
0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a
};
int ossl_quic_provide_initial_secret(OSSL_LIB_CTX *libctx,
const char *propq,
const QUIC_CONN_ID *dst_conn_id,
int is_server,
struct ossl_qrx_st *qrx,
struct ossl_qtx_st *qtx)
{
unsigned char initial_secret[32];
unsigned char client_initial_secret[32], server_initial_secret[32];
unsigned char *rx_secret, *tx_secret;
EVP_MD *sha256;
if (qrx == NULL && qtx == NULL)
return 1;
/* Initial encryption always uses SHA-256. */
if ((sha256 = EVP_MD_fetch(libctx, "SHA256", propq)) == NULL)
return 0;
if (is_server) {
rx_secret = client_initial_secret;
tx_secret = server_initial_secret;
} else {
rx_secret = server_initial_secret;
tx_secret = client_initial_secret;
}
/* Derive initial secret from destination connection ID. */
if (!ossl_quic_hkdf_extract(libctx, propq,
sha256,
quic_v1_initial_salt,
sizeof(quic_v1_initial_salt),
dst_conn_id->id,
dst_conn_id->id_len,
initial_secret,
sizeof(initial_secret)))
goto err;
/* Derive "client in" secret. */
if (((qtx != NULL && tx_secret == client_initial_secret)
|| (qrx != NULL && rx_secret == client_initial_secret))
&& !tls13_hkdf_expand_ex(libctx, propq,
sha256,
initial_secret,
quic_client_in_label,
sizeof(quic_client_in_label),
NULL, 0,
client_initial_secret,
sizeof(client_initial_secret), 0))
goto err;
/* Derive "server in" secret. */
if (((qtx != NULL && tx_secret == server_initial_secret)
|| (qrx != NULL && rx_secret == server_initial_secret))
&& !tls13_hkdf_expand_ex(libctx, propq,
sha256,
initial_secret,
quic_server_in_label,
sizeof(quic_server_in_label),
NULL, 0,
server_initial_secret,
sizeof(server_initial_secret), 0))
goto err;
/* Setup RX EL. Initial encryption always uses AES-128-GCM. */
if (qrx != NULL
&& !ossl_qrx_provide_secret(qrx, QUIC_ENC_LEVEL_INITIAL,
QRL_SUITE_AES128GCM,
sha256,
rx_secret,
sizeof(server_initial_secret)))
goto err;
/*
* ossl_qrx_provide_secret takes ownership of our ref to SHA256, so if we
* are initialising both sides, get a new ref for the following call for the
* TX side.
*/
if (qrx != NULL && qtx != NULL && !EVP_MD_up_ref(sha256)) {
sha256 = NULL;
goto err;
}
/* Setup TX cipher. */
if (qtx != NULL
&& !ossl_qtx_provide_secret(qtx, QUIC_ENC_LEVEL_INITIAL,
QRL_SUITE_AES128GCM,
sha256,
tx_secret,
sizeof(server_initial_secret)))
goto err;
return 1;
err:
EVP_MD_free(sha256);
return 0;
}
/*
* QUIC Record Layer Ciphersuite Info
* ==================================
@@ -61,21 +177,29 @@ struct suite_info {
const char *cipher_name, *md_name;
uint32_t secret_len, cipher_key_len, cipher_iv_len, cipher_tag_len;
uint32_t hdr_prot_key_len, hdr_prot_cipher_id;
uint64_t max_pkt, max_forged_pkt;
};
static const struct suite_info suite_aes128gcm = {
"AES-128-GCM", "SHA256", 32, 16, 12, 16, 16,
QUIC_HDR_PROT_CIPHER_AES_128
QUIC_HDR_PROT_CIPHER_AES_128,
((uint64_t)1) << 23, /* Limits as prescribed by RFC 9001 */
((uint64_t)1) << 52,
};
static const struct suite_info suite_aes256gcm = {
"AES-256-GCM", "SHA384", 48, 32, 12, 16, 32,
QUIC_HDR_PROT_CIPHER_AES_256
QUIC_HDR_PROT_CIPHER_AES_256,
((uint64_t)1) << 23, /* Limits as prescribed by RFC 9001 */
((uint64_t)1) << 52,
};
static const struct suite_info suite_chacha20poly1305 = {
"ChaCha20-Poly1305", "SHA256", 32, 32, 12, 16, 32,
QUIC_HDR_PROT_CIPHER_CHACHA
QUIC_HDR_PROT_CIPHER_CHACHA,
/* Do not use UINT64_MAX here as this represents an invalid value */
UINT64_MAX - 1, /* No applicable limit for this suite (RFC 9001) */
((uint64_t)1) << 36, /* Limit as prescribed by RFC 9001 */
};
static const struct suite_info *get_suite(uint32_t suite_id)
@@ -139,3 +263,15 @@ uint32_t ossl_qrl_get_suite_hdr_prot_key_len(uint32_t suite_id)
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->hdr_prot_key_len : 0;
}
uint64_t ossl_qrl_get_suite_max_pkt(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->max_pkt : UINT64_MAX;
}
uint64_t ossl_qrl_get_suite_max_forged_pkt(uint32_t suite_id)
{
const struct suite_info *c = get_suite(suite_id);
return c != NULL ? c->max_forged_pkt : UINT64_MAX;
}
+63 -7
View File
@@ -406,7 +406,8 @@ int ossl_quic_wire_encode_pkt_hdr(WPACKET *pkt,
QUIC_PKT_HDR_PTRS *ptrs)
{
unsigned char b0;
size_t off_start, off_sample, off_sample_end, off_pn;
size_t off_start, off_sample, off_pn;
unsigned char *start = WPACKET_get_curr(pkt);
if (!WPACKET_get_total_written(pkt, &off_start))
return 0;
@@ -517,19 +518,74 @@ int ossl_quic_wire_encode_pkt_hdr(WPACKET *pkt,
return 0;
off_sample = off_pn + 4;
if (!WPACKET_get_total_written(pkt, &off_sample_end))
return 0;
if (ptrs != NULL) {
ptrs->raw_start = (unsigned char *)pkt->buf->data + off_start;
ptrs->raw_sample = (unsigned char *)pkt->buf->data + off_sample;
ptrs->raw_sample_len = off_sample_end - off_sample;
ptrs->raw_pn = (unsigned char *)pkt->buf->data + off_pn;
ptrs->raw_start = start;
ptrs->raw_sample = start + (off_sample - off_start);
ptrs->raw_sample_len
= WPACKET_get_curr(pkt) + hdr->len - ptrs->raw_sample;
ptrs->raw_pn = start + (off_pn - off_start);
}
return 1;
}
int ossl_quic_wire_get_encoded_pkt_hdr_len(size_t short_conn_id_len,
const QUIC_PKT_HDR *hdr)
{
size_t len = 0, enclen;
/* Cannot serialize a partial header, or one whose DCID length is wrong. */
if (hdr->partial
|| (hdr->type == QUIC_PKT_TYPE_1RTT
&& hdr->dst_conn_id.id_len != short_conn_id_len))
return 0;
if (hdr->type == QUIC_PKT_TYPE_1RTT) {
/* Short header. */
/*
* Cannot serialize a header whose DCID length is wrong, or with an
* invalid PN length.
*/
if (hdr->dst_conn_id.id_len != short_conn_id_len
|| short_conn_id_len > QUIC_MAX_CONN_ID_LEN
|| hdr->pn_len < 1 || hdr->pn_len > 4)
return 0;
return 1 + short_conn_id_len + hdr->pn_len;
} else {
/* Long header. */
if (hdr->dst_conn_id.id_len > QUIC_MAX_CONN_ID_LEN
|| hdr->src_conn_id.id_len > QUIC_MAX_CONN_ID_LEN)
return 0;
if (hdr->type != QUIC_PKT_TYPE_VERSION_NEG
&& hdr->type != QUIC_PKT_TYPE_RETRY
&& (hdr->pn_len < 1 || hdr->pn_len > 4))
return 0;
len += 1 /* Initial byte */ + 4 /* Version */
+ 1 + hdr->dst_conn_id.id_len /* DCID Len, DCID */
+ 1 + hdr->src_conn_id.id_len /* SCID Len, SCID */
+ hdr->pn_len; /* PN */
if (hdr->type == QUIC_PKT_TYPE_INITIAL) {
enclen = ossl_quic_vlint_encode_len(hdr->token_len);
if (!enclen)
return 0;
len += enclen;
}
enclen = ossl_quic_vlint_encode_len(hdr->len);
if (!enclen)
return 0;
len += enclen;
return len;
}
}
int ossl_quic_wire_get_pkt_hdr_dst_conn_id(const unsigned char *buf,
size_t buf_len,
size_t short_conn_id_len,
+726 -310
View File
File diff suppressed because it is too large Load Diff