file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/include/internal/core.h
/* * Copyright 2019-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_INTERNAL_CORE_H # define OSSL_INTERNAL_CORE_H # pragma once /* * namespaces: * * ossl_method_ Core Method API */ /* * construct an arbitrary method from a dispatch table found by looking * up a match for the < operation_id, name, property > combination. * constructor and destructor are the constructor and destructor for that * arbitrary object. * * These objects are normally cached, unless the provider says not to cache. * However, force_cache can be used to force caching whatever the provider * says (for example, because the application knows better). */ typedef struct ossl_method_construct_method_st { /* Get a temporary store */ void *(*get_tmp_store)(void *data); /* Reserve the appropriate method store */ int (*lock_store)(void *store, void *data); /* Unreserve the appropriate method store */ int (*unlock_store)(void *store, void *data); /* Get an already existing method from a store */ void *(*get)(void *store, const OSSL_PROVIDER **prov, void *data); /* Store a method in a store */ int (*put)(void *store, void *method, const OSSL_PROVIDER *prov, const char *name, const char *propdef, void *data); /* Construct a new method */ void *(*construct)(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov, void *data); /* Destruct a method */ void (*destruct)(void *method, void *data); } OSSL_METHOD_CONSTRUCT_METHOD; void *ossl_method_construct(OSSL_LIB_CTX *ctx, int operation_id, OSSL_PROVIDER **provider_rw, int force_cache, OSSL_METHOD_CONSTRUCT_METHOD *mcm, void *mcm_data); void ossl_algorithm_do_all(OSSL_LIB_CTX *libctx, int operation_id, OSSL_PROVIDER *provider, int (*pre)(OSSL_PROVIDER *, int operation_id, int no_store, void *data, int *result), int (*reserve_store)(int no_store, void *data), void (*fn)(OSSL_PROVIDER *provider, const OSSL_ALGORITHM *algo, int no_store, void *data), int (*unreserve_store)(void *data), int (*post)(OSSL_PROVIDER *, int operation_id, int no_store, void *data, int *result), void *data); char *ossl_algorithm_get1_first_name(const OSSL_ALGORITHM *algo); __owur int ossl_lib_ctx_write_lock(OSSL_LIB_CTX *ctx); __owur int ossl_lib_ctx_read_lock(OSSL_LIB_CTX *ctx); int ossl_lib_ctx_unlock(OSSL_LIB_CTX *ctx); int ossl_lib_ctx_is_child(OSSL_LIB_CTX *ctx); #endif
./openssl/include/internal/quic_channel.h
/* * Copyright 2022-2023 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_CHANNEL_H # define OSSL_QUIC_CHANNEL_H # include <openssl/ssl.h> # include "internal/quic_types.h" # include "internal/quic_record_tx.h" # include "internal/quic_wire.h" # include "internal/quic_predef.h" # include "internal/time.h" # include "internal/thread.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Channel * ============ * * A QUIC channel (QUIC_CHANNEL) is an object which binds together all of the * various pieces of QUIC into a single top-level object, and handles connection * state which is not specific to the client or server roles. In particular, it * is strictly separated from the libssl front end I/O API personality layer, * and is not an SSL object. * * The name QUIC_CHANNEL is chosen because QUIC_CONNECTION is already in use, * but functionally these relate to the same thing (a QUIC connection). The use * of two separate objects ensures clean separation between the API personality * layer and common code for handling connections, and between the functionality * which is specific to clients and which is specific to servers, and the * functionality which is common to both. * * The API personality layer provides SSL objects (e.g. a QUIC_CONNECTION) which * consume a QUIC channel and implement a specific public API. Things which are * handled by the API personality layer include emulation of blocking semantics, * handling of SSL object mode flags like non-partial write mode, etc. * * Where the QUIC_CHANNEL is used in a server role, there is one QUIC_CHANNEL * per connection. In the future a QUIC Channel Manager will probably be defined * to handle ownership of resources which are shared between connections (e.g. * demuxers). Since we only use server-side functionality for dummy test servers * for now, which only need to handle one connection at a time, this is not * currently modelled. * * Synchronisation * --------------- * * To support thread assisted mode, QUIC_CHANNEL can be used by multiple * threads. **It is the caller's responsibility to ensure that the QUIC_CHANNEL * is only accessed (whether via its methods or via direct access to its state) * while the channel mutex is held**, except for methods explicitly marked as * not requiring prior locking. This is an unchecked precondition. * * The instantiator of the channel is responsible for providing a suitable * mutex which then serves as the channel mutex; see QUIC_CHANNEL_ARGS. */ /* * The function does not acquire the channel mutex and assumes it is already * held by the calling thread. * * Any function tagged with this has the following precondition: * * Precondition: must hold channel mutex (unchecked) */ # define QUIC_NEEDS_LOCK /* * The function acquires the channel mutex and releases it before returning in * all circumstances. * * Any function tagged with this has the following precondition and * postcondition: * * Precondition: must not hold channel mutex (unchecked) * Postcondition: channel mutex is not held (by calling thread) */ # define QUIC_TAKES_LOCK /* * The function acquires the channel mutex and leaves it acquired * when returning success. * * Any function tagged with this has the following precondition and * postcondition: * * Precondition: must not hold channel mutex (unchecked) * Postcondition: channel mutex is held by calling thread * or function returned failure */ # define QUIC_ACQUIRES_LOCK # define QUIC_TODO_LOCK # define QUIC_CHANNEL_STATE_IDLE 0 # define QUIC_CHANNEL_STATE_ACTIVE 1 # define QUIC_CHANNEL_STATE_TERMINATING_CLOSING 2 # define QUIC_CHANNEL_STATE_TERMINATING_DRAINING 3 # define QUIC_CHANNEL_STATE_TERMINATED 4 typedef struct quic_channel_args_st { /* * The QUIC_PORT which the channel is to belong to. The lifetime of the * QUIC_PORT must exceed that of the created channel. */ QUIC_PORT *port; /* LCIDM to register LCIDs with. */ QUIC_LCIDM *lcidm; /* SRTM to register SRTs with. */ QUIC_SRTM *srtm; int is_server; SSL *tls; } QUIC_CHANNEL_ARGS; /* Represents the cause for a connection's termination. */ typedef struct quic_terminate_cause_st { /* * If we are in a TERMINATING or TERMINATED state, this is the error code * associated with the error. This field is valid iff we are in the * TERMINATING or TERMINATED states. */ uint64_t error_code; /* * If terminate_app is set and this is nonzero, this is the frame type which * caused the connection to be terminated. */ uint64_t frame_type; /* * Optional reason string. When calling ossl_quic_channel_local_close, if a * reason string pointer is passed, it is copied and stored inside * QUIC_CHANNEL for the remainder of the lifetime of the channel object. * Thus the string pointed to by this value, if non-NULL, is valid for the * lifetime of the QUIC_CHANNEL object. */ const char *reason; /* * Length of reason in bytes. The reason is supposed to contain a UTF-8 * string but may be arbitrary data if the reason came from the network. */ size_t reason_len; /* Is this error code in the transport (0) or application (1) space? */ unsigned int app : 1; /* * If set, the cause of the termination is a received CONNECTION_CLOSE * frame. Otherwise, we decided to terminate ourselves and sent a * CONNECTION_CLOSE frame (regardless of whether the peer later also sends * one). */ unsigned int remote : 1; } QUIC_TERMINATE_CAUSE; /* * Create a new QUIC channel using the given arguments. The argument structure * does not need to remain allocated. Returns NULL on failure. * * Only QUIC_PORT should use this function. */ QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args); /* No-op if ch is NULL. */ void ossl_quic_channel_free(QUIC_CHANNEL *ch); /* Set mutator callbacks for test framework support */ int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch, ossl_mutate_packet_cb mutatecb, ossl_finish_mutate_cb finishmutatecb, void *mutatearg); /* * Connection Lifecycle Events * =========================== * * Various events that can be raised on the channel by other parts of the QUIC * implementation. Some of these are suitable for general use by any part of the * code (e.g. ossl_quic_channel_raise_protocol_error), others are for very * specific use by particular components only (e.g. * ossl_quic_channel_on_handshake_confirmed). */ /* * To be used by a QUIC connection. Starts the channel. For a client-mode * channel, this starts sending the first handshake layer message, etc. Can only * be called in the idle state; successive calls are ignored. */ int ossl_quic_channel_start(QUIC_CHANNEL *ch); /* Start a locally initiated connection shutdown. */ void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code, const char *app_reason); /* * Called when the handshake is confirmed. */ int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch); /* * Raises a protocol error. This is intended to be the universal call suitable * for handling of all peer-triggered protocol violations or errors detected by * us. We specify a QUIC transport-scope error code and optional frame type * which was responsible. If a frame type is not applicable, specify zero. The * reason string is not currently handled, but should be a string of static * storage duration. If the connection has already terminated due to a previous * protocol error, this is a no-op; first error wins. * * Usually the ossl_quic_channel_raise_protocol_error() function should be used. * The ossl_quic_channel_raise_protocol_error_loc() function can be used * directly for passing through existing call site information from an existing * error. */ void ossl_quic_channel_raise_protocol_error_loc(QUIC_CHANNEL *ch, uint64_t error_code, uint64_t frame_type, const char *reason, ERR_STATE *err_state, const char *src_file, int src_line, const char *src_func); #define ossl_quic_channel_raise_protocol_error(ch, error_code, frame_type, reason) \ ossl_quic_channel_raise_protocol_error_loc((ch), (error_code), \ (frame_type), \ (reason), \ NULL, \ OPENSSL_FILE, \ OPENSSL_LINE, \ OPENSSL_FUNC) #define ossl_quic_channel_raise_protocol_error_state(ch, error_code, frame_type, reason, state) \ ossl_quic_channel_raise_protocol_error_loc((ch), (error_code), \ (frame_type), \ (reason), \ (state), \ OPENSSL_FILE, \ OPENSSL_LINE, \ OPENSSL_FUNC) /* * Returns 1 if permanent net error was detected on the QUIC_CHANNEL, * 0 otherwise. */ int ossl_quic_channel_net_error(QUIC_CHANNEL *ch); /* Restore saved error state (best effort) */ void ossl_quic_channel_restore_err_state(QUIC_CHANNEL *ch); /* For RXDP use. */ void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch, OSSL_QUIC_FRAME_CONN_CLOSE *f); void ossl_quic_channel_on_new_conn_id(QUIC_CHANNEL *ch, OSSL_QUIC_FRAME_NEW_CONN_ID *f); /* Temporarily exposed during QUIC_PORT transition. */ int ossl_quic_channel_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer, const QUIC_CONN_ID *peer_scid, const QUIC_CONN_ID *peer_dcid); /* For use by QUIC_PORT. You should not need to call this directly. */ void ossl_quic_channel_subtick(QUIC_CHANNEL *ch, QUIC_TICK_RESULT *r, uint32_t flags); /* For use by QUIC_PORT only. */ void ossl_quic_channel_raise_net_error(QUIC_CHANNEL *ch); /* For use by QUIC_PORT only. */ void ossl_quic_channel_on_stateless_reset(QUIC_CHANNEL *ch); void ossl_quic_channel_inject(QUIC_CHANNEL *ch, QUIC_URXE *e); /* * Queries and Accessors * ===================== */ /* Gets the reactor which can be used to tick/poll on the channel. */ QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch); /* Gets the QSM used with the channel. */ QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch); /* Gets the statistics manager used with the channel. */ OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch); /* * Gets/sets the current peer address. Generally this should be used before * starting a channel in client mode. */ int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr); int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr); /* * Returns an existing stream by stream ID. Returns NULL if the stream does not * exist. */ QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch, uint64_t stream_id); /* Returns 1 if channel is terminating or terminated. */ int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch); const QUIC_TERMINATE_CAUSE * ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch); int ossl_quic_channel_is_closing(const QUIC_CHANNEL *ch); int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch); int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch); int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch); int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch); QUIC_PORT *ossl_quic_channel_get0_port(QUIC_CHANNEL *ch); QUIC_ENGINE *ossl_quic_channel_get0_engine(QUIC_CHANNEL *ch); QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch); SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch); /* * Retrieves a pointer to the channel mutex which was provided at the time the * channel was instantiated. In order to allow locks to be acquired and released * with the correct granularity, it is the caller's responsibility to ensure * this lock is held for write while calling any QUIC_CHANNEL method, except for * methods explicitly designed otherwise. * * This method is thread safe and does not require prior locking. It can also be * called while the lock is already held. Note that this is simply a convenience * function to access the mutex which was passed to the channel at instantiation * time; it does not belong to the channel but rather is presumed to belong to * the owner of the channel. */ CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch); /* * Creates a new locally-initiated stream in the stream mapper, choosing an * appropriate stream ID. If is_uni is 1, creates a unidirectional stream, else * creates a bidirectional stream. Returns NULL on failure. */ QUIC_STREAM *ossl_quic_channel_new_stream_local(QUIC_CHANNEL *ch, int is_uni); /* * Creates a new remotely-initiated stream in the stream mapper. The stream ID * is used to confirm the initiator and determine the stream type. The stream is * automatically added to the QSM's accept queue. A pointer to the stream is * also returned. Returns NULL on failure. */ QUIC_STREAM *ossl_quic_channel_new_stream_remote(QUIC_CHANNEL *ch, uint64_t stream_id); /* * Configures incoming stream auto-reject. If enabled, incoming streams have * both their sending and receiving parts automatically rejected using * STOP_SENDING and STREAM_RESET frames. aec is the application error * code to be used for those frames. */ void ossl_quic_channel_set_incoming_stream_auto_reject(QUIC_CHANNEL *ch, int enable, uint64_t aec); /* * Causes the channel to reject the sending and receiving parts of a stream, * as though autorejected. Can be used if a stream has already been * accepted. */ void ossl_quic_channel_reject_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs); /* Replace local connection ID in TXP and DEMUX for testing purposes. */ int ossl_quic_channel_replace_local_cid(QUIC_CHANNEL *ch, const QUIC_CONN_ID *conn_id); /* Setters for the msg_callback and msg_callback_arg */ void ossl_quic_channel_set_msg_callback(QUIC_CHANNEL *ch, ossl_msg_cb msg_callback, SSL *msg_callback_ssl); void ossl_quic_channel_set_msg_callback_arg(QUIC_CHANNEL *ch, void *msg_callback_arg); /* Testing use only - sets a TXKU threshold packet count override value. */ void ossl_quic_channel_set_txku_threshold_override(QUIC_CHANNEL *ch, uint64_t tx_pkt_threshold); /* Testing use only - gets current 1-RTT key epochs for QTX and QRX. */ uint64_t ossl_quic_channel_get_tx_key_epoch(QUIC_CHANNEL *ch); uint64_t ossl_quic_channel_get_rx_key_epoch(QUIC_CHANNEL *ch); /* Artificially trigger a spontaneous TXKU if possible. */ int ossl_quic_channel_trigger_txku(QUIC_CHANNEL *ch); int ossl_quic_channel_has_pending(const QUIC_CHANNEL *ch); /* Force transmission of an ACK-eliciting packet. */ int ossl_quic_channel_ping(QUIC_CHANNEL *ch); /* * These queries exist for diagnostic purposes only. They may roll over. * Do not rely on them for non-testing purposes. */ uint16_t ossl_quic_channel_get_diag_num_rx_ack(QUIC_CHANNEL *ch); /* * Diagnostic use only. Gets the current local CID. */ void ossl_quic_channel_get_diag_local_cid(QUIC_CHANNEL *ch, QUIC_CONN_ID *cid); /* * Returns 1 if stream count flow control allows us to create a new * locally-initiated stream. */ int ossl_quic_channel_is_new_local_stream_admissible(QUIC_CHANNEL *ch, int is_uni); # endif #endif
./openssl/include/internal/quic_types.h
/* * Copyright 2022-2023 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_TYPES_H # define OSSL_QUIC_TYPES_H # include <openssl/ssl.h> # include <internal/ssl.h> # include <assert.h> # include <string.h> # ifndef OPENSSL_NO_QUIC /* QUIC encryption levels. */ enum { QUIC_ENC_LEVEL_INITIAL = 0, QUIC_ENC_LEVEL_HANDSHAKE, QUIC_ENC_LEVEL_0RTT, QUIC_ENC_LEVEL_1RTT, QUIC_ENC_LEVEL_NUM /* Must be the ultimate entry */ }; /* QUIC packet number spaces. */ enum { QUIC_PN_SPACE_INITIAL = 0, QUIC_PN_SPACE_HANDSHAKE, /* New entries must go here, so that QUIC_PN_SPACE_APP is the penultimate */ QUIC_PN_SPACE_APP, QUIC_PN_SPACE_NUM /* Must be the ultimate entry */ }; static ossl_unused ossl_inline uint32_t ossl_quic_enc_level_to_pn_space(uint32_t enc_level) { switch (enc_level) { case QUIC_ENC_LEVEL_INITIAL: return QUIC_PN_SPACE_INITIAL; case QUIC_ENC_LEVEL_HANDSHAKE: return QUIC_PN_SPACE_HANDSHAKE; case QUIC_ENC_LEVEL_0RTT: case QUIC_ENC_LEVEL_1RTT: return QUIC_PN_SPACE_APP; default: assert(0); return QUIC_PN_SPACE_APP; } } /* QUIC packet number representation. */ typedef uint64_t QUIC_PN; # define QUIC_PN_INVALID UINT64_MAX static ossl_unused ossl_inline QUIC_PN ossl_quic_pn_max(QUIC_PN a, QUIC_PN b) { return a > b ? a : b; } static ossl_unused ossl_inline QUIC_PN ossl_quic_pn_min(QUIC_PN a, QUIC_PN b) { return a < b ? a : b; } static ossl_unused ossl_inline int ossl_quic_pn_valid(QUIC_PN pn) { return pn < (((QUIC_PN)1) << 62); } /* QUIC connection ID representation. */ # define QUIC_MAX_CONN_ID_LEN 20 # define QUIC_MIN_ODCID_LEN 8 /* RFC 9000 s. 7.2 */ typedef struct quic_conn_id_st { unsigned char id_len, id[QUIC_MAX_CONN_ID_LEN]; } QUIC_CONN_ID; static ossl_unused ossl_inline int ossl_quic_conn_id_eq(const QUIC_CONN_ID *a, const QUIC_CONN_ID *b) { if (a->id_len != b->id_len || a->id_len > QUIC_MAX_CONN_ID_LEN) return 0; return memcmp(a->id, b->id, a->id_len) == 0; } /* * Generates a random CID of the given length. libctx may be NULL. * Returns 1 on success or 0 on failure. */ int ossl_quic_gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid); # define QUIC_MIN_INITIAL_DGRAM_LEN 1200 # define QUIC_DEFAULT_ACK_DELAY_EXP 3 # define QUIC_MAX_ACK_DELAY_EXP 20 # define QUIC_DEFAULT_MAX_ACK_DELAY 25 # define QUIC_MIN_ACTIVE_CONN_ID_LIMIT 2 /* Arbitrary choice of default idle timeout (not an RFC value). */ # define QUIC_DEFAULT_IDLE_TIMEOUT 30000 # define QUIC_STATELESS_RESET_TOKEN_LEN 16 typedef struct { unsigned char token[QUIC_STATELESS_RESET_TOKEN_LEN]; } QUIC_STATELESS_RESET_TOKEN; /* * An encoded preferred_addr transport parameter cannot be shorter or longer * than these lengths in bytes. */ # define QUIC_MIN_ENCODED_PREFERRED_ADDR_LEN 41 # define QUIC_MAX_ENCODED_PREFERRED_ADDR_LEN 61 # endif #endif
./openssl/include/internal/comp.h
/* * Copyright 2016-2021 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 <openssl/comp.h> void ossl_comp_zlib_cleanup(void); void ossl_comp_brotli_cleanup(void); void ossl_comp_zstd_cleanup(void);
./openssl/include/internal/quic_srtm.h
/* * Copyright 2023 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_INTERNAL_QUIC_SRTM_H # define OSSL_INTERNAL_QUIC_SRTM_H # pragma once # include "internal/e_os.h" # include "internal/time.h" # include "internal/quic_types.h" # include "internal/quic_wire.h" # include "internal/quic_predef.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Stateless Reset Token Manager * ================================== * * The stateless reset token manager is responsible for mapping stateless reset * tokens to connections. It is used to identify stateless reset tokens in * incoming packets. In this regard it can be considered an alternate "routing" * mechanism for incoming packets, and is somewhat analogous with the LCIDM, * except that it uses SRTs to route rather than DCIDs. * * The SRTM specifically stores a bidirectional mapping of the form * * (opaque pointer, sequence number) [1] <-> [0..n] SRT * * The (opaque pointer, sequence number) tuple is used to refer to an entry (for * example for the purposes of removing it later when it is no longer needed). * Likewise, an entry can be looked up using SRT to get the opaque pointer and * sequence number. * * It is important to note that the same SRT may exist multiple times and map to * multiple (opaque pointer, sequence number) tuples, for example, if we * initiate multiple connections to the same peer using the same local QUIC_PORT * and the peer decides to behave bizarrely and issue the same SRT for both * connections. It should not do this, but we have to be resilient against * byzantine peer behaviour. Thus we are capable of storing multiple identical * SRTs for different (opaque pointer, sequence number) keys. * * The SRTM supports arbitrary insertion, arbitrary deletion of specific keys * identified by a (opaque pointer, sequence number) key, and mass deletion of * all entries under a specific opaque pointer. It supports lookup by SRT to * identify zero or more corresponding (opaque pointer, sequence number) tuples. * * The opaque pointer may be used for any purpose but is intended to represent a * connection identity and must therefore be consistent (usefully comparable). */ /* Creates a new empty SRTM instance. */ QUIC_SRTM *ossl_quic_srtm_new(OSSL_LIB_CTX *libctx, const char *propq); /* Frees a SRTM instance. No-op if srtm is NULL. */ void ossl_quic_srtm_free(QUIC_SRTM *srtm); /* * Add a (opaque, seq_num) -> SRT entry to the SRTM. This operation fails if a * SRT entry already exists with the same (opaque, seq_num) tuple. The token is * copied. Returns 1 on success or 0 on failure. */ int ossl_quic_srtm_add(QUIC_SRTM *srtm, void *opaque, uint64_t seq_num, const QUIC_STATELESS_RESET_TOKEN *token); /* * Removes an entry by identifying it via its (opaque, seq_num) tuple. * Returns 1 if the entry was found and removed, and 0 if it was not found. */ int ossl_quic_srtm_remove(QUIC_SRTM *srtm, void *opaque, uint64_t seq_num); /* * Removes all entries (opaque, *) with the given opaque pointer. * * Returns 1 on success and 0 on failure. If no entries with the given opaque * pointer were found, this is considered a success condition. */ int ossl_quic_srtm_cull(QUIC_SRTM *strm, void *opaque); /* * Looks up a SRT to find the corresponding opaque pointer and sequence number. * An output field pointer can be set to NULL if it is not required. * * This function is designed to avoid exposing timing channels on token values * or the contents of the SRT mapping. * * If there are several identical SRTs, idx can be used to get the nth entry. * Call this function with idx set to 0 first, and keep calling it after * incrementing idx until it returns 0. * * Returns 1 if an entry was found and 0 otherwise. */ int ossl_quic_srtm_lookup(QUIC_SRTM *srtm, const QUIC_STATELESS_RESET_TOKEN *token, size_t idx, void **opaque, uint64_t *seq_num); /* Verify internal invariants and assert if they are not met. */ void ossl_quic_srtm_check(const QUIC_SRTM *srtm); # endif #endif
./openssl/include/internal/err.h
/* * Copyright 2016-2021 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_INTERNAL_ERR_H # define OSSL_INTERNAL_ERR_H # pragma once void err_free_strings_int(void); #endif
./openssl/include/internal/conf.h
/* * Copyright 2016-2021 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_INTERNAL_CONF_H # define OSSL_INTERNAL_CONF_H # pragma once # include <openssl/conf.h> # define DEFAULT_CONF_MFLAGS \ (CONF_MFLAGS_DEFAULT_SECTION | \ CONF_MFLAGS_IGNORE_MISSING_FILE | \ CONF_MFLAGS_IGNORE_RETURN_CODES) struct ossl_init_settings_st { char *filename; char *appname; unsigned long flags; }; int ossl_config_int(const OPENSSL_INIT_SETTINGS *); void ossl_no_config_int(void); void ossl_config_modules_free(void); #endif
./openssl/include/internal/event_queue.h
/* * Copyright 2022-2023 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_INTERNAL_EVENT_QUEUE_H # define OSSL_INTERNAL_EVENT_QUEUE_H # pragma once # include "internal/priority_queue.h" # include "internal/time.h" /* * Opaque type holding an event. */ typedef struct ossl_event_st OSSL_EVENT; DEFINE_PRIORITY_QUEUE_OF(OSSL_EVENT); /* * Public type representing an event queue, the underlying structure being * opaque. */ typedef struct ossl_event_queue_st OSSL_EVENT_QUEUE; /* * Public type representing a event queue entry. * It is (internally) public so that it can be embedded into other structures, * it should otherwise be treated as opaque. */ struct ossl_event_st { uint32_t type; /* What type of event this is */ uint32_t priority; /* What priority this event has */ OSSL_TIME when; /* When the event is scheduled to happen */ void *ctx; /* User argument passed to call backs */ void *payload; /* Event specific data of unknown kind */ size_t payload_size; /* Length (in bytes) of event specific data */ /* These fields are for internal use only */ PRIORITY_QUEUE_OF(OSSL_EVENT) *queue; /* Queue containing this event */ size_t ref; /* ID for this event */ unsigned int flag_dynamic : 1; /* Malloced or not? */ }; /* * Utility function to populate an event structure and add it to the queue */ int ossl_event_queue_add(OSSL_EVENT_QUEUE *queue, OSSL_EVENT *event, uint32_t type, uint32_t priority, OSSL_TIME when, void *ctx, void *payload, size_t payload_size); /* * Utility functions to extract event fields */ static ossl_unused ossl_inline uint32_t ossl_event_get_type(const OSSL_EVENT *event) { return event->type; } static ossl_unused ossl_inline uint32_t ossl_event_get_priority(const OSSL_EVENT *event) { return event->priority; } static ossl_unused ossl_inline OSSL_TIME ossl_event_get_when(const OSSL_EVENT *event) { return event->when; } static ossl_unused ossl_inline void *ossl_event_get0_ctx(const OSSL_EVENT *event) { return event->ctx; } static ossl_unused ossl_inline void *ossl_event_get0_payload(const OSSL_EVENT *event, size_t *length) { if (length != NULL) *length = event->payload_size; return event->payload; } /* * Create and free a queue. */ OSSL_EVENT_QUEUE *ossl_event_queue_new(void); void ossl_event_queue_free(OSSL_EVENT_QUEUE *queue); /* * Schedule a new event into an event queue. * * The event parameters are taken from the function arguments. * * The function returns NULL on failure and the added event on success. */ OSSL_EVENT *ossl_event_queue_add_new(OSSL_EVENT_QUEUE *queue, uint32_t type, uint32_t priority, OSSL_TIME when, void *ctx, void *payload, size_t payload_size) ; /* * Schedule an event into an event queue. * * The event parameters are taken from the function arguments. * * The function returns 0 on failure and 1 on success. */ int ossl_event_queue_add(OSSL_EVENT_QUEUE *queue, OSSL_EVENT *event, uint32_t type, uint32_t priority, OSSL_TIME when, void *ctx, void *payload, size_t payload_size); /* * Delete an event from the queue. * This will cause the early deletion function to be called if it is non-NULL. * A pointer to the event structure is returned. */ int ossl_event_queue_remove(OSSL_EVENT_QUEUE *queue, OSSL_EVENT *event); /* * Free a dynamic event. * Is a NOP for a static event. */ void ossl_event_free(OSSL_EVENT *event); /* * Return the time until the next event for the specified event, if the event's * time is past, zero is returned. Once activated, the event reference becomes * invalid and this function becomes undefined. */ OSSL_TIME ossl_event_time_until(const OSSL_EVENT *event); /* * Return the time until the next event in the queue. * If the next event is in the past, zero is returned. */ OSSL_TIME ossl_event_queue_time_until_next(const OSSL_EVENT_QUEUE *queue); /* * Postpone an event to trigger at the specified time. * If the event has triggered, this function's behaviour is undefined. */ int ossl_event_queue_postpone_until(OSSL_EVENT_QUEUE *queue, OSSL_EVENT *event, OSSL_TIME when); /* * Return the next event to process. */ int ossl_event_queue_get1_next_event(OSSL_EVENT_QUEUE *queue, OSSL_EVENT **event); #endif
./openssl/include/internal/quic_vlint.h
/* * Copyright 2022-2023 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_INTERNAL_QUIC_VLINT_H # define OSSL_INTERNAL_QUIC_VLINT_H # pragma once # include "internal/e_os.h" # ifndef OPENSSL_NO_QUIC /* The smallest value requiring a 1, 2, 4, or 8-byte representation. */ #define OSSL_QUIC_VLINT_1B_MIN 0 #define OSSL_QUIC_VLINT_2B_MIN 64 #define OSSL_QUIC_VLINT_4B_MIN 16384 #define OSSL_QUIC_VLINT_8B_MIN 1073741824 /* The largest value representable in a given number of bytes. */ #define OSSL_QUIC_VLINT_1B_MAX (OSSL_QUIC_VLINT_2B_MIN - 1) #define OSSL_QUIC_VLINT_2B_MAX (OSSL_QUIC_VLINT_4B_MIN - 1) #define OSSL_QUIC_VLINT_4B_MAX (OSSL_QUIC_VLINT_8B_MIN - 1) #define OSSL_QUIC_VLINT_8B_MAX (((uint64_t)1 << 62) - 1) /* The largest value representable as a variable-length integer. */ #define OSSL_QUIC_VLINT_MAX OSSL_QUIC_VLINT_8B_MAX /* * Returns the number of bytes needed to encode v in the QUIC variable-length * integer encoding. * * Returns 0 if v exceeds OSSL_QUIC_VLINT_MAX. */ static ossl_unused ossl_inline size_t ossl_quic_vlint_encode_len(uint64_t v) { if (v < OSSL_QUIC_VLINT_2B_MIN) return 1; if (v < OSSL_QUIC_VLINT_4B_MIN) return 2; if (v < OSSL_QUIC_VLINT_8B_MIN) return 4; if (v <= OSSL_QUIC_VLINT_MAX) return 8; return 0; } /* * This function writes a QUIC varable-length encoded integer to buf. * The smallest usable representation is used. * * It is the caller's responsibility to ensure that the buffer is big enough by * calling ossl_quic_vlint_encode_len(v) before calling this function. * * Precondition: buf is at least ossl_quic_vlint_enc_len(v) bytes in size * (unchecked) * Precondition: v does not exceed OSSL_QUIC_VLINT_MAX * (unchecked) */ void ossl_quic_vlint_encode(unsigned char *buf, uint64_t v); /* * This function writes a QUIC variable-length encoded integer to buf. The * specified number of bytes n are used for the encoding, which means that the * encoded value may take up more space than necessary. * * It is the caller's responsibility to ensure that the buffer is of at least n * bytes, and that v is representable by a n-byte QUIC variable-length integer. * The representable ranges are: * * 1-byte encoding: [0, 2** 6-1] * 2-byte encoding: [0, 2**14-1] * 4-byte encoding: [0, 2**30-1] * 8-byte encoding: [0, 2**62-1] * * Precondition: buf is at least n bytes in size (unchecked) * Precondition: v does not exceed the representable range * (ossl_quic_vlint_encode_len(v) <= n) (unchecked) * Precondition: v does not exceed OSSL_QUIC_VLINT_MAX * (unchecked) */ void ossl_quic_vlint_encode_n(unsigned char *buf, uint64_t v, int n); /* * Given the first byte of an encoded QUIC variable-length integer, returns * the number of bytes comprising the encoded integer, including the first * byte. */ static ossl_unused ossl_inline size_t ossl_quic_vlint_decode_len(uint8_t first_byte) { return 1U << ((first_byte & 0xC0) >> 6); } /* * Given a buffer containing an encoded QUIC variable-length integer, returns * the decoded value. The buffer must be of at least * ossl_quic_vlint_decode_len(buf[0]) bytes in size, and the caller is responsible * for checking this. * * Precondition: buf is at least ossl_quic_vlint_decode_len(buf[0]) bytes in size * (unchecked) */ uint64_t ossl_quic_vlint_decode_unchecked(const unsigned char *buf); /* * Given a buffer buf of buf_len bytes in length, attempts to decode an encoded * QUIC variable-length integer at the start of the buffer and writes the result * to *v. If buf_len is inadequate, suggesting a truncated encoded integer, the * function fails and 0 is returned. Otherwise, returns the number of bytes * consumed. * * Precondition: buf is at least buf_len bytes in size * Precondition: v (unchecked) */ int ossl_quic_vlint_decode(const unsigned char *buf, size_t buf_len, uint64_t *v); # endif #endif
./openssl/include/internal/quic_thread_assist.h
/* * Copyright 2023 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_THREAD_ASSIST_H # define OSSL_QUIC_THREAD_ASSIST_H # include <openssl/ssl.h> # include "internal/thread.h" # include "internal/time.h" # if defined(OPENSSL_NO_QUIC) || defined(OPENSSL_NO_THREAD_POOL) # define OPENSSL_NO_QUIC_THREAD_ASSIST # endif # ifndef OPENSSL_NO_QUIC_THREAD_ASSIST /* * QUIC Thread Assisted Functionality * ================================== * * Where OS threading support is available, QUIC can optionally support a thread * assisted mode of operation. The purpose of this mode of operation is to * ensure that assorted timeout events which QUIC expects to be handled in a * timely manner can be handled without the application needing to ensure that * SSL_tick() is called on time. This is not needed if the application always * has a call blocking to SSL_read() or SSL_write() (or another I/O function) on * a QUIC SSL object, but if the application goes for long periods of time * without making any such call to a QUIC SSL object, libssl cannot ordinarily * guarantee that QUIC timeout events will be serviced in a timely fashion. * Thread assisted mode is therefore of use to applications which do not always * have an ongoing call to an I/O function on a QUIC SSL object but also do not * want to have to arrange periodic ticking. * * A consequence of this is that the intrusiveness of thread assisted mode upon * the general architecture of our QUIC engine is actually fairly limited and * amounts to an automatic ticking of the QUIC engine when timeouts expire, * synchronised correctly with an application's own threads using locking. */ typedef struct quic_thread_assist_st { QUIC_CHANNEL *ch; CRYPTO_CONDVAR *cv; CRYPTO_THREAD *t; int teardown, joined; OSSL_TIME (*now_cb)(void *arg); void *now_cb_arg; } QUIC_THREAD_ASSIST; /* * Initialise the thread assist object. The channel must have a valid mutex * configured on it which will be retrieved automatically. It is assumed that * the mutex is currently held when this function is called. This function does * not affect the state of the mutex. */ int ossl_quic_thread_assist_init_start(QUIC_THREAD_ASSIST *qta, QUIC_CHANNEL *ch, OSSL_TIME (*now_cb)(void *arg), void *now_cb_arg); /* * Request the thread assist helper to begin stopping the assist thread. This * returns before the teardown is complete. Idempotent; multiple calls to this * function are inconsequential. * * Precondition: channel mutex must be held (unchecked) */ int ossl_quic_thread_assist_stop_async(QUIC_THREAD_ASSIST *qta); /* * Wait until the thread assist helper is torn down. This automatically implies * the effects of ossl_quic_thread_assist_stop_async(). Returns immediately * if the teardown has already completed. * * Precondition: channel mutex must be held (unchecked) */ int ossl_quic_thread_assist_wait_stopped(QUIC_THREAD_ASSIST *qta); /* * Deallocates state associated with the thread assist helper. * ossl_quic_thread_assist_wait_stopped() must have returned successfully before * calling this. It does not matter whether the channel mutex is held or not. * * Precondition: ossl_quic_thread_assist_wait_stopped() has returned 1 * (asserted) */ int ossl_quic_thread_assist_cleanup(QUIC_THREAD_ASSIST *qta); /* * Must be called to notify the assist thread if the channel deadline changes. * * Precondition: channel mutex must be held (unchecked) */ int ossl_quic_thread_assist_notify_deadline_changed(QUIC_THREAD_ASSIST *qta); # endif #endif
./openssl/include/internal/bio_tfo.h
/* * Copyright 2022-2023 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 */ /* * Contains definitions for simplifying the use of TCP Fast Open * (RFC7413) in OpenSSL socket BIOs. */ /* If a supported OS is added here, update test/bio_tfo_test.c */ #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO) # if defined(OPENSSL_SYS_MACOSX) || defined(__FreeBSD__) # include <sys/sysctl.h> # endif /* * OSSL_TFO_SYSCTL is used to determine if TFO is supported by * this kernel, and if supported, if it is enabled. This is more of * a problem on FreeBSD 10.3 ~ 11.4, where TCP_FASTOPEN was defined, * but not enabled by default in the kernel, and only for the server. * Linux does not have sysctlbyname(), and the closest equivalent * is to go into the /proc filesystem, but I'm not sure it's * worthwhile. * * On MacOS and Linux: * These operating systems use a single parameter to control TFO. * The OSSL_TFO_CLIENT_FLAG and OSSL_TFO_SERVER_FLAGS are used to * determine if TFO is enabled for the client and server respectively. * * OSSL_TFO_CLIENT_FLAG = 1 = client TFO enabled * OSSL_TFO_SERVER_FLAG = 2 = server TFO enabled * * Such that: * 0 = TFO disabled * 3 = server and client TFO enabled * * macOS 10.14 and later support TFO. * Linux kernel 3.6 added support for client TFO. * Linux kernel 3.7 added support for server TFO. * Linux kernel 3.13 enabled TFO by default. * Linux kernel 4.11 added the TCP_FASTOPEN_CONNECT option. * * On FreeBSD: * FreeBSD 10.3 ~ 11.4 uses a single sysctl for server enable. * FreeBSD 12.0 and later uses separate sysctls for server and * client enable. * * Some options are purposely NOT defined per-platform * * OSSL_TFO_SYSCTL * Defined as a sysctlbyname() option to determine if * TFO is enabled in the kernel (macOS, FreeBSD) * * OSSL_TFO_SERVER_SOCKOPT * Defined to indicate the socket option used to enable * TFO on a server socket (all) * * OSSL_TFO_SERVER_SOCKOPT_VALUE * Value to be used with OSSL_TFO_SERVER_SOCKOPT * * OSSL_TFO_CONNECTX * Use the connectx() function to make a client connection * (macOS) * * OSSL_TFO_CLIENT_SOCKOPT * Defined to indicate the socket option used to enable * TFO on a client socket (FreeBSD, Linux 4.14 and later) * * OSSL_TFO_SENDTO * Defined to indicate the sendto() message type to * be used to initiate a TFO connection (FreeBSD, * Linux pre-4.14) * * OSSL_TFO_DO_NOT_CONNECT * Defined to skip calling connect() when creating a * client socket (macOS, FreeBSD, Linux pre-4.14) */ # if defined(OPENSSL_SYS_WINDOWS) /* * NO WINDOWS SUPPORT * * But this is what would be used on the server: * * define OSSL_TFO_SERVER_SOCKOPT TCP_FASTOPEN * define OSSL_TFO_SERVER_SOCKOPT_VALUE 1 * * Still have to figure out client support */ # undef TCP_FASTOPEN # endif /* NO VMS SUPPORT */ # if defined(OPENSSL_SYS_VMS) # undef TCP_FASTOPEN # endif # if defined(OPENSSL_SYS_MACOSX) # define OSSL_TFO_SYSCTL "net.inet.tcp.fastopen" # define OSSL_TFO_SERVER_SOCKOPT TCP_FASTOPEN # define OSSL_TFO_SERVER_SOCKOPT_VALUE 1 # define OSSL_TFO_CONNECTX 1 # define OSSL_TFO_DO_NOT_CONNECT 1 # define OSSL_TFO_CLIENT_FLAG 1 # define OSSL_TFO_SERVER_FLAG 2 # endif # if defined(__FreeBSD__) # if defined(TCP_FASTOPEN_PSK_LEN) /* As of 12.0 these are the SYSCTLs */ # define OSSL_TFO_SYSCTL_SERVER "net.inet.tcp.fastopen.server_enable" # define OSSL_TFO_SYSCTL_CLIENT "net.inet.tcp.fastopen.client_enable" # define OSSL_TFO_SERVER_SOCKOPT TCP_FASTOPEN # define OSSL_TFO_SERVER_SOCKOPT_VALUE MAX_LISTEN # define OSSL_TFO_CLIENT_SOCKOPT TCP_FASTOPEN # define OSSL_TFO_DO_NOT_CONNECT 1 # define OSSL_TFO_SENDTO 0 /* These are the same because the sysctl are client/server-specific */ # define OSSL_TFO_CLIENT_FLAG 1 # define OSSL_TFO_SERVER_FLAG 1 # else /* 10.3 through 11.4 SYSCTL - ONLY SERVER SUPPORT */ # define OSSL_TFO_SYSCTL "net.inet.tcp.fastopen.enabled" # define OSSL_TFO_SERVER_SOCKOPT TCP_FASTOPEN # define OSSL_TFO_SERVER_SOCKOPT_VALUE MAX_LISTEN # define OSSL_TFO_SERVER_FLAG 1 # endif # endif # if defined(OPENSSL_SYS_LINUX) /* OSSL_TFO_PROC not used, but of interest */ # define OSSL_TFO_PROC "/proc/sys/net/ipv4/tcp_fastopen" # define OSSL_TFO_SERVER_SOCKOPT TCP_FASTOPEN # define OSSL_TFO_SERVER_SOCKOPT_VALUE MAX_LISTEN # if defined(TCP_FASTOPEN_CONNECT) # define OSSL_TFO_CLIENT_SOCKOPT TCP_FASTOPEN_CONNECT # else # define OSSL_TFO_SENDTO MSG_FASTOPEN # define OSSL_TFO_DO_NOT_CONNECT 1 # endif # define OSSL_TFO_CLIENT_FLAG 1 # define OSSL_TFO_SERVER_FLAG 2 # endif #endif
./openssl/include/internal/property.h
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. 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_INTERNAL_PROPERTY_H # define OSSL_INTERNAL_PROPERTY_H # pragma once # include "internal/cryptlib.h" typedef struct ossl_method_store_st OSSL_METHOD_STORE; typedef struct ossl_property_list_st OSSL_PROPERTY_LIST; typedef enum { OSSL_PROPERTY_TYPE_STRING, OSSL_PROPERTY_TYPE_NUMBER, OSSL_PROPERTY_TYPE_VALUE_UNDEFINED } OSSL_PROPERTY_TYPE; typedef struct ossl_property_definition_st OSSL_PROPERTY_DEFINITION; /* Initialisation */ int ossl_property_parse_init(OSSL_LIB_CTX *ctx); /* Property definition parser */ OSSL_PROPERTY_LIST *ossl_parse_property(OSSL_LIB_CTX *ctx, const char *defn); /* Property query parser */ OSSL_PROPERTY_LIST *ossl_parse_query(OSSL_LIB_CTX *ctx, const char *s, int create_values); /* Property checker of query vs definition */ int ossl_property_match_count(const OSSL_PROPERTY_LIST *query, const OSSL_PROPERTY_LIST *defn); int ossl_property_is_enabled(OSSL_LIB_CTX *ctx, const char *property_name, const OSSL_PROPERTY_LIST *prop_list); /* Free a parsed property list */ void ossl_property_free(OSSL_PROPERTY_LIST *p); /* Get a property from a property list */ const OSSL_PROPERTY_DEFINITION * ossl_property_find_property(const OSSL_PROPERTY_LIST *list, OSSL_LIB_CTX *libctx, const char *name); OSSL_PROPERTY_TYPE ossl_property_get_type(const OSSL_PROPERTY_DEFINITION *prop); const char *ossl_property_get_string_value(OSSL_LIB_CTX *libctx, const OSSL_PROPERTY_DEFINITION *prop); int64_t ossl_property_get_number_value(const OSSL_PROPERTY_DEFINITION *prop); /* Implementation store functions */ OSSL_METHOD_STORE *ossl_method_store_new(OSSL_LIB_CTX *ctx); void ossl_method_store_free(OSSL_METHOD_STORE *store); int ossl_method_lock_store(OSSL_METHOD_STORE *store); int ossl_method_unlock_store(OSSL_METHOD_STORE *store); int ossl_method_store_add(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov, int nid, const char *properties, void *method, int (*method_up_ref)(void *), void (*method_destruct)(void *)); int ossl_method_store_remove(OSSL_METHOD_STORE *store, int nid, const void *method); void ossl_method_store_do_all(OSSL_METHOD_STORE *store, void (*fn)(int id, void *method, void *fnarg), void *fnarg); int ossl_method_store_fetch(OSSL_METHOD_STORE *store, int nid, const char *prop_query, const OSSL_PROVIDER **prov, void **method); int ossl_method_store_remove_all_provided(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov); /* Get the global properties associate with the specified library context */ OSSL_PROPERTY_LIST **ossl_ctx_global_properties(OSSL_LIB_CTX *ctx, int loadconfig); /* property query cache functions */ int ossl_method_store_cache_get(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov, int nid, const char *prop_query, void **result); int ossl_method_store_cache_set(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov, int nid, const char *prop_query, void *result, int (*method_up_ref)(void *), void (*method_destruct)(void *)); __owur int ossl_method_store_cache_flush_all(OSSL_METHOD_STORE *store); /* Merge two property queries together */ OSSL_PROPERTY_LIST *ossl_property_merge(const OSSL_PROPERTY_LIST *a, const OSSL_PROPERTY_LIST *b); size_t ossl_property_list_to_string(OSSL_LIB_CTX *ctx, const OSSL_PROPERTY_LIST *list, char *buf, size_t bufsize); int ossl_global_properties_no_mirrored(OSSL_LIB_CTX *libctx); void ossl_global_properties_stop_mirroring(OSSL_LIB_CTX *libctx); #endif
./openssl/include/internal/propertyerr.h
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 2020-2021 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_INTERNAL_PROPERTYERR_H # define OSSL_INTERNAL_PROPERTYERR_H # pragma once # include <openssl/opensslconf.h> # include <openssl/symhacks.h> # ifdef __cplusplus extern "C" { # endif int ossl_err_load_PROP_strings(void); /* * PROP reason codes. */ # define PROP_R_NAME_TOO_LONG 100 # define PROP_R_NOT_AN_ASCII_CHARACTER 101 # define PROP_R_NOT_AN_HEXADECIMAL_DIGIT 102 # define PROP_R_NOT_AN_IDENTIFIER 103 # define PROP_R_NOT_AN_OCTAL_DIGIT 104 # define PROP_R_NOT_A_DECIMAL_DIGIT 105 # define PROP_R_NO_MATCHING_STRING_DELIMITER 106 # define PROP_R_NO_VALUE 107 # define PROP_R_PARSE_FAILED 108 # define PROP_R_STRING_TOO_LONG 109 # define PROP_R_TRAILING_CHARACTERS 110 # ifdef __cplusplus } # endif #endif
./openssl/include/internal/constant_time.h
/* * Copyright 2014-2021 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_INTERNAL_CONSTANT_TIME_H # define OSSL_INTERNAL_CONSTANT_TIME_H # pragma once # include <stdlib.h> # include <string.h> # include <openssl/e_os2.h> /* For 'ossl_inline' */ /*- * The boolean methods return a bitmask of all ones (0xff...f) for true * and 0 for false. This is useful for choosing a value based on the result * of a conditional in constant time. For example, * if (a < b) { * c = a; * } else { * c = b; * } * can be written as * unsigned int lt = constant_time_lt(a, b); * c = constant_time_select(lt, a, b); */ /* Returns the given value with the MSB copied to all the other bits. */ static ossl_inline unsigned int constant_time_msb(unsigned int a); /* Convenience method for uint32_t. */ static ossl_inline uint32_t constant_time_msb_32(uint32_t a); /* Convenience method for uint64_t. */ static ossl_inline uint64_t constant_time_msb_64(uint64_t a); /* Returns 0xff..f if a < b and 0 otherwise. */ static ossl_inline unsigned int constant_time_lt(unsigned int a, unsigned int b); /* Convenience method for getting an 8-bit mask. */ static ossl_inline unsigned char constant_time_lt_8(unsigned int a, unsigned int b); /* Convenience method for uint64_t. */ static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b); /* Returns 0xff..f if a >= b and 0 otherwise. */ static ossl_inline unsigned int constant_time_ge(unsigned int a, unsigned int b); /* Convenience method for getting an 8-bit mask. */ static ossl_inline unsigned char constant_time_ge_8(unsigned int a, unsigned int b); /* Returns 0xff..f if a == 0 and 0 otherwise. */ static ossl_inline unsigned int constant_time_is_zero(unsigned int a); /* Convenience method for getting an 8-bit mask. */ static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a); /* Convenience method for getting a 32-bit mask. */ static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a); /* Returns 0xff..f if a == b and 0 otherwise. */ static ossl_inline unsigned int constant_time_eq(unsigned int a, unsigned int b); /* Convenience method for getting an 8-bit mask. */ static ossl_inline unsigned char constant_time_eq_8(unsigned int a, unsigned int b); /* Signed integers. */ static ossl_inline unsigned int constant_time_eq_int(int a, int b); /* Convenience method for getting an 8-bit mask. */ static ossl_inline unsigned char constant_time_eq_int_8(int a, int b); /*- * Returns (mask & a) | (~mask & b). * * When |mask| is all 1s or all 0s (as returned by the methods above), * the select methods return either |a| (if |mask| is nonzero) or |b| * (if |mask| is zero). */ static ossl_inline unsigned int constant_time_select(unsigned int mask, unsigned int a, unsigned int b); /* Convenience method for unsigned chars. */ static ossl_inline unsigned char constant_time_select_8(unsigned char mask, unsigned char a, unsigned char b); /* Convenience method for uint32_t. */ static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a, uint32_t b); /* Convenience method for uint64_t. */ static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a, uint64_t b); /* Convenience method for signed integers. */ static ossl_inline int constant_time_select_int(unsigned int mask, int a, int b); static ossl_inline unsigned int constant_time_msb(unsigned int a) { return 0 - (a >> (sizeof(a) * 8 - 1)); } static ossl_inline uint32_t constant_time_msb_32(uint32_t a) { return 0 - (a >> 31); } static ossl_inline uint64_t constant_time_msb_64(uint64_t a) { return 0 - (a >> 63); } static ossl_inline size_t constant_time_msb_s(size_t a) { return 0 - (a >> (sizeof(a) * 8 - 1)); } static ossl_inline unsigned int constant_time_lt(unsigned int a, unsigned int b) { return constant_time_msb(a ^ ((a ^ b) | ((a - b) ^ b))); } static ossl_inline size_t constant_time_lt_s(size_t a, size_t b) { return constant_time_msb_s(a ^ ((a ^ b) | ((a - b) ^ b))); } static ossl_inline unsigned char constant_time_lt_8(unsigned int a, unsigned int b) { return (unsigned char)constant_time_lt(a, b); } static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b) { return constant_time_msb_64(a ^ ((a ^ b) | ((a - b) ^ b))); } static ossl_inline unsigned int constant_time_ge(unsigned int a, unsigned int b) { return ~constant_time_lt(a, b); } static ossl_inline size_t constant_time_ge_s(size_t a, size_t b) { return ~constant_time_lt_s(a, b); } static ossl_inline unsigned char constant_time_ge_8(unsigned int a, unsigned int b) { return (unsigned char)constant_time_ge(a, b); } static ossl_inline unsigned char constant_time_ge_8_s(size_t a, size_t b) { return (unsigned char)constant_time_ge_s(a, b); } static ossl_inline unsigned int constant_time_is_zero(unsigned int a) { return constant_time_msb(~a & (a - 1)); } static ossl_inline size_t constant_time_is_zero_s(size_t a) { return constant_time_msb_s(~a & (a - 1)); } static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a) { return (unsigned char)constant_time_is_zero(a); } static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a) { return constant_time_msb_32(~a & (a - 1)); } static ossl_inline uint64_t constant_time_is_zero_64(uint64_t a) { return constant_time_msb_64(~a & (a - 1)); } static ossl_inline unsigned int constant_time_eq(unsigned int a, unsigned int b) { return constant_time_is_zero(a ^ b); } static ossl_inline size_t constant_time_eq_s(size_t a, size_t b) { return constant_time_is_zero_s(a ^ b); } static ossl_inline unsigned char constant_time_eq_8(unsigned int a, unsigned int b) { return (unsigned char)constant_time_eq(a, b); } static ossl_inline unsigned char constant_time_eq_8_s(size_t a, size_t b) { return (unsigned char)constant_time_eq_s(a, b); } static ossl_inline unsigned int constant_time_eq_int(int a, int b) { return constant_time_eq((unsigned)(a), (unsigned)(b)); } static ossl_inline unsigned char constant_time_eq_int_8(int a, int b) { return constant_time_eq_8((unsigned)(a), (unsigned)(b)); } /* * Returns the value unmodified, but avoids optimizations. * The barriers prevent the compiler from narrowing down the * possible value range of the mask and ~mask in the select * statements, which avoids the recognition of the select * and turning it into a conditional load or branch. */ static ossl_inline unsigned int value_barrier(unsigned int a) { #if !defined(OPENSSL_NO_ASM) && defined(__GNUC__) unsigned int r; __asm__("" : "=r"(r) : "0"(a)); #else volatile unsigned int r = a; #endif return r; } /* Convenience method for uint32_t. */ static ossl_inline uint32_t value_barrier_32(uint32_t a) { #if !defined(OPENSSL_NO_ASM) && defined(__GNUC__) uint32_t r; __asm__("" : "=r"(r) : "0"(a)); #else volatile uint32_t r = a; #endif return r; } /* Convenience method for uint64_t. */ static ossl_inline uint64_t value_barrier_64(uint64_t a) { #if !defined(OPENSSL_NO_ASM) && defined(__GNUC__) uint64_t r; __asm__("" : "=r"(r) : "0"(a)); #else volatile uint64_t r = a; #endif return r; } /* Convenience method for size_t. */ static ossl_inline size_t value_barrier_s(size_t a) { #if !defined(OPENSSL_NO_ASM) && defined(__GNUC__) size_t r; __asm__("" : "=r"(r) : "0"(a)); #else volatile size_t r = a; #endif return r; } static ossl_inline unsigned int constant_time_select(unsigned int mask, unsigned int a, unsigned int b) { return (value_barrier(mask) & a) | (value_barrier(~mask) & b); } static ossl_inline size_t constant_time_select_s(size_t mask, size_t a, size_t b) { return (value_barrier_s(mask) & a) | (value_barrier_s(~mask) & b); } static ossl_inline unsigned char constant_time_select_8(unsigned char mask, unsigned char a, unsigned char b) { return (unsigned char)constant_time_select(mask, a, b); } static ossl_inline int constant_time_select_int(unsigned int mask, int a, int b) { return (int)constant_time_select(mask, (unsigned)(a), (unsigned)(b)); } static ossl_inline int constant_time_select_int_s(size_t mask, int a, int b) { return (int)constant_time_select((unsigned)mask, (unsigned)(a), (unsigned)(b)); } static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a, uint32_t b) { return (value_barrier_32(mask) & a) | (value_barrier_32(~mask) & b); } static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a, uint64_t b) { return (value_barrier_64(mask) & a) | (value_barrier_64(~mask) & b); } /* * mask must be 0xFFFFFFFF or 0x00000000. * * if (mask) { * uint32_t tmp = *a; * * *a = *b; * *b = tmp; * } */ static ossl_inline void constant_time_cond_swap_32(uint32_t mask, uint32_t *a, uint32_t *b) { uint32_t xor = *a ^ *b; xor &= mask; *a ^= xor; *b ^= xor; } /* * mask must be 0xFFFFFFFF or 0x00000000. * * if (mask) { * uint64_t tmp = *a; * * *a = *b; * *b = tmp; * } */ static ossl_inline void constant_time_cond_swap_64(uint64_t mask, uint64_t *a, uint64_t *b) { uint64_t xor = *a ^ *b; xor &= mask; *a ^= xor; *b ^= xor; } /* * mask must be 0xFF or 0x00. * "constant time" is per len. * * if (mask) { * unsigned char tmp[len]; * * memcpy(tmp, a, len); * memcpy(a, b); * memcpy(b, tmp); * } */ static ossl_inline void constant_time_cond_swap_buff(unsigned char mask, unsigned char *a, unsigned char *b, size_t len) { size_t i; unsigned char tmp; for (i = 0; i < len; i++) { tmp = a[i] ^ b[i]; tmp &= mask; a[i] ^= tmp; b[i] ^= tmp; } } /* * table is a two dimensional array of bytes. Each row has rowsize elements. * Copies row number idx into out. rowsize and numrows are not considered * private. */ static ossl_inline void constant_time_lookup(void *out, const void *table, size_t rowsize, size_t numrows, size_t idx) { size_t i, j; const unsigned char *tablec = (const unsigned char *)table; unsigned char *outc = (unsigned char *)out; unsigned char mask; memset(out, 0, rowsize); /* Note idx may underflow - but that is well defined */ for (i = 0; i < numrows; i++, idx--) { mask = (unsigned char)constant_time_is_zero_s(idx); for (j = 0; j < rowsize; j++) *(outc + j) |= constant_time_select_8(mask, *(tablec++), 0); } } /* * Expected usage pattern is to unconditionally set error and then * wipe it if there was no actual error. |clear| is 1 or 0. */ void err_clear_last_constant_time(int clear); #endif /* OSSL_INTERNAL_CONSTANT_TIME_H */
./openssl/include/internal/bio_addr.h
/* * 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_BIO_ADDR_H # define OSSL_BIO_ADDR_H # include "internal/e_os.h" # include "internal/sockets.h" # ifndef OPENSSL_NO_SOCK union bio_addr_st { struct sockaddr sa; # if OPENSSL_USE_IPV6 struct sockaddr_in6 s_in6; # endif struct sockaddr_in s_in; # ifndef OPENSSL_NO_UNIX_SOCK struct sockaddr_un s_un; # endif }; # endif #endif
./openssl/include/internal/tsan_assist.h
/* * Copyright 2018-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 */ /* * Contemporary compilers implement lock-free atomic memory access * primitives that facilitate writing "thread-opportunistic" or even real * multi-threading low-overhead code. "Thread-opportunistic" is when * exact result is not required, e.g. some statistics, or execution flow * doesn't have to be unambiguous. Simplest example is lazy "constant" * initialization when one can synchronize on variable itself, e.g. * * if (var == NOT_YET_INITIALIZED) * var = function_returning_same_value(); * * This does work provided that loads and stores are single-instruction * operations (and integer ones are on *all* supported platforms), but * it upsets Thread Sanitizer. Suggested solution is * * if (tsan_load(&var) == NOT_YET_INITIALIZED) * tsan_store(&var, function_returning_same_value()); * * Production machine code would be the same, so one can wonder why * bother. Having Thread Sanitizer accept "thread-opportunistic" code * allows to move on trouble-shooting real bugs. * * Resolving Thread Sanitizer nits was the initial purpose for this module, * but it was later extended with more nuanced primitives that are useful * even in "non-opportunistic" scenarios. Most notably verifying if a shared * structure is fully initialized and bypassing the initialization lock. * It's suggested to view macros defined in this module as "annotations" for * thread-safe lock-free code, "Thread-Safe ANnotations"... * * It's assumed that ATOMIC_{LONG|INT}_LOCK_FREE are assigned same value as * ATOMIC_POINTER_LOCK_FREE. And check for >= 2 ensures that corresponding * code is inlined. It should be noted that statistics counters become * accurate in such case. * * Special note about TSAN_QUALIFIER. It might be undesired to use it in * a shared header. Because whether operation on specific variable or member * is atomic or not might be irrelevant in other modules. In such case one * can use TSAN_QUALIFIER in cast specifically when it has to count. */ #ifndef OSSL_INTERNAL_TSAN_ASSIST_H # define OSSL_INTERNAL_TSAN_ASSIST_H # pragma once # if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \ && !defined(__STDC_NO_ATOMICS__) # include <stdatomic.h> # if defined(ATOMIC_POINTER_LOCK_FREE) \ && ATOMIC_POINTER_LOCK_FREE >= 2 # define TSAN_QUALIFIER _Atomic # define tsan_load(ptr) atomic_load_explicit((ptr), memory_order_relaxed) # define tsan_store(ptr, val) atomic_store_explicit((ptr), (val), memory_order_relaxed) # define tsan_add(ptr, n) atomic_fetch_add_explicit((ptr), (n), memory_order_relaxed) # define tsan_ld_acq(ptr) atomic_load_explicit((ptr), memory_order_acquire) # define tsan_st_rel(ptr, val) atomic_store_explicit((ptr), (val), memory_order_release) # endif # elif defined(__GNUC__) && defined(__ATOMIC_RELAXED) # if defined(__GCC_ATOMIC_POINTER_LOCK_FREE) \ && __GCC_ATOMIC_POINTER_LOCK_FREE >= 2 # define TSAN_QUALIFIER volatile # define tsan_load(ptr) __atomic_load_n((ptr), __ATOMIC_RELAXED) # define tsan_store(ptr, val) __atomic_store_n((ptr), (val), __ATOMIC_RELAXED) # define tsan_add(ptr, n) __atomic_fetch_add((ptr), (n), __ATOMIC_RELAXED) # define tsan_ld_acq(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE) # define tsan_st_rel(ptr, val) __atomic_store_n((ptr), (val), __ATOMIC_RELEASE) # endif # elif defined(_MSC_VER) && _MSC_VER>=1200 \ && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64) || \ defined(_M_ARM64) || (defined(_M_ARM) && _M_ARM >= 7 && !defined(_WIN32_WCE))) /* * There is subtle dependency on /volatile:<iso|ms> command-line option. * "ms" implies same semantic as memory_order_acquire for loads and * memory_order_release for stores, while "iso" - memory_order_relaxed for * either. Real complication is that defaults are different on x86 and ARM. * There is explanation for that, "ms" is backward compatible with earlier * compiler versions, while multi-processor ARM can be viewed as brand new * platform to MSC and its users, and with non-relaxed semantic taking toll * with additional instructions and penalties, it kind of makes sense to * default to "iso"... */ # define TSAN_QUALIFIER volatile # if defined(_M_ARM) || defined(_M_ARM64) # define _InterlockedExchangeAdd _InterlockedExchangeAdd_nf # pragma intrinsic(_InterlockedExchangeAdd_nf) # pragma intrinsic(__iso_volatile_load32, __iso_volatile_store32) # ifdef _WIN64 # define _InterlockedExchangeAdd64 _InterlockedExchangeAdd64_nf # pragma intrinsic(_InterlockedExchangeAdd64_nf) # pragma intrinsic(__iso_volatile_load64, __iso_volatile_store64) # define tsan_load(ptr) (sizeof(*(ptr)) == 8 ? __iso_volatile_load64(ptr) \ : __iso_volatile_load32(ptr)) # define tsan_store(ptr, val) (sizeof(*(ptr)) == 8 ? __iso_volatile_store64((ptr), (val)) \ : __iso_volatile_store32((ptr), (val))) # else # define tsan_load(ptr) __iso_volatile_load32(ptr) # define tsan_store(ptr, val) __iso_volatile_store32((ptr), (val)) # endif # else # define tsan_load(ptr) (*(ptr)) # define tsan_store(ptr, val) (*(ptr) = (val)) # endif # pragma intrinsic(_InterlockedExchangeAdd) # ifdef _WIN64 # pragma intrinsic(_InterlockedExchangeAdd64) # define tsan_add(ptr, n) (sizeof(*(ptr)) == 8 ? _InterlockedExchangeAdd64((ptr), (n)) \ : _InterlockedExchangeAdd((ptr), (n))) # else # define tsan_add(ptr, n) _InterlockedExchangeAdd((ptr), (n)) # endif # if !defined(_ISO_VOLATILE) # define tsan_ld_acq(ptr) (*(ptr)) # define tsan_st_rel(ptr, val) (*(ptr) = (val)) # endif # endif # ifndef TSAN_QUALIFIER # ifdef OPENSSL_THREADS # define TSAN_QUALIFIER volatile # define TSAN_REQUIRES_LOCKING # else /* OPENSSL_THREADS */ # define TSAN_QUALIFIER # endif /* OPENSSL_THREADS */ # define tsan_load(ptr) (*(ptr)) # define tsan_store(ptr, val) (*(ptr) = (val)) # define tsan_add(ptr, n) (*(ptr) += (n)) /* * Lack of tsan_ld_acq and tsan_ld_rel means that compiler support is not * sophisticated enough to support them. Code that relies on them should be * protected with #ifdef tsan_ld_acq with locked fallback. */ # endif # define tsan_counter(ptr) tsan_add((ptr), 1) # define tsan_decr(ptr) tsan_add((ptr), -1) #endif
./openssl/include/internal/numbers.h
/* * Copyright 2015-2023 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_INTERNAL_NUMBERS_H # define OSSL_INTERNAL_NUMBERS_H # pragma once # include <limits.h> # if (-1 & 3) == 0x03 /* Two's complement */ # define __MAXUINT__(T) ((T) -1) # define __MAXINT__(T) ((T) ((((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)) ^ __MAXUINT__(T))) # define __MININT__(T) (-__MAXINT__(T) - 1) # elif (-1 & 3) == 0x02 /* One's complement */ # define __MAXUINT__(T) (((T) -1) + 1) # define __MAXINT__(T) ((T) ((((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)) ^ __MAXUINT__(T))) # define __MININT__(T) (-__MAXINT__(T)) # elif (-1 & 3) == 0x01 /* Sign/magnitude */ # define __MAXINT__(T) ((T) (((((T) 1) << ((sizeof(T) * CHAR_BIT) - 2)) - 1) | (((T) 1) << ((sizeof(T) * CHAR_BIT) - 2)))) # define __MAXUINT__(T) ((T) (__MAXINT__(T) | (((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)))) # define __MININT__(T) (-__MAXINT__(T)) # else # error "do not know the integer encoding on this architecture" # endif # ifndef INT8_MAX # define INT8_MIN __MININT__(int8_t) # define INT8_MAX __MAXINT__(int8_t) # define UINT8_MAX __MAXUINT__(uint8_t) # endif # ifndef INT16_MAX # define INT16_MIN __MININT__(int16_t) # define INT16_MAX __MAXINT__(int16_t) # define UINT16_MAX __MAXUINT__(uint16_t) # endif # ifndef INT32_MAX # define INT32_MIN __MININT__(int32_t) # define INT32_MAX __MAXINT__(int32_t) # define UINT32_MAX __MAXUINT__(uint32_t) # endif # ifndef INT64_MAX # define INT64_MIN __MININT__(int64_t) # define INT64_MAX __MAXINT__(int64_t) # define UINT64_MAX __MAXUINT__(uint64_t) # endif /* * 64-bit processor with LP64 ABI */ # ifdef SIXTY_FOUR_BIT_LONG # ifndef UINT32_C # define UINT32_C(c) (c) # endif # ifndef UINT64_C # define UINT64_C(c) (c##UL) # endif # endif /* * 64-bit processor other than LP64 ABI */ # ifdef SIXTY_FOUR_BIT # ifndef UINT32_C # define UINT32_C(c) (c##UL) # endif # ifndef UINT64_C # define UINT64_C(c) (c##ULL) # endif # endif # ifndef INT128_MAX # if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__ == 16 typedef __int128_t int128_t; typedef __uint128_t uint128_t; # define INT128_MIN __MININT__(int128_t) # define INT128_MAX __MAXINT__(int128_t) # define UINT128_MAX __MAXUINT__(uint128_t) # endif # endif # ifndef SIZE_MAX # define SIZE_MAX __MAXUINT__(size_t) # endif # ifndef OSSL_INTMAX_MAX # define OSSL_INTMAX_MIN __MININT__(ossl_intmax_t) # define OSSL_INTMAX_MAX __MAXINT__(ossl_intmax_t) # define OSSL_UINTMAX_MAX __MAXUINT__(ossl_uintmax_t) # endif #endif
./openssl/include/internal/dane.h
/* * Copyright 2015-2021 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_INTERNAL_DANE_H #define OSSL_INTERNAL_DANE_H # pragma once # include <openssl/safestack.h> /*- * Certificate usages: * https://tools.ietf.org/html/rfc6698#section-2.1.1 */ #define DANETLS_USAGE_PKIX_TA 0 #define DANETLS_USAGE_PKIX_EE 1 #define DANETLS_USAGE_DANE_TA 2 #define DANETLS_USAGE_DANE_EE 3 #define DANETLS_USAGE_LAST DANETLS_USAGE_DANE_EE /*- * Selectors: * https://tools.ietf.org/html/rfc6698#section-2.1.2 */ #define DANETLS_SELECTOR_CERT 0 #define DANETLS_SELECTOR_SPKI 1 #define DANETLS_SELECTOR_LAST DANETLS_SELECTOR_SPKI /*- * Matching types: * https://tools.ietf.org/html/rfc6698#section-2.1.3 */ #define DANETLS_MATCHING_FULL 0 #define DANETLS_MATCHING_2256 1 #define DANETLS_MATCHING_2512 2 #define DANETLS_MATCHING_LAST DANETLS_MATCHING_2512 typedef struct danetls_record_st { uint8_t usage; uint8_t selector; uint8_t mtype; unsigned char *data; size_t dlen; EVP_PKEY *spki; } danetls_record; DEFINE_STACK_OF(danetls_record) /* * Shared DANE context */ struct dane_ctx_st { const EVP_MD **mdevp; /* mtype -> digest */ uint8_t *mdord; /* mtype -> preference */ uint8_t mdmax; /* highest supported mtype */ unsigned long flags; /* feature bitmask */ }; /* * Per connection DANE state */ struct ssl_dane_st { struct dane_ctx_st *dctx; STACK_OF(danetls_record) *trecs; STACK_OF(X509) *certs; /* DANE-TA(2) Cert(0) Full(0) certs */ danetls_record *mtlsa; /* Matching TLSA record */ X509 *mcert; /* DANE matched cert */ uint32_t umask; /* Usages present */ int mdpth; /* Depth of matched cert */ int pdpth; /* Depth of PKIX trust */ unsigned long flags; /* feature bitmask */ }; #define DANETLS_ENABLED(dane) \ ((dane) != NULL && sk_danetls_record_num((dane)->trecs) > 0) #define DANETLS_USAGE_BIT(u) (((uint32_t)1) << u) #define DANETLS_PKIX_TA_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_PKIX_TA)) #define DANETLS_PKIX_EE_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_PKIX_EE)) #define DANETLS_DANE_TA_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_DANE_TA)) #define DANETLS_DANE_EE_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_DANE_EE)) #define DANETLS_PKIX_MASK (DANETLS_PKIX_TA_MASK | DANETLS_PKIX_EE_MASK) #define DANETLS_DANE_MASK (DANETLS_DANE_TA_MASK | DANETLS_DANE_EE_MASK) #define DANETLS_TA_MASK (DANETLS_PKIX_TA_MASK | DANETLS_DANE_TA_MASK) #define DANETLS_EE_MASK (DANETLS_PKIX_EE_MASK | DANETLS_DANE_EE_MASK) #define DANETLS_HAS_PKIX(dane) ((dane) && ((dane)->umask & DANETLS_PKIX_MASK)) #define DANETLS_HAS_DANE(dane) ((dane) && ((dane)->umask & DANETLS_DANE_MASK)) #define DANETLS_HAS_TA(dane) ((dane) && ((dane)->umask & DANETLS_TA_MASK)) #define DANETLS_HAS_EE(dane) ((dane) && ((dane)->umask & DANETLS_EE_MASK)) #define DANETLS_HAS_PKIX_TA(dane) ((dane)&&((dane)->umask & DANETLS_PKIX_TA_MASK)) #define DANETLS_HAS_PKIX_EE(dane) ((dane)&&((dane)->umask & DANETLS_PKIX_EE_MASK)) #define DANETLS_HAS_DANE_TA(dane) ((dane)&&((dane)->umask & DANETLS_DANE_TA_MASK)) #define DANETLS_HAS_DANE_EE(dane) ((dane)&&((dane)->umask & DANETLS_DANE_EE_MASK)) #endif /* OSSL_INTERNAL_DANE_H */
./openssl/include/internal/uint_set.h
/* * 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_UINT_SET_H # define OSSL_UINT_SET_H #include "openssl/params.h" #include "internal/list.h" /* * uint64_t Integer Sets * ===================== * * Utilities for managing a logical set of unsigned 64-bit integers. The * structure tracks each contiguous range of integers using one allocation and * is thus optimised for cases where integers tend to appear consecutively. * Queries are optimised under the assumption that they will generally be made * on integers near the end of the set. * * Discussion of implementation details can be found in uint_set.c. */ typedef struct uint_range_st { uint64_t start, end; } UINT_RANGE; typedef struct uint_set_item_st UINT_SET_ITEM; struct uint_set_item_st { OSSL_LIST_MEMBER(uint_set, UINT_SET_ITEM); UINT_RANGE range; }; DEFINE_LIST_OF(uint_set, UINT_SET_ITEM); typedef OSSL_LIST(uint_set) UINT_SET; void ossl_uint_set_init(UINT_SET *s); void ossl_uint_set_destroy(UINT_SET *s); /* * Insert a range into a integer set. Returns 0 on allocation failure, in which * case the integer set is in a valid but undefined state. Otherwise, returns 1. * Ranges can overlap existing ranges without limitation. If a range is a subset * of an existing range in the set, this is a no-op and returns 1. */ int ossl_uint_set_insert(UINT_SET *s, const UINT_RANGE *range); /* * Remove a range from the set. Returns 0 on allocation failure, in which case * the integer set is unchanged. Otherwise, returns 1. Ranges which are not * already in the set can be removed without issue. If a passed range is not in * the integer set at all, this is a no-op and returns 1. */ int ossl_uint_set_remove(UINT_SET *s, const UINT_RANGE *range); /* Returns 1 iff the given integer is in the integer set. */ int ossl_uint_set_query(const UINT_SET *s, uint64_t v); #endif
./openssl/include/internal/quic_cc.h
/* * Copyright 2022-2023 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_CC_H # define OSSL_QUIC_CC_H #include "openssl/params.h" #include "internal/time.h" #include "internal/quic_predef.h" # ifndef OPENSSL_NO_QUIC typedef struct ossl_cc_ack_info_st { /* The time the packet being acknowledged was originally sent. */ OSSL_TIME tx_time; /* The size in bytes of the packet being acknowledged. */ size_t tx_size; } OSSL_CC_ACK_INFO; typedef struct ossl_cc_loss_info_st { /* The time the packet being lost was originally sent. */ OSSL_TIME tx_time; /* The size in bytes of the packet which has been determined lost. */ size_t tx_size; } OSSL_CC_LOSS_INFO; typedef struct ossl_cc_ecn_info_st { /* * The time at which the largest acked PN (in the incoming ACK frame) was * sent. */ OSSL_TIME largest_acked_time; } OSSL_CC_ECN_INFO; /* Parameter (read-write): Maximum datagram payload length in bytes. */ #define OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN "max_dgram_payload_len" /* Diagnostic (read-only): current congestion window size in bytes. */ #define OSSL_CC_OPTION_CUR_CWND_SIZE "cur_cwnd_size" /* Diagnostic (read-only): minimum congestion window size in bytes. */ #define OSSL_CC_OPTION_MIN_CWND_SIZE "min_cwnd_size" /* Diagnostic (read-only): current net bytes in flight. */ #define OSSL_CC_OPTION_CUR_BYTES_IN_FLIGHT "bytes_in_flight" /* Diagnostic (read-only): method-specific state value. */ #define OSSL_CC_OPTION_CUR_STATE "cur_state" /* * Congestion control abstract interface. * * This interface is broadly based on the design described in RFC 9002. However, * the demarcation between the ACKM and the congestion controller does not * exactly match that delineated in the RFC 9002 pseudocode. Where aspects of * the demarcation involve the congestion controller accessing internal state of * the ACKM, the interface has been revised where possible to provide the * information needed by the congestion controller and avoid needing to give the * congestion controller access to the ACKM's internal data structures. * * Particular changes include: * * - In our implementation, it is the responsibility of the ACKM to determine * if a loss event constitutes persistent congestion. * * - In our implementation, it is the responsibility of the ACKM to determine * if the ECN-CE counter has increased. The congestion controller is simply * informed when an ECN-CE event occurs. * * All of these changes are intended to avoid having a congestion controller * have to access ACKM internal state. */ #define OSSL_CC_LOST_FLAG_PERSISTENT_CONGESTION (1U << 0) struct ossl_cc_method_st { /* * Instantiation. */ OSSL_CC_DATA *(*new)(OSSL_TIME (*now_cb)(void *arg), void *now_cb_arg); void (*free)(OSSL_CC_DATA *ccdata); /* * Reset of state. */ void (*reset)(OSSL_CC_DATA *ccdata); /* * Escape hatch for option configuration. * * params is an array of OSSL_PARAM structures. * * Returns 1 on success and 0 on failure. */ int (*set_input_params)(OSSL_CC_DATA *ccdata, const OSSL_PARAM *params); /* * (Re)bind output (diagnostic) information. * * params is an array of OSSL_PARAM structures used to output values. The * storage locations associated with each parameter are stored internally * and updated whenever the state of the congestion controller is updated; * thus, the storage locations associated with the OSSL_PARAMs passed in the * call to this function must remain valid until the congestion controller * is freed or those parameters are unbound. A given parameter name may be * bound to only one location at a time. The params structures themselves * do not need to remain allocated after this call returns. * * Returns 1 on success and 0 on failure. */ int (*bind_diagnostics)(OSSL_CC_DATA *ccdata, OSSL_PARAM *params); /* * Unbind diagnostic information. The parameters with the given names are * unbound, cancelling the effects of a previous call to bind_diagnostic(). * params is an array of OSSL_PARAMs. The values of the parameters are * ignored. If a parameter is already unbound, there is no effect for that * parameter but other parameters are still unbound. * * Returns 1 on success or 0 on failure. */ int (*unbind_diagnostics)(OSSL_CC_DATA *ccdata, OSSL_PARAM *params); /* * Returns the amount of additional data (above and beyond the data * currently in flight) which can be sent in bytes. Returns 0 if no more * data can be sent at this time. The return value of this method * can vary as time passes. */ uint64_t (*get_tx_allowance)(OSSL_CC_DATA *ccdata); /* * Returns the time at which the return value of get_tx_allowance might be * higher than its current value. This is not a guarantee and spurious * wakeups are allowed. Returns ossl_time_infinite() if there is no current * wakeup deadline. */ OSSL_TIME (*get_wakeup_deadline)(OSSL_CC_DATA *ccdata); /* * The On Data Sent event. num_bytes should be the size of the packet in * bytes (or the aggregate size of multiple packets which have just been * sent). */ int (*on_data_sent)(OSSL_CC_DATA *ccdata, uint64_t num_bytes); /* * The On Data Acked event. See OSSL_CC_ACK_INFO structure for details * of the information to be passed. */ int (*on_data_acked)(OSSL_CC_DATA *ccdata, const OSSL_CC_ACK_INFO *info); /* * The On Data Lost event. See OSSL_CC_LOSS_INFO structure for details * of the information to be passed. * * Note: When the ACKM determines that a set of multiple packets has been * lost, it is useful for a congestion control algorithm to be able to * process this as a single loss event rather than multiple loss events. * Thus, calling this function may cause the congestion controller to defer * state updates under the assumption that subsequent calls to * on_data_lost() representing further lost packets in the same loss event * may be forthcoming. Always call on_data_lost_finished() after one or more * calls to on_data_lost(). */ int (*on_data_lost)(OSSL_CC_DATA *ccdata, const OSSL_CC_LOSS_INFO *info); /* * To be called after a sequence of one or more on_data_lost() calls * representing multiple packets in a single loss detection incident. * * Flags may be 0 or OSSL_CC_LOST_FLAG_PERSISTENT_CONGESTION. */ int (*on_data_lost_finished)(OSSL_CC_DATA *ccdata, uint32_t flags); /* * For use when a PN space is invalidated or a packet must otherwise be * 'undone' for congestion control purposes without acting as a loss signal. * Only the size of the packet is needed. */ int (*on_data_invalidated)(OSSL_CC_DATA *ccdata, uint64_t num_bytes); /* * Called from the ACKM when detecting an increased ECN-CE value in an ACK * frame. This indicates congestion. * * Note that this differs from the RFC's conceptual segregation of the loss * detection and congestion controller functions, as in our implementation * the ACKM is responsible for detecting increases to ECN-CE and simply * tells the congestion controller when ECN-triggered congestion has * occurred. This allows a slightly more efficient implementation and * narrower interface between the ACKM and CC. */ int (*on_ecn)(OSSL_CC_DATA *ccdata, const OSSL_CC_ECN_INFO *info); }; extern const OSSL_CC_METHOD ossl_cc_dummy_method; extern const OSSL_CC_METHOD ossl_cc_newreno_method; # endif #endif
./openssl/include/internal/packet.h
/* * Copyright 2015-2023 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_INTERNAL_PACKET_H # define OSSL_INTERNAL_PACKET_H # pragma once # include <string.h> # include <openssl/bn.h> # include <openssl/buffer.h> # include <openssl/crypto.h> # include <openssl/e_os2.h> # include "internal/numbers.h" typedef struct { /* Pointer to where we are currently reading from */ const unsigned char *curr; /* Number of bytes remaining */ size_t remaining; } PACKET; /* Internal unchecked shorthand; don't use outside this file. */ static ossl_inline void packet_forward(PACKET *pkt, size_t len) { pkt->curr += len; pkt->remaining -= len; } /* * Returns the number of bytes remaining to be read in the PACKET */ static ossl_inline size_t PACKET_remaining(const PACKET *pkt) { return pkt->remaining; } /* * Returns a pointer to the first byte after the packet data. * Useful for integrating with non-PACKET parsing code. * Specifically, we use PACKET_end() to verify that a d2i_... call * has consumed the entire packet contents. */ static ossl_inline const unsigned char *PACKET_end(const PACKET *pkt) { return pkt->curr + pkt->remaining; } /* * Returns a pointer to the PACKET's current position. * For use in non-PACKETized APIs. */ static ossl_inline const unsigned char *PACKET_data(const PACKET *pkt) { return pkt->curr; } /* * Initialise a PACKET with |len| bytes held in |buf|. This does not make a * copy of the data so |buf| must be present for the whole time that the PACKET * is being used. */ __owur static ossl_inline int PACKET_buf_init(PACKET *pkt, const unsigned char *buf, size_t len) { /* Sanity check for negative values. */ if (len > (size_t)(SIZE_MAX / 2)) return 0; pkt->curr = buf; pkt->remaining = len; return 1; } /* Initialize a PACKET to hold zero bytes. */ static ossl_inline void PACKET_null_init(PACKET *pkt) { pkt->curr = NULL; pkt->remaining = 0; } /* * Returns 1 if the packet has length |num| and its contents equal the |num| * bytes read from |ptr|. Returns 0 otherwise (lengths or contents not equal). * If lengths are equal, performs the comparison in constant time. */ __owur static ossl_inline int PACKET_equal(const PACKET *pkt, const void *ptr, size_t num) { if (PACKET_remaining(pkt) != num) return 0; return CRYPTO_memcmp(pkt->curr, ptr, num) == 0; } /* * Peek ahead and initialize |subpkt| with the next |len| bytes read from |pkt|. * Data is not copied: the |subpkt| packet will share its underlying buffer with * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|. */ __owur static ossl_inline int PACKET_peek_sub_packet(const PACKET *pkt, PACKET *subpkt, size_t len) { if (PACKET_remaining(pkt) < len) return 0; return PACKET_buf_init(subpkt, pkt->curr, len); } /* * Initialize |subpkt| with the next |len| bytes read from |pkt|. Data is not * copied: the |subpkt| packet will share its underlying buffer with the * original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|. */ __owur static ossl_inline int PACKET_get_sub_packet(PACKET *pkt, PACKET *subpkt, size_t len) { if (!PACKET_peek_sub_packet(pkt, subpkt, len)) return 0; packet_forward(pkt, len); return 1; } /* * Peek ahead at 2 bytes in network order from |pkt| and store the value in * |*data| */ __owur static ossl_inline int PACKET_peek_net_2(const PACKET *pkt, unsigned int *data) { if (PACKET_remaining(pkt) < 2) return 0; *data = ((unsigned int)(*pkt->curr)) << 8; *data |= *(pkt->curr + 1); return 1; } /* Equivalent of n2s */ /* Get 2 bytes in network order from |pkt| and store the value in |*data| */ __owur static ossl_inline int PACKET_get_net_2(PACKET *pkt, unsigned int *data) { if (!PACKET_peek_net_2(pkt, data)) return 0; packet_forward(pkt, 2); return 1; } /* Same as PACKET_get_net_2() but for a size_t */ __owur static ossl_inline int PACKET_get_net_2_len(PACKET *pkt, size_t *data) { unsigned int i; int ret = PACKET_get_net_2(pkt, &i); if (ret) *data = (size_t)i; return ret; } /* * Peek ahead at 3 bytes in network order from |pkt| and store the value in * |*data| */ __owur static ossl_inline int PACKET_peek_net_3(const PACKET *pkt, unsigned long *data) { if (PACKET_remaining(pkt) < 3) return 0; *data = ((unsigned long)(*pkt->curr)) << 16; *data |= ((unsigned long)(*(pkt->curr + 1))) << 8; *data |= *(pkt->curr + 2); return 1; } /* Equivalent of n2l3 */ /* Get 3 bytes in network order from |pkt| and store the value in |*data| */ __owur static ossl_inline int PACKET_get_net_3(PACKET *pkt, unsigned long *data) { if (!PACKET_peek_net_3(pkt, data)) return 0; packet_forward(pkt, 3); return 1; } /* Same as PACKET_get_net_3() but for a size_t */ __owur static ossl_inline int PACKET_get_net_3_len(PACKET *pkt, size_t *data) { unsigned long i; int ret = PACKET_get_net_3(pkt, &i); if (ret) *data = (size_t)i; return ret; } /* * Peek ahead at 4 bytes in network order from |pkt| and store the value in * |*data| */ __owur static ossl_inline int PACKET_peek_net_4(const PACKET *pkt, unsigned long *data) { if (PACKET_remaining(pkt) < 4) return 0; *data = ((unsigned long)(*pkt->curr)) << 24; *data |= ((unsigned long)(*(pkt->curr + 1))) << 16; *data |= ((unsigned long)(*(pkt->curr + 2))) << 8; *data |= *(pkt->curr + 3); return 1; } /* * Peek ahead at 8 bytes in network order from |pkt| and store the value in * |*data| */ __owur static ossl_inline int PACKET_peek_net_8(const PACKET *pkt, uint64_t *data) { if (PACKET_remaining(pkt) < 8) return 0; *data = ((uint64_t)(*pkt->curr)) << 56; *data |= ((uint64_t)(*(pkt->curr + 1))) << 48; *data |= ((uint64_t)(*(pkt->curr + 2))) << 40; *data |= ((uint64_t)(*(pkt->curr + 3))) << 32; *data |= ((uint64_t)(*(pkt->curr + 4))) << 24; *data |= ((uint64_t)(*(pkt->curr + 5))) << 16; *data |= ((uint64_t)(*(pkt->curr + 6))) << 8; *data |= *(pkt->curr + 7); return 1; } /* Equivalent of n2l */ /* Get 4 bytes in network order from |pkt| and store the value in |*data| */ __owur static ossl_inline int PACKET_get_net_4(PACKET *pkt, unsigned long *data) { if (!PACKET_peek_net_4(pkt, data)) return 0; packet_forward(pkt, 4); return 1; } /* Same as PACKET_get_net_4() but for a size_t */ __owur static ossl_inline int PACKET_get_net_4_len(PACKET *pkt, size_t *data) { unsigned long i; int ret = PACKET_get_net_4(pkt, &i); if (ret) *data = (size_t)i; return ret; } /* Get 8 bytes in network order from |pkt| and store the value in |*data| */ __owur static ossl_inline int PACKET_get_net_8(PACKET *pkt, uint64_t *data) { if (!PACKET_peek_net_8(pkt, data)) return 0; packet_forward(pkt, 8); return 1; } /* Peek ahead at 1 byte from |pkt| and store the value in |*data| */ __owur static ossl_inline int PACKET_peek_1(const PACKET *pkt, unsigned int *data) { if (!PACKET_remaining(pkt)) return 0; *data = *pkt->curr; return 1; } /* Get 1 byte from |pkt| and store the value in |*data| */ __owur static ossl_inline int PACKET_get_1(PACKET *pkt, unsigned int *data) { if (!PACKET_peek_1(pkt, data)) return 0; packet_forward(pkt, 1); return 1; } /* Same as PACKET_get_1() but for a size_t */ __owur static ossl_inline int PACKET_get_1_len(PACKET *pkt, size_t *data) { unsigned int i; int ret = PACKET_get_1(pkt, &i); if (ret) *data = (size_t)i; return ret; } /* * Peek ahead at 4 bytes in reverse network order from |pkt| and store the value * in |*data| */ __owur static ossl_inline int PACKET_peek_4(const PACKET *pkt, unsigned long *data) { if (PACKET_remaining(pkt) < 4) return 0; *data = *pkt->curr; *data |= ((unsigned long)(*(pkt->curr + 1))) << 8; *data |= ((unsigned long)(*(pkt->curr + 2))) << 16; *data |= ((unsigned long)(*(pkt->curr + 3))) << 24; return 1; } /* Equivalent of c2l */ /* * Get 4 bytes in reverse network order from |pkt| and store the value in * |*data| */ __owur static ossl_inline int PACKET_get_4(PACKET *pkt, unsigned long *data) { if (!PACKET_peek_4(pkt, data)) return 0; packet_forward(pkt, 4); return 1; } /* * Peek ahead at |len| bytes from the |pkt| and store a pointer to them in * |*data|. This just points at the underlying buffer that |pkt| is using. The * caller should not free this data directly (it will be freed when the * underlying buffer gets freed */ __owur static ossl_inline int PACKET_peek_bytes(const PACKET *pkt, const unsigned char **data, size_t len) { if (PACKET_remaining(pkt) < len) return 0; *data = pkt->curr; return 1; } /* * Read |len| bytes from the |pkt| and store a pointer to them in |*data|. This * just points at the underlying buffer that |pkt| is using. The caller should * not free this data directly (it will be freed when the underlying buffer gets * freed */ __owur static ossl_inline int PACKET_get_bytes(PACKET *pkt, const unsigned char **data, size_t len) { if (!PACKET_peek_bytes(pkt, data, len)) return 0; packet_forward(pkt, len); return 1; } /* Peek ahead at |len| bytes from |pkt| and copy them to |data| */ __owur static ossl_inline int PACKET_peek_copy_bytes(const PACKET *pkt, unsigned char *data, size_t len) { if (PACKET_remaining(pkt) < len) return 0; memcpy(data, pkt->curr, len); return 1; } /* * Read |len| bytes from |pkt| and copy them to |data|. * The caller is responsible for ensuring that |data| can hold |len| bytes. */ __owur static ossl_inline int PACKET_copy_bytes(PACKET *pkt, unsigned char *data, size_t len) { if (!PACKET_peek_copy_bytes(pkt, data, len)) return 0; packet_forward(pkt, len); return 1; } /* * Copy packet data to |dest|, and set |len| to the number of copied bytes. * If the packet has more than |dest_len| bytes, nothing is copied. * Returns 1 if the packet data fits in |dest_len| bytes, 0 otherwise. * Does not forward PACKET position (because it is typically the last thing * done with a given PACKET). */ __owur static ossl_inline int PACKET_copy_all(const PACKET *pkt, unsigned char *dest, size_t dest_len, size_t *len) { if (PACKET_remaining(pkt) > dest_len) { *len = 0; return 0; } *len = pkt->remaining; memcpy(dest, pkt->curr, pkt->remaining); return 1; } /* * Copy |pkt| bytes to a newly allocated buffer and store a pointer to the * result in |*data|, and the length in |len|. * If |*data| is not NULL, the old data is OPENSSL_free'd. * If the packet is empty, or malloc fails, |*data| will be set to NULL. * Returns 1 if the malloc succeeds and 0 otherwise. * Does not forward PACKET position (because it is typically the last thing * done with a given PACKET). */ __owur static ossl_inline int PACKET_memdup(const PACKET *pkt, unsigned char **data, size_t *len) { size_t length; OPENSSL_free(*data); *data = NULL; *len = 0; length = PACKET_remaining(pkt); if (length == 0) return 1; *data = OPENSSL_memdup(pkt->curr, length); if (*data == NULL) return 0; *len = length; return 1; } /* * Read a C string from |pkt| and copy to a newly allocated, NUL-terminated * buffer. Store a pointer to the result in |*data|. * If |*data| is not NULL, the old data is OPENSSL_free'd. * If the data in |pkt| does not contain a NUL-byte, the entire data is * copied and NUL-terminated. * Returns 1 if the malloc succeeds and 0 otherwise. * Does not forward PACKET position (because it is typically the last thing done * with a given PACKET). */ __owur static ossl_inline int PACKET_strndup(const PACKET *pkt, char **data) { OPENSSL_free(*data); /* This will succeed on an empty packet, unless pkt->curr == NULL. */ *data = OPENSSL_strndup((const char *)pkt->curr, PACKET_remaining(pkt)); return (*data != NULL); } /* Returns 1 if |pkt| contains at least one 0-byte, 0 otherwise. */ static ossl_inline int PACKET_contains_zero_byte(const PACKET *pkt) { return memchr(pkt->curr, 0, pkt->remaining) != NULL; } /* Move the current reading position forward |len| bytes */ __owur static ossl_inline int PACKET_forward(PACKET *pkt, size_t len) { if (PACKET_remaining(pkt) < len) return 0; packet_forward(pkt, len); return 1; } /* * Reads a variable-length vector prefixed with a one-byte length, and stores * the contents in |subpkt|. |pkt| can equal |subpkt|. * Data is not copied: the |subpkt| packet will share its underlying buffer with * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|. * Upon failure, the original |pkt| and |subpkt| are not modified. */ __owur static ossl_inline int PACKET_get_length_prefixed_1(PACKET *pkt, PACKET *subpkt) { unsigned int length; const unsigned char *data; PACKET tmp = *pkt; if (!PACKET_get_1(&tmp, &length) || !PACKET_get_bytes(&tmp, &data, (size_t)length)) { return 0; } *pkt = tmp; subpkt->curr = data; subpkt->remaining = length; return 1; } /* * Like PACKET_get_length_prefixed_1, but additionally, fails when there are * leftover bytes in |pkt|. */ __owur static ossl_inline int PACKET_as_length_prefixed_1(PACKET *pkt, PACKET *subpkt) { unsigned int length; const unsigned char *data; PACKET tmp = *pkt; if (!PACKET_get_1(&tmp, &length) || !PACKET_get_bytes(&tmp, &data, (size_t)length) || PACKET_remaining(&tmp) != 0) { return 0; } *pkt = tmp; subpkt->curr = data; subpkt->remaining = length; return 1; } /* * Reads a variable-length vector prefixed with a two-byte length, and stores * the contents in |subpkt|. |pkt| can equal |subpkt|. * Data is not copied: the |subpkt| packet will share its underlying buffer with * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|. * Upon failure, the original |pkt| and |subpkt| are not modified. */ __owur static ossl_inline int PACKET_get_length_prefixed_2(PACKET *pkt, PACKET *subpkt) { unsigned int length; const unsigned char *data; PACKET tmp = *pkt; if (!PACKET_get_net_2(&tmp, &length) || !PACKET_get_bytes(&tmp, &data, (size_t)length)) { return 0; } *pkt = tmp; subpkt->curr = data; subpkt->remaining = length; return 1; } /* * Like PACKET_get_length_prefixed_2, but additionally, fails when there are * leftover bytes in |pkt|. */ __owur static ossl_inline int PACKET_as_length_prefixed_2(PACKET *pkt, PACKET *subpkt) { unsigned int length; const unsigned char *data; PACKET tmp = *pkt; if (!PACKET_get_net_2(&tmp, &length) || !PACKET_get_bytes(&tmp, &data, (size_t)length) || PACKET_remaining(&tmp) != 0) { return 0; } *pkt = tmp; subpkt->curr = data; subpkt->remaining = length; return 1; } /* * Reads a variable-length vector prefixed with a three-byte length, and stores * the contents in |subpkt|. |pkt| can equal |subpkt|. * Data is not copied: the |subpkt| packet will share its underlying buffer with * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|. * Upon failure, the original |pkt| and |subpkt| are not modified. */ __owur static ossl_inline int PACKET_get_length_prefixed_3(PACKET *pkt, PACKET *subpkt) { unsigned long length; const unsigned char *data; PACKET tmp = *pkt; if (!PACKET_get_net_3(&tmp, &length) || !PACKET_get_bytes(&tmp, &data, (size_t)length)) { return 0; } *pkt = tmp; subpkt->curr = data; subpkt->remaining = length; return 1; } /* Writeable packets */ typedef struct wpacket_sub WPACKET_SUB; struct wpacket_sub { /* The parent WPACKET_SUB if we have one or NULL otherwise */ WPACKET_SUB *parent; /* * Offset into the buffer where the length of this WPACKET goes. We use an * offset in case the buffer grows and gets reallocated. */ size_t packet_len; /* Number of bytes in the packet_len or 0 if we don't write the length */ size_t lenbytes; /* Number of bytes written to the buf prior to this packet starting */ size_t pwritten; /* Flags for this sub-packet */ unsigned int flags; }; typedef struct wpacket_st WPACKET; struct wpacket_st { /* The buffer where we store the output data */ BUF_MEM *buf; /* Fixed sized buffer which can be used as an alternative to buf */ unsigned char *staticbuf; /* * Offset into the buffer where we are currently writing. We use an offset * in case the buffer grows and gets reallocated. */ size_t curr; /* Number of bytes written so far */ size_t written; /* Maximum number of bytes we will allow to be written to this WPACKET */ size_t maxsize; /* Our sub-packets (always at least one if not finished) */ WPACKET_SUB *subs; /* Writing from the end first? */ unsigned int endfirst : 1; }; /* Flags */ /* Default */ #define WPACKET_FLAGS_NONE 0 /* Error on WPACKET_close() if no data written to the WPACKET */ #define WPACKET_FLAGS_NON_ZERO_LENGTH 1 /* * Abandon all changes on WPACKET_close() if no data written to the WPACKET, * i.e. this does not write out a zero packet length */ #define WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH 2 /* QUIC variable-length integer length prefix */ #define WPACKET_FLAGS_QUIC_VLINT 4 /* * Initialise a WPACKET with the buffer in |buf|. The buffer must exist * for the whole time that the WPACKET is being used. Additionally |lenbytes| of * data is preallocated at the start of the buffer to store the length of the * WPACKET once we know it. */ int WPACKET_init_len(WPACKET *pkt, BUF_MEM *buf, size_t lenbytes); /* * Same as WPACKET_init_len except there is no preallocation of the WPACKET * length. */ int WPACKET_init(WPACKET *pkt, BUF_MEM *buf); /* * Same as WPACKET_init_len except there is no underlying buffer. No data is * ever actually written. We just keep track of how much data would have been * written if a buffer was there. */ int WPACKET_init_null(WPACKET *pkt, size_t lenbytes); /* * Same as WPACKET_init_null except we set the WPACKET to assume DER length * encoding for sub-packets. */ int WPACKET_init_null_der(WPACKET *pkt); /* * Same as WPACKET_init_len except we do not use a growable BUF_MEM structure. * A fixed buffer of memory |buf| of size |len| is used instead. A failure will * occur if you attempt to write beyond the end of the buffer */ int WPACKET_init_static_len(WPACKET *pkt, unsigned char *buf, size_t len, size_t lenbytes); /* * Same as WPACKET_init_static_len except lenbytes is always 0, and we set the * WPACKET to write to the end of the buffer moving towards the start and use * DER length encoding for sub-packets. */ int WPACKET_init_der(WPACKET *pkt, unsigned char *buf, size_t len); /* * Set the flags to be applied to the current sub-packet */ int WPACKET_set_flags(WPACKET *pkt, unsigned int flags); /* * Closes the most recent sub-packet. It also writes out the length of the * packet to the required location (normally the start of the WPACKET) if * appropriate. The top level WPACKET should be closed using WPACKET_finish() * instead of this function. */ int WPACKET_close(WPACKET *pkt); /* * The same as WPACKET_close() but only for the top most WPACKET. Additionally * frees memory resources for this WPACKET. */ int WPACKET_finish(WPACKET *pkt); /* * Iterate through all the sub-packets and write out their lengths as if they * were being closed. The lengths will be overwritten with the final lengths * when the sub-packets are eventually closed (which may be different if more * data is added to the WPACKET). This function fails if a sub-packet is of 0 * length and WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH is set. */ int WPACKET_fill_lengths(WPACKET *pkt); /* * Initialise a new sub-packet. Additionally |lenbytes| of data is preallocated * at the start of the sub-packet to store its length once we know it. Don't * call this directly. Use the convenience macros below instead. */ int WPACKET_start_sub_packet_len__(WPACKET *pkt, size_t lenbytes); /* * Convenience macros for calling WPACKET_start_sub_packet_len with different * lengths */ #define WPACKET_start_sub_packet_u8(pkt) \ WPACKET_start_sub_packet_len__((pkt), 1) #define WPACKET_start_sub_packet_u16(pkt) \ WPACKET_start_sub_packet_len__((pkt), 2) #define WPACKET_start_sub_packet_u24(pkt) \ WPACKET_start_sub_packet_len__((pkt), 3) #define WPACKET_start_sub_packet_u32(pkt) \ WPACKET_start_sub_packet_len__((pkt), 4) /* * Same as WPACKET_start_sub_packet_len__() except no bytes are pre-allocated * for the sub-packet length. */ int WPACKET_start_sub_packet(WPACKET *pkt); /* * Allocate bytes in the WPACKET for the output. This reserves the bytes * and counts them as "written", but doesn't actually do the writing. A pointer * to the allocated bytes is stored in |*allocbytes|. |allocbytes| may be NULL. * WARNING: the allocated bytes must be filled in immediately, without further * WPACKET_* calls. If not then the underlying buffer may be realloc'd and * change its location. */ int WPACKET_allocate_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes); /* * The same as WPACKET_allocate_bytes() except additionally a new sub-packet is * started for the allocated bytes, and then closed immediately afterwards. The * number of length bytes for the sub-packet is in |lenbytes|. Don't call this * directly. Use the convenience macros below instead. */ int WPACKET_sub_allocate_bytes__(WPACKET *pkt, size_t len, unsigned char **allocbytes, size_t lenbytes); /* * Convenience macros for calling WPACKET_sub_allocate_bytes with different * lengths */ #define WPACKET_sub_allocate_bytes_u8(pkt, len, bytes) \ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 1) #define WPACKET_sub_allocate_bytes_u16(pkt, len, bytes) \ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 2) #define WPACKET_sub_allocate_bytes_u24(pkt, len, bytes) \ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 3) #define WPACKET_sub_allocate_bytes_u32(pkt, len, bytes) \ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 4) /* * The same as WPACKET_allocate_bytes() except the reserved bytes are not * actually counted as written. Typically this will be for when we don't know * how big arbitrary data is going to be up front, but we do know what the * maximum size will be. If this function is used, then it should be immediately * followed by a WPACKET_allocate_bytes() call before any other WPACKET * functions are called (unless the write to the allocated bytes is abandoned). * * For example: If we are generating a signature, then the size of that * signature may not be known in advance. We can use WPACKET_reserve_bytes() to * handle this: * * if (!WPACKET_sub_reserve_bytes_u16(&pkt, EVP_PKEY_get_size(pkey), &sigbytes1) * || EVP_SignFinal(md_ctx, sigbytes1, &siglen, pkey) <= 0 * || !WPACKET_sub_allocate_bytes_u16(&pkt, siglen, &sigbytes2) * || sigbytes1 != sigbytes2) * goto err; */ int WPACKET_reserve_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes); /* * The "reserve_bytes" equivalent of WPACKET_sub_allocate_bytes__() */ int WPACKET_sub_reserve_bytes__(WPACKET *pkt, size_t len, unsigned char **allocbytes, size_t lenbytes); /* * Convenience macros for WPACKET_sub_reserve_bytes with different lengths */ #define WPACKET_sub_reserve_bytes_u8(pkt, len, bytes) \ WPACKET_reserve_bytes__((pkt), (len), (bytes), 1) #define WPACKET_sub_reserve_bytes_u16(pkt, len, bytes) \ WPACKET_sub_reserve_bytes__((pkt), (len), (bytes), 2) #define WPACKET_sub_reserve_bytes_u24(pkt, len, bytes) \ WPACKET_sub_reserve_bytes__((pkt), (len), (bytes), 3) #define WPACKET_sub_reserve_bytes_u32(pkt, len, bytes) \ WPACKET_sub_reserve_bytes__((pkt), (len), (bytes), 4) /* * Write the value stored in |val| into the WPACKET. The value will consume * |bytes| amount of storage. An error will occur if |val| cannot be * accommodated in |bytes| storage, e.g. attempting to write the value 256 into * 1 byte will fail. Don't call this directly. Use the convenience macros below * instead. */ int WPACKET_put_bytes__(WPACKET *pkt, uint64_t val, size_t bytes); /* * Convenience macros for calling WPACKET_put_bytes with different * lengths */ #define WPACKET_put_bytes_u8(pkt, val) \ WPACKET_put_bytes__((pkt), (val), 1) #define WPACKET_put_bytes_u16(pkt, val) \ WPACKET_put_bytes__((pkt), (val), 2) #define WPACKET_put_bytes_u24(pkt, val) \ WPACKET_put_bytes__((pkt), (val), 3) #define WPACKET_put_bytes_u32(pkt, val) \ WPACKET_put_bytes__((pkt), (val), 4) #define WPACKET_put_bytes_u64(pkt, val) \ WPACKET_put_bytes__((pkt), (val), 8) /* Set a maximum size that we will not allow the WPACKET to grow beyond */ int WPACKET_set_max_size(WPACKET *pkt, size_t maxsize); /* Copy |len| bytes of data from |*src| into the WPACKET. */ int WPACKET_memcpy(WPACKET *pkt, const void *src, size_t len); /* Set |len| bytes of data to |ch| into the WPACKET. */ int WPACKET_memset(WPACKET *pkt, int ch, size_t len); /* * Copy |len| bytes of data from |*src| into the WPACKET and prefix with its * length (consuming |lenbytes| of data for the length). Don't call this * directly. Use the convenience macros below instead. */ int WPACKET_sub_memcpy__(WPACKET *pkt, const void *src, size_t len, size_t lenbytes); /* Convenience macros for calling WPACKET_sub_memcpy with different lengths */ #define WPACKET_sub_memcpy_u8(pkt, src, len) \ WPACKET_sub_memcpy__((pkt), (src), (len), 1) #define WPACKET_sub_memcpy_u16(pkt, src, len) \ WPACKET_sub_memcpy__((pkt), (src), (len), 2) #define WPACKET_sub_memcpy_u24(pkt, src, len) \ WPACKET_sub_memcpy__((pkt), (src), (len), 3) #define WPACKET_sub_memcpy_u32(pkt, src, len) \ WPACKET_sub_memcpy__((pkt), (src), (len), 4) /* * Return the total number of bytes written so far to the underlying buffer * including any storage allocated for length bytes */ int WPACKET_get_total_written(WPACKET *pkt, size_t *written); /* * Returns the length of the current sub-packet. This excludes any bytes * allocated for the length itself. */ int WPACKET_get_length(WPACKET *pkt, size_t *len); /* * Returns a pointer to the current write location, but does not allocate any * bytes. */ unsigned char *WPACKET_get_curr(WPACKET *pkt); /* Returns true if the underlying buffer is actually NULL */ int WPACKET_is_null_buf(WPACKET *pkt); /* Release resources in a WPACKET if a failure has occurred. */ void WPACKET_cleanup(WPACKET *pkt); #endif /* OSSL_INTERNAL_PACKET_H */
./openssl/include/internal/sm3.h
/* * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2017 Ribose Inc. 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 */ /* This header can move into provider when legacy support is removed */ #ifndef OSSL_INTERNAL_SM3_H # define OSSL_INTERNAL_SM3_H # pragma once # include <openssl/opensslconf.h> # ifdef OPENSSL_NO_SM3 # error SM3 is disabled. # endif # define SM3_DIGEST_LENGTH 32 # define SM3_WORD unsigned int # define SM3_CBLOCK 64 # define SM3_LBLOCK (SM3_CBLOCK/4) typedef struct SM3state_st { SM3_WORD A, B, C, D, E, F, G, H; SM3_WORD Nl, Nh; SM3_WORD data[SM3_LBLOCK]; unsigned int num; } SM3_CTX; int ossl_sm3_init(SM3_CTX *c); int ossl_sm3_update(SM3_CTX *c, const void *data, size_t len); int ossl_sm3_final(unsigned char *md, SM3_CTX *c); #endif /* OSSL_INTERNAL_SM3_H */
./openssl/include/internal/nelem.h
/* * Copyright 2017-2021 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_INTERNAL_NELEM_H # define OSSL_INTERNAL_NELEM_H # pragma once # define OSSL_NELEM(x) (sizeof(x)/sizeof((x)[0])) #endif
./openssl/include/internal/ring_buf.h
/* * Copyright 2022-2023 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_INTERNAL_RING_BUF_H # define OSSL_INTERNAL_RING_BUF_H # pragma once # include <openssl/e_os2.h> /* For 'ossl_inline' */ # include "internal/safe_math.h" /* * ================================================================== * Byte-wise ring buffer which supports pushing and popping blocks of multiple * bytes at a time. The logical offset of each byte for the purposes of a QUIC * stream is tracked. Bytes can be popped from the ring buffer in two stages; * first they are popped, and then they are culled. Bytes which have been popped * but not yet culled will not be overwritten, and can be restored. */ struct ring_buf { void *start; size_t alloc; /* size of buffer allocation in bytes */ /* * Logical offset of the head (where we append to). This is the current size * of the QUIC stream. This increases monotonically. */ uint64_t head_offset; /* * Logical offset of the cull tail. Data is no longer needed and is * deallocated as the cull tail advances, which occurs as data is * acknowledged. This increases monotonically. */ uint64_t ctail_offset; }; OSSL_SAFE_MATH_UNSIGNED(u64, uint64_t) #define MAX_OFFSET (((uint64_t)1) << 62) /* QUIC-imposed limit */ static ossl_inline int ring_buf_init(struct ring_buf *r) { r->start = NULL; r->alloc = 0; r->head_offset = r->ctail_offset = 0; return 1; } static ossl_inline void ring_buf_destroy(struct ring_buf *r, int cleanse) { if (cleanse) OPENSSL_clear_free(r->start, r->alloc); else OPENSSL_free(r->start); r->start = NULL; r->alloc = 0; } static ossl_inline size_t ring_buf_used(struct ring_buf *r) { return (size_t)(r->head_offset - r->ctail_offset); } static ossl_inline size_t ring_buf_avail(struct ring_buf *r) { return r->alloc - ring_buf_used(r); } static ossl_inline int ring_buf_write_at(struct ring_buf *r, uint64_t logical_offset, const unsigned char *buf, size_t buf_len) { size_t avail, idx, l; unsigned char *start = r->start; int i, err = 0; avail = ring_buf_avail(r); if (logical_offset < r->ctail_offset || safe_add_u64(logical_offset, buf_len, &err) > safe_add_u64(r->head_offset, avail, &err) || safe_add_u64(r->head_offset, buf_len, &err) > MAX_OFFSET || err) return 0; for (i = 0; buf_len > 0 && i < 2; ++i) { idx = logical_offset % r->alloc; l = r->alloc - idx; if (buf_len < l) l = buf_len; memcpy(start + idx, buf, l); if (r->head_offset < logical_offset + l) r->head_offset = logical_offset + l; logical_offset += l; buf += l; buf_len -= l; } assert(buf_len == 0); return 1; } static ossl_inline size_t ring_buf_push(struct ring_buf *r, const unsigned char *buf, size_t buf_len) { size_t pushed = 0, avail, idx, l; unsigned char *start = r->start; for (;;) { avail = ring_buf_avail(r); if (buf_len > avail) buf_len = avail; if (buf_len > MAX_OFFSET - r->head_offset) buf_len = (size_t)(MAX_OFFSET - r->head_offset); if (buf_len == 0) break; idx = r->head_offset % r->alloc; l = r->alloc - idx; if (buf_len < l) l = buf_len; memcpy(start + idx, buf, l); r->head_offset += l; buf += l; buf_len -= l; pushed += l; } return pushed; } static ossl_inline const unsigned char *ring_buf_get_ptr(const struct ring_buf *r, uint64_t logical_offset, size_t *max_len) { unsigned char *start = r->start; size_t idx; if (logical_offset >= r->head_offset || logical_offset < r->ctail_offset) return NULL; idx = logical_offset % r->alloc; *max_len = r->alloc - idx; return start + idx; } /* * Retrieves data out of the read side of the ring buffer starting at the given * logical offset. *buf is set to point to a contiguous span of bytes and * *buf_len is set to the number of contiguous bytes. After this function * returns, there may or may not be more bytes available at the logical offset * of (logical_offset + *buf_len) by calling this function again. If the logical * offset is out of the range retained by the ring buffer, returns 0, else * returns 1. A logical offset at the end of the range retained by the ring * buffer is not considered an error and is returned with a *buf_len of 0. * * The ring buffer state is not changed. */ static ossl_inline int ring_buf_get_buf_at(const struct ring_buf *r, uint64_t logical_offset, const unsigned char **buf, size_t *buf_len) { const unsigned char *start = r->start; size_t idx, l; if (logical_offset > r->head_offset || logical_offset < r->ctail_offset) return 0; if (r->alloc == 0) { *buf = NULL; *buf_len = 0; return 1; } idx = logical_offset % r->alloc; l = (size_t)(r->head_offset - logical_offset); if (l > r->alloc - idx) l = r->alloc - idx; *buf = start + idx; *buf_len = l; return 1; } static ossl_inline void ring_buf_cpop_range(struct ring_buf *r, uint64_t start, uint64_t end, int cleanse) { assert(end >= start); if (start > r->ctail_offset || end >= MAX_OFFSET) return; if (cleanse && r->alloc > 0 && end > r->ctail_offset) { size_t idx = r->ctail_offset % r->alloc; uint64_t cleanse_end = end + 1; size_t l; if (cleanse_end > r->head_offset) cleanse_end = r->head_offset; l = (size_t)(cleanse_end - r->ctail_offset); if (l > r->alloc - idx) { OPENSSL_cleanse((unsigned char *)r->start + idx, r->alloc - idx); l -= r->alloc - idx; idx = 0; } if (l > 0) OPENSSL_cleanse((unsigned char *)r->start + idx, l); } r->ctail_offset = end + 1; /* Allow culling unpushed data */ if (r->head_offset < r->ctail_offset) r->head_offset = r->ctail_offset; } static ossl_inline int ring_buf_resize(struct ring_buf *r, size_t num_bytes, int cleanse) { struct ring_buf rnew = {0}; const unsigned char *src = NULL; size_t src_len = 0, copied = 0; if (num_bytes == r->alloc) return 1; if (num_bytes < ring_buf_used(r)) return 0; rnew.start = OPENSSL_malloc(num_bytes); if (rnew.start == NULL) return 0; rnew.alloc = num_bytes; rnew.head_offset = r->head_offset - ring_buf_used(r); rnew.ctail_offset = rnew.head_offset; for (;;) { if (!ring_buf_get_buf_at(r, r->ctail_offset + copied, &src, &src_len)) { OPENSSL_free(rnew.start); return 0; } if (src_len == 0) break; if (ring_buf_push(&rnew, src, src_len) != src_len) { OPENSSL_free(rnew.start); return 0; } copied += src_len; } assert(rnew.head_offset == r->head_offset); rnew.ctail_offset = r->ctail_offset; ring_buf_destroy(r, cleanse); memcpy(r, &rnew, sizeof(*r)); return 1; } #endif /* OSSL_INTERNAL_RING_BUF_H */
./openssl/include/internal/quic_wire_pkt.h
/* * Copyright 2022-2023 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_WIRE_PKT_H # define OSSL_QUIC_WIRE_PKT_H # include <openssl/ssl.h> # include "internal/packet_quic.h" # include "internal/quic_types.h" # ifndef OPENSSL_NO_QUIC # define QUIC_VERSION_NONE ((uint32_t)0) /* Used for version negotiation */ # define QUIC_VERSION_1 ((uint32_t)1) /* QUIC v1 */ /* QUIC logical packet type. These do not match wire values. */ # define QUIC_PKT_TYPE_INITIAL 1 # define QUIC_PKT_TYPE_0RTT 2 # define QUIC_PKT_TYPE_HANDSHAKE 3 # define QUIC_PKT_TYPE_RETRY 4 # 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; } } static ossl_inline ossl_unused uint32_t ossl_quic_enc_level_to_pkt_type(uint32_t enc_level) { switch (enc_level) { case QUIC_ENC_LEVEL_INITIAL: return QUIC_PKT_TYPE_INITIAL; case QUIC_ENC_LEVEL_HANDSHAKE: return QUIC_PKT_TYPE_HANDSHAKE; case QUIC_ENC_LEVEL_0RTT: return QUIC_PKT_TYPE_0RTT; case QUIC_ENC_LEVEL_1RTT: return QUIC_PKT_TYPE_1RTT; default: return UINT32_MAX; } } /* Determine if a packet type contains an encrypted payload. */ static ossl_inline ossl_unused int ossl_quic_pkt_type_is_encrypted(uint32_t pkt_type) { switch (pkt_type) { case QUIC_PKT_TYPE_RETRY: case QUIC_PKT_TYPE_VERSION_NEG: return 0; default: return 1; } } /* Determine if a packet type contains a PN field. */ static ossl_inline ossl_unused int ossl_quic_pkt_type_has_pn(uint32_t pkt_type) { /* * Currently a packet has a PN iff it is encrypted. This could change * someday. */ return ossl_quic_pkt_type_is_encrypted(pkt_type); } /* * Determine if a packet type can appear with other packets in a datagram. Some * packet types must be the sole packet in a datagram. */ static ossl_inline ossl_unused int ossl_quic_pkt_type_can_share_dgram(uint32_t pkt_type) { /* * Currently only the encrypted packet types can share a datagram. This * could change someday. */ return ossl_quic_pkt_type_is_encrypted(pkt_type); } /* * Determine if the packet type must come at the end of the datagram (due to the * lack of a length field). */ static ossl_inline ossl_unused int ossl_quic_pkt_type_must_be_last(uint32_t pkt_type) { /* * Any packet type which cannot share a datagram obviously must come last. * 1-RTT also must come last as it lacks a length field. */ return !ossl_quic_pkt_type_can_share_dgram(pkt_type) || pkt_type == QUIC_PKT_TYPE_1RTT; } /* * Determine if the packet type has a version field. */ static ossl_inline ossl_unused int ossl_quic_pkt_type_has_version(uint32_t pkt_type) { return pkt_type != QUIC_PKT_TYPE_1RTT && pkt_type != QUIC_PKT_TYPE_VERSION_NEG; } /* * Determine if the packet type has a SCID field. */ static ossl_inline ossl_unused int ossl_quic_pkt_type_has_scid(uint32_t pkt_type) { return pkt_type != QUIC_PKT_TYPE_1RTT; } /* * Smallest possible QUIC packet size as per RFC (aside from version negotiation * packets). */ # define QUIC_MIN_VALID_PKT_LEN_CRYPTO 21 # define QUIC_MIN_VALID_PKT_LEN_VERSION_NEG 7 # define QUIC_MIN_VALID_PKT_LEN QUIC_MIN_VALID_PKT_LEN_VERSION_NEG typedef struct quic_pkt_hdr_ptrs_st QUIC_PKT_HDR_PTRS; /* * QUIC Packet Header Protection * ============================= * * Functions to apply and remove QUIC packet header protection. A header * protector is initialised using ossl_quic_hdr_protector_init and must be * destroyed using ossl_quic_hdr_protector_cleanup when no longer needed. */ typedef struct quic_hdr_protector_st { OSSL_LIB_CTX *libctx; const char *propq; EVP_CIPHER_CTX *cipher_ctx; EVP_CIPHER *cipher; uint32_t cipher_id; } QUIC_HDR_PROTECTOR; # define QUIC_HDR_PROT_CIPHER_AES_128 1 # define QUIC_HDR_PROT_CIPHER_AES_256 2 # define QUIC_HDR_PROT_CIPHER_CHACHA 3 /* * Initialises a header protector. * * cipher_id: * The header protection cipher method to use. One of * QUIC_HDR_PROT_CIPHER_*. Must be chosen based on negotiated TLS cipher * suite. * * quic_hp_key: * This must be the "quic hp" key derived from a traffic secret. * * The length of the quic_hp_key must correspond to that expected for the * given cipher ID. * * The header protector performs amortisable initialisation in this function, * therefore a header protector should be used for as long as possible. * * Returns 1 on success and 0 on failure. */ int ossl_quic_hdr_protector_init(QUIC_HDR_PROTECTOR *hpr, OSSL_LIB_CTX *libctx, const char *propq, uint32_t cipher_id, const unsigned char *quic_hp_key, size_t quic_hp_key_len); /* * Destroys a header protector. This is also safe to call on a zero-initialized * OSSL_QUIC_HDR_PROTECTOR structure which has not been initialized, or which * has already been destroyed. */ void ossl_quic_hdr_protector_cleanup(QUIC_HDR_PROTECTOR *hpr); /* * Removes header protection from a packet. The packet payload must currently be * encrypted (i.e., you must remove header protection before decrypting packets * received). The function examines the header buffer to determine which bytes * of the header need to be decrypted. * * If this function fails, no data is modified. * * This is implemented as a call to ossl_quic_hdr_protector_decrypt_fields(). * * Returns 1 on success and 0 on failure. */ int ossl_quic_hdr_protector_decrypt(QUIC_HDR_PROTECTOR *hpr, QUIC_PKT_HDR_PTRS *ptrs); /* * Applies header protection to a packet. The packet payload must already have * been encrypted (i.e., you must apply header protection after encrypting * a packet). The function examines the header buffer to determine which bytes * of the header need to be encrypted. * * This is implemented as a call to ossl_quic_hdr_protector_encrypt_fields(). * * Returns 1 on success and 0 on failure. */ int ossl_quic_hdr_protector_encrypt(QUIC_HDR_PROTECTOR *hpr, QUIC_PKT_HDR_PTRS *ptrs); /* * Removes header protection from a packet. The packet payload must currently * be encrypted. This is a low-level function which assumes you have already * determined which parts of the packet header need to be decrypted. * * sample: * The range of bytes in the packet to be used to generate the header * protection mask. It is permissible to set sample_len to the size of the * remainder of the packet; this function will only use as many bytes as * needed. If not enough sample bytes are provided, this function fails. * * first_byte: * The first byte of the QUIC packet header to be decrypted. * * pn: * Pointer to the start of the PN field. The caller is responsible * for ensuring at least four bytes follow this pointer. * * Returns 1 on success and 0 on failure. */ int ossl_quic_hdr_protector_decrypt_fields(QUIC_HDR_PROTECTOR *hpr, const unsigned char *sample, size_t sample_len, unsigned char *first_byte, unsigned char *pn_bytes); /* * Works analogously to ossl_hdr_protector_decrypt_fields, but applies header * protection instead of removing it. */ int ossl_quic_hdr_protector_encrypt_fields(QUIC_HDR_PROTECTOR *hpr, const unsigned char *sample, size_t sample_len, unsigned char *first_byte, unsigned char *pn_bytes); /* * QUIC Packet Header * ================== * * This structure provides a logical representation of a QUIC packet header. * * QUIC packet formats fall into the following categories: * * Long Packets, which is subdivided into five possible packet types: * Version Negotiation (a special case); * Initial; * 0-RTT; * Handshake; and * Retry * * Short Packets, which comprises only a single packet type (1-RTT). * * The packet formats vary and common fields are found in some packets but * not others. The below table indicates which fields are present in which * kinds of packet. * indicates header protection is applied. * * SLLLLL Legend: 1=1-RTT, i=Initial, 0=0-RTT, h=Handshake * 1i0hrv r=Retry, v=Version Negotiation * ------ * 1i0hrv Header Form (0=Short, 1=Long) * 1i0hr Fixed Bit (always 1) * 1 Spin Bit * 1 * Reserved Bits * 1 * Key Phase * 1i0h * Packet Number Length * i0hr? Long Packet Type * i0h Type-Specific Bits * i0hr Version (note: always 0 for Version Negotiation packets) * 1i0hrv Destination Connection ID * i0hrv Source Connection ID * 1i0h * Packet Number * i Token * i0h Length * r Retry Token * r Retry Integrity Tag * * For each field below, the conditions under which the field is valid are * specified. If a field is not currently valid, it is initialized to a zero or * NULL value. */ typedef struct quic_pkt_hdr_st { /* [ALL] A QUIC_PKT_TYPE_* value. Always valid. */ unsigned int type :8; /* [S] Value of the spin bit. Valid if (type == 1RTT). */ unsigned int spin_bit :1; /* * [S] Value of the Key Phase bit in the short packet. * Valid if (type == 1RTT && !partial). */ unsigned int key_phase :1; /* * [1i0h] Length of packet number in bytes. This is the decoded value. * Valid if ((type == 1RTT || (version && type != RETRY)) && !partial). */ unsigned int pn_len :4; /* * [ALL] Set to 1 if this is a partial decode because the packet header * has not yet been deprotected. pn_len, pn and key_phase are not valid if * this is set. */ unsigned int partial :1; /* * [ALL] Whether the fixed bit was set. Note that only Version Negotiation * packets are allowed to have this unset, so this will always be 1 for all * other packet types (decode will fail if it is not set). Ignored when * encoding unless encoding a Version Negotiation packet. */ unsigned int fixed :1; /* * The unused bits in the low 4 bits of a Retry packet header's first byte. * This is used to ensure that Retry packets have the same bit-for-bit * representation in their header when decoding and encoding them again. * This is necessary to validate Retry packet headers. */ unsigned int unused :4; /* * The 'Reserved' bits in an Initial, Handshake, 0-RTT or 1-RTT packet * header's first byte. These are provided so that the caller can validate * that they are zero, as this must be done after packet protection is * successfully removed to avoid creating a timing channel. */ unsigned int reserved :2; /* [L] Version field. Valid if (type != 1RTT). */ uint32_t version; /* [ALL] The destination connection ID. Always valid. */ QUIC_CONN_ID dst_conn_id; /* * [L] The source connection ID. * Valid if (type != 1RTT). */ QUIC_CONN_ID src_conn_id; /* * [1i0h] Relatively-encoded packet number in raw, encoded form. The correct * decoding of this value is context-dependent. The number of bytes valid in * this buffer is determined by pn_len above. If the decode was partial, * this field is not valid. * * Valid if ((type == 1RTT || (version && type != RETRY)) && !partial). */ unsigned char pn[4]; /* * [i] Token field in Initial packet. Points to memory inside the decoded * PACKET, and therefore is valid for as long as the PACKET's buffer is * valid. token_len is the length of the token in bytes. * * Valid if (type == INITIAL). */ const unsigned char *token; size_t token_len; /* * [ALL] Payload length in bytes. * * Though 1-RTT, Retry and Version Negotiation packets do not contain an * explicit length field, this field is always valid and is used by the * packet header encoding and decoding routines to describe the payload * length, regardless of whether the packet type encoded or decoded uses an * explicit length indication. */ size_t len; /* * Pointer to start of payload data in the packet. Points to memory inside * the decoded PACKET, and therefore is valid for as long as the PACKET'S * buffer is valid. The length of the buffer in bytes is in len above. * * For Version Negotiation packets, points to the array of supported * versions. * * For Retry packets, points to the Retry packet payload, which comprises * the Retry Token followed by a 16-byte Retry Integrity Tag. * * Regardless of whether a packet is a Version Negotiation packet (where the * payload contains a list of supported versions), a Retry packet (where the * payload contains a Retry Token and Retry Integrity Tag), or any other * packet type (where the payload contains frames), the payload is not * validated and the user must parse the payload bearing this in mind. * * If the decode was partial (partial is set), this points to the start of * the packet number field, rather than the protected payload, as the length * of the packet number field is unknown. The len field reflects this in * this case (i.e., the len field is the number of payload bytes plus the * number of bytes comprising the PN). */ const unsigned char *data; } QUIC_PKT_HDR; /* * Extra information which can be output by the packet header decode functions * for the assistance of the header protector. This avoids the header protector * needing to partially re-decode the packet header. */ struct quic_pkt_hdr_ptrs_st { unsigned char *raw_start; /* start of packet */ unsigned char *raw_sample; /* start of sampling range */ size_t raw_sample_len; /* maximum length of sampling range */ /* * Start of PN field. Guaranteed to be NULL unless at least four bytes are * available via this pointer. */ unsigned char *raw_pn; }; /* * If partial is 1, reads the unprotected parts of a protected packet header * from a PACKET, performing a partial decode. * * If partial is 0, the input is assumed to have already had header protection * removed, and all header fields are decoded. * * If nodata is 1, the input is assumed to have no payload data in it. Otherwise * payload data must be present. * * On success, the logical decode of the packet header is written to *hdr. * hdr->partial is set or cleared according to whether a partial decode was * performed. *ptrs is filled with pointers to various parts of the packet * buffer. * * In order to decode short packets, the connection ID length being used must be * known contextually, and should be passed as short_conn_id_len. If * short_conn_id_len is set to an invalid value (a value greater than * QUIC_MAX_CONN_ID_LEN), this function fails when trying to decode a short * packet, but succeeds for long packets. * * Returns 1 on success and 0 on failure. */ int ossl_quic_wire_decode_pkt_hdr(PACKET *pkt, size_t short_conn_id_len, int partial, int nodata, QUIC_PKT_HDR *hdr, QUIC_PKT_HDR_PTRS *ptrs); /* * Encodes a packet header. The packet is written to pkt. * * The length of the (encrypted) packet payload should be written to hdr->len * and will be placed in the serialized packet header. The payload data itself * is not copied; the caller should write hdr->len bytes of encrypted payload to * the WPACKET immediately after the call to this function. However, * WPACKET_reserve_bytes is called for the payload size. * * This function does not apply header protection. You must apply header * protection yourself after calling this function. *ptrs is filled with * pointers which can be passed to a header protector, but this must be * performed after the encrypted payload is written. * * The pointers in *ptrs are direct pointers into the WPACKET buffer. If more * data is written to the WPACKET buffer, WPACKET buffer reallocations may * occur, causing these pointers to become invalid. Therefore, you must not call * any write WPACKET function between this call and the call to * ossl_quic_hdr_protector_encrypt. This function calls WPACKET_reserve_bytes * for the payload length, so you may assume hdr->len bytes are already free to * write at the WPACKET cursor location once this function returns successfully. * It is recommended that you call this function, write the encrypted payload, * call ossl_quic_hdr_protector_encrypt, and then call * WPACKET_allocate_bytes(hdr->len). * * Version Negotiation and Retry packets do not use header protection; for these * header types, the fields in *ptrs are all written as zero. Version * Negotiation, Retry and 1-RTT packets do not contain a Length field, but * hdr->len bytes of data are still reserved in the WPACKET. * * If serializing a short packet and short_conn_id_len does not match the DCID * specified in hdr, the function fails. * * Returns 1 on success and 0 on failure. */ int ossl_quic_wire_encode_pkt_hdr(WPACKET *pkt, size_t short_conn_id_len, const QUIC_PKT_HDR *hdr, QUIC_PKT_HDR_PTRS *ptrs); /* * Retrieves only the DCID from a packet header. This is intended for demuxer * use. It avoids the need to parse the rest of the packet header twice. * * Information on packet length is not decoded, as this only needs to be used on * the first packet in a datagram, therefore this takes a buffer and not a * PACKET. * * Returns 1 on success and 0 on failure. */ int ossl_quic_wire_get_pkt_hdr_dst_conn_id(const unsigned char *buf, size_t buf_len, 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 * ====================== */ /* * Decode an encoded packet header QUIC PN. * * enc_pn is the raw encoded PN to decode. enc_pn_len is its length in bytes as * indicated by packet headers. largest_pn is the largest PN successfully * processed in the relevant PN space. * * The resulting PN is written to *res_pn. * * Returns 1 on success or 0 on failure. */ int ossl_quic_wire_decode_pkt_hdr_pn(const unsigned char *enc_pn, size_t enc_pn_len, QUIC_PN largest_pn, QUIC_PN *res_pn); /* * Determine how many bytes should be used to encode a PN. Returns the number of * bytes (which will be in range [1, 4]). */ int ossl_quic_wire_determine_pn_len(QUIC_PN pn, QUIC_PN largest_acked); /* * Encode a PN for a packet header using the specified number of bytes, which * should have been determined by calling ossl_quic_wire_determine_pn_len. The * PN encoding process is done in two parts to allow the caller to override PN * encoding length if it wishes. * * Returns 1 on success and 0 on failure. */ int ossl_quic_wire_encode_pkt_hdr_pn(QUIC_PN pn, unsigned char *enc_pn, size_t enc_pn_len); /* * Retry Integrity Tags * ==================== */ # define QUIC_RETRY_INTEGRITY_TAG_LEN 16 /* * Validate a retry integrity tag. Returns 1 if the tag is valid. * * Must be called on a hdr with a type of QUIC_PKT_TYPE_RETRY with a valid data * pointer. * * client_initial_dcid must be the original DCID used by the client in its first * Initial packet, as this is used to calculate the Retry Integrity Tag. * * Returns 0 if the tag is invalid, if called on any other type of packet or if * the body is too short. */ int ossl_quic_validate_retry_integrity_tag(OSSL_LIB_CTX *libctx, const char *propq, const QUIC_PKT_HDR *hdr, const QUIC_CONN_ID *client_initial_dcid); /* * Calculates a retry integrity tag. Returns 0 on error, for example if hdr does * not have a type of QUIC_PKT_TYPE_RETRY. * * client_initial_dcid must be the original DCID used by the client in its first * Initial packet, as this is used to calculate the Retry Integrity Tag. * * tag must point to a buffer of QUIC_RETRY_INTEGRITY_TAG_LEN bytes in size. * * Note that hdr->data must point to the Retry packet body, and hdr->len must * include the space for the Retry Integrity Tag. (This means that you can * easily fill in a tag in a Retry packet you are generating by calling this * function and passing (hdr->data + hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN) as * the tag argument.) This function fails if hdr->len is too short to contain a * Retry Integrity Tag. */ int ossl_quic_calculate_retry_integrity_tag(OSSL_LIB_CTX *libctx, const char *propq, const QUIC_PKT_HDR *hdr, const QUIC_CONN_ID *client_initial_dcid, unsigned char *tag); # endif #endif
./openssl/include/internal/passphrase.h
/* * Copyright 2020-2021 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_INTERNAL_PASSPHRASE_H # define OSSL_INTERNAL_PASSPHRASE_H # pragma once /* * This is a passphrase reader bridge with bells and whistles. * * On one hand, an API may wish to offer all sorts of passphrase callback * possibilities to users, or may have to do so for historical reasons. * On the other hand, that same API may have demands from other interfaces, * notably from the libcrypto <-> provider interface, which uses * OSSL_PASSPHRASE_CALLBACK consistently. * * The structure and functions below are the fundaments for bridging one * passphrase callback form to another. * * In addition, extra features are included (this may be a growing list): * * - password caching. This is to be used by APIs where it's likely * that the same passphrase may be asked for more than once, but the * user shouldn't get prompted more than once. For example, this is * useful for OSSL_DECODER, which may have to use a passphrase while * trying to find out what input it has. */ /* * Structure to hold whatever the calling user may specify. This structure * is intended to be integrated into API specific structures or to be used * as a local on-stack variable type. Therefore, no functions to allocate * or freed it on the heap is offered. */ struct ossl_passphrase_data_st { enum { is_expl_passphrase = 1, /* Explicit passphrase given by user */ is_pem_password, /* pem_password_cb given by user */ is_ossl_passphrase, /* OSSL_PASSPHRASE_CALLBACK given by user */ is_ui_method /* UI_METHOD given by user */ } type; union { struct { char *passphrase_copy; size_t passphrase_len; } expl_passphrase; struct { pem_password_cb *password_cb; void *password_cbarg; } pem_password; struct { OSSL_PASSPHRASE_CALLBACK *passphrase_cb; void *passphrase_cbarg; } ossl_passphrase; struct { const UI_METHOD *ui_method; void *ui_method_data; } ui_method; } _; /*- * Flags section */ /* Set to indicate that caching should be done */ unsigned int flag_cache_passphrase:1; /*- * Misc section: caches and other */ char *cached_passphrase; size_t cached_passphrase_len; }; /* Structure manipulation */ void ossl_pw_clear_passphrase_data(struct ossl_passphrase_data_st *data); void ossl_pw_clear_passphrase_cache(struct ossl_passphrase_data_st *data); int ossl_pw_set_passphrase(struct ossl_passphrase_data_st *data, const unsigned char *passphrase, size_t passphrase_len); int ossl_pw_set_pem_password_cb(struct ossl_passphrase_data_st *data, pem_password_cb *cb, void *cbarg); int ossl_pw_set_ossl_passphrase_cb(struct ossl_passphrase_data_st *data, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg); int ossl_pw_set_ui_method(struct ossl_passphrase_data_st *data, const UI_METHOD *ui_method, void *ui_data); int ossl_pw_enable_passphrase_caching(struct ossl_passphrase_data_st *data); int ossl_pw_disable_passphrase_caching(struct ossl_passphrase_data_st *data); /* Central function for direct calls */ int ossl_pw_get_passphrase(char *pass, size_t pass_size, size_t *pass_len, const OSSL_PARAM params[], int verify, struct ossl_passphrase_data_st *data); /* Callback functions */ /* * All of these callback expect that the callback argument is a * struct ossl_passphrase_data_st */ pem_password_cb ossl_pw_pem_password; pem_password_cb ossl_pw_pvk_password; /* One callback for encoding (verification prompt) and one for decoding */ OSSL_PASSPHRASE_CALLBACK ossl_pw_passphrase_callback_enc; OSSL_PASSPHRASE_CALLBACK ossl_pw_passphrase_callback_dec; #endif
./openssl/include/internal/quic_demux.h
/* * Copyright 2022-2023 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_DEMUX_H # define OSSL_QUIC_DEMUX_H # include <openssl/ssl.h> # include "internal/quic_types.h" # include "internal/quic_predef.h" # include "internal/bio_addr.h" # include "internal/time.h" # include "internal/list.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Demuxer * ============ * * The QUIC connection demuxer is the entity responsible for receiving datagrams * from the network via a datagram BIO. It parses the headers of the first * packet in the datagram to determine that packet's DCID and hands off * processing of the entire datagram to a single callback function which can * decide how to handle and route the datagram, for example by looking up * a QRX instance and injecting the URXE into that QRX. * * A QRX will typically be instantiated per QUIC connection and contains the * cryptographic resources needed to decrypt QUIC packets for that connection. * However, it is up to the callback function to handle routing, for example by * consulting a LCIDM instance. Thus the demuxer has no specific knowledge of * any QRX and is not coupled to it. All CID knowledge is also externalised into * a LCIDM or other CID state tracking object, without the DEMUX being coupled * to any particular DCID resolution mechanism. * * URX Queue * --------- * * Since the demuxer must handle the initial reception of datagrams from the OS, * RX queue management for new, unprocessed datagrams is also handled by the * demuxer. * * The demuxer maintains a queue of Unprocessed RX Entries (URXEs), which store * unprocessed (i.e., encrypted, unvalidated) data received from the network. * The URXE queue is designed to allow multiple datagrams to be received in a * single call to BIO_recvmmsg, where supported. * * One URXE is used per received datagram. Each datagram may contain multiple * 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 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 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 * implementation internals, this poses no problem, and has a number of * advantages: * * - Fields in the URXE can be allocated to support requirements in other * components, like the QRX, which would otherwise have to allocate extra * memory corresponding to each URXE. * * - 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 * ------------------- * * The URXE queue is maintained as a simple doubly-linked list. URXE entries are * moved between different lists in their lifecycle (for example, from a free * list to a pending list and vice versa). The buffer into which datagrams are * received immediately follows this URXE header structure and is part of the * same allocation. */ /* Maximum number of packets we allow to exist in one datagram. */ #define QUIC_MAX_PKT_PER_URXE (sizeof(uint64_t) * 8) struct quic_urxe_st { OSSL_LIST_MEMBER(urxe, QUIC_URXE); /* * The URXE data starts after this structure so we don't need a pointer. * data_len stores the current length (i.e., the length of the received * datagram) and alloc_len stores the allocation length. The URXE will be * reallocated if we need a larger allocation than is available, though this * should not be common as we will have a good idea of worst-case MTUs up * front. */ size_t data_len, alloc_len; /* * 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 QRX only; not used by the demuxer. */ uint64_t processed, hpr_removed; /* * Address of peer we received the datagram from, and the local interface * address we received it on. If local address support is not enabled, local * is zeroed. */ BIO_ADDR peer, local; /* * Time at which datagram was received (or ossl_time_zero()) if a now * function was not provided). */ OSSL_TIME time; /* * Used by the QRX to mark whether a datagram has been deferred. Used by the * QRX only; not used by the demuxer. */ char deferred; /* * Used by the DEMUX to track if a URXE has been handed out. Used primarily * for debugging purposes. */ char demux_state; }; /* Accessors for URXE buffer. */ static ossl_unused ossl_inline unsigned char * ossl_quic_urxe_data(const QUIC_URXE *e) { return (unsigned char *)&e[1]; } static ossl_unused ossl_inline unsigned char * ossl_quic_urxe_data_end(const QUIC_URXE *e) { return ossl_quic_urxe_data(e) + e->data_len; } /* List structure tracking a queue of URXEs. */ DEFINE_LIST_OF(urxe, QUIC_URXE); typedef OSSL_LIST(urxe) QUIC_URXE_LIST; /* * List management helpers. These are used by the demuxer but can also be used * by users of the demuxer to manage URXEs. */ void ossl_quic_urxe_remove(QUIC_URXE_LIST *l, QUIC_URXE *e); void ossl_quic_urxe_insert_head(QUIC_URXE_LIST *l, QUIC_URXE *e); void ossl_quic_urxe_insert_tail(QUIC_URXE_LIST *l, QUIC_URXE *e); /* * Called when a datagram is received for a given connection ID. * * e is a URXE containing the datagram payload. It is permissible for the callee * to mutate this buffer; once the demuxer calls this callback, it will never * read the buffer again. * * If a DCID was identified for the datagram, dcid is non-NULL; otherwise * it is NULL. * * The callee must arrange for ossl_quic_demux_release_urxe or * ossl_quic_demux_reinject_urxe to be called on the URXE at some point in the * future (this need not be before the callback returns). * * At the time the callback is made, the URXE will not be in any queue, * therefore the callee can use the prev and next fields as it wishes. */ typedef void (ossl_quic_demux_cb_fn)(QUIC_URXE *e, void *arg, const QUIC_CONN_ID *dcid); /* * Creates a new demuxer. The given BIO is used to receive datagrams from the * network using BIO_recvmmsg. short_conn_id_len is the length of destination * connection IDs used in RX'd packets; it must have the same value for all * connections used on a socket. default_urxe_alloc_len is the buffer size to * receive datagrams into; it should be a value large enough to contain any * received datagram according to local MTUs, etc. * * now is an optional function used to determine the time a datagram was * received. now_arg is an opaque argument passed to the function. If now is * NULL, ossl_time_zero() is used as the datagram reception time. */ QUIC_DEMUX *ossl_quic_demux_new(BIO *net_bio, size_t short_conn_id_len, OSSL_TIME (*now)(void *arg), void *now_arg); /* * Destroy a demuxer. All URXEs must have been released back to the demuxer * before calling this. No-op if demux is NULL. */ void ossl_quic_demux_free(QUIC_DEMUX *demux); /* * Changes the BIO which the demuxer reads from. This also sets the MTU if the * BIO supports querying the MTU. */ void ossl_quic_demux_set_bio(QUIC_DEMUX *demux, BIO *net_bio); /* * Changes the MTU in bytes we use to receive datagrams. */ int ossl_quic_demux_set_mtu(QUIC_DEMUX *demux, unsigned int mtu); /* * Set the default packet handler. This is used for incoming packets which don't * match a registered DCID. This is only needed for servers. If a default packet * handler is not set, a packet which doesn't match a registered DCID is * silently dropped. A default packet handler may be unset by passing NULL. * * The handler is responsible for ensuring that ossl_quic_demux_reinject_urxe or * ossl_quic_demux_release_urxe is called on the passed packet at some point in * the future, which may or may not be before the handler returns. */ void ossl_quic_demux_set_default_handler(QUIC_DEMUX *demux, ossl_quic_demux_cb_fn *cb, void *cb_arg); /* * Releases a URXE back to the demuxer. No reference must be made to the URXE or * its buffer after calling this function. The URXE must not be in any queue; * that is, its prev and next pointers must be NULL. */ void ossl_quic_demux_release_urxe(QUIC_DEMUX *demux, QUIC_URXE *e); /* * Reinjects a URXE which was issued to a registered DCID callback or the * default packet handler callback back into the pending queue. This is useful * when a packet has been handled by the default packet handler callback such * that a DCID has now been registered and can be dispatched normally by DCID. * Once this has been called, the caller must not touch the URXE anymore and * must not also call ossl_quic_demux_release_urxe(). * * The URXE is reinjected at the head of the queue, so it will be reprocessed * immediately. */ void ossl_quic_demux_reinject_urxe(QUIC_DEMUX *demux, QUIC_URXE *e); /* * Process any unprocessed RX'd datagrams, by calling registered callbacks by * connection ID, reading more datagrams from the BIO if necessary. * * Returns one of the following values: * * QUIC_DEMUX_PUMP_RES_OK * At least one incoming datagram was processed. * * QUIC_DEMUX_PUMP_RES_TRANSIENT_FAIL * No more incoming datagrams are currently available. * Call again later. * * QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL * Either the network read BIO has failed in a non-transient fashion, or * the QUIC implementation has encountered an internal state, assertion * or allocation error. The caller should tear down the connection * similarly to in the case of a protocol violation. * */ #define QUIC_DEMUX_PUMP_RES_OK 1 #define QUIC_DEMUX_PUMP_RES_TRANSIENT_FAIL (-1) #define QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL (-2) int ossl_quic_demux_pump(QUIC_DEMUX *demux); /* * Artificially inject a packet into the demuxer for testing purposes. The * buffer must not exceed the URXE size being used by the demuxer. * * If peer or local are NULL, their respective fields are zeroed in the injected * URXE. * * Returns 1 on success or 0 on failure. */ int ossl_quic_demux_inject(QUIC_DEMUX *demux, const unsigned char *buf, size_t buf_len, const BIO_ADDR *peer, const BIO_ADDR *local); /* * Returns 1 if there are any pending URXEs. */ int ossl_quic_demux_has_pending(const QUIC_DEMUX *demux); # endif #endif
./openssl/include/internal/deprecated.h
/* * Copyright 2016-2021 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 */ /* * This header file should be included by internal code that needs to use APIs * that have been deprecated for public use, but where those symbols will still * be available internally. For example the EVP and provider code needs to use * low level APIs that are otherwise deprecated. * * This header *must* be the first OpenSSL header included by a source file. */ #ifndef OSSL_INTERNAL_DEPRECATED_H # define OSSL_INTERNAL_DEPRECATED_H # pragma once # include <openssl/configuration.h> # undef OPENSSL_NO_DEPRECATED # define OPENSSL_SUPPRESS_DEPRECATED # include <openssl/macros.h> #endif
./openssl/include/internal/quic_record_util.h
/* * Copyright 2022-2023 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_UTIL_H # define OSSL_QUIC_RECORD_UTIL_H # include <openssl/ssl.h> # include "internal/quic_types.h" # ifndef OPENSSL_NO_QUIC struct ossl_qrx_st; struct ossl_qtx_st; /* * QUIC Key Derivation Utilities * ============================= */ /* HKDF-Extract(salt, IKM) (RFC 5869) */ int ossl_quic_hkdf_extract(OSSL_LIB_CTX *libctx, const char *propq, const EVP_MD *md, const unsigned char *salt, size_t salt_len, 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 * ================================== */ /* Available QUIC Record Layer (QRL) ciphersuites. */ # define QRL_SUITE_AES128GCM 1 /* SHA256 */ # define QRL_SUITE_AES256GCM 2 /* SHA384 */ # define QRL_SUITE_CHACHA20POLY1305 3 /* SHA256 */ /* Returns cipher name in bytes or NULL if suite ID is invalid. */ const char *ossl_qrl_get_suite_cipher_name(uint32_t suite_id); /* Returns hash function name in bytes or NULL if suite ID is invalid. */ const char *ossl_qrl_get_suite_md_name(uint32_t suite_id); /* Returns secret length in bytes or 0 if suite ID is invalid. */ uint32_t ossl_qrl_get_suite_secret_len(uint32_t suite_id); /* Returns key length in bytes or 0 if suite ID is invalid. */ uint32_t ossl_qrl_get_suite_cipher_key_len(uint32_t suite_id); /* Returns IV length in bytes or 0 if suite ID is invalid. */ uint32_t ossl_qrl_get_suite_cipher_iv_len(uint32_t suite_id); /* Returns AEAD auth tag length in bytes or 0 if suite ID is invalid. */ uint32_t ossl_qrl_get_suite_cipher_tag_len(uint32_t suite_id); /* Returns a QUIC_HDR_PROT_CIPHER_* value or 0 if suite ID is invalid. */ 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 #endif
./openssl/include/internal/quic_reactor.h
/* * Copyright 2022-2023 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_REACTOR_H # define OSSL_QUIC_REACTOR_H # include "internal/time.h" # include "internal/sockets.h" # include "internal/quic_predef.h" # include <openssl/bio.h> # ifndef OPENSSL_NO_QUIC /* * Core I/O Reactor Framework * ========================== * * Manages use of async network I/O which the QUIC stack is built on. The core * mechanic looks like this: * * - There is a pollable FD for both the read and write side respectively. * Readability and writeability of these FDs respectively determines when * network I/O is available. * * - The reactor can export these FDs to the user, as well as flags indicating * whether the user should listen for readability, writeability, or neither. * * - The reactor can export a timeout indication to the user, indicating when * the reactor should be called (via libssl APIs) regardless of whether * the network socket has become ready. * * The reactor is based around a tick callback which is essentially the mutator * function. The mutator attempts to do whatever it can, attempting to perform * network I/O to the extent currently feasible. When done, the mutator returns * information to the reactor indicating when it should be woken up again: * * - Should it be woken up when network RX is possible? * - Should it be woken up when network TX is possible? * - Should it be woken up no later than some deadline X? * * The intention is that ALL I/O-related SSL_* functions with side effects (e.g. * SSL_read/SSL_write) consist of three phases: * * - Optionally mutate the QUIC machine's state. * - Optionally tick the QUIC reactor. * - Optionally mutate the QUIC machine's state. * * For example, SSL_write is a mutation (appending to a stream buffer) followed * by an optional tick (generally expected as we may want to send the data * immediately, though not strictly needed if transmission is being deferred due * to Nagle's algorithm, etc.). * * SSL_read is also a mutation and in principle does not need to tick the * reactor, but it generally will anyway to ensure that the reactor is regularly * ticked by an application which is only reading and not writing. * * If the SSL object is being used in blocking mode, SSL_read may need to block * if no data is available yet, and SSL_write may need to block if buffers * are full. * * The internals of the QUIC I/O engine always use asynchronous I/O. If the * application desires blocking semantics, we handle this by adding a blocking * adaptation layer on top of our internal asynchronous I/O API as exposed by * the reactor interface. */ struct quic_tick_result_st { char net_read_desired; char net_write_desired; OSSL_TIME tick_deadline; }; static ossl_inline ossl_unused void ossl_quic_tick_result_merge_into(QUIC_TICK_RESULT *r, const QUIC_TICK_RESULT *src) { r->net_read_desired = r->net_read_desired || src->net_read_desired; r->net_write_desired = r->net_write_desired || src->net_write_desired; r->tick_deadline = ossl_time_min(r->tick_deadline, src->tick_deadline); } struct quic_reactor_st { /* * BIO poll descriptors which can be polled. poll_r is a poll descriptor * which becomes readable when the QUIC state machine can potentially do * work, and poll_w is a poll descriptor which becomes writable when the * QUIC state machine can potentially do work. Generally, either of these * conditions means that SSL_tick() should be called, or another SSL * function which implicitly calls SSL_tick() (e.g. SSL_read/SSL_write()). */ BIO_POLL_DESCRIPTOR poll_r, poll_w; OSSL_TIME tick_deadline; /* ossl_time_infinite() if none currently applicable */ void (*tick_cb)(QUIC_TICK_RESULT *res, void *arg, uint32_t flags); void *tick_cb_arg; /* * These are true if we would like to know when we can read or write from * the network respectively. */ unsigned int net_read_desired : 1; unsigned int net_write_desired : 1; /* * Are the read and write poll descriptors we are currently configured with * things we can actually poll? */ unsigned int can_poll_r : 1; unsigned int can_poll_w : 1; }; void ossl_quic_reactor_init(QUIC_REACTOR *rtor, void (*tick_cb)(QUIC_TICK_RESULT *res, void *arg, uint32_t flags), void *tick_cb_arg, OSSL_TIME initial_tick_deadline); void ossl_quic_reactor_set_poll_r(QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *r); void ossl_quic_reactor_set_poll_w(QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *w); const BIO_POLL_DESCRIPTOR *ossl_quic_reactor_get_poll_r(const QUIC_REACTOR *rtor); const BIO_POLL_DESCRIPTOR *ossl_quic_reactor_get_poll_w(const QUIC_REACTOR *rtor); int ossl_quic_reactor_can_poll_r(const QUIC_REACTOR *rtor); int ossl_quic_reactor_can_poll_w(const QUIC_REACTOR *rtor); int ossl_quic_reactor_can_support_poll_descriptor(const QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *d); int ossl_quic_reactor_net_read_desired(QUIC_REACTOR *rtor); int ossl_quic_reactor_net_write_desired(QUIC_REACTOR *rtor); OSSL_TIME ossl_quic_reactor_get_tick_deadline(QUIC_REACTOR *rtor); /* * Do whatever work can be done, and as much work as can be done. This involves * e.g. seeing if we can read anything from the network (if we want to), seeing * if we can write anything to the network (if we want to), etc. * * If the CHANNEL_ONLY flag is set, this indicates that we should only * touch state which is synchronised by the channel mutex. */ #define QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY (1U << 0) int ossl_quic_reactor_tick(QUIC_REACTOR *rtor, uint32_t flags); /* * Blocking I/O Adaptation Layer * ============================= * * The blocking I/O adaptation layer implements blocking I/O on top of our * asynchronous core. * * The core mechanism is block_until_pred(), which does not return until pred() * returns a value other than 0. The blocker uses OS I/O synchronisation * primitives (e.g. poll(2)) and ticks the reactor until the predicate is * satisfied. The blocker is not required to call pred() more than once between * tick calls. * * When pred returns a non-zero value, that value is returned by this function. * This can be used to allow pred() to indicate error conditions and short * circuit the blocking process. * * A return value of -1 is reserved for network polling errors. Therefore this * return value should not be used by pred() if ambiguity is not desired. Note * that the predicate function can always arrange its own output mechanism, for * example by passing a structure of its own as the argument. * * If the SKIP_FIRST_TICK flag is set, the first call to reactor_tick() before * the first call to pred() is skipped. This is useful if it is known that * ticking the reactor again will not be useful (e.g. because it has already * been done). * * This function assumes a write lock is held for the entire QUIC_CHANNEL. If * mutex is non-NULL, it must be a lock currently held for write; it will be * unlocked during any sleep, and then relocked for write afterwards. * * Precondition: mutex is NULL or is held for write (unchecked) * Postcondition: mutex is NULL or is held for write (unless * CRYPTO_THREAD_write_lock fails) */ #define SKIP_FIRST_TICK (1U << 0) int ossl_quic_reactor_block_until_pred(QUIC_REACTOR *rtor, int (*pred)(void *arg), void *pred_arg, uint32_t flags, CRYPTO_RWLOCK *mutex); # endif #endif
./openssl/include/internal/hpke_util.h
/* * 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_INTERNAL_HPKE_UTIL_H # define OSSL_INTERNAL_HPKE_UTIL_H # pragma once /* Constants from RFC 9180 Section 7.1 and 7.3 */ # define OSSL_HPKE_MAX_SECRET 64 # define OSSL_HPKE_MAX_PUBLIC 133 # define OSSL_HPKE_MAX_PRIVATE 66 # define OSSL_HPKE_MAX_KDF_INPUTLEN 64 /* * max length of a base-nonce (the Nn field from OSSL_HPKE_AEAD_INFO), this * is used for a local stack array size */ # define OSSL_HPKE_MAX_NONCELEN 12 /* * @brief info about a KEM * Used to store constants from Section 7.1 "Table 2 KEM IDs" * and the bitmask for EC curves described in Section 7.1.3 DeriveKeyPair */ typedef struct { uint16_t kem_id; /* code point for key encipherment method */ const char *keytype; /* string form of algtype "EC"/"X25519"/"X448" */ const char *groupname; /* string form of EC group for NIST curves */ const char *mdname; /* hash alg name for the HKDF */ size_t Nsecret; /* size of secrets */ size_t Nenc; /* length of encapsulated key */ size_t Npk; /* length of public key */ size_t Nsk; /* length of raw private key */ uint8_t bitmask; } OSSL_HPKE_KEM_INFO; /* * @brief info about a KDF */ typedef struct { uint16_t kdf_id; /* code point for KDF */ const char *mdname; /* hash alg name for the HKDF */ size_t Nh; /* length of hash/extract output */ } OSSL_HPKE_KDF_INFO; /* * @brief info about an AEAD */ typedef struct { uint16_t aead_id; /* code point for aead alg */ const char *name; /* alg name */ size_t taglen; /* aead tag len */ size_t Nk; /* size of a key for this aead */ size_t Nn; /* length of a nonce for this aead */ } OSSL_HPKE_AEAD_INFO; const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_curve(const char *curve); const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_id(uint16_t kemid); const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_random(OSSL_LIB_CTX *ctx); const OSSL_HPKE_KDF_INFO *ossl_HPKE_KDF_INFO_find_id(uint16_t kdfid); const OSSL_HPKE_KDF_INFO *ossl_HPKE_KDF_INFO_find_random(OSSL_LIB_CTX *ctx); const OSSL_HPKE_AEAD_INFO *ossl_HPKE_AEAD_INFO_find_id(uint16_t aeadid); const OSSL_HPKE_AEAD_INFO *ossl_HPKE_AEAD_INFO_find_random(OSSL_LIB_CTX *ctx); int ossl_hpke_kdf_extract(EVP_KDF_CTX *kctx, unsigned char *prk, size_t prklen, const unsigned char *salt, size_t saltlen, const unsigned char *ikm, size_t ikmlen); int ossl_hpke_kdf_expand(EVP_KDF_CTX *kctx, unsigned char *okm, size_t okmlen, const unsigned char *prk, size_t prklen, const unsigned char *info, size_t infolen); int ossl_hpke_labeled_extract(EVP_KDF_CTX *kctx, unsigned char *prk, size_t prklen, const unsigned char *salt, size_t saltlen, const char *protocol_label, const unsigned char *suiteid, size_t suiteidlen, const char *label, const unsigned char *ikm, size_t ikmlen); int ossl_hpke_labeled_expand(EVP_KDF_CTX *kctx, unsigned char *okm, size_t okmlen, const unsigned char *prk, size_t prklen, const char *protocol_label, const unsigned char *suiteid, size_t suiteidlen, const char *label, const unsigned char *info, size_t infolen); EVP_KDF_CTX *ossl_kdf_ctx_create(const char *kdfname, const char *mdname, OSSL_LIB_CTX *libctx, const char *propq); int ossl_hpke_str2suite(const char *suitestr, OSSL_HPKE_SUITE *suite); #endif
./openssl/include/internal/thread.h
/* * Copyright 2019-2021 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 OPENSSL_INTERNAL_THREAD_H # define OPENSSL_INTERNAL_THREAD_H # include <openssl/configuration.h> # include <internal/thread_arch.h> # include <openssl/e_os2.h> # include <openssl/types.h> # include <internal/cryptlib.h> # include "crypto/context.h" void *ossl_crypto_thread_start(OSSL_LIB_CTX *ctx, CRYPTO_THREAD_ROUTINE start, void *data); int ossl_crypto_thread_join(void *task, CRYPTO_THREAD_RETVAL *retval); int ossl_crypto_thread_clean(void *vhandle); uint64_t ossl_get_avail_threads(OSSL_LIB_CTX *ctx); # if defined(OPENSSL_THREADS) # define OSSL_LIB_CTX_GET_THREADS(CTX) \ ossl_lib_ctx_get_data(CTX, OSSL_LIB_CTX_THREAD_INDEX); typedef struct openssl_threads_st { uint64_t max_threads; uint64_t active_threads; CRYPTO_MUTEX *lock; CRYPTO_CONDVAR *cond_finished; } OSSL_LIB_CTX_THREADS; # endif /* defined(OPENSSL_THREADS) */ #endif /* OPENSSL_INTERNAL_THREAD_H */
./openssl/include/internal/quic_wire.h
/* * Copyright 2022-2023 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_INTERNAL_QUIC_WIRE_H # define OSSL_INTERNAL_QUIC_WIRE_H # pragma once # include "internal/e_os.h" # include "internal/time.h" # include "internal/quic_types.h" # include "internal/packet_quic.h" # ifndef OPENSSL_NO_QUIC # define OSSL_QUIC_FRAME_TYPE_PADDING 0x00 # define OSSL_QUIC_FRAME_TYPE_PING 0x01 # define OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN 0x02 # define OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN 0x03 # define OSSL_QUIC_FRAME_TYPE_RESET_STREAM 0x04 # define OSSL_QUIC_FRAME_TYPE_STOP_SENDING 0x05 # define OSSL_QUIC_FRAME_TYPE_CRYPTO 0x06 # define OSSL_QUIC_FRAME_TYPE_NEW_TOKEN 0x07 # define OSSL_QUIC_FRAME_TYPE_MAX_DATA 0x10 # define OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA 0x11 # define OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI 0x12 # define OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI 0x13 # define OSSL_QUIC_FRAME_TYPE_DATA_BLOCKED 0x14 # define OSSL_QUIC_FRAME_TYPE_STREAM_DATA_BLOCKED 0x15 # define OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_BIDI 0x16 # define OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_UNI 0x17 # define OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID 0x18 # define OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID 0x19 # define OSSL_QUIC_FRAME_TYPE_PATH_CHALLENGE 0x1A # define OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE 0x1B # define OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_TRANSPORT 0x1C # define OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_APP 0x1D # define OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE 0x1E # define OSSL_QUIC_FRAME_FLAG_STREAM_FIN 0x01 # define OSSL_QUIC_FRAME_FLAG_STREAM_LEN 0x02 # define OSSL_QUIC_FRAME_FLAG_STREAM_OFF 0x04 # define OSSL_QUIC_FRAME_FLAG_STREAM_MASK ((uint64_t)0x07) /* Low 3 bits of the type contain flags */ # define OSSL_QUIC_FRAME_TYPE_STREAM 0x08 /* base ID */ # define OSSL_QUIC_FRAME_TYPE_STREAM_FIN \ (OSSL_QUIC_FRAME_TYPE_STREAM | \ OSSL_QUIC_FRAME_FLAG_STREAM_FIN) # define OSSL_QUIC_FRAME_TYPE_STREAM_LEN \ (OSSL_QUIC_FRAME_TYPE_STREAM | \ OSSL_QUIC_FRAME_FLAG_STREAM_LEN) # define OSSL_QUIC_FRAME_TYPE_STREAM_LEN_FIN \ (OSSL_QUIC_FRAME_TYPE_STREAM | \ OSSL_QUIC_FRAME_FLAG_STREAM_LEN | \ OSSL_QUIC_FRAME_FLAG_STREAM_FIN) # define OSSL_QUIC_FRAME_TYPE_STREAM_OFF \ (OSSL_QUIC_FRAME_TYPE_STREAM | \ OSSL_QUIC_FRAME_FLAG_STREAM_OFF) # define OSSL_QUIC_FRAME_TYPE_STREAM_OFF_FIN \ (OSSL_QUIC_FRAME_TYPE_STREAM | \ OSSL_QUIC_FRAME_FLAG_STREAM_OFF | \ OSSL_QUIC_FRAME_FLAG_STREAM_FIN) # define OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN \ (OSSL_QUIC_FRAME_TYPE_STREAM | \ OSSL_QUIC_FRAME_FLAG_STREAM_OFF | \ OSSL_QUIC_FRAME_FLAG_STREAM_LEN) # define OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN_FIN \ (OSSL_QUIC_FRAME_TYPE_STREAM | \ OSSL_QUIC_FRAME_FLAG_STREAM_OFF | \ OSSL_QUIC_FRAME_FLAG_STREAM_LEN | \ OSSL_QUIC_FRAME_FLAG_STREAM_FIN) # define OSSL_QUIC_FRAME_TYPE_IS_STREAM(x) \ (((x) & ~OSSL_QUIC_FRAME_FLAG_STREAM_MASK) == OSSL_QUIC_FRAME_TYPE_STREAM) # define OSSL_QUIC_FRAME_TYPE_IS_ACK(x) \ (((x) & ~(uint64_t)1) == OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN) # define OSSL_QUIC_FRAME_TYPE_IS_MAX_STREAMS(x) \ (((x) & ~(uint64_t)1) == OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI) # define OSSL_QUIC_FRAME_TYPE_IS_STREAMS_BLOCKED(x) \ (((x) & ~(uint64_t)1) == OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_BIDI) # define OSSL_QUIC_FRAME_TYPE_IS_CONN_CLOSE(x) \ (((x) & ~(uint64_t)1) == OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_TRANSPORT) const char *ossl_quic_frame_type_to_string(uint64_t frame_type); static ossl_unused ossl_inline int ossl_quic_frame_type_is_ack_eliciting(uint64_t frame_type) { switch (frame_type) { case OSSL_QUIC_FRAME_TYPE_PADDING: case OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN: case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN: case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_TRANSPORT: case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_APP: return 0; default: return 1; } } /* QUIC Transport Parameter Types */ # define QUIC_TPARAM_ORIG_DCID 0x00 # define QUIC_TPARAM_MAX_IDLE_TIMEOUT 0x01 # define QUIC_TPARAM_STATELESS_RESET_TOKEN 0x02 # define QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE 0x03 # define QUIC_TPARAM_INITIAL_MAX_DATA 0x04 # define QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL 0x05 # define QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE 0x06 # define QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI 0x07 # define QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI 0x08 # define QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI 0x09 # define QUIC_TPARAM_ACK_DELAY_EXP 0x0A # define QUIC_TPARAM_MAX_ACK_DELAY 0x0B # define QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION 0x0C # define QUIC_TPARAM_PREFERRED_ADDR 0x0D # define QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT 0x0E # define QUIC_TPARAM_INITIAL_SCID 0x0F # define QUIC_TPARAM_RETRY_SCID 0x10 /* * QUIC Frame Logical Representations * ================================== */ /* QUIC Frame: ACK */ typedef struct ossl_quic_ack_range_st { /* * Represents an inclusive range of packet numbers [start, end]. * start must be <= end. */ QUIC_PN start, end; } OSSL_QUIC_ACK_RANGE; typedef struct ossl_quic_frame_ack_st { /* * A sequence of packet number ranges [[start, end]...]. * * The ranges must be sorted in descending order, for example: * [ 95, 100] * [ 90, 92] * etc. * * As such, ack_ranges[0].end is always the highest packet number * being acknowledged and ack_ranges[num_ack_ranges-1].start is * always the lowest packet number being acknowledged. * * num_ack_ranges must be greater than zero, as an ACK frame must * acknowledge at least one packet number. */ OSSL_QUIC_ACK_RANGE *ack_ranges; size_t num_ack_ranges; OSSL_TIME delay_time; uint64_t ect0, ect1, ecnce; unsigned int ecn_present : 1; } OSSL_QUIC_FRAME_ACK; /* Returns 1 if the given frame contains the given PN. */ int ossl_quic_frame_ack_contains_pn(const OSSL_QUIC_FRAME_ACK *ack, QUIC_PN pn); /* QUIC Frame: STREAM */ typedef struct ossl_quic_frame_stream_st { uint64_t stream_id; /* Stream ID */ uint64_t offset; /* Logical offset in stream */ uint64_t len; /* Length of data in bytes */ const unsigned char *data; /* * On encode, this determines whether the len field should be encoded or * not. If zero, the len field is not encoded and it is assumed the frame * runs to the end of the packet. * * On decode, this determines whether the frame had an explicitly encoded * length. If not set, the frame runs to the end of the packet and len has * been set accordingly. */ unsigned int has_explicit_len : 1; /* 1 if this is the end of the stream */ unsigned int is_fin : 1; } OSSL_QUIC_FRAME_STREAM; /* QUIC Frame: CRYPTO */ typedef struct ossl_quic_frame_crypto_st { uint64_t offset; /* Logical offset in stream */ uint64_t len; /* Length of the data in bytes */ const unsigned char *data; } OSSL_QUIC_FRAME_CRYPTO; /* QUIC Frame: RESET_STREAM */ typedef struct ossl_quic_frame_reset_stream_st { uint64_t stream_id; uint64_t app_error_code; uint64_t final_size; } OSSL_QUIC_FRAME_RESET_STREAM; /* QUIC Frame: STOP_SENDING */ typedef struct ossl_quic_frame_stop_sending_st { uint64_t stream_id; uint64_t app_error_code; } OSSL_QUIC_FRAME_STOP_SENDING; /* QUIC Frame: NEW_CONNECTION_ID */ typedef struct ossl_quic_frame_new_conn_id_st { uint64_t seq_num; uint64_t retire_prior_to; QUIC_CONN_ID conn_id; QUIC_STATELESS_RESET_TOKEN stateless_reset; } OSSL_QUIC_FRAME_NEW_CONN_ID; /* QUIC Frame: CONNECTION_CLOSE */ typedef struct ossl_quic_frame_conn_close_st { unsigned int is_app : 1; /* 0: transport error, 1: app error */ uint64_t error_code; /* 62-bit transport or app error code */ uint64_t frame_type; /* transport errors only */ char *reason; /* UTF-8 string, not necessarily zero-terminated */ size_t reason_len; /* Length of reason in bytes */ } OSSL_QUIC_FRAME_CONN_CLOSE; /* * QUIC Wire Format Encoding * ========================= * * These functions return 1 on success and 0 on failure. */ /* * Encodes zero or more QUIC PADDING frames to the packet writer. Each PADDING * frame consumes one byte; num_bytes specifies the number of bytes of padding * to write. */ int ossl_quic_wire_encode_padding(WPACKET *pkt, size_t num_bytes); /* * Encodes a QUIC PING frame to the packet writer. This frame type takes * no arguments. */ int ossl_quic_wire_encode_frame_ping(WPACKET *pkt); /* * Encodes a QUIC ACK frame to the packet writer, given a logical representation * of the ACK frame. * * The ACK ranges passed must be sorted in descending order. * * The logical representation stores a list of packet number ranges. The wire * encoding is slightly different and stores the first range in the list * in a different manner. * * The ack_delay_exponent argument specifies the index of a power of two by * which the ack->ack_delay field is be divided. This exponent value must match * the value used when decoding. */ int ossl_quic_wire_encode_frame_ack(WPACKET *pkt, uint32_t ack_delay_exponent, const OSSL_QUIC_FRAME_ACK *ack); /* * Encodes a QUIC RESET_STREAM frame to the packet writer, given a logical * representation of the RESET_STREAM frame. */ int ossl_quic_wire_encode_frame_reset_stream(WPACKET *pkt, const OSSL_QUIC_FRAME_RESET_STREAM *f); /* * Encodes a QUIC STOP_SENDING frame to the packet writer, given a logical * representation of the STOP_SENDING frame. */ int ossl_quic_wire_encode_frame_stop_sending(WPACKET *pkt, const OSSL_QUIC_FRAME_STOP_SENDING *f); /* * Encodes a QUIC CRYPTO frame header to the packet writer. * * To create a well-formed frame, the data written using this function must be * immediately followed by f->len bytes of data. */ int ossl_quic_wire_encode_frame_crypto_hdr(WPACKET *hdr, const OSSL_QUIC_FRAME_CRYPTO *f); /* * Returns the number of bytes which will be required to encode the given * CRYPTO frame header. Does not include the payload bytes in the count. * Returns 0 if input is invalid. */ size_t ossl_quic_wire_get_encoded_frame_len_crypto_hdr(const OSSL_QUIC_FRAME_CRYPTO *f); /* * Encodes a QUIC CRYPTO frame to the packet writer. * * This function returns a pointer to a buffer of f->len bytes which the caller * should fill however it wishes. If f->data is non-NULL, it is automatically * copied to the target buffer, otherwise the caller must fill the returned * buffer. Returns NULL on failure. */ void *ossl_quic_wire_encode_frame_crypto(WPACKET *pkt, const OSSL_QUIC_FRAME_CRYPTO *f); /* * Encodes a QUIC NEW_TOKEN frame to the packet writer. */ int ossl_quic_wire_encode_frame_new_token(WPACKET *pkt, const unsigned char *token, size_t token_len); /* * Encodes a QUIC STREAM frame's header to the packet writer. The f->stream_id, * f->offset and f->len fields are the values for the respective Stream ID, * Offset and Length fields. * * If f->is_fin is non-zero, the frame is marked as the final frame in the * stream. * * If f->has_explicit_len is zerro, the frame is assumed to be the final frame * in the packet, which the caller is responsible for ensuring; the Length * field is then omitted. * * To create a well-formed frame, the data written using this function must be * immediately followed by f->len bytes of stream data. */ int ossl_quic_wire_encode_frame_stream_hdr(WPACKET *pkt, const OSSL_QUIC_FRAME_STREAM *f); /* * Returns the number of bytes which will be required to encode the given * STREAM frame header. Does not include the payload bytes in the count. * Returns 0 if input is invalid. */ size_t ossl_quic_wire_get_encoded_frame_len_stream_hdr(const OSSL_QUIC_FRAME_STREAM *f); /* * Functions similarly to ossl_quic_wire_encode_frame_stream_hdr, but it also * allocates space for f->len bytes of data after the header, creating a * well-formed QUIC STREAM frame in one call. * * A pointer to the bytes allocated for the framme payload is returned, * which the caller can fill however it wishes. If f->data is non-NULL, * it is automatically copied to the target buffer, otherwise the caller * must fill the returned buffer. Returns NULL on failure. */ void *ossl_quic_wire_encode_frame_stream(WPACKET *pkt, const OSSL_QUIC_FRAME_STREAM *f); /* * Encodes a QUIC MAX_DATA frame to the packet writer. */ int ossl_quic_wire_encode_frame_max_data(WPACKET *pkt, uint64_t max_data); /* * Encodes a QUIC MAX_STREAM_DATA frame to the packet writer. */ int ossl_quic_wire_encode_frame_max_stream_data(WPACKET *pkt, uint64_t stream_id, uint64_t max_data); /* * Encodes a QUIC MAX_STREAMS frame to the packet writer. * * If is_uni is 0, the count specifies the maximum number of * bidirectional streams; else it specifies the maximum number of unidirectional * streams. */ int ossl_quic_wire_encode_frame_max_streams(WPACKET *pkt, char is_uni, uint64_t max_streams); /* * Encodes a QUIC DATA_BLOCKED frame to the packet writer. */ int ossl_quic_wire_encode_frame_data_blocked(WPACKET *pkt, uint64_t max_data); /* * Encodes a QUIC STREAM_DATA_BLOCKED frame to the packet writer. */ int ossl_quic_wire_encode_frame_stream_data_blocked(WPACKET *pkt, uint64_t stream_id, uint64_t max_stream_data); /* * Encodes a QUIC STREAMS_BLOCKED frame to the packet writer. * * If is_uni is 0, the count specifies the maximum number of * bidirectional streams; else it specifies the maximum number of unidirectional * streams. */ int ossl_quic_wire_encode_frame_streams_blocked(WPACKET *pkt, char is_uni, uint64_t max_streams); /* * Encodes a QUIC NEW_CONNECTION_ID frame to the packet writer, given a logical * representation of the NEW_CONNECTION_ID frame. * * The buffer pointed to by the conn_id field must be valid for the duration of * the call. */ int ossl_quic_wire_encode_frame_new_conn_id(WPACKET *pkt, const OSSL_QUIC_FRAME_NEW_CONN_ID *f); /* * Encodes a QUIC RETIRE_CONNECTION_ID frame to the packet writer. */ int ossl_quic_wire_encode_frame_retire_conn_id(WPACKET *pkt, uint64_t seq_num); /* * Encodes a QUIC PATH_CHALLENGE frame to the packet writer. */ int ossl_quic_wire_encode_frame_path_challenge(WPACKET *pkt, uint64_t data); /* * Encodes a QUIC PATH_RESPONSE frame to the packet writer. */ int ossl_quic_wire_encode_frame_path_response(WPACKET *pkt, uint64_t data); /* * Encodes a QUIC CONNECTION_CLOSE frame to the packet writer, given a logical * representation of the CONNECTION_CLOSE frame. * * The reason field may be NULL, in which case no reason is encoded. If the * reason field is non-NULL, it must point to a valid UTF-8 string and * reason_len must be set to the length of the reason string in bytes. The * reason string need not be zero terminated. */ int ossl_quic_wire_encode_frame_conn_close(WPACKET *pkt, const OSSL_QUIC_FRAME_CONN_CLOSE *f); /* * Encodes a QUIC HANDSHAKE_DONE frame to the packet writer. This frame type * takes no arguiments. */ int ossl_quic_wire_encode_frame_handshake_done(WPACKET *pkt); /* * Encodes a QUIC transport parameter TLV with the given ID into the WPACKET. * The payload is an arbitrary buffer. * * If value is non-NULL, the value is copied into the packet. * If it is NULL, value_len bytes are allocated for the payload and the caller * should fill the buffer using the returned pointer. * * Returns a pointer to the start of the payload on success, or NULL on failure. */ unsigned char *ossl_quic_wire_encode_transport_param_bytes(WPACKET *pkt, uint64_t id, const unsigned char *value, size_t value_len); /* * Encodes a QUIC transport parameter TLV with the given ID into the WPACKET. * The payload is a QUIC variable-length integer with the given value. */ int ossl_quic_wire_encode_transport_param_int(WPACKET *pkt, uint64_t id, uint64_t value); /* * Encodes a QUIC transport parameter TLV with a given ID into the WPACKET. * The payload is a QUIC connection ID. */ int ossl_quic_wire_encode_transport_param_cid(WPACKET *wpkt, uint64_t id, const QUIC_CONN_ID *cid); /* * QUIC Wire Format Decoding * ========================= * * These functions return 1 on success or 0 for failure. Typical reasons * why these functions may fail include: * * - A frame decode function is called but the frame in the PACKET's buffer * is not of the correct type. * * - A variable-length field in the encoded frame appears to exceed the bounds * of the PACKET's buffer. * * These functions should be called with the PACKET pointing to the start of the * frame (including the initial type field), and consume an entire frame * including its type field. The expectation is that the caller will have * already discerned the frame type using ossl_quic_wire_peek_frame_header(). */ /* * Decodes the type field header of a QUIC frame (without advancing the current * position). This can be used to determine the frame type and determine which * frame decoding function to call. */ int ossl_quic_wire_peek_frame_header(PACKET *pkt, uint64_t *type, int *was_minimal); /* * Like ossl_quic_wire_peek_frame_header, but advances the current position * so that the type field is consumed. For advanced use only. */ int ossl_quic_wire_skip_frame_header(PACKET *pkt, uint64_t *type); /* * Determines how many ranges are needed to decode a QUIC ACK frame. * * The number of ranges which must be allocated before the call to * ossl_quic_wire_decode_frame_ack is written to *total_ranges. * * The PACKET is not advanced. */ int ossl_quic_wire_peek_frame_ack_num_ranges(const PACKET *pkt, uint64_t *total_ranges); /* * Decodes a QUIC ACK frame. The ack_ranges field of the passed structure should * point to a preallocated array of ACK ranges and the num_ack_ranges field * should specify the length of allocation. * * *total_ranges is written with the number of ranges in the decoded frame, * which may be greater than the number of ranges which were decoded (i.e. if * num_ack_ranges was too small to decode all ranges). * * On success, this function modifies the num_ack_ranges field to indicate the * number of ranges in the decoded frame. This is the number of entries in the * ACK ranges array written by this function; any additional entries are not * modified. * * If the number of ACK ranges in the decoded frame exceeds that in * num_ack_ranges, as many ACK ranges as possible are decoded into the range * array. The caller can use the value written to *total_ranges to detect this * condition, as *total_ranges will exceed num_ack_ranges. * * If ack is NULL, the frame is still decoded, but only *total_ranges is * written. This can be used to determine the number of ranges which must be * allocated. * * The ack_delay_exponent argument specifies the index of a power of two used to * decode the ack_delay field. This must match the ack_delay_exponent value used * to encode the frame. */ int ossl_quic_wire_decode_frame_ack(PACKET *pkt, uint32_t ack_delay_exponent, OSSL_QUIC_FRAME_ACK *ack, uint64_t *total_ranges); /* * Decodes a QUIC RESET_STREAM frame. */ int ossl_quic_wire_decode_frame_reset_stream(PACKET *pkt, OSSL_QUIC_FRAME_RESET_STREAM *f); /* * Decodes a QUIC STOP_SENDING frame. */ int ossl_quic_wire_decode_frame_stop_sending(PACKET *pkt, OSSL_QUIC_FRAME_STOP_SENDING *f); /* * Decodes a QUIC CRYPTO frame. * * f->data is set to point inside the packet buffer inside the PACKET, therefore * it is safe to access for as long as the packet buffer exists. If nodata is * set to 1 then reading the PACKET stops after the frame header and f->data is * set to NULL. */ int ossl_quic_wire_decode_frame_crypto(PACKET *pkt, int nodata, OSSL_QUIC_FRAME_CRYPTO *f); /* * Decodes a QUIC NEW_TOKEN frame. *token is written with a pointer to the token * bytes and *token_len is written with the length of the token in bytes. */ int ossl_quic_wire_decode_frame_new_token(PACKET *pkt, const unsigned char **token, size_t *token_len); /* * Decodes a QUIC STREAM frame. * * If nodata is set to 1 then reading the PACKET stops after the frame header * and f->data is set to NULL. In this case f->len will also be 0 in the event * that "has_explicit_len" is 0. * * If the frame did not contain an offset field, f->offset is set to 0, as the * absence of an offset field is equivalent to an offset of 0. * * If the frame contained a length field, f->has_explicit_len is set to 1 and * the length of the data is placed in f->len. This function ensures that the * length does not exceed the packet buffer, thus it is safe to access f->data. * * If the frame did not contain a length field, this means that the frame runs * until the end of the packet. This function sets f->has_explicit_len to zero, * and f->len to the amount of data remaining in the input buffer. Therefore, * this function should be used with a PACKET representing a single packet (and * not e.g. multiple packets). * * Note also that this means f->len is always valid after this function returns * successfully, regardless of the value of f->has_explicit_len. * * f->data points inside the packet buffer inside the PACKET, therefore it is * safe to access for as long as the packet buffer exists. * * f->is_fin is set according to whether the frame was marked as ending the * stream. */ int ossl_quic_wire_decode_frame_stream(PACKET *pkt, int nodata, OSSL_QUIC_FRAME_STREAM *f); /* * Decodes a QUIC MAX_DATA frame. The Maximum Data field is written to * *max_data. */ int ossl_quic_wire_decode_frame_max_data(PACKET *pkt, uint64_t *max_data); /* * Decodes a QUIC MAX_STREAM_DATA frame. The Stream ID is written to *stream_id * and Maximum Stream Data field is written to *max_stream_data. */ int ossl_quic_wire_decode_frame_max_stream_data(PACKET *pkt, uint64_t *stream_id, uint64_t *max_stream_data); /* * Decodes a QUIC MAX_STREAMS frame. The Maximum Streams field is written to * *max_streams. * * Whether the limit concerns bidirectional streams or unidirectional streams is * denoted by the frame type; the caller should examine the frame type to * determine this. */ int ossl_quic_wire_decode_frame_max_streams(PACKET *pkt, uint64_t *max_streams); /* * Decodes a QUIC DATA_BLOCKED frame. The Maximum Data field is written to * *max_data. */ int ossl_quic_wire_decode_frame_data_blocked(PACKET *pkt, uint64_t *max_data); /* * Decodes a QUIC STREAM_DATA_BLOCKED frame. The Stream ID and Maximum Stream * Data fields are written to *stream_id and *max_stream_data respectively. */ int ossl_quic_wire_decode_frame_stream_data_blocked(PACKET *pkt, uint64_t *stream_id, uint64_t *max_stream_data); /* * Decodes a QUIC STREAMS_BLOCKED frame. The Maximum Streams field is written to * *max_streams. * * Whether the limit concerns bidirectional streams or unidirectional streams is * denoted by the frame type; the caller should examine the frame type to * determine this. */ int ossl_quic_wire_decode_frame_streams_blocked(PACKET *pkt, uint64_t *max_streams); /* * Decodes a QUIC NEW_CONNECTION_ID frame. The logical representation of the * frame is written to *f. * * The conn_id field is set to point to the connection ID string inside the * packet buffer; it is therefore valid for as long as the PACKET's buffer is * valid. The conn_id_len field is set to the length of the connection ID string * in bytes. */ int ossl_quic_wire_decode_frame_new_conn_id(PACKET *pkt, OSSL_QUIC_FRAME_NEW_CONN_ID *f); /* * Decodes a QUIC RETIRE_CONNECTION_ID frame. The Sequence Number field * is written to *seq_num. */ int ossl_quic_wire_decode_frame_retire_conn_id(PACKET *pkt, uint64_t *seq_num); /* * Decodes a QUIC PATH_CHALLENGE frame. The Data field is written to *data. */ int ossl_quic_wire_decode_frame_path_challenge(PACKET *pkt, uint64_t *data); /* * Decodes a QUIC PATH_CHALLENGE frame. The Data field is written to *data. */ int ossl_quic_wire_decode_frame_path_response(PACKET *pkt, uint64_t *data); /* * Decodes a QUIC CONNECTION_CLOSE frame. The logical representation * of the frame is written to *f. * * The reason field is set to point to the UTF-8 reason string inside * the packet buffer; it is therefore valid for as long as the PACKET's * buffer is valid. The reason_len field is set to the length of the * reason string in bytes. * * IMPORTANT: The reason string is not zero-terminated. * * Returns 1 on success or 0 on failure. */ int ossl_quic_wire_decode_frame_conn_close(PACKET *pkt, OSSL_QUIC_FRAME_CONN_CLOSE *f); /* * Decodes one or more PADDING frames. PADDING frames have no arguments. * * Returns the number of PADDING frames decoded or 0 on error. */ size_t ossl_quic_wire_decode_padding(PACKET *pkt); /* * Decodes a PING frame. The frame has no arguments. */ int ossl_quic_wire_decode_frame_ping(PACKET *pkt); /* * Decodes a HANDSHAKE_DONE frame. The frame has no arguments. */ int ossl_quic_wire_decode_frame_handshake_done(PACKET *pkt); /* * Peeks at the ID of the next QUIC transport parameter TLV in the stream. * The ID is written to *id. */ int ossl_quic_wire_peek_transport_param(PACKET *pkt, uint64_t *id); /* * Decodes a QUIC transport parameter TLV. A pointer to the value buffer is * returned on success. This points inside the PACKET's buffer and is therefore * valid as long as the PACKET's buffer is valid. * * The transport parameter ID is written to *id (if non-NULL) and the length of * the payload in bytes is written to *len. * * Returns NULL on failure. */ const unsigned char *ossl_quic_wire_decode_transport_param_bytes(PACKET *pkt, uint64_t *id, size_t *len); /* * Decodes a QUIC transport parameter TLV containing a variable-length integer. * * The transport parameter ID is written to *id (if non-NULL) and the value is * written to *value. */ int ossl_quic_wire_decode_transport_param_int(PACKET *pkt, uint64_t *id, uint64_t *value); /* * Decodes a QUIC transport parameter TLV containing a connection ID. * * The transport parameter ID is written to *id (if non-NULL) and the value is * written to *value. */ int ossl_quic_wire_decode_transport_param_cid(PACKET *pkt, uint64_t *id, QUIC_CONN_ID *cid); /* * Decodes a QUIC transport parameter TLV containing a preferred_address. */ typedef struct quic_preferred_addr_st { uint16_t ipv4_port, ipv6_port; unsigned char ipv4[4], ipv6[16]; QUIC_STATELESS_RESET_TOKEN stateless_reset; QUIC_CONN_ID cid; } QUIC_PREFERRED_ADDR; int ossl_quic_wire_decode_transport_param_preferred_addr(PACKET *pkt, QUIC_PREFERRED_ADDR *p); # endif #endif
./openssl/include/internal/symhacks.h
/* * Copyright 2019-2021 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_INTERNAL_SYMHACKS_H # define OSSL_INTERNAL_SYMHACKS_H # pragma once # include <openssl/e_os2.h> # if defined(OPENSSL_SYS_VMS) /* ossl_provider_gettable_params vs OSSL_PROVIDER_gettable_params */ # undef ossl_provider_gettable_params # define ossl_provider_gettable_params ossl_int_prov_gettable_params /* ossl_provider_get_params vs OSSL_PROVIDER_get_params */ # undef ossl_provider_get_params # define ossl_provider_get_params ossl_int_prov_get_params # endif #endif /* ! defined HEADER_VMS_IDHACKS_H */
./openssl/include/internal/ffc.h
/* * Copyright 2019-2023 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_INTERNAL_FFC_H # define OSSL_INTERNAL_FFC_H # pragma once # include <openssl/core.h> # include <openssl/bn.h> # include <openssl/evp.h> # include <openssl/dh.h> /* Uses Error codes from DH */ # include <openssl/params.h> # include <openssl/param_build.h> # include "internal/sizes.h" /* Default value for gindex when canonical generation of g is not used */ # define FFC_UNVERIFIABLE_GINDEX -1 /* The different types of FFC keys */ # define FFC_PARAM_TYPE_DSA 0 # define FFC_PARAM_TYPE_DH 1 /* * The mode used by functions that share code for both generation and * verification. See ossl_ffc_params_FIPS186_4_gen_verify(). */ #define FFC_PARAM_MODE_VERIFY 0 #define FFC_PARAM_MODE_GENERATE 1 /* Return codes for generation and validation of FFC parameters */ #define FFC_PARAM_RET_STATUS_FAILED 0 #define FFC_PARAM_RET_STATUS_SUCCESS 1 /* Returned if validating and g is only partially verifiable */ #define FFC_PARAM_RET_STATUS_UNVERIFIABLE_G 2 /* Validation flags */ # define FFC_PARAM_FLAG_VALIDATE_PQ 0x01 # define FFC_PARAM_FLAG_VALIDATE_G 0x02 # define FFC_PARAM_FLAG_VALIDATE_PQG \ (FFC_PARAM_FLAG_VALIDATE_PQ | FFC_PARAM_FLAG_VALIDATE_G) #define FFC_PARAM_FLAG_VALIDATE_LEGACY 0x04 /* * NB: These values must align with the equivalently named macros in * openssl/dh.h. We cannot use those macros here in case DH has been disabled. */ # define FFC_CHECK_P_NOT_PRIME 0x00001 # define FFC_CHECK_P_NOT_SAFE_PRIME 0x00002 # define FFC_CHECK_UNKNOWN_GENERATOR 0x00004 # define FFC_CHECK_NOT_SUITABLE_GENERATOR 0x00008 # define FFC_CHECK_Q_NOT_PRIME 0x00010 # define FFC_CHECK_INVALID_Q_VALUE 0x00020 # define FFC_CHECK_INVALID_J_VALUE 0x00040 /* * 0x80, 0x100 reserved by include/openssl/dh.h with check bits that are not * relevant for FFC. */ # define FFC_CHECK_MISSING_SEED_OR_COUNTER 0x00200 # define FFC_CHECK_INVALID_G 0x00400 # define FFC_CHECK_INVALID_PQ 0x00800 # define FFC_CHECK_INVALID_COUNTER 0x01000 # define FFC_CHECK_P_MISMATCH 0x02000 # define FFC_CHECK_Q_MISMATCH 0x04000 # define FFC_CHECK_G_MISMATCH 0x08000 # define FFC_CHECK_COUNTER_MISMATCH 0x10000 # define FFC_CHECK_BAD_LN_PAIR 0x20000 # define FFC_CHECK_INVALID_SEED_SIZE 0x40000 /* Validation Return codes */ # define FFC_ERROR_PUBKEY_TOO_SMALL 0x01 # define FFC_ERROR_PUBKEY_TOO_LARGE 0x02 # define FFC_ERROR_PUBKEY_INVALID 0x04 # define FFC_ERROR_NOT_SUITABLE_GENERATOR 0x08 # define FFC_ERROR_PRIVKEY_TOO_SMALL 0x10 # define FFC_ERROR_PRIVKEY_TOO_LARGE 0x20 # define FFC_ERROR_PASSED_NULL_PARAM 0x40 /* * Finite field cryptography (FFC) domain parameters are used by DH and DSA. * Refer to FIPS186_4 Appendix A & B. */ typedef struct ffc_params_st { /* Primes */ BIGNUM *p; BIGNUM *q; /* Generator */ BIGNUM *g; /* DH X9.42 Optional Subgroup factor j >= 2 where p = j * q + 1 */ BIGNUM *j; /* Required for FIPS186_4 validation of p, q and optionally canonical g */ unsigned char *seed; /* If this value is zero the hash size is used as the seed length */ size_t seedlen; /* Required for FIPS186_4 validation of p and q */ int pcounter; int nid; /* The identity of a named group */ /* * Required for FIPS186_4 generation & validation of canonical g. * It uses unverifiable g if this value is -1. */ int gindex; int h; /* loop counter for unverifiable g */ unsigned int flags; /* * The digest to use for generation or validation. If this value is NULL, * then the digest is chosen using the value of N. */ const char *mdname; const char *mdprops; /* Default key length for known named groups according to RFC7919 */ int keylength; } FFC_PARAMS; void ossl_ffc_params_init(FFC_PARAMS *params); void ossl_ffc_params_cleanup(FFC_PARAMS *params); void ossl_ffc_params_set0_pqg(FFC_PARAMS *params, BIGNUM *p, BIGNUM *q, BIGNUM *g); void ossl_ffc_params_get0_pqg(const FFC_PARAMS *params, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g); void ossl_ffc_params_set0_j(FFC_PARAMS *d, BIGNUM *j); int ossl_ffc_params_set_seed(FFC_PARAMS *params, const unsigned char *seed, size_t seedlen); void ossl_ffc_params_set_gindex(FFC_PARAMS *params, int index); void ossl_ffc_params_set_pcounter(FFC_PARAMS *params, int index); void ossl_ffc_params_set_h(FFC_PARAMS *params, int index); void ossl_ffc_params_set_flags(FFC_PARAMS *params, unsigned int flags); void ossl_ffc_params_enable_flags(FFC_PARAMS *params, unsigned int flags, int enable); void ossl_ffc_set_digest(FFC_PARAMS *params, const char *alg, const char *props); int ossl_ffc_params_set_validate_params(FFC_PARAMS *params, const unsigned char *seed, size_t seedlen, int counter); void ossl_ffc_params_get_validate_params(const FFC_PARAMS *params, unsigned char **seed, size_t *seedlen, int *pcounter); int ossl_ffc_params_copy(FFC_PARAMS *dst, const FFC_PARAMS *src); int ossl_ffc_params_cmp(const FFC_PARAMS *a, const FFC_PARAMS *b, int ignore_q); #ifndef FIPS_MODULE int ossl_ffc_params_print(BIO *bp, const FFC_PARAMS *ffc, int indent); #endif /* FIPS_MODULE */ int ossl_ffc_params_FIPS186_4_generate(OSSL_LIB_CTX *libctx, FFC_PARAMS *params, int type, size_t L, size_t N, int *res, BN_GENCB *cb); int ossl_ffc_params_FIPS186_2_generate(OSSL_LIB_CTX *libctx, FFC_PARAMS *params, int type, size_t L, size_t N, int *res, BN_GENCB *cb); int ossl_ffc_params_FIPS186_4_gen_verify(OSSL_LIB_CTX *libctx, FFC_PARAMS *params, int mode, int type, size_t L, size_t N, int *res, BN_GENCB *cb); int ossl_ffc_params_FIPS186_2_gen_verify(OSSL_LIB_CTX *libctx, FFC_PARAMS *params, int mode, int type, size_t L, size_t N, int *res, BN_GENCB *cb); int ossl_ffc_params_simple_validate(OSSL_LIB_CTX *libctx, const FFC_PARAMS *params, int paramstype, int *res); int ossl_ffc_params_full_validate(OSSL_LIB_CTX *libctx, const FFC_PARAMS *params, int paramstype, int *res); int ossl_ffc_params_FIPS186_4_validate(OSSL_LIB_CTX *libctx, const FFC_PARAMS *params, int type, int *res, BN_GENCB *cb); int ossl_ffc_params_FIPS186_2_validate(OSSL_LIB_CTX *libctx, const FFC_PARAMS *params, int type, int *res, BN_GENCB *cb); int ossl_ffc_generate_private_key(BN_CTX *ctx, const FFC_PARAMS *params, int N, int s, BIGNUM *priv); int ossl_ffc_params_validate_unverifiable_g(BN_CTX *ctx, BN_MONT_CTX *mont, const BIGNUM *p, const BIGNUM *q, const BIGNUM *g, BIGNUM *tmp, int *ret); int ossl_ffc_validate_public_key(const FFC_PARAMS *params, const BIGNUM *pub_key, int *ret); int ossl_ffc_validate_public_key_partial(const FFC_PARAMS *params, const BIGNUM *pub_key, int *ret); int ossl_ffc_validate_private_key(const BIGNUM *upper, const BIGNUM *priv_key, int *ret); int ossl_ffc_params_todata(const FFC_PARAMS *ffc, OSSL_PARAM_BLD *tmpl, OSSL_PARAM params[]); int ossl_ffc_params_fromdata(FFC_PARAMS *ffc, const OSSL_PARAM params[]); typedef struct dh_named_group_st DH_NAMED_GROUP; const DH_NAMED_GROUP *ossl_ffc_name_to_dh_named_group(const char *name); const DH_NAMED_GROUP *ossl_ffc_uid_to_dh_named_group(int uid); #ifndef OPENSSL_NO_DH const DH_NAMED_GROUP *ossl_ffc_numbers_to_dh_named_group(const BIGNUM *p, const BIGNUM *q, const BIGNUM *g); #endif int ossl_ffc_named_group_get_uid(const DH_NAMED_GROUP *group); const char *ossl_ffc_named_group_get_name(const DH_NAMED_GROUP *); #ifndef OPENSSL_NO_DH int ossl_ffc_named_group_get_keylength(const DH_NAMED_GROUP *group); const BIGNUM *ossl_ffc_named_group_get_q(const DH_NAMED_GROUP *group); int ossl_ffc_named_group_set(FFC_PARAMS *ffc, const DH_NAMED_GROUP *group); #endif #endif /* OSSL_INTERNAL_FFC_H */
./openssl/include/internal/cryptlib.h
/* * Copyright 1995-2023 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_INTERNAL_CRYPTLIB_H # define OSSL_INTERNAL_CRYPTLIB_H # pragma once # ifdef OPENSSL_USE_APPLINK # define BIO_FLAGS_UPLINK_INTERNAL 0x8000 # include "ms/uplink.h" # else # define BIO_FLAGS_UPLINK_INTERNAL 0 # endif # include "internal/common.h" # include <openssl/crypto.h> # include <openssl/buffer.h> # include <openssl/bio.h> # include <openssl/asn1.h> # include <openssl/err.h> typedef struct ex_callback_st EX_CALLBACK; DEFINE_STACK_OF(EX_CALLBACK) typedef struct mem_st MEM; DEFINE_LHASH_OF_EX(MEM); void OPENSSL_cpuid_setup(void); #if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) extern unsigned int OPENSSL_ia32cap_P[]; #endif void OPENSSL_showfatal(const char *fmta, ...); int ossl_do_ex_data_init(OSSL_LIB_CTX *ctx); void ossl_crypto_cleanup_all_ex_data_int(OSSL_LIB_CTX *ctx); int openssl_init_fork_handlers(void); int openssl_get_fork_id(void); char *ossl_safe_getenv(const char *name); extern CRYPTO_RWLOCK *memdbg_lock; int openssl_strerror_r(int errnum, char *buf, size_t buflen); # if !defined(OPENSSL_NO_STDIO) FILE *openssl_fopen(const char *filename, const char *mode); # else void *openssl_fopen(const char *filename, const char *mode); # endif uint32_t OPENSSL_rdtsc(void); size_t OPENSSL_instrument_bus(unsigned int *, size_t); size_t OPENSSL_instrument_bus2(unsigned int *, size_t, size_t); /* ex_data structures */ /* * Each structure type (sometimes called a class), that supports * exdata has a stack of callbacks for each instance. */ struct ex_callback_st { long argl; /* Arbitrary long */ void *argp; /* Arbitrary void * */ int priority; /* Priority ordering for freeing */ CRYPTO_EX_new *new_func; CRYPTO_EX_free *free_func; CRYPTO_EX_dup *dup_func; }; /* * The state for each class. This could just be a typedef, but * a structure allows future changes. */ typedef struct ex_callbacks_st { STACK_OF(EX_CALLBACK) *meth; } EX_CALLBACKS; typedef struct ossl_ex_data_global_st { CRYPTO_RWLOCK *ex_data_lock; EX_CALLBACKS ex_data[CRYPTO_EX_INDEX__COUNT]; } OSSL_EX_DATA_GLOBAL; /* OSSL_LIB_CTX */ # define OSSL_LIB_CTX_PROVIDER_STORE_RUN_ONCE_INDEX 0 # define OSSL_LIB_CTX_DEFAULT_METHOD_STORE_RUN_ONCE_INDEX 1 # define OSSL_LIB_CTX_METHOD_STORE_RUN_ONCE_INDEX 2 # define OSSL_LIB_CTX_MAX_RUN_ONCE 3 # define OSSL_LIB_CTX_EVP_METHOD_STORE_INDEX 0 # define OSSL_LIB_CTX_PROVIDER_STORE_INDEX 1 # define OSSL_LIB_CTX_PROPERTY_DEFN_INDEX 2 # define OSSL_LIB_CTX_PROPERTY_STRING_INDEX 3 # define OSSL_LIB_CTX_NAMEMAP_INDEX 4 # define OSSL_LIB_CTX_DRBG_INDEX 5 # define OSSL_LIB_CTX_DRBG_NONCE_INDEX 6 # define OSSL_LIB_CTX_RAND_CRNGT_INDEX 7 # ifdef FIPS_MODULE # define OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX 8 # endif # define OSSL_LIB_CTX_FIPS_PROV_INDEX 9 # define OSSL_LIB_CTX_ENCODER_STORE_INDEX 10 # define OSSL_LIB_CTX_DECODER_STORE_INDEX 11 # define OSSL_LIB_CTX_SELF_TEST_CB_INDEX 12 # define OSSL_LIB_CTX_BIO_PROV_INDEX 13 # define OSSL_LIB_CTX_GLOBAL_PROPERTIES 14 # define OSSL_LIB_CTX_STORE_LOADER_STORE_INDEX 15 # define OSSL_LIB_CTX_PROVIDER_CONF_INDEX 16 # define OSSL_LIB_CTX_BIO_CORE_INDEX 17 # define OSSL_LIB_CTX_CHILD_PROVIDER_INDEX 18 # define OSSL_LIB_CTX_THREAD_INDEX 19 # define OSSL_LIB_CTX_DECODER_CACHE_INDEX 20 # define OSSL_LIB_CTX_MAX_INDEXES 20 OSSL_LIB_CTX *ossl_lib_ctx_get_concrete(OSSL_LIB_CTX *ctx); int ossl_lib_ctx_is_default(OSSL_LIB_CTX *ctx); int ossl_lib_ctx_is_global_default(OSSL_LIB_CTX *ctx); /* Functions to retrieve pointers to data by index */ void *ossl_lib_ctx_get_data(OSSL_LIB_CTX *, int /* index */); void ossl_lib_ctx_default_deinit(void); OSSL_EX_DATA_GLOBAL *ossl_lib_ctx_get_ex_data_global(OSSL_LIB_CTX *ctx); const char *ossl_lib_ctx_get_descriptor(OSSL_LIB_CTX *libctx); OSSL_LIB_CTX *ossl_crypto_ex_data_get_ossl_lib_ctx(const CRYPTO_EX_DATA *ad); int ossl_crypto_new_ex_data_ex(OSSL_LIB_CTX *ctx, int class_index, void *obj, CRYPTO_EX_DATA *ad); int ossl_crypto_get_ex_new_index_ex(OSSL_LIB_CTX *ctx, int class_index, long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func, int priority); int ossl_crypto_free_ex_index_ex(OSSL_LIB_CTX *ctx, int class_index, int idx); /* Function for simple binary search */ /* Flags */ # define OSSL_BSEARCH_VALUE_ON_NOMATCH 0x01 # define OSSL_BSEARCH_FIRST_VALUE_ON_MATCH 0x02 const void *ossl_bsearch(const void *key, const void *base, int num, int size, int (*cmp) (const void *, const void *), int flags); char *ossl_sk_ASN1_UTF8STRING2text(STACK_OF(ASN1_UTF8STRING) *text, const char *sep, size_t max_len); char *ossl_ipaddr_to_asc(unsigned char *p, int len); char *ossl_buf2hexstr_sep(const unsigned char *buf, long buflen, char sep); unsigned char *ossl_hexstr2buf_sep(const char *str, long *buflen, const char sep); #endif
./openssl/include/internal/quic_cfq.h
/* * Copyright 2022-2023 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_CFQ_H # define OSSL_QUIC_CFQ_H # include <openssl/ssl.h> # include "internal/quic_types.h" # include "internal/quic_predef.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Control Frame Queue Item * ============================= * * The CFQ item structure has a public and a private part. This structure * documents the public part. */ typedef struct quic_cfq_item_st QUIC_CFQ_ITEM; struct quic_cfq_item_st { /* * These fields are not used by the CFQ, but are a convenience to assist the * TXPIM in keeping a list of GCR control frames which were sent in a * packet. They may be used for any purpose. */ QUIC_CFQ_ITEM *pkt_prev, *pkt_next; /* All other fields are private; use ossl_quic_cfq_item_* accessors. */ }; # define QUIC_CFQ_STATE_NEW 0 # define QUIC_CFQ_STATE_TX 1 /* If set, do not retransmit on loss */ #define QUIC_CFQ_ITEM_FLAG_UNRELIABLE (1U << 0) /* Returns the frame type of a CFQ item. */ uint64_t ossl_quic_cfq_item_get_frame_type(const QUIC_CFQ_ITEM *item); /* Returns a pointer to the encoded buffer of a CFQ item. */ const unsigned char *ossl_quic_cfq_item_get_encoded(const QUIC_CFQ_ITEM *item); /* Returns the length of the encoded buffer in bytes. */ size_t ossl_quic_cfq_item_get_encoded_len(const QUIC_CFQ_ITEM *item); /* Returns the CFQ item state, a QUIC_CFQ_STATE_* value. */ int ossl_quic_cfq_item_get_state(const QUIC_CFQ_ITEM *item); /* Returns the PN space for the CFQ item. */ uint32_t ossl_quic_cfq_item_get_pn_space(const QUIC_CFQ_ITEM *item); /* Returns 1 if this is an unreliable frame. */ int ossl_quic_cfq_item_is_unreliable(const QUIC_CFQ_ITEM *item); /* * QUIC Control Frame Queue * ======================== */ QUIC_CFQ *ossl_quic_cfq_new(void); void ossl_quic_cfq_free(QUIC_CFQ *cfq); /* * Input Side * ---------- */ /* * Enqueue a frame to the CFQ. * * encoded points to the opaque encoded frame. * * free_cb is called by the CFQ when the buffer is no longer needed; * free_cb_arg is an opaque value passed to free_cb. * * priority determines the relative ordering of control frames in a packet. * Lower numerical values for priority mean that a frame should come earlier in * a packet. pn_space is a QUIC_PN_SPACE_* value. * * On success, returns a QUIC_CFQ_ITEM pointer which acts as a handle to * the queued frame. On failure, returns NULL. * * The frame is initially in the TX state, so there is no need to call * ossl_quic_cfq_mark_tx() immediately after calling this function. * * The frame type is duplicated as the frame_type argument here, even though it * is also encoded into the buffer. This allows the caller to determine the * frame type if desired without having to decode the frame. * * flags is zero or more QUIC_CFQ_ITEM_FLAG values. */ typedef void (cfq_free_cb)(unsigned char *buf, size_t buf_len, void *arg); QUIC_CFQ_ITEM *ossl_quic_cfq_add_frame(QUIC_CFQ *cfq, uint32_t priority, uint32_t pn_space, uint64_t frame_type, uint32_t flags, const unsigned char *encoded, size_t encoded_len, cfq_free_cb *free_cb, void *free_cb_arg); /* * Effects an immediate transition of the given CFQ item to the TX state. */ void ossl_quic_cfq_mark_tx(QUIC_CFQ *cfq, QUIC_CFQ_ITEM *item); /* * Effects an immediate transition of the given CFQ item to the NEW state, * allowing the frame to be retransmitted. If priority is not UINT32_MAX, * the priority is changed to the given value. */ void ossl_quic_cfq_mark_lost(QUIC_CFQ *cfq, QUIC_CFQ_ITEM *item, uint32_t priority); /* * Releases a CFQ item. The item may be in either state (NEW or TX) prior to the * call. The QUIC_CFQ_ITEM pointer must not be used following this call. */ void ossl_quic_cfq_release(QUIC_CFQ *cfq, QUIC_CFQ_ITEM *item); /* * Output Side * ----------- */ /* * Gets the highest priority CFQ item in the given PN space awaiting * transmission. If there are none, returns NULL. */ QUIC_CFQ_ITEM *ossl_quic_cfq_get_priority_head(const QUIC_CFQ *cfq, uint32_t pn_space); /* * Given a CFQ item, gets the next CFQ item awaiting transmission in priority * order in the given PN space. In other words, given the return value of * ossl_quic_cfq_get_priority_head(), returns the next-lower priority item. * Returns NULL if the given item is the last item in priority order. */ QUIC_CFQ_ITEM *ossl_quic_cfq_item_get_priority_next(const QUIC_CFQ_ITEM *item, uint32_t pn_space); # endif #endif
./openssl/include/internal/bio.h
/* * Copyright 2016-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_INTERNAL_BIO_H # define OSSL_INTERNAL_BIO_H # pragma once # include <openssl/core.h> # include <openssl/bio.h> struct bio_method_st { int type; char *name; int (*bwrite) (BIO *, const char *, size_t, size_t *); int (*bwrite_old) (BIO *, const char *, int); int (*bread) (BIO *, char *, size_t, size_t *); int (*bread_old) (BIO *, char *, int); int (*bputs) (BIO *, const char *); int (*bgets) (BIO *, char *, int); long (*ctrl) (BIO *, int, long, void *); int (*create) (BIO *); int (*destroy) (BIO *); long (*callback_ctrl) (BIO *, int, BIO_info_cb *); int (*bsendmmsg) (BIO *, BIO_MSG *, size_t, size_t, uint64_t, size_t *); int (*brecvmmsg) (BIO *, BIO_MSG *, size_t, size_t, uint64_t, size_t *); }; void bio_free_ex_data(BIO *bio); void bio_cleanup(void); /* Old style to new style BIO_METHOD conversion functions */ int bwrite_conv(BIO *bio, const char *data, size_t datal, size_t *written); int bread_conv(BIO *bio, char *data, size_t datal, size_t *read); /* Changes to these internal BIOs must also update include/openssl/bio.h */ # define BIO_CTRL_SET_KTLS 72 # define BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG 74 # define BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG 75 # define BIO_CTRL_SET_KTLS_TX_ZEROCOPY_SENDFILE 90 /* * This is used with socket BIOs: * BIO_FLAGS_KTLS_TX means we are using ktls with this BIO for sending. * BIO_FLAGS_KTLS_TX_CTRL_MSG means we are about to send a ctrl message next. * BIO_FLAGS_KTLS_RX means we are using ktls with this BIO for receiving. * BIO_FLAGS_KTLS_TX_ZEROCOPY_SENDFILE means we are using the zerocopy mode with * this BIO for sending using sendfile. */ # define BIO_FLAGS_KTLS_TX_CTRL_MSG 0x1000 # define BIO_FLAGS_KTLS_RX 0x2000 # define BIO_FLAGS_KTLS_TX 0x4000 # define BIO_FLAGS_KTLS_TX_ZEROCOPY_SENDFILE 0x8000 /* KTLS related controls and flags */ # define BIO_set_ktls_flag(b, is_tx) \ BIO_set_flags(b, (is_tx) ? BIO_FLAGS_KTLS_TX : BIO_FLAGS_KTLS_RX) # define BIO_should_ktls_flag(b, is_tx) \ BIO_test_flags(b, (is_tx) ? BIO_FLAGS_KTLS_TX : BIO_FLAGS_KTLS_RX) # define BIO_set_ktls_ctrl_msg_flag(b) \ BIO_set_flags(b, BIO_FLAGS_KTLS_TX_CTRL_MSG) # define BIO_should_ktls_ctrl_msg_flag(b) \ BIO_test_flags(b, BIO_FLAGS_KTLS_TX_CTRL_MSG) # define BIO_clear_ktls_ctrl_msg_flag(b) \ BIO_clear_flags(b, BIO_FLAGS_KTLS_TX_CTRL_MSG) # define BIO_set_ktls_zerocopy_sendfile_flag(b) \ BIO_set_flags(b, BIO_FLAGS_KTLS_TX_ZEROCOPY_SENDFILE) # define BIO_set_ktls(b, keyblob, is_tx) \ BIO_ctrl(b, BIO_CTRL_SET_KTLS, is_tx, keyblob) # define BIO_set_ktls_ctrl_msg(b, record_type) \ BIO_ctrl(b, BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG, record_type, NULL) # define BIO_clear_ktls_ctrl_msg(b) \ BIO_ctrl(b, BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG, 0, NULL) # define BIO_set_ktls_tx_zerocopy_sendfile(b) \ BIO_ctrl(b, BIO_CTRL_SET_KTLS_TX_ZEROCOPY_SENDFILE, 0, NULL) /* Functions to allow the core to offer the CORE_BIO type to providers */ OSSL_CORE_BIO *ossl_core_bio_new_from_bio(BIO *bio); OSSL_CORE_BIO *ossl_core_bio_new_file(const char *filename, const char *mode); OSSL_CORE_BIO *ossl_core_bio_new_mem_buf(const void *buf, int len); int ossl_core_bio_read_ex(OSSL_CORE_BIO *cb, void *data, size_t dlen, size_t *readbytes); int ossl_core_bio_write_ex(OSSL_CORE_BIO *cb, const void *data, size_t dlen, size_t *written); int ossl_core_bio_gets(OSSL_CORE_BIO *cb, char *buf, int size); int ossl_core_bio_puts(OSSL_CORE_BIO *cb, const char *buf); long ossl_core_bio_ctrl(OSSL_CORE_BIO *cb, int cmd, long larg, void *parg); int ossl_core_bio_up_ref(OSSL_CORE_BIO *cb); int ossl_core_bio_free(OSSL_CORE_BIO *cb); int ossl_core_bio_vprintf(OSSL_CORE_BIO *cb, const char *format, va_list args); int ossl_bio_init_core(OSSL_LIB_CTX *libctx, const OSSL_DISPATCH *fns); #endif
./openssl/include/internal/quic_error.h
/* * Copyright 2022-2023 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_ERROR_H # define OSSL_QUIC_ERROR_H # include <openssl/ssl.h> # ifndef OPENSSL_NO_QUIC /* RFC 9000 Section 20.1 */ # define QUIC_ERR_NO_ERROR 0x00 # define QUIC_ERR_INTERNAL_ERROR 0x01 # define QUIC_ERR_CONNECTION_REFUSED 0x02 # define QUIC_ERR_FLOW_CONTROL_ERROR 0x03 # define QUIC_ERR_STREAM_LIMIT_ERROR 0x04 # define QUIC_ERR_STREAM_STATE_ERROR 0x05 # define QUIC_ERR_FINAL_SIZE_ERROR 0x06 # define QUIC_ERR_FRAME_ENCODING_ERROR 0x07 # define QUIC_ERR_TRANSPORT_PARAMETER_ERROR 0x08 # define QUIC_ERR_CONNECTION_ID_LIMIT_ERROR 0x09 # define QUIC_ERR_PROTOCOL_VIOLATION 0x0A # define QUIC_ERR_INVALID_TOKEN 0x0B # define QUIC_ERR_APPLICATION_ERROR 0x0C # define QUIC_ERR_CRYPTO_BUFFER_EXCEEDED 0x0D # define QUIC_ERR_KEY_UPDATE_ERROR 0x0E # define QUIC_ERR_AEAD_LIMIT_REACHED 0x0F # define QUIC_ERR_NO_VIABLE_PATH 0x10 /* Inclusive range for handshake-specific errors. */ # define QUIC_ERR_CRYPTO_ERR_BEGIN 0x0100 # define QUIC_ERR_CRYPTO_ERR_END 0x01FF # define QUIC_ERR_CRYPTO_ERR(X) \ (QUIC_ERR_CRYPTO_ERR_BEGIN + (X)) # define QUIC_ERR_CRYPTO_UNEXPECTED_MESSAGE \ QUIC_ERR_CRYPTO_ERR(SSL3_AD_UNEXPECTED_MESSAGE) # define QUIC_ERR_CRYPTO_MISSING_EXT \ QUIC_ERR_CRYPTO_ERR(TLS13_AD_MISSING_EXTENSION) # define QUIC_ERR_CRYPTO_NO_APP_PROTO \ QUIC_ERR_CRYPTO_ERR(TLS1_AD_NO_APPLICATION_PROTOCOL) const char *ossl_quic_err_to_string(uint64_t error_code); # endif #endif
./openssl/include/internal/namemap.h
/* * Copyright 2019-2021 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/cryptlib.h" typedef struct ossl_namemap_st OSSL_NAMEMAP; OSSL_NAMEMAP *ossl_namemap_stored(OSSL_LIB_CTX *libctx); OSSL_NAMEMAP *ossl_namemap_new(void); void ossl_namemap_free(OSSL_NAMEMAP *namemap); int ossl_namemap_empty(OSSL_NAMEMAP *namemap); int ossl_namemap_add_name(OSSL_NAMEMAP *namemap, int number, const char *name); /* * The number<->name relationship is 1<->many * Therefore, the name->number mapping is a simple function, while the * number->name mapping is an iterator. */ int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name); int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap, const char *name, size_t name_len); const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number, size_t idx); int ossl_namemap_doall_names(const OSSL_NAMEMAP *namemap, int number, void (*fn)(const char *name, void *data), void *data); /* * A utility that handles several names in a string, divided by a given * separator. */ int ossl_namemap_add_names(OSSL_NAMEMAP *namemap, int number, const char *names, const char separator);
./openssl/include/internal/quic_txpim.h
/* * Copyright 2022-2023 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_TXPIM_H # define OSSL_QUIC_TXPIM_H # include <openssl/ssl.h> # include "internal/quic_types.h" # include "internal/quic_predef.h" # include "internal/quic_cfq.h" # include "internal/quic_ackm.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Transmitted Packet Information Manager * =========================================== */ typedef struct quic_txpim_pkt_st { /* ACKM-specific data. Caller should fill this. */ OSSL_ACKM_TX_PKT ackm_pkt; /* Linked list of CFQ items in this packet. */ QUIC_CFQ_ITEM *retx_head; /* Reserved for FIFD use. */ QUIC_FIFD *fifd; /* Regenerate-strategy frames. */ unsigned int had_handshake_done_frame : 1; unsigned int had_max_data_frame : 1; unsigned int had_max_streams_bidi_frame : 1; unsigned int had_max_streams_uni_frame : 1; unsigned int had_ack_frame : 1; unsigned int had_conn_close : 1; /* Private data follows. */ } QUIC_TXPIM_PKT; /* Represents a range of bytes in an application or CRYPTO stream. */ typedef struct quic_txpim_chunk_st { /* The stream ID, or UINT64_MAX for the CRYPTO stream. */ uint64_t stream_id; /* * The inclusive range of bytes in the stream. Exceptionally, if end < * start, designates a frame of zero length (used for FIN-only frames). In * this case end is the number of the final byte (i.e., one less than the * final size of the stream). */ uint64_t start, end; /* * Whether a FIN was sent for this stream in the packet. Not valid for * CRYPTO stream. */ unsigned int has_fin : 1; /* * If set, a STOP_SENDING frame was sent for this stream ID. (If no data was * sent for the stream, set end < start.) */ unsigned int has_stop_sending : 1; /* * If set, a RESET_STREAM frame was sent for this stream ID. (If no data was * sent for the stream, set end < start.) */ unsigned int has_reset_stream : 1; } QUIC_TXPIM_CHUNK; QUIC_TXPIM *ossl_quic_txpim_new(void); /* * Frees the TXPIM. All QUIC_TXPIM_PKTs which have been handed out by the TXPIM * must be released via a call to ossl_quic_txpim_pkt_release() before calling * this function. */ void ossl_quic_txpim_free(QUIC_TXPIM *txpim); /* * Allocates a new QUIC_TXPIM_PKT structure from the pool. Returns NULL on * failure. The returned structure is cleared of all data and is in a fresh * initial state. */ QUIC_TXPIM_PKT *ossl_quic_txpim_pkt_alloc(QUIC_TXPIM *txpim); /* * Releases the TXPIM packet, returning it to the pool. */ void ossl_quic_txpim_pkt_release(QUIC_TXPIM *txpim, QUIC_TXPIM_PKT *fpkt); /* Clears the chunk list of the packet, removing all entries. */ void ossl_quic_txpim_pkt_clear_chunks(QUIC_TXPIM_PKT *fpkt); /* Appends a chunk to the packet. The structure is copied. */ int ossl_quic_txpim_pkt_append_chunk(QUIC_TXPIM_PKT *fpkt, const QUIC_TXPIM_CHUNK *chunk); /* Adds a CFQ item to the packet by prepending it to the retx_head list. */ void ossl_quic_txpim_pkt_add_cfq_item(QUIC_TXPIM_PKT *fpkt, QUIC_CFQ_ITEM *item); /* * Returns a pointer to an array of stream chunk information structures for the * given packet. The caller must call ossl_quic_txpim_pkt_get_num_chunks() to * determine the length of this array. The returned pointer is invalidated * if the chunk list is mutated, for example via a call to * ossl_quic_txpim_pkt_append_chunk() or ossl_quic_txpim_pkt_clear_chunks(). * * The chunks are sorted by (stream_id, start) in ascending order. */ const QUIC_TXPIM_CHUNK *ossl_quic_txpim_pkt_get_chunks(const QUIC_TXPIM_PKT *fpkt); /* * Returns the number of entries in the array returned by * ossl_quic_txpim_pkt_get_chunks(). */ size_t ossl_quic_txpim_pkt_get_num_chunks(const QUIC_TXPIM_PKT *fpkt); /* * Returns the number of QUIC_TXPIM_PKTs allocated by the given TXPIM that have * yet to be returned to the TXPIM. */ size_t ossl_quic_txpim_get_in_use(const QUIC_TXPIM *txpim); # endif #endif
./openssl/include/internal/tlsgroups.h
/* * Copyright 2017-2021 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_INTERNAL_TLSGROUPS_H # define OSSL_INTERNAL_TLSGROUPS_H # pragma once # define OSSL_TLS_GROUP_ID_sect163k1 0x0001 # define OSSL_TLS_GROUP_ID_sect163r1 0x0002 # define OSSL_TLS_GROUP_ID_sect163r2 0x0003 # define OSSL_TLS_GROUP_ID_sect193r1 0x0004 # define OSSL_TLS_GROUP_ID_sect193r2 0x0005 # define OSSL_TLS_GROUP_ID_sect233k1 0x0006 # define OSSL_TLS_GROUP_ID_sect233r1 0x0007 # define OSSL_TLS_GROUP_ID_sect239k1 0x0008 # define OSSL_TLS_GROUP_ID_sect283k1 0x0009 # define OSSL_TLS_GROUP_ID_sect283r1 0x000A # define OSSL_TLS_GROUP_ID_sect409k1 0x000B # define OSSL_TLS_GROUP_ID_sect409r1 0x000C # define OSSL_TLS_GROUP_ID_sect571k1 0x000D # define OSSL_TLS_GROUP_ID_sect571r1 0x000E # define OSSL_TLS_GROUP_ID_secp160k1 0x000F # define OSSL_TLS_GROUP_ID_secp160r1 0x0010 # define OSSL_TLS_GROUP_ID_secp160r2 0x0011 # define OSSL_TLS_GROUP_ID_secp192k1 0x0012 # define OSSL_TLS_GROUP_ID_secp192r1 0x0013 # define OSSL_TLS_GROUP_ID_secp224k1 0x0014 # define OSSL_TLS_GROUP_ID_secp224r1 0x0015 # define OSSL_TLS_GROUP_ID_secp256k1 0x0016 # define OSSL_TLS_GROUP_ID_secp256r1 0x0017 # define OSSL_TLS_GROUP_ID_secp384r1 0x0018 # define OSSL_TLS_GROUP_ID_secp521r1 0x0019 # define OSSL_TLS_GROUP_ID_brainpoolP256r1 0x001A # define OSSL_TLS_GROUP_ID_brainpoolP384r1 0x001B # define OSSL_TLS_GROUP_ID_brainpoolP512r1 0x001C # define OSSL_TLS_GROUP_ID_x25519 0x001D # define OSSL_TLS_GROUP_ID_x448 0x001E # define OSSL_TLS_GROUP_ID_brainpoolP256r1_tls13 0x001F # define OSSL_TLS_GROUP_ID_brainpoolP384r1_tls13 0x0020 # define OSSL_TLS_GROUP_ID_brainpoolP512r1_tls13 0x0021 # define OSSL_TLS_GROUP_ID_gc256A 0x0022 # define OSSL_TLS_GROUP_ID_gc256B 0x0023 # define OSSL_TLS_GROUP_ID_gc256C 0x0024 # define OSSL_TLS_GROUP_ID_gc256D 0x0025 # define OSSL_TLS_GROUP_ID_gc512A 0x0026 # define OSSL_TLS_GROUP_ID_gc512B 0x0027 # define OSSL_TLS_GROUP_ID_gc512C 0x0028 # define OSSL_TLS_GROUP_ID_ffdhe2048 0x0100 # define OSSL_TLS_GROUP_ID_ffdhe3072 0x0101 # define OSSL_TLS_GROUP_ID_ffdhe4096 0x0102 # define OSSL_TLS_GROUP_ID_ffdhe6144 0x0103 # define OSSL_TLS_GROUP_ID_ffdhe8192 0x0104 #endif
./openssl/include/internal/quic_statm.h
/* * Copyright 2022-2023 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_STATS_H # define OSSL_QUIC_STATS_H # include <openssl/ssl.h> # include "internal/time.h" # include "internal/quic_predef.h" # ifndef OPENSSL_NO_QUIC struct ossl_statm_st { OSSL_TIME smoothed_rtt, latest_rtt, min_rtt, rtt_variance; char have_first_sample; }; typedef struct ossl_rtt_info_st { /* As defined in RFC 9002. */ OSSL_TIME smoothed_rtt, latest_rtt, rtt_variance, min_rtt; } OSSL_RTT_INFO; int ossl_statm_init(OSSL_STATM *statm); void ossl_statm_destroy(OSSL_STATM *statm); void ossl_statm_get_rtt_info(OSSL_STATM *statm, OSSL_RTT_INFO *rtt_info); void ossl_statm_update_rtt(OSSL_STATM *statm, OSSL_TIME ack_delay, OSSL_TIME override_latest_rtt); # endif #endif
./openssl/include/internal/unicode.h
/* * Copyright 2021 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_INTERNAL_UNICODE_H # define OSSL_INTERNAL_UNICODE_H # pragma once typedef enum { SURROGATE_MIN = 0xd800UL, SURROGATE_MAX = 0xdfffUL, UNICODE_MAX = 0x10ffffUL, UNICODE_LIMIT } UNICODE_CONSTANTS; static ossl_unused ossl_inline int is_unicode_surrogate(unsigned long value) { return value >= SURROGATE_MIN && value <= SURROGATE_MAX; } static ossl_unused ossl_inline int is_unicode_valid(unsigned long value) { return value <= UNICODE_MAX && !is_unicode_surrogate(value); } #endif
./openssl/include/internal/refcount.h
/* * Copyright 2016-2023 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_INTERNAL_REFCOUNT_H # define OSSL_INTERNAL_REFCOUNT_H # pragma once # include <openssl/e_os2.h> # include <openssl/trace.h> # include <openssl/err.h> # if defined(OPENSSL_THREADS) && !defined(OPENSSL_DEV_NO_ATOMICS) # if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \ && !defined(__STDC_NO_ATOMICS__) # include <stdatomic.h> # define HAVE_C11_ATOMICS # endif # if defined(HAVE_C11_ATOMICS) && defined(ATOMIC_INT_LOCK_FREE) \ && ATOMIC_INT_LOCK_FREE > 0 # define HAVE_ATOMICS 1 typedef struct { _Atomic int val; } CRYPTO_REF_COUNT; static inline int CRYPTO_UP_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = atomic_fetch_add_explicit(&refcnt->val, 1, memory_order_relaxed) + 1; return 1; } /* * Changes to shared structure other than reference counter have to be * serialized. And any kind of serialization implies a release fence. This * means that by the time reference counter is decremented all other * changes are visible on all processors. Hence decrement itself can be * relaxed. In case it hits zero, object will be destructed. Since it's * last use of the object, destructor programmer might reason that access * to mutable members doesn't have to be serialized anymore, which would * otherwise imply an acquire fence. Hence conditional acquire fence... */ static inline int CRYPTO_DOWN_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = atomic_fetch_sub_explicit(&refcnt->val, 1, memory_order_relaxed) - 1; if (*ret == 0) atomic_thread_fence(memory_order_acquire); return 1; } static inline int CRYPTO_GET_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = atomic_load_explicit(&refcnt->val, memory_order_relaxed); return 1; } # elif defined(__GNUC__) && defined(__ATOMIC_RELAXED) && __GCC_ATOMIC_INT_LOCK_FREE > 0 # define HAVE_ATOMICS 1 typedef struct { int val; } CRYPTO_REF_COUNT; static __inline__ int CRYPTO_UP_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = __atomic_fetch_add(&refcnt->val, 1, __ATOMIC_RELAXED) + 1; return 1; } static __inline__ int CRYPTO_DOWN_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = __atomic_fetch_sub(&refcnt->val, 1, __ATOMIC_RELAXED) - 1; if (*ret == 0) __atomic_thread_fence(__ATOMIC_ACQUIRE); return 1; } static __inline__ int CRYPTO_GET_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = __atomic_load_n(&refcnt->val, __ATOMIC_RELAXED); return 1; } # elif defined(__ICL) && defined(_WIN32) # define HAVE_ATOMICS 1 typedef struct { volatile int val; } CRYPTO_REF_COUNT; static __inline int CRYPTO_UP_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedExchangeAdd((void *)&refcnt->val, 1) + 1; return 1; } static __inline int CRYPTO_DOWN_REF(CRYPTO_REF_COUNT *val, int *refcnt) { *ret = _InterlockedExchangeAdd((void *)&refcnt->val, -1) - 1; return 1; } static __inline int CRYPTO_GET_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedOr((void *)&refcnt->val, 0); return 1; } # elif defined(_MSC_VER) && _MSC_VER>=1200 # define HAVE_ATOMICS 1 typedef struct { volatile int val; } CRYPTO_REF_COUNT; # if (defined(_M_ARM) && _M_ARM>=7 && !defined(_WIN32_WCE)) || defined(_M_ARM64) # include <intrin.h> # if defined(_M_ARM64) && !defined(_ARM_BARRIER_ISH) # define _ARM_BARRIER_ISH _ARM64_BARRIER_ISH # endif static __inline int CRYPTO_UP_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedExchangeAdd_nf(&refcnt->val, 1) + 1; return 1; } static __inline int CRYPTO_DOWN_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedExchangeAdd_nf(&refcnt->val, -1) - 1; if (*ret == 0) __dmb(_ARM_BARRIER_ISH); return 1; } static __inline int CRYPTO_GET_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedOr_nf((void *)&refcnt->val, 0); return 1; } # else # if !defined(_WIN32_WCE) # pragma intrinsic(_InterlockedExchangeAdd) # else # if _WIN32_WCE >= 0x600 extern long __cdecl _InterlockedExchangeAdd(long volatile*, long); # else /* under Windows CE we still have old-style Interlocked* functions */ extern long __cdecl InterlockedExchangeAdd(long volatile*, long); # define _InterlockedExchangeAdd InterlockedExchangeAdd # endif # endif static __inline int CRYPTO_UP_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedExchangeAdd(&refcnt->val, 1) + 1; return 1; } static __inline int CRYPTO_DOWN_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedExchangeAdd(&refcnt->val, -1) - 1; return 1; } static __inline int CRYPTO_GET_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = _InterlockedExchangeAdd(&refcnt->val, 0); return 1; } # endif # endif # endif /* !OPENSSL_DEV_NO_ATOMICS */ /* * All the refcounting implementations above define HAVE_ATOMICS, so if it's * still undefined here (such as when OPENSSL_DEV_NO_ATOMICS is defined), it * means we need to implement a fallback. This fallback uses locks. */ # ifndef HAVE_ATOMICS typedef struct { int val; # ifdef OPENSSL_THREADS CRYPTO_RWLOCK *lock; # endif } CRYPTO_REF_COUNT; # ifdef OPENSSL_THREADS static ossl_unused ossl_inline int CRYPTO_UP_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { return CRYPTO_atomic_add(&refcnt->val, 1, ret, refcnt->lock); } static ossl_unused ossl_inline int CRYPTO_DOWN_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { return CRYPTO_atomic_add(&refcnt->val, -1, ret, refcnt->lock); } static ossl_unused ossl_inline int CRYPTO_GET_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { return CRYPTO_atomic_load_int(&refcnt->val, ret, refcnt->lock); } # define CRYPTO_NEW_FREE_DEFINED 1 static ossl_unused ossl_inline int CRYPTO_NEW_REF(CRYPTO_REF_COUNT *refcnt, int n) { refcnt->val = n; refcnt->lock = CRYPTO_THREAD_lock_new(); if (refcnt->lock == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); return 0; } return 1; } static ossl_unused ossl_inline void CRYPTO_FREE_REF(CRYPTO_REF_COUNT *refcnt) \ { if (refcnt != NULL) CRYPTO_THREAD_lock_free(refcnt->lock); } # else /* OPENSSL_THREADS */ static ossl_unused ossl_inline int CRYPTO_UP_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { refcnt->val++; *ret = refcnt->val; return 1; } static ossl_unused ossl_inline int CRYPTO_DOWN_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { refcnt->val--; *ret = refcnt->val; return 1; } static ossl_unused ossl_inline int CRYPTO_GET_REF(CRYPTO_REF_COUNT *refcnt, int *ret) { *ret = refcnt->val; return 1; } # endif /* OPENSSL_THREADS */ # endif # ifndef CRYPTO_NEW_FREE_DEFINED static ossl_unused ossl_inline int CRYPTO_NEW_REF(CRYPTO_REF_COUNT *refcnt, int n) { refcnt->val = n; return 1; } static ossl_unused ossl_inline void CRYPTO_FREE_REF(CRYPTO_REF_COUNT *refcnt) \ { } # endif /* CRYPTO_NEW_FREE_DEFINED */ #undef CRYPTO_NEW_FREE_DEFINED # if !defined(NDEBUG) && !defined(OPENSSL_NO_STDIO) # define REF_ASSERT_ISNT(test) \ (void)((test) ? (OPENSSL_die("refcount error", __FILE__, __LINE__), 1) : 0) # else # define REF_ASSERT_ISNT(i) # endif # define REF_PRINT_EX(text, count, object) \ OSSL_TRACE3(REF_COUNT, "%p:%4d:%s\n", (object), (count), (text)); # define REF_PRINT_COUNT(text, object) \ REF_PRINT_EX(text, object->references.val, (void *)object) #endif
./openssl/include/internal/recordmethod.h
/* * Copyright 2022-2023 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_INTERNAL_RECORDMETHOD_H # define OSSL_INTERNAL_RECORDMETHOD_H # pragma once # include <openssl/ssl.h> /* * We use the term "record" here to refer to a packet of data. Records are * typically protected via a cipher and MAC, or an AEAD cipher (although not * always). This usage of the term record is consistent with the TLS concept. * In QUIC the term "record" is not used but it is analogous to the QUIC term * "packet". The interface in this file applies to all protocols that protect * records/packets of data, i.e. (D)TLS and QUIC. The term record is used to * refer to both contexts. */ /* * An OSSL_RECORD_METHOD is a protocol specific method which provides the * functions for reading and writing records for that protocol. Which * OSSL_RECORD_METHOD to use for a given protocol is defined by the SSL_METHOD. */ typedef struct ossl_record_method_st OSSL_RECORD_METHOD; /* * An OSSL_RECORD_LAYER is just an externally defined opaque pointer created by * the method */ typedef struct ossl_record_layer_st OSSL_RECORD_LAYER; # define OSSL_RECORD_ROLE_CLIENT 0 # define OSSL_RECORD_ROLE_SERVER 1 # define OSSL_RECORD_DIRECTION_READ 0 # define OSSL_RECORD_DIRECTION_WRITE 1 /* * Protection level. For <= TLSv1.2 only "NONE" and "APPLICATION" are used. */ # define OSSL_RECORD_PROTECTION_LEVEL_NONE 0 # define OSSL_RECORD_PROTECTION_LEVEL_EARLY 1 # define OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE 2 # define OSSL_RECORD_PROTECTION_LEVEL_APPLICATION 3 # define OSSL_RECORD_RETURN_SUCCESS 1 # define OSSL_RECORD_RETURN_RETRY 0 # define OSSL_RECORD_RETURN_NON_FATAL_ERR -1 # define OSSL_RECORD_RETURN_FATAL -2 # define OSSL_RECORD_RETURN_EOF -3 /* * Template for creating a record. A record consists of the |type| of data it * will contain (e.g. alert, handshake, application data, etc) along with a * buffer of payload data in |buf| of length |buflen|. */ struct ossl_record_template_st { unsigned char type; unsigned int version; const unsigned char *buf; size_t buflen; }; typedef struct ossl_record_template_st OSSL_RECORD_TEMPLATE; /* * Rather than a "method" approach, we could make this fetchable - Should we? * There could be some complexity in finding suitable record layer implementations * e.g. we need to find one that matches the negotiated protocol, cipher, * extensions, etc. The selection_cb approach given above doesn't work so well * if unknown third party providers with OSSL_RECORD_METHOD implementations are * loaded. */ /* * If this becomes public API then we will need functions to create and * free an OSSL_RECORD_METHOD, as well as functions to get/set the various * function pointers....unless we make it fetchable. */ struct ossl_record_method_st { /* * Create a new OSSL_RECORD_LAYER object for handling the protocol version * set by |vers|. |role| is 0 for client and 1 for server. |direction| * indicates either read or write. |level| is the protection level as * described above. |settings| are mandatory settings that will cause the * new() call to fail if they are not understood (for example to require * Encrypt-Then-Mac support). |options| are optional settings that will not * cause the new() call to fail if they are not understood (for example * whether to use "read ahead" or not). * * The BIO in |transport| is the BIO for the underlying transport layer. * Where the direction is "read", then this BIO will only ever be used for * reading data. Where the direction is "write", then this BIO will only * every be used for writing data. * * An SSL object will always have at least 2 OSSL_RECORD_LAYER objects in * force at any one time (one for reading and one for writing). In some * protocols more than 2 might be used (e.g. in DTLS for retransmitting * messages from an earlier epoch). * * The created OSSL_RECORD_LAYER object is stored in *ret on success (or * NULL otherwise). The return value will be one of * OSSL_RECORD_RETURN_SUCCESS, OSSL_RECORD_RETURN_FATAL or * OSSL_RECORD_RETURN_NON_FATAL. A non-fatal return means that creation of * the record layer has failed because it is unsuitable, but an alternative * record layer can be tried instead. */ /* * If we eventually make this fetchable then we will need to use something * other than EVP_CIPHER. Also mactype would not be a NID, but a string. For * now though, this works. */ int (*new_record_layer)(OSSL_LIB_CTX *libctx, const char *propq, int vers, int role, int direction, int level, uint16_t epoch, unsigned char *secret, size_t secretlen, unsigned char *key, size_t keylen, unsigned char *iv, size_t ivlen, unsigned char *mackey, size_t mackeylen, const EVP_CIPHER *ciph, size_t taglen, int mactype, const EVP_MD *md, COMP_METHOD *comp, const EVP_MD *kdfdigest, BIO *prev, BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer, const OSSL_PARAM *settings, const OSSL_PARAM *options, const OSSL_DISPATCH *fns, void *cbarg, void *rlarg, OSSL_RECORD_LAYER **ret); int (*free)(OSSL_RECORD_LAYER *rl); /* Returns 1 if we have unprocessed data buffered or 0 otherwise */ int (*unprocessed_read_pending)(OSSL_RECORD_LAYER *rl); /* * Returns 1 if we have processed data buffered that can be read or 0 otherwise * - not necessarily app data */ int (*processed_read_pending)(OSSL_RECORD_LAYER *rl); /* * The amount of processed app data that is internally buffered and * available to read */ size_t (*app_data_pending)(OSSL_RECORD_LAYER *rl); /* * Find out the maximum number of records that the record layer is prepared * to process in a single call to write_records. It is the caller's * responsibility to ensure that no call to write_records exceeds this * number of records. |type| is the type of the records that the caller * wants to write, and |len| is the total amount of data that it wants * to send. |maxfrag| is the maximum allowed fragment size based on user * configuration, or TLS parameter negotiation. |*preffrag| contains on * entry the default fragment size that will actually be used based on user * configuration. This will always be less than or equal to |maxfrag|. On * exit the record layer may update this to an alternative fragment size to * be used. This must always be less than or equal to |maxfrag|. */ size_t (*get_max_records)(OSSL_RECORD_LAYER *rl, uint8_t type, size_t len, size_t maxfrag, size_t *preffrag); /* * Write |numtempl| records from the array of record templates pointed to * by |templates|. Each record should be no longer than the value returned * by get_max_record_len(), and there should be no more records than the * value returned by get_max_records(). * Where possible the caller will attempt to ensure that all records are the * same length, except the last record. This may not always be possible so * the record method implementation should not rely on this being the case. * In the event of a retry the caller should call retry_write_records() * to try again. No more calls to write_records() should be attempted until * retry_write_records() returns success. * Buffers allocated for the record templates can be freed immediately after * write_records() returns - even in the case a retry. * The record templates represent the plaintext payload. The encrypted * output is written to the |transport| BIO. * Returns: * 1 on success * 0 on retry * -1 on failure */ int (*write_records)(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates, size_t numtempl); /* * Retry a previous call to write_records. The caller should continue to * call this until the function returns with success or failure. After * each retry more of the data may have been incrementally sent. * Returns: * 1 on success * 0 on retry * -1 on failure */ int (*retry_write_records)(OSSL_RECORD_LAYER *rl); /* * Read a record and return the record layer version and record type in * the |rversion| and |type| parameters. |*data| is set to point to a * record layer buffer containing the record payload data and |*datalen| * is filled in with the length of that data. The |epoch| and |seq_num| * values are only used if DTLS has been negotiated. In that case they are * filled in with the epoch and sequence number from the record. * An opaque record layer handle for the record is returned in |*rechandle| * which is used in a subsequent call to |release_record|. The buffer must * remain available until all the bytes from record are released via one or * more release_record calls. * * Internally the OSSL_RECORD_METHOD implementation may read/process * multiple records in one go and buffer them. */ int (*read_record)(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion, uint8_t *type, const unsigned char **data, size_t *datalen, uint16_t *epoch, unsigned char *seq_num); /* * Release length bytes from a buffer associated with a record previously * read with read_record. Once all the bytes from a record are released, the * whole record and its associated buffer is released. Records are * guaranteed to be released in the order that they are read. */ int (*release_record)(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length); /* * In the event that a fatal error is returned from the functions above then * get_alert_code() can be called to obtain a more details identifier for * the error. In (D)TLS this is the alert description code. */ int (*get_alert_code)(OSSL_RECORD_LAYER *rl); /* * Update the transport BIO from the one originally set in the * new_record_layer call */ int (*set1_bio)(OSSL_RECORD_LAYER *rl, BIO *bio); /* Called when protocol negotiation selects a protocol version to use */ int (*set_protocol_version)(OSSL_RECORD_LAYER *rl, int version); /* * Whether we are allowed to receive unencrypted alerts, even if we might * otherwise expect encrypted records. Ignored by protocol versions where * this isn't relevant */ void (*set_plain_alerts)(OSSL_RECORD_LAYER *rl, int allow); /* * Called immediately after creation of the record layer if we are in a * first handshake. Also called at the end of the first handshake */ void (*set_first_handshake)(OSSL_RECORD_LAYER *rl, int first); /* * Set the maximum number of pipelines that the record layer should process. * The default is 1. */ void (*set_max_pipelines)(OSSL_RECORD_LAYER *rl, size_t max_pipelines); /* * Called to tell the record layer whether we are currently "in init" or * not. Default at creation of the record layer is "yes". */ void (*set_in_init)(OSSL_RECORD_LAYER *rl, int in_init); /* * Get a short or long human readable description of the record layer state */ void (*get_state)(OSSL_RECORD_LAYER *rl, const char **shortstr, const char **longstr); /* * Set new options or modify ones that were originally specified in the * new_record_layer call. */ int (*set_options)(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options); const COMP_METHOD *(*get_compression)(OSSL_RECORD_LAYER *rl); /* * Set the maximum fragment length to be used for the record layer. This * will override any previous value supplied for the "max_frag_len" * setting during construction of the record layer. */ void (*set_max_frag_len)(OSSL_RECORD_LAYER *rl, size_t max_frag_len); /* * The maximum expansion in bytes that the record layer might add while * writing a record */ size_t (*get_max_record_overhead)(OSSL_RECORD_LAYER *rl); /* * Increment the record sequence number */ int (*increment_sequence_ctr)(OSSL_RECORD_LAYER *rl); /* * Allocate read or write buffers. Does nothing if already allocated. * Assumes default buffer length and 1 pipeline. */ int (*alloc_buffers)(OSSL_RECORD_LAYER *rl); /* * Free read or write buffers. Fails if there is pending read or write * data. Buffers are automatically reallocated on next read/write. */ int (*free_buffers)(OSSL_RECORD_LAYER *rl); }; /* Standard built-in record methods */ extern const OSSL_RECORD_METHOD ossl_tls_record_method; # ifndef OPENSSL_NO_KTLS extern const OSSL_RECORD_METHOD ossl_ktls_record_method; # endif extern const OSSL_RECORD_METHOD ossl_dtls_record_method; #endif /* !defined(OSSL_INTERNAL_RECORDMETHOD_H) */
./openssl/include/internal/sslconf.h
/* * Copyright 2018-2021 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_INTERNAL_SSLCONF_H # define OSSL_INTERNAL_SSLCONF_H # pragma once typedef struct ssl_conf_cmd_st SSL_CONF_CMD; const SSL_CONF_CMD *conf_ssl_get(size_t idx, const char **name, size_t *cnt); int conf_ssl_name_find(const char *name, size_t *idx); void conf_ssl_get_cmd(const SSL_CONF_CMD *cmd, size_t idx, char **cmdstr, char **arg); #endif
./openssl/include/internal/der.h
/* * Copyright 2020-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_INTERNAL_DER_H # define OSSL_INTERNAL_DER_H # pragma once # include <openssl/bn.h> # include "internal/packet.h" /* * NOTE: X.690 numbers the identifier octet bits 1 to 8. * We use the same numbering in comments here. */ /* Well known primitive tags */ /* * DER UNIVERSAL tags, occupying bits 1-5 in the DER identifier byte * These are only valid for the UNIVERSAL class. With the other classes, * these bits have a different meaning. */ # define DER_P_EOC 0 /* BER End Of Contents tag */ # define DER_P_BOOLEAN 1 # define DER_P_INTEGER 2 # define DER_P_BIT_STRING 3 # define DER_P_OCTET_STRING 4 # define DER_P_NULL 5 # define DER_P_OBJECT 6 # define DER_P_OBJECT_DESCRIPTOR 7 # define DER_P_EXTERNAL 8 # define DER_P_REAL 9 # define DER_P_ENUMERATED 10 # define DER_P_UTF8STRING 12 # define DER_P_SEQUENCE 16 # define DER_P_SET 17 # define DER_P_NUMERICSTRING 18 # define DER_P_PRINTABLESTRING 19 # define DER_P_T61STRING 20 # define DER_P_VIDEOTEXSTRING 21 # define DER_P_IA5STRING 22 # define DER_P_UTCTIME 23 # define DER_P_GENERALIZEDTIME 24 # define DER_P_GRAPHICSTRING 25 # define DER_P_ISO64STRING 26 # define DER_P_GENERALSTRING 27 # define DER_P_UNIVERSALSTRING 28 # define DER_P_BMPSTRING 30 /* DER Flags, occupying bit 6 in the DER identifier byte */ # define DER_F_PRIMITIVE 0x00 # define DER_F_CONSTRUCTED 0x20 /* DER classes tags, occupying bits 7-8 in the DER identifier byte */ # define DER_C_UNIVERSAL 0x00 # define DER_C_APPLICATION 0x40 # define DER_C_CONTEXT 0x80 # define DER_C_PRIVATE 0xC0 /* * Run-time constructors. * * They all construct DER backwards, so care should be taken to use them * that way. */ /* This can be used for all items that don't have a context */ # define DER_NO_CONTEXT -1 int ossl_DER_w_precompiled(WPACKET *pkt, int tag, const unsigned char *precompiled, size_t precompiled_n); int ossl_DER_w_boolean(WPACKET *pkt, int tag, int b); int ossl_DER_w_uint32(WPACKET *pkt, int tag, uint32_t v); int ossl_DER_w_bn(WPACKET *pkt, int tag, const BIGNUM *v); int ossl_DER_w_null(WPACKET *pkt, int tag); int ossl_DER_w_octet_string(WPACKET *pkt, int tag, const unsigned char *data, size_t data_n); int ossl_DER_w_octet_string_uint32(WPACKET *pkt, int tag, uint32_t value); /* * All constructors for constructed elements have a begin and a end function */ int ossl_DER_w_begin_sequence(WPACKET *pkt, int tag); int ossl_DER_w_end_sequence(WPACKET *pkt, int tag); #endif
./openssl/include/internal/quic_engine.h
/* * Copyright 2023 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_ENGINE_H # define OSSL_QUIC_ENGINE_H # include <openssl/ssl.h> # include "internal/quic_predef.h" # include "internal/quic_port.h" # include "internal/thread_arch.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Engine * =========== * * A QUIC Engine (QUIC_ENGINE) represents an event processing domain for the * purposes of QUIC and contains zero or more subsidiary QUIC_PORT instances * (each of which currently represents a UDP socket), each of which in turn * contains zero or more subsidiary QUIC_CHANNEL instances, each of which * represents a single QUIC connection. All QUIC_PORT instances must belong * to a QUIC_ENGINE. * * TODO(QUIC SERVER): Currently a QUIC_PORT belongs to a single QUIC_CHANNEL. * This will cease to be the case once connection migration and/or multipath is * implemented, so in future a channel might be associated with multiple ports. * * A QUIC engine is the root object in a QUIC event domain, and is responsible * for managing event processing for all QUIC ports and channels (e.g. timeouts, * clock management, the QUIC_REACTOR instance, etc.). */ typedef struct quic_engine_args_st { OSSL_LIB_CTX *libctx; const char *propq; /* * This must be a mutex the lifetime of which will exceed that of the engine * and all ports and channels. The instantiator of the engine is responsible * for providing a mutex as this makes it easier to handle instantiation and * teardown of channels in situations potentially requiring locking. * * Note that this is a MUTEX not a RWLOCK as it needs to be an OS mutex for * compatibility with an OS's condition variable wait API, whereas RWLOCK * may, depending on the build configuration, be implemented using an OS's * mutex primitive or using its RW mutex primitive. */ CRYPTO_MUTEX *mutex; OSSL_TIME (*now_cb)(void *arg); void *now_cb_arg; } QUIC_ENGINE_ARGS; QUIC_ENGINE *ossl_quic_engine_new(const QUIC_ENGINE_ARGS *args); void ossl_quic_engine_free(QUIC_ENGINE *qeng); /* * Create a port which is a child of the engine. args->engine shall be NULL. */ QUIC_PORT *ossl_quic_engine_create_port(QUIC_ENGINE *qeng, const QUIC_PORT_ARGS *args); /* Gets the mutex used by the engine. */ CRYPTO_MUTEX *ossl_quic_engine_get0_mutex(QUIC_ENGINE *qeng); /* Gets the current time. */ OSSL_TIME ossl_quic_engine_get_time(QUIC_ENGINE *qeng); /* For testing use. While enabled, ticking is not performed. */ void ossl_quic_engine_set_inhibit_tick(QUIC_ENGINE *qeng, int inhibit); /* Gets the reactor which can be used to tick/poll on the port. */ QUIC_REACTOR *ossl_quic_engine_get0_reactor(QUIC_ENGINE *qeng); # endif #endif
./openssl/include/internal/quic_stream_map.h
/* * Copyright 2022-2023 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_INTERNAL_QUIC_STREAM_MAP_H # define OSSL_INTERNAL_QUIC_STREAM_MAP_H # pragma once # include "internal/e_os.h" # include "internal/time.h" # include "internal/common.h" # include "internal/quic_types.h" # include "internal/quic_predef.h" # include "internal/quic_stream.h" # include "internal/quic_fc.h" # include <openssl/lhash.h> # ifndef OPENSSL_NO_QUIC /* * QUIC Stream * =========== * * Logical QUIC stream composing all relevant send and receive components. */ typedef struct quic_stream_list_node_st QUIC_STREAM_LIST_NODE; struct quic_stream_list_node_st { QUIC_STREAM_LIST_NODE *prev, *next; }; /* * QUIC Send Stream States * ----------------------- * * These correspond to the states defined in RFC 9000 s. 3.1, with the * exception of the NONE state which represents the absence of a send stream * part. * * Invariants in each state are noted in comments below. In particular, once all * data has been acknowledged received, or we have reset the stream, we don't * need to keep the QUIC_SSTREAM and data buffers around. Of course, we also * don't have a QUIC_SSTREAM on a receive-only stream. */ #define QUIC_SSTREAM_STATE_NONE 0 /* --- sstream == NULL */ #define QUIC_SSTREAM_STATE_READY 1 /* \ */ #define QUIC_SSTREAM_STATE_SEND 2 /* |-- sstream != NULL */ #define QUIC_SSTREAM_STATE_DATA_SENT 3 /* / */ #define QUIC_SSTREAM_STATE_DATA_RECVD 4 /* \ */ #define QUIC_SSTREAM_STATE_RESET_SENT 5 /* |-- sstream == NULL */ #define QUIC_SSTREAM_STATE_RESET_RECVD 6 /* / */ /* * QUIC Receive Stream States * -------------------------- * * These correspond to the states defined in RFC 9000 s. 3.2, with the exception * of the NONE state which represents the absence of a receive stream part. * * Invariants in each state are noted in comments below. In particular, once all * data has been read by the application, we don't need to keep the QUIC_RSTREAM * and data buffers around. If the receive part is instead reset before it is * finished, we also don't need to keep the QUIC_RSTREAM around. Finally, we * don't need a QUIC_RSTREAM on a send-only stream. */ #define QUIC_RSTREAM_STATE_NONE 0 /* --- rstream == NULL */ #define QUIC_RSTREAM_STATE_RECV 1 /* \ */ #define QUIC_RSTREAM_STATE_SIZE_KNOWN 2 /* |-- rstream != NULL */ #define QUIC_RSTREAM_STATE_DATA_RECVD 3 /* / */ #define QUIC_RSTREAM_STATE_DATA_READ 4 /* \ */ #define QUIC_RSTREAM_STATE_RESET_RECVD 5 /* |-- rstream == NULL */ #define QUIC_RSTREAM_STATE_RESET_READ 6 /* / */ struct quic_stream_st { QUIC_STREAM_LIST_NODE active_node; /* for use by QUIC_STREAM_MAP */ QUIC_STREAM_LIST_NODE accept_node; /* accept queue of remotely-created streams */ QUIC_STREAM_LIST_NODE ready_for_gc_node; /* queue of streams now ready for GC */ /* Temporary link used by TXP. */ QUIC_STREAM *txp_next; /* * QUIC Stream ID. Do not assume that this encodes a type as this is a * version-specific property and may change between QUIC versions; instead, * use the type field. */ uint64_t id; /* * Application Error Code (AEC) used for STOP_SENDING frame. * This is only valid if stop_sending is 1. */ uint64_t stop_sending_aec; /* * Application Error Code (AEC) used for RESET_STREAM frame. * This is only valid if reset_stream is 1. */ uint64_t reset_stream_aec; /* * Application Error Code (AEC) for incoming STOP_SENDING frame. * This is only valid if peer_stop_sending is 1. */ uint64_t peer_stop_sending_aec; /* * Application Error Code (AEC) for incoming RESET_STREAM frame. * This is only valid if peer_reset_stream is 1. */ uint64_t peer_reset_stream_aec; /* Temporary value used by TXP. */ uint64_t txp_txfc_new_credit_consumed; /* * The final size of the send stream. Although this information can be * discerned from a QUIC_SSTREAM, it is stored separately as we need to keep * track of this even if we have thrown away the QUIC_SSTREAM. Use * ossl_quic_stream_send_get_final_size to determine if this contain a * valid value or if there is no final size yet for a sending part. * * For the receive part, the final size is tracked by the stream-level RXFC; * use ossl_quic_stream_recv_get_final_size or * ossl_quic_rxfc_get_final_size. */ uint64_t send_final_size; /* * Send stream part and receive stream part buffer management objects. * * DO NOT test these pointers (sstream, rstream) for NULL. Determine the * state of the send or receive stream part first using the appropriate * function; then the invariant of that state guarantees that sstream or * rstream either is or is not NULL respectively, therefore there is no * valid use case for testing these pointers for NULL. In particular, a * stream with a send part can still have sstream as NULL, and a stream with * a receive part can still have rstream as NULL. QUIC_SSTREAM and * QUIC_RSTREAM are stream buffer resource management objects which exist * only when they need to for buffer management purposes. The existence or * non-existence of a QUIC_SSTREAM or QUIC_RSTREAM object does not * correspond with whether a stream's respective send or receive part * logically exists or not. */ QUIC_SSTREAM *sstream; /* NULL if RX-only */ QUIC_RSTREAM *rstream; /* NULL if TX only */ /* Stream-level flow control managers. */ QUIC_TXFC txfc; /* NULL if RX-only */ QUIC_RXFC rxfc; /* NULL if TX-only */ unsigned int type : 8; /* QUIC_STREAM_INITIATOR_*, QUIC_STREAM_DIR_* */ unsigned int send_state : 8; /* QUIC_SSTREAM_STATE_* */ unsigned int recv_state : 8; /* QUIC_RSTREAM_STATE_* */ /* 1 iff this QUIC_STREAM is on the active queue (invariant). */ unsigned int active : 1; /* * This is a copy of the QUIC connection as_server value, indicating * whether we are locally operating as a server or not. Having this * significantly simplifies stream type determination relative to our * perspective. It never changes after a QUIC_STREAM is created and is the * same for all QUIC_STREAMS under a QUIC_STREAM_MAP. */ unsigned int as_server : 1; /* * Has STOP_SENDING been requested (by us)? Note that this is not the same * as want_stop_sending below, as a STOP_SENDING frame may already have been * sent and fully acknowledged. */ unsigned int stop_sending : 1; /* * Has RESET_STREAM been requested (by us)? Works identically to * STOP_SENDING for transmission purposes. */ /* Has our peer sent a STOP_SENDING frame? */ unsigned int peer_stop_sending : 1; /* Temporary flags used by TXP. */ unsigned int txp_sent_fc : 1; unsigned int txp_sent_stop_sending : 1; unsigned int txp_sent_reset_stream : 1; unsigned int txp_drained : 1; unsigned int txp_blocked : 1; /* Frame regeneration flags. */ unsigned int want_max_stream_data : 1; /* used for regen only */ unsigned int want_stop_sending : 1; /* used for gen or regen */ unsigned int want_reset_stream : 1; /* used for gen or regen */ /* Flags set when frames *we* sent were acknowledged. */ unsigned int acked_stop_sending : 1; /* * The stream's XSO has been deleted. Pending GC. * * Here is how stream deletion works: * * - A QUIC_STREAM cannot be deleted until it is neither in the accept * queue nor has an associated XSO. This condition occurs when and only * when deleted is true. * * - Once this is the case (i.e., no user-facing API object exposing the * stream), we can delete the stream once we determine that all of our * protocol obligations requiring us to keep the QUIC_STREAM around have * been met. * * The following frames relate to the streams layer for a specific * stream: * * STREAM * * RX Obligations: * Ignore for a deleted stream. * * (This is different from our obligation for a * locally-initiated stream ID we have not created yet, * which we must treat as a protocol error. This can be * distinguished via a simple monotonic counter.) * * TX Obligations: * None, once we've decided to (someday) delete the stream. * * STOP_SENDING * * We cannot delete the stream until we have finished informing * the peer that we are not going to be listening to it * anymore. * * RX Obligations: * When we delete a stream we must have already had a FIN * or RESET_STREAM we transmitted acknowledged by the peer. * Thus we can ignore STOP_SENDING frames for deleted * streams (if they occur, they are probably just * retransmissions). * * TX Obligations: * _Acknowledged_ receipt of a STOP_SENDING frame by the * peer (unless the peer's send part has already FIN'd). * * RESET_STREAM * * We cannot delete the stream until we have finished informing * the peer that we are not going to be transmitting on it * anymore. * * RX Obligations: * This indicates the peer is not going to send any more * data on the stream. We don't need to care about this * since once a stream is marked for deletion we don't care * about any data it does send. We can ignore this for * deleted streams. The important criterion is that the * peer has been successfully delivered our STOP_SENDING * frame. * * TX Obligations: * _Acknowledged_ receipt of a RESET_STREAM frame or FIN by * the peer. * * MAX_STREAM_DATA * * RX Obligations: * Ignore. Since we are not going to be sending any more * data on a stream once it has been marked for deletion, * we don't need to care about flow control information. * * TX Obligations: * None. * * In other words, our protocol obligation is simply: * * - either: * - the peer has acknowledged receipt of a STOP_SENDING frame sent * by us; -or- * - we have received a FIN and all preceding segments from the peer * * [NOTE: The actual criterion required here is simply 'we have * received a FIN from the peer'. However, due to reordering and * retransmissions we might subsequently receive non-FIN segments * out of order. The FIN means we know the peer will stop * transmitting on the stream at *some* point, but by sending * STOP_SENDING we can avoid these needless retransmissions we * will just ignore anyway. In actuality we could just handle all * cases by sending a STOP_SENDING. The strategy we choose is to * only avoid sending a STOP_SENDING and rely on a received FIN * when we have received all preceding data, as this makes it * reasonably certain no benefit would be gained by sending * STOP_SENDING.] * * TODO(QUIC FUTURE): Implement the latter case (currently we just always do STOP_SENDING). * * and; * * - we have drained our send stream (for a finished send stream) * and got acknowledgement all parts of it including the FIN, or * sent a RESET_STREAM frame and got acknowledgement of that frame. * * Once these conditions are met, we can GC the QUIC_STREAM. * */ unsigned int deleted : 1; /* Set to 1 once the above conditions are actually met. */ unsigned int ready_for_gc : 1; /* Set to 1 if this is currently counted in the shutdown flush stream count. */ unsigned int shutdown_flush : 1; }; #define QUIC_STREAM_INITIATOR_CLIENT 0 #define QUIC_STREAM_INITIATOR_SERVER 1 #define QUIC_STREAM_INITIATOR_MASK 1 #define QUIC_STREAM_DIR_BIDI 0 #define QUIC_STREAM_DIR_UNI 2 #define QUIC_STREAM_DIR_MASK 2 void ossl_quic_stream_check(const QUIC_STREAM *s); /* * Returns 1 if the QUIC_STREAM was initiated by the endpoint with the server * role. */ static ossl_inline ossl_unused int ossl_quic_stream_is_server_init(const QUIC_STREAM *s) { return (s->type & QUIC_STREAM_INITIATOR_MASK) == QUIC_STREAM_INITIATOR_SERVER; } /* * Returns 1 if the QUIC_STREAM is bidirectional and 0 if it is unidirectional. */ static ossl_inline ossl_unused int ossl_quic_stream_is_bidi(const QUIC_STREAM *s) { return (s->type & QUIC_STREAM_DIR_MASK) == QUIC_STREAM_DIR_BIDI; } /* Returns 1 if the QUIC_STREAM was locally initiated. */ static ossl_inline ossl_unused int ossl_quic_stream_is_local_init(const QUIC_STREAM *s) { return ossl_quic_stream_is_server_init(s) == s->as_server; } /* * Returns 1 if the QUIC_STREAM has a sending part, based on its stream type. * * Do NOT use (s->sstream != NULL) to test this; use this function. Note that * even if this function returns 1, s->sstream might be NULL if the QUIC_SSTREAM * has been deemed no longer needed, for example due to a RESET_STREAM. */ static ossl_inline ossl_unused int ossl_quic_stream_has_send(const QUIC_STREAM *s) { return s->send_state != QUIC_SSTREAM_STATE_NONE; } /* * Returns 1 if the QUIC_STREAM has a receiving part, based on its stream type. * * Do NOT use (s->rstream != NULL) to test this; use this function. Note that * even if this function returns 1, s->rstream might be NULL if the QUIC_RSTREAM * has been deemed no longer needed, for example if the receive stream is * completely finished with. */ static ossl_inline ossl_unused int ossl_quic_stream_has_recv(const QUIC_STREAM *s) { return s->recv_state != QUIC_RSTREAM_STATE_NONE; } /* * Returns 1 if the QUIC_STREAM has a QUIC_SSTREAM send buffer associated with * it. If this returns 1, s->sstream is guaranteed to be non-NULL. The converse * is not necessarily true; erasure of a send stream buffer which is no longer * required is an optimisation which the QSM may, but is not obliged, to * perform. * * This call should be used where it is desired to do something with the send * stream buffer but there is no more specific send state restriction which is * applicable. * * Note: This does NOT indicate whether it is suitable to allow an application * to append to the buffer. DATA_SENT indicates all data (including FIN) has * been *sent*; the absence of DATA_SENT does not mean a FIN has not been queued * (meaning no more application data can be appended). This is enforced by * QUIC_SSTREAM. */ static ossl_inline ossl_unused int ossl_quic_stream_has_send_buffer(const QUIC_STREAM *s) { switch (s->send_state) { case QUIC_SSTREAM_STATE_READY: case QUIC_SSTREAM_STATE_SEND: case QUIC_SSTREAM_STATE_DATA_SENT: return 1; default: return 0; } } /* * Returns 1 if the QUIC_STREAM has a sending part which is in one of the reset * states. */ static ossl_inline ossl_unused int ossl_quic_stream_send_is_reset(const QUIC_STREAM *s) { return s->send_state == QUIC_SSTREAM_STATE_RESET_SENT || s->send_state == QUIC_SSTREAM_STATE_RESET_RECVD; } /* * Returns 1 if the QUIC_STREAM has a QUIC_RSTREAM receive buffer associated * with it. If this returns 1, s->rstream is guaranteed to be non-NULL. The * converse is not necessarily true; erasure of a receive stream buffer which is * no longer required is an optimisation which the QSM may, but is not obliged, * to perform. * * This call should be used where it is desired to do something with the receive * stream buffer but there is no more specific receive state restriction which is * applicable. */ static ossl_inline ossl_unused int ossl_quic_stream_has_recv_buffer(const QUIC_STREAM *s) { switch (s->recv_state) { case QUIC_RSTREAM_STATE_RECV: case QUIC_RSTREAM_STATE_SIZE_KNOWN: case QUIC_RSTREAM_STATE_DATA_RECVD: return 1; default: return 0; } } /* * Returns 1 if the QUIC_STREAM has a receiving part which is in one of the * reset states. */ static ossl_inline ossl_unused int ossl_quic_stream_recv_is_reset(const QUIC_STREAM *s) { return s->recv_state == QUIC_RSTREAM_STATE_RESET_RECVD || s->recv_state == QUIC_RSTREAM_STATE_RESET_READ; } /* * Returns 1 if the stream has a send part and that part has a final size. * * If final_size is non-NULL, *final_size is the final size (on success) or an * undefined value otherwise. */ static ossl_inline ossl_unused int ossl_quic_stream_send_get_final_size(const QUIC_STREAM *s, uint64_t *final_size) { switch (s->send_state) { default: case QUIC_SSTREAM_STATE_NONE: return 0; case QUIC_SSTREAM_STATE_SEND: /* * SEND may or may not have had a FIN - even if we have a FIN we do not * move to DATA_SENT until we have actually sent all the data. So * ask the QUIC_SSTREAM. */ return ossl_quic_sstream_get_final_size(s->sstream, final_size); case QUIC_SSTREAM_STATE_DATA_SENT: case QUIC_SSTREAM_STATE_DATA_RECVD: case QUIC_SSTREAM_STATE_RESET_SENT: case QUIC_SSTREAM_STATE_RESET_RECVD: if (final_size != NULL) *final_size = s->send_final_size; return 1; } } /* * Returns 1 if the stream has a receive part and that part has a final size. * * If final_size is non-NULL, *final_size is the final size (on success) or an * undefined value otherwise. */ static ossl_inline ossl_unused int ossl_quic_stream_recv_get_final_size(const QUIC_STREAM *s, uint64_t *final_size) { switch (s->recv_state) { default: case QUIC_RSTREAM_STATE_NONE: case QUIC_RSTREAM_STATE_RECV: return 0; case QUIC_RSTREAM_STATE_SIZE_KNOWN: case QUIC_RSTREAM_STATE_DATA_RECVD: case QUIC_RSTREAM_STATE_DATA_READ: case QUIC_RSTREAM_STATE_RESET_RECVD: case QUIC_RSTREAM_STATE_RESET_READ: if (!ossl_assert(ossl_quic_rxfc_get_final_size(&s->rxfc, final_size))) return 0; return 1; } } /* * QUIC Stream Map * =============== * * The QUIC stream map: * * - maps stream IDs to QUIC_STREAM objects; * - tracks which streams are 'active' (currently have data for transmission); * - allows iteration over the active streams only. * */ struct quic_stream_map_st { LHASH_OF(QUIC_STREAM) *map; QUIC_STREAM_LIST_NODE active_list; QUIC_STREAM_LIST_NODE accept_list; QUIC_STREAM_LIST_NODE ready_for_gc_list; size_t rr_stepping, rr_counter; size_t num_accept, num_shutdown_flush; QUIC_STREAM *rr_cur; uint64_t (*get_stream_limit_cb)(int uni, void *arg); void *get_stream_limit_cb_arg; QUIC_RXFC *max_streams_bidi_rxfc; QUIC_RXFC *max_streams_uni_rxfc; int is_server; }; /* * get_stream_limit is a callback which is called to retrieve the current stream * limit for streams created by us. This mechanism is not used for * peer-initiated streams. If a stream's stream ID is x, a stream is allowed if * (x >> 2) < returned limit value; i.e., the returned value is exclusive. * * If uni is 1, get the limit for locally-initiated unidirectional streams, else * get the limit for locally-initiated bidirectional streams. * * If the callback is NULL, stream limiting is not applied. * Stream limiting is used to determine if frames can currently be produced for * a stream. */ int ossl_quic_stream_map_init(QUIC_STREAM_MAP *qsm, uint64_t (*get_stream_limit_cb)(int uni, void *arg), void *get_stream_limit_cb_arg, QUIC_RXFC *max_streams_bidi_rxfc, QUIC_RXFC *max_streams_uni_rxfc, int is_server); /* * Any streams still in the map will be released as though * ossl_quic_stream_map_release was called on them. */ void ossl_quic_stream_map_cleanup(QUIC_STREAM_MAP *qsm); /* * Allocate a new stream. type is a combination of one QUIC_STREAM_INITIATOR_* * value and one QUIC_STREAM_DIR_* value. Note that clients can e.g. allocate * server-initiated streams as they will need to allocate a QUIC_STREAM * structure to track any stream created by the server, etc. * * stream_id must be a valid value. Returns NULL if a stream already exists * with the given ID. */ QUIC_STREAM *ossl_quic_stream_map_alloc(QUIC_STREAM_MAP *qsm, uint64_t stream_id, int type); /* * Releases a stream object. Note that this must only be done once the teardown * process is entirely complete and the object will never be referenced again. */ void ossl_quic_stream_map_release(QUIC_STREAM_MAP *qsm, QUIC_STREAM *stream); /* * Calls visit_cb() for each stream in the map. visit_cb_arg is an opaque * argument which is passed through. */ void ossl_quic_stream_map_visit(QUIC_STREAM_MAP *qsm, void (*visit_cb)(QUIC_STREAM *stream, void *arg), void *visit_cb_arg); /* * Retrieves a stream by stream ID. Returns NULL if it does not exist. */ QUIC_STREAM *ossl_quic_stream_map_get_by_id(QUIC_STREAM_MAP *qsm, uint64_t stream_id); /* * Marks the given stream as active or inactive based on its state. Idempotent. * * When a stream is marked active, it becomes available in the iteration list, * and when a stream is marked inactive, it no longer appears in the iteration * list. * * Calling this function invalidates any iterator currently pointing at the * given stream object, but iterators not currently pointing at the given stream * object are not invalidated. */ void ossl_quic_stream_map_update_state(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s); /* * Sets the RR stepping value, n. The RR rotation will be advanced every n * packets. The default value is 1. */ void ossl_quic_stream_map_set_rr_stepping(QUIC_STREAM_MAP *qsm, size_t stepping); /* * Returns 1 if the stream ordinal given is allowed by the current stream count * flow control limit, assuming a locally initiated stream of a type described * by is_uni. * * Note that stream_ordinal is a stream ordinal, not a stream ID. */ int ossl_quic_stream_map_is_local_allowed_by_stream_limit(QUIC_STREAM_MAP *qsm, uint64_t stream_ordinal, int is_uni); /* * Stream Send Part * ================ */ /* * Ensures that the sending part has transitioned out of the READY state (i.e., * to SEND, or a subsequent state). This function is named as it is because, * while on paper the distinction between READY and SEND is whether we have * started transmitting application data, in practice the meaningful distinction * between the two states is whether we have allocated a stream ID to the stream * or not. QUIC permits us to defer stream ID allocation until first STREAM (or * STREAM_DATA_BLOCKED) frame transmission for locally-initiated streams. * * Our implementation does not currently do this and we allocate stream IDs up * front, however we may revisit this in the future. Calling this represents a * demand for a stream ID by the caller and ensures one has been allocated to * the stream, and causes us to transition to SEND if we are still in the READY * state. * * Returns 0 if there is no send part (caller error) and 1 otherwise. */ int ossl_quic_stream_map_ensure_send_part_id(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Transitions from SEND to the DATA_SENT state. Note that this is NOT the same * as the point in time at which the final size of the stream becomes known * (i.e., the time at which ossl_quic_sstream_fin()) is called as it occurs when * we have SENT all data on a given stream send part, not merely buffered it. * Note that this transition is NOT reversed in the event of some of that data * being lost. * * Returns 1 if the state transition was successfully taken. Returns 0 if there * is no send part (caller error) or if the state transition cannot be taken * because the send part is not in the SEND state. */ int ossl_quic_stream_map_notify_all_data_sent(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Transitions from the DATA_SENT to DATA_RECVD state; should be called * when all transmitted stream data is ACKed by the peer. * * Returns 1 if the state transition was successfully taken. Returns 0 if there * is no send part (caller error) or the state transition cannot be taken * because the send part is not in the DATA_SENT state. Because * ossl_quic_stream_map_notify_all_data_sent() should always be called prior to * this function, the send state must already be in DATA_SENT in order for this * function to succeed. */ int ossl_quic_stream_map_notify_totally_acked(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Resets the sending part of a stream. This is a transition from the READY, * SEND or DATA_SENT send stream states to the RESET_SENT state. * * This function returns 1 if the transition is taken (i.e., if the send stream * part was in one of the states above), or if it is already in the RESET_SENT * state (idempotent operation), or if it has reached the RESET_RECVD state. * * It returns 0 if in the DATA_RECVD state, as a send stream cannot be reset * in this state. It also returns 0 if there is no send part (caller error). */ int ossl_quic_stream_map_reset_stream_send_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs, uint64_t aec); /* * Transitions from the RESET_SENT to the RESET_RECVD state. This should be * called when a sent RESET_STREAM frame has been acknowledged by the peer. * * This function returns 1 if the transition is taken (i.e., if the send stream * part was in one of the states above) or if it is already in the RESET_RECVD * state (idempotent operation). * * It returns 0 if not in the RESET_SENT or RESET_RECVD states, as this function * should only be called after we have already sent a RESET_STREAM frame and * entered the RESET_SENT state. It also returns 0 if there is no send part * (caller error). */ int ossl_quic_stream_map_notify_reset_stream_acked(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Stream Receive Part * =================== */ /* * Transitions from the RECV receive stream state to the SIZE_KNOWN state. This * should be called once a STREAM frame is received for the stream with the FIN * bit set. final_size should be the final size of the stream in bytes. * * Returns 1 if the transition was taken. */ int ossl_quic_stream_map_notify_size_known_recv_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs, uint64_t final_size); /* * Transitions from the SIZE_KNOWN receive stream state to the DATA_RECVD state. * This should be called once all data for a receive stream is received. * * Returns 1 if the transition was taken. */ int ossl_quic_stream_map_notify_totally_received(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Transitions from the DATA_RECVD receive stream state to the DATA_READ state. * This should be called once all data for a receive stream is read by the * application. * * Returns 1 if the transition was taken. */ int ossl_quic_stream_map_notify_totally_read(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Transitions from the RECV, SIZE_KNOWN or DATA_RECVD receive stream state to * the RESET_RECVD state. This should be called on RESET_STREAM. * * Returns 1 if the transition was taken. */ int ossl_quic_stream_map_notify_reset_recv_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs, uint64_t app_error_code, uint64_t final_size); /* * Transitions from the RESET_RECVD receive stream state to the RESET_READ * receive stream state. This should be called when the application is notified * of a stream reset. */ int ossl_quic_stream_map_notify_app_read_reset_recv_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Marks the receiving part of a stream for STOP_SENDING. This is orthogonal to * receive stream state as it does not affect it directly. * * Returns 1 if the receiving part of a stream was not already marked for * STOP_SENDING. * Returns 0 otherwise, which need not be considered an error. */ int ossl_quic_stream_map_stop_sending_recv_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs, uint64_t aec); /* * Marks the stream as wanting a STOP_SENDING frame transmitted. It is not valid * to call this if ossl_quic_stream_map_stop_sending_recv_part() has not been * called. For TXP use. */ int ossl_quic_stream_map_schedule_stop_sending(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* * Accept Queue Management * ======================= */ /* * Adds a stream to the accept queue. */ void ossl_quic_stream_map_push_accept_queue(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s); /* * Returns the next item to be popped from the accept queue, or NULL if it is * empty. */ QUIC_STREAM *ossl_quic_stream_map_peek_accept_queue(QUIC_STREAM_MAP *qsm); /* * Removes a stream from the accept queue. rtt is the estimated connection RTT. * The stream is retired for the purposes of MAX_STREAMS RXFC. * * Precondition: s is in the accept queue. */ void ossl_quic_stream_map_remove_from_accept_queue(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s, OSSL_TIME rtt); /* Returns the length of the accept queue. */ size_t ossl_quic_stream_map_get_accept_queue_len(QUIC_STREAM_MAP *qsm); /* * Shutdown Flush and GC * ===================== */ /* * Delete streams ready for GC. Pointers to those QUIC_STREAM objects become * invalid. */ void ossl_quic_stream_map_gc(QUIC_STREAM_MAP *qsm); /* * Begins shutdown stream flush triage. Analyses all streams, including deleted * but not yet GC'd streams, to determine if we should wait for that stream to * be fully flushed before shutdown. After calling this, call * ossl_quic_stream_map_is_shutdown_flush_finished() to determine if all * shutdown flush eligible streams have been flushed. */ void ossl_quic_stream_map_begin_shutdown_flush(QUIC_STREAM_MAP *qsm); /* * Returns 1 if all shutdown flush eligible streams have finished flushing, * or if ossl_quic_stream_map_begin_shutdown_flush() has not been called. */ int ossl_quic_stream_map_is_shutdown_flush_finished(QUIC_STREAM_MAP *qsm); /* * QUIC Stream Iterator * ==================== * * Allows the current set of active streams to be walked using a RR-based * algorithm. Each time ossl_quic_stream_iter_init is called, the RR algorithm * is stepped. The RR algorithm rotates the iteration order such that the next * active stream is returned first after n calls to ossl_quic_stream_iter_init, * where n is the stepping value configured via * ossl_quic_stream_map_set_rr_stepping. * * Suppose there are three active streams and the configured stepping is n: * * Iteration 0n: [Stream 1] [Stream 2] [Stream 3] * Iteration 1n: [Stream 2] [Stream 3] [Stream 1] * Iteration 2n: [Stream 3] [Stream 1] [Stream 2] * */ typedef struct quic_stream_iter_st { QUIC_STREAM_MAP *qsm; QUIC_STREAM *first_stream, *stream; } QUIC_STREAM_ITER; /* * Initialise an iterator, advancing the RR algorithm as necessary (if * advance_rr is 1). After calling this, it->stream will be the first stream in * the iteration sequence, or NULL if there are no active streams. */ void ossl_quic_stream_iter_init(QUIC_STREAM_ITER *it, QUIC_STREAM_MAP *qsm, int advance_rr); /* * Advances to next stream in iteration sequence. You do not need to call this * immediately after calling ossl_quic_stream_iter_init(). If the end of the * list is reached, it->stream will be NULL after calling this. */ void ossl_quic_stream_iter_next(QUIC_STREAM_ITER *it); # endif #endif
./openssl/include/internal/sizes.h
/* * Copyright 2020-2021 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_INTERNAL_SIZES_H # define OSSL_INTERNAL_SIZES_H # pragma once /* * Max sizes used to allocate buffers with a fixed sizes, for example for * stack allocations, structure fields, ... */ # define OSSL_MAX_NAME_SIZE 50 /* Algorithm name */ # define OSSL_MAX_PROPQUERY_SIZE 256 /* Property query strings */ # define OSSL_MAX_ALGORITHM_ID_SIZE 256 /* AlgorithmIdentifier DER */ #endif
./openssl/include/internal/asn1.h
/* * Copyright 2020-2021 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_INTERNAL_ASN1_H # define OSSL_INTERNAL_ASN1_H # pragma once # include <openssl/bio.h> int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb); #endif
./openssl/include/internal/o_dir.h
/* * Copyright 2004-2021 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 */ /* * This file is dual-licensed and is also available under the following * terms: * * Copyright (c) 2004, Richard Levitte <richard@levitte.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef OSSL_INTERNAL_O_DIR_H # define OSSL_INTERNAL_O_DIR_H # pragma once typedef struct OPENSSL_dir_context_st OPENSSL_DIR_CTX; /* * returns NULL on error or end-of-directory. If it is end-of-directory, * errno will be zero */ const char *OPENSSL_DIR_read(OPENSSL_DIR_CTX **ctx, const char *directory); /* returns 1 on success, 0 on error */ int OPENSSL_DIR_end(OPENSSL_DIR_CTX **ctx); #endif /* LPDIR_H */
./openssl/include/internal/sha3.h
/* * Copyright 2019-2021 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 */ /* This header can move into provider when legacy support is removed */ #ifndef OSSL_INTERNAL_SHA3_H # define OSSL_INTERNAL_SHA3_H # pragma once # include <openssl/e_os2.h> # include <stddef.h> # define KECCAK1600_WIDTH 1600 # define SHA3_MDSIZE(bitlen) (bitlen / 8) # define KMAC_MDSIZE(bitlen) 2 * (bitlen / 8) # define SHA3_BLOCKSIZE(bitlen) (KECCAK1600_WIDTH - bitlen * 2) / 8 typedef struct keccak_st KECCAK1600_CTX; typedef size_t (sha3_absorb_fn)(void *vctx, const void *in, size_t inlen); typedef int (sha3_final_fn)(void *vctx, unsigned char *out, size_t outlen); typedef int (sha3_squeeze_fn)(void *vctx, unsigned char *out, size_t outlen); typedef struct prov_sha3_meth_st { sha3_absorb_fn *absorb; sha3_final_fn *final; sha3_squeeze_fn *squeeze; } PROV_SHA3_METHOD; #define XOF_STATE_INIT 0 #define XOF_STATE_ABSORB 1 #define XOF_STATE_FINAL 2 #define XOF_STATE_SQUEEZE 3 struct keccak_st { uint64_t A[5][5]; unsigned char buf[KECCAK1600_WIDTH / 8 - 32]; size_t block_size; /* cached ctx->digest->block_size */ size_t md_size; /* output length, variable in XOF */ size_t bufsz; /* used bytes in below buffer */ unsigned char pad; PROV_SHA3_METHOD meth; int xof_state; }; void ossl_sha3_reset(KECCAK1600_CTX *ctx); int ossl_sha3_init(KECCAK1600_CTX *ctx, unsigned char pad, size_t bitlen); int ossl_keccak_kmac_init(KECCAK1600_CTX *ctx, unsigned char pad, size_t bitlen); int ossl_sha3_update(KECCAK1600_CTX *ctx, const void *_inp, size_t len); int ossl_sha3_final(KECCAK1600_CTX *ctx, unsigned char *out, size_t outlen); int ossl_sha3_squeeze(KECCAK1600_CTX *ctx, unsigned char *out, size_t outlen); size_t SHA3_absorb(uint64_t A[5][5], const unsigned char *inp, size_t len, size_t r); #endif /* OSSL_INTERNAL_SHA3_H */
./openssl/include/internal/quic_fc.h
/* * Copyright 2022-2023 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_FC_H # define OSSL_QUIC_FC_H # include <openssl/ssl.h> # include "internal/time.h" # ifndef OPENSSL_NO_QUIC /* * TX Flow Controller (TXFC) * ========================= * * For discussion, see doc/designs/quic-design/quic-fc.md. */ typedef struct quic_txfc_st QUIC_TXFC; struct quic_txfc_st { QUIC_TXFC *parent; /* stream-level iff non-NULL */ uint64_t swm, cwm; char has_become_blocked; }; /* * Initialises a TX flow controller. conn_txfc should be non-NULL and point to * the connection-level flow controller if the TXFC is for stream-level flow * control, and NULL otherwise. */ int ossl_quic_txfc_init(QUIC_TXFC *txfc, QUIC_TXFC *conn_txfc); /* * Gets the parent (i.e., connection-level) TX flow controller. Returns NULL if * called on a connection-level TX flow controller. */ QUIC_TXFC *ossl_quic_txfc_get_parent(QUIC_TXFC *txfc); /* * Bump the credit watermark (CWM) value. This is the 'On TX Window Updated' * operation. This function is a no-op if it has already been called with an * equal or higher CWM value. * * It returns 1 iff the call resulted in the CWM being bumped and 0 if it was * not increased because it has already been called with an equal or higher CWM * value. This is not an error per se but may indicate a local programming error * or a protocol error in a remote peer. */ int ossl_quic_txfc_bump_cwm(QUIC_TXFC *txfc, uint64_t cwm); /* * Get the number of bytes by which we are in credit. This is the number of * controlled bytes we are allowed to send. (Thus if this function returns 0, we * are currently blocked.) * * If called on a stream-level TXFC, ossl_quic_txfc_get_credit is called on * the connection-level TXFC as well, and the lesser of the two values is * returned. The consumed value is the amount already consumed on the connection * level TXFC. */ uint64_t ossl_quic_txfc_get_credit(QUIC_TXFC *txfc, uint64_t consumed); /* * Like ossl_quic_txfc_get_credit(), but when called on a stream-level TXFC, * retrieves only the stream-level credit value and does not clamp it based on * connection-level flow control. Any credit value is reduced by the consumed * amount. */ uint64_t ossl_quic_txfc_get_credit_local(QUIC_TXFC *txfc, uint64_t consumed); /* * Consume num_bytes of credit. This is the 'On TX' operation. This should be * called when we transmit any controlled bytes. Calling this with an argument * of 0 is a no-op. * * We must never transmit more controlled bytes than we are in credit for (see * the return value of ossl_quic_txfc_get_credit()). If you call this function * with num_bytes greater than our current credit, this function consumes the * remainder of the credit and returns 0. This indicates a serious programming * error on the caller's part. Otherwise, the function returns 1. * * If called on a stream-level TXFC, ossl_quic_txfc_consume_credit() is called * on the connection-level TXFC also. If the call to that function on the * connection-level TXFC returns zero, this function will also return zero. */ int ossl_quic_txfc_consume_credit(QUIC_TXFC *txfc, uint64_t num_bytes); /* * Like ossl_quic_txfc_consume_credit(), but when called on a stream-level TXFC, * consumes only from the stream-level credit and does not inform the * connection-level TXFC. */ int ossl_quic_txfc_consume_credit_local(QUIC_TXFC *txfc, uint64_t num_bytes); /* * This flag is provided for convenience. A caller is not required to use it. It * is a boolean flag set whenever our credit drops to zero. If clear is 1, the * flag is cleared. The old value of the flag is returned. Callers may use this * to determine if they need to send a DATA_BLOCKED or STREAM_DATA_BLOCKED * frame, which should contain the value returned by ossl_quic_txfc_get_cwm(). */ int ossl_quic_txfc_has_become_blocked(QUIC_TXFC *txfc, int clear); /* * Get the current CWM value. This is mainly only needed when generating a * DATA_BLOCKED or STREAM_DATA_BLOCKED frame, or for diagnostic purposes. */ uint64_t ossl_quic_txfc_get_cwm(QUIC_TXFC *txfc); /* * Get the current spent watermark (SWM) value. This is purely for diagnostic * use and should not be needed in normal circumstances. */ uint64_t ossl_quic_txfc_get_swm(QUIC_TXFC *txfc); /* * RX Flow Controller (RXFC) * ========================= */ typedef struct quic_rxfc_st QUIC_RXFC; struct quic_rxfc_st { /* * swm is the sent/received watermark, which tracks how much we have * received from the peer. rwm is the retired watermark, which tracks how * much has been passed to the application. esrwm is the rwm value at which * the current auto-tuning epoch started. hwm is the highest stream length * (STREAM frame offset + payload length) we have seen from a STREAM frame * yet. */ uint64_t cwm, swm, rwm, esrwm, hwm, cur_window_size, max_window_size; OSSL_TIME epoch_start; OSSL_TIME (*now)(void *arg); void *now_arg; QUIC_RXFC *parent; unsigned char error_code, has_cwm_changed, is_fin, standalone; }; /* * Initialises an RX flow controller. conn_rxfc should be non-NULL and point to * a connection-level RXFC if the RXFC is for stream-level flow control, and * NULL otherwise. initial_window_size and max_window_size specify the initial * and absolute maximum window sizes, respectively. Window size values are * expressed in bytes and determine how much credit the RXFC extends to the peer * to transmit more data at a time. */ int ossl_quic_rxfc_init(QUIC_RXFC *rxfc, QUIC_RXFC *conn_rxfc, uint64_t initial_window_size, uint64_t max_window_size, OSSL_TIME (*now)(void *arg), void *now_arg); /* * Initialises an RX flow controller which is used by itself and not under a * connection-level RX flow controller. This can be used for stream count * enforcement as well as CRYPTO buffer enforcement. */ int ossl_quic_rxfc_init_standalone(QUIC_RXFC *rxfc, uint64_t initial_window_size, OSSL_TIME (*now)(void *arg), void *now_arg); /* * Gets the parent (i.e., connection-level) RXFC. Returns NULL if called on a * connection-level RXFC. */ QUIC_RXFC *ossl_quic_rxfc_get_parent(QUIC_RXFC *rxfc); /* * Changes the current maximum window size value. */ void ossl_quic_rxfc_set_max_window_size(QUIC_RXFC *rxfc, size_t max_window_size); /* * To be called whenever a STREAM frame is received. * * end is the value (offset + len), where offset is the offset field of the * STREAM frame and len is the length of the STREAM frame's payload in bytes. * * is_fin should be 1 if the STREAM frame had the FIN flag set and 0 otherwise. * * This function may be used on a stream-level RXFC only. The connection-level * RXFC will have its state updated by the stream-level RXFC. * * You should check ossl_quic_rxfc_has_error() on both connection-level and * stream-level RXFCs after calling this function, as an incoming STREAM frame * may cause flow control limits to be exceeded by an errant peer. This * function still returns 1 in this case, as this is not a caller error. * * Returns 1 on success or 0 on failure. */ int ossl_quic_rxfc_on_rx_stream_frame(QUIC_RXFC *rxfc, uint64_t end, int is_fin); /* * To be called whenever controlled bytes are retired, i.e. when bytes are * dequeued from a QUIC stream and passed to the application. num_bytes * is the number of bytes which were passed to the application. * * You should call this only on a stream-level RXFC. This function will update * the connection-level RXFC automatically. * * rtt should be the current best understanding of the RTT to the peer, as * offered by the Statistics Manager. * * You should check ossl_quic_rxfc_has_cwm_changed() after calling this * function, as it may have caused the RXFC to decide to grant more flow control * credit to the peer. * * Returns 1 on success and 0 on failure. */ int ossl_quic_rxfc_on_retire(QUIC_RXFC *rxfc, uint64_t num_bytes, OSSL_TIME rtt); /* * Returns the current CWM which the RXFC thinks the peer should have. * * Note that the RXFC will increase this value in response to events, at which * time a MAX_DATA or MAX_STREAM_DATA frame must be generated. Use * ossl_quic_rxfc_has_cwm_changed() to detect this condition. * * This value increases monotonically. */ uint64_t ossl_quic_rxfc_get_cwm(QUIC_RXFC *rxfc); /* * Returns the current SWM. This is the total number of bytes the peer has * transmitted to us. This is intended for diagnostic use only; you should * not need it. */ uint64_t ossl_quic_rxfc_get_swm(QUIC_RXFC *rxfc); /* * Returns the current RWM. This is the total number of bytes that has been * retired. This is intended for diagnostic use only; you should not need it. */ uint64_t ossl_quic_rxfc_get_rwm(QUIC_RXFC *rxfc); /* * Returns the CWM changed flag. If clear is 1, the flag is cleared and the old * value is returned. */ int ossl_quic_rxfc_has_cwm_changed(QUIC_RXFC *rxfc, int clear); /* * Returns a QUIC_ERR_* error code if a flow control error has been detected. * Otherwise, returns QUIC_ERR_NO_ERROR. If clear is 1, the error is cleared * and the old value is returned. * * May return one of the following values: * * QUIC_ERR_FLOW_CONTROL_ERROR: * This indicates a flow control protocol violation by the remote peer; the * connection should be terminated in this event. * QUIC_ERR_FINAL_SIZE: * The peer attempted to change the stream length after ending the stream. */ int ossl_quic_rxfc_get_error(QUIC_RXFC *rxfc, int clear); /* * Returns 1 if the RXFC is a stream-level RXFC and the RXFC knows the final * size for the stream in bytes. If this is the case and final_size is non-NULL, * writes the final size to *final_size. Otherwise, returns 0. */ int ossl_quic_rxfc_get_final_size(const QUIC_RXFC *rxfc, uint64_t *final_size); # endif #endif
./openssl/include/internal/list.h
/* * 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_INTERNAL_LIST_H # define OSSL_INTERNAL_LIST_H # pragma once # include <string.h> # include <assert.h> # ifdef NDEBUG # define OSSL_LIST_DBG(x) # else # define OSSL_LIST_DBG(x) x; # endif # define LIST_FOREACH_FROM(p, name, init) \ for ((p) = (init); \ (p) != NULL; \ (p) = ossl_list_##name##_next(p)) # define LIST_FOREACH(p, name, l) \ LIST_FOREACH_FROM(p, name, ossl_list_##name##_head(l)) # define LIST_FOREACH_REV_FROM(p, name, init) \ for ((p) = (init); \ (p) != NULL; \ (p) = ossl_list_##name##_prev(p)) # define LIST_FOREACH_REV(p, name, l) \ LIST_FOREACH_FROM(p, name, ossl_list_##name##_tail(l)) # define LIST_FOREACH_DELSAFE_FROM(p, pn, name, init) \ for ((p) = (init); \ (p) != NULL && (((pn) = ossl_list_##name##_next(p)), 1); \ (p) = (pn)) #define LIST_FOREACH_DELSAFE(p, pn, name, l) \ LIST_FOREACH_DELSAFE_FROM(p, pn, name, ossl_list_##name##_head(l)) # define LIST_FOREACH_REV_DELSAFE_FROM(p, pn, name, init) \ for ((p) = (init); \ (p) != NULL && (((pn) = ossl_list_##name##_prev(p)), 1); \ (p) = (pn)) # define LIST_FOREACH_REV_DELSAFE(p, pn, name, l) \ LIST_FOREACH_REV_DELSAFE_FROM(p, pn, name, ossl_list_##name##_tail(l)) /* Define a list structure */ # define OSSL_LIST(name) OSSL_LIST_ ## name /* Define fields to include an element of a list */ # define OSSL_LIST_MEMBER(name, type) \ struct { \ type *next, *prev; \ OSSL_LIST_DBG(struct ossl_list_st_ ## name *list) \ } ossl_list_ ## name # define DECLARE_LIST_OF(name, type) \ typedef struct ossl_list_st_ ## name OSSL_LIST(name); \ struct ossl_list_st_ ## name { \ type *alpha, *omega; \ size_t num_elems; \ } \ # define DEFINE_LIST_OF_IMPL(name, type) \ static ossl_unused ossl_inline void \ ossl_list_##name##_init(OSSL_LIST(name) *list) \ { \ memset(list, 0, sizeof(*list)); \ } \ static ossl_unused ossl_inline void \ ossl_list_##name##_init_elem(type *elem) \ { \ memset(&elem->ossl_list_ ## name, 0, \ sizeof(elem->ossl_list_ ## name)); \ } \ static ossl_unused ossl_inline int \ ossl_list_##name##_is_empty(const OSSL_LIST(name) *list) \ { \ return list->num_elems == 0; \ } \ static ossl_unused ossl_inline size_t \ ossl_list_##name##_num(const OSSL_LIST(name) *list) \ { \ return list->num_elems; \ } \ static ossl_unused ossl_inline type * \ ossl_list_##name##_head(const OSSL_LIST(name) *list) \ { \ assert(list->alpha == NULL \ || list->alpha->ossl_list_ ## name.list == list); \ return list->alpha; \ } \ static ossl_unused ossl_inline type * \ ossl_list_##name##_tail(const OSSL_LIST(name) *list) \ { \ assert(list->omega == NULL \ || list->omega->ossl_list_ ## name.list == list); \ return list->omega; \ } \ static ossl_unused ossl_inline type * \ ossl_list_##name##_next(const type *elem) \ { \ assert(elem->ossl_list_ ## name.next == NULL \ || elem->ossl_list_ ## name.next \ ->ossl_list_ ## name.prev == elem); \ return elem->ossl_list_ ## name.next; \ } \ static ossl_unused ossl_inline type * \ ossl_list_##name##_prev(const type *elem) \ { \ assert(elem->ossl_list_ ## name.prev == NULL \ || elem->ossl_list_ ## name.prev \ ->ossl_list_ ## name.next == elem); \ return elem->ossl_list_ ## name.prev; \ } \ static ossl_unused ossl_inline void \ ossl_list_##name##_remove(OSSL_LIST(name) *list, type *elem) \ { \ assert(elem->ossl_list_ ## name.list == list); \ OSSL_LIST_DBG(elem->ossl_list_ ## name.list = NULL) \ if (list->alpha == elem) \ list->alpha = elem->ossl_list_ ## name.next; \ if (list->omega == elem) \ list->omega = elem->ossl_list_ ## name.prev; \ if (elem->ossl_list_ ## name.prev != NULL) \ elem->ossl_list_ ## name.prev->ossl_list_ ## name.next = \ elem->ossl_list_ ## name.next; \ if (elem->ossl_list_ ## name.next != NULL) \ elem->ossl_list_ ## name.next->ossl_list_ ## name.prev = \ elem->ossl_list_ ## name.prev; \ list->num_elems--; \ memset(&elem->ossl_list_ ## name, 0, \ sizeof(elem->ossl_list_ ## name)); \ } \ static ossl_unused ossl_inline void \ ossl_list_##name##_insert_head(OSSL_LIST(name) *list, type *elem) \ { \ assert(elem->ossl_list_ ## name.list == NULL); \ OSSL_LIST_DBG(elem->ossl_list_ ## name.list = list) \ if (list->alpha != NULL) \ list->alpha->ossl_list_ ## name.prev = elem; \ elem->ossl_list_ ## name.next = list->alpha; \ elem->ossl_list_ ## name.prev = NULL; \ list->alpha = elem; \ if (list->omega == NULL) \ list->omega = elem; \ list->num_elems++; \ } \ static ossl_unused ossl_inline void \ ossl_list_##name##_insert_tail(OSSL_LIST(name) *list, type *elem) \ { \ assert(elem->ossl_list_ ## name.list == NULL); \ OSSL_LIST_DBG(elem->ossl_list_ ## name.list = list) \ if (list->omega != NULL) \ list->omega->ossl_list_ ## name.next = elem; \ elem->ossl_list_ ## name.prev = list->omega; \ elem->ossl_list_ ## name.next = NULL; \ list->omega = elem; \ if (list->alpha == NULL) \ list->alpha = elem; \ list->num_elems++; \ } \ static ossl_unused ossl_inline void \ ossl_list_##name##_insert_before(OSSL_LIST(name) *list, type *e, \ type *elem) \ { \ assert(elem->ossl_list_ ## name.list == NULL); \ OSSL_LIST_DBG(elem->ossl_list_ ## name.list = list) \ elem->ossl_list_ ## name.next = e; \ elem->ossl_list_ ## name.prev = e->ossl_list_ ## name.prev; \ if (e->ossl_list_ ## name.prev != NULL) \ e->ossl_list_ ## name.prev->ossl_list_ ## name.next = elem; \ e->ossl_list_ ## name.prev = elem; \ if (list->alpha == e) \ list->alpha = elem; \ list->num_elems++; \ } \ static ossl_unused ossl_inline void \ ossl_list_##name##_insert_after(OSSL_LIST(name) *list, type *e, \ type *elem) \ { \ assert(elem->ossl_list_ ## name.list == NULL); \ OSSL_LIST_DBG(elem->ossl_list_ ## name.list = list) \ elem->ossl_list_ ## name.prev = e; \ elem->ossl_list_ ## name.next = e->ossl_list_ ## name.next; \ if (e->ossl_list_ ## name.next != NULL) \ e->ossl_list_ ## name.next->ossl_list_ ## name.prev = elem; \ e->ossl_list_ ## name.next = elem; \ if (list->omega == e) \ list->omega = elem; \ list->num_elems++; \ } \ struct ossl_list_st_ ## name # define DEFINE_LIST_OF(name, type) \ DECLARE_LIST_OF(name, type); \ DEFINE_LIST_OF_IMPL(name, type) #endif
./openssl/include/internal/param_build_set.h
/* * Copyright 2020-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_INTERNAL_PARAM_BUILD_SET_H # define OSSL_INTERNAL_PARAM_BUILD_SET_H # pragma once # include <openssl/safestack.h> # include <openssl/param_build.h> # include "internal/cryptlib.h" typedef union { OSSL_UNION_ALIGN; } OSSL_PARAM_ALIGNED_BLOCK; # define OSSL_PARAM_ALIGN_SIZE sizeof(OSSL_PARAM_ALIGNED_BLOCK) size_t ossl_param_bytes_to_blocks(size_t bytes); void ossl_param_set_secure_block(OSSL_PARAM *last, void *secure_buffer, size_t secure_buffer_sz); int ossl_param_build_set_int(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, int num); int ossl_param_build_set_long(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, long num); int ossl_param_build_set_utf8_string(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const char *buf); int ossl_param_build_set_octet_string(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const unsigned char *data, size_t data_len); int ossl_param_build_set_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const BIGNUM *bn); int ossl_param_build_set_bn_pad(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const BIGNUM *bn, size_t sz); int ossl_param_build_set_signed_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const BIGNUM *bn); int ossl_param_build_set_signed_bn_pad(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const BIGNUM *bn, size_t sz); int ossl_param_build_set_multi_key_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *names[], STACK_OF(BIGNUM_const) *stk); #endif /* OSSL_INTERNAL_PARAM_BUILD_SET_H */
./openssl/include/internal/quic_sf_list.h
/* * Copyright 2022-2023 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_SF_LIST_H # define OSSL_QUIC_SF_LIST_H #include "internal/common.h" #include "internal/uint_set.h" #include "internal/quic_record_rx.h" /* * Stream frame list * ================= * * This data structure supports similar operations as uint64 set but * it has slightly different invariants and also carries data associated with * the ranges in the list. * * Operations: * Insert frame (optimized insertion at the beginning and at the end). * Iterated peek into the frame(s) from the beginning. * Dropping frames from the beginning up to an offset (exclusive). * * Invariant: The frames in the list are sorted by the start and end bounds. * Invariant: There are no fully overlapping frames or frames that would * be fully encompassed by another frame in the list. * Invariant: No frame has start > end. * Invariant: The range start is inclusive the end is exclusive to be * able to mark an empty frame. * Invariant: The offset never points further than into the first frame. */ # ifndef OPENSSL_NO_QUIC typedef struct stream_frame_st STREAM_FRAME; typedef struct sframe_list_st { STREAM_FRAME *head, *tail; /* Is the tail frame final. */ unsigned int fin; /* Number of stream frames in the list. */ size_t num_frames; /* Offset of data not yet dropped */ uint64_t offset; /* Is head locked ? */ int head_locked; /* Cleanse data on release? */ int cleanse; } SFRAME_LIST; /* * Initializes the stream frame list fl. */ void ossl_sframe_list_init(SFRAME_LIST *fl); /* * Destroys the stream frame list fl releasing any data * still present inside it. */ void ossl_sframe_list_destroy(SFRAME_LIST *fl); /* * Insert a stream frame data into the list. * The data covers an offset range (range.start is inclusive, * range.end is exclusive). * fin should be set if this is the final frame of the stream. * Returns an error if a frame cannot be inserted - due to * STREAM_FRAME allocation error, or in case of erroneous * fin flag (this is an ossl_assert() check so a caller must * check it on its own too). */ int ossl_sframe_list_insert(SFRAME_LIST *fl, UINT_RANGE *range, OSSL_QRX_PKT *pkt, const unsigned char *data, int fin); /* * Iterator to peek at the contiguous frames at the beginning * of the frame list fl. * The *data covers an offset range (range.start is inclusive, * range.end is exclusive). * *fin is set if this is the final frame of the stream. * Opaque iterator *iter can be used to peek at the subsequent * frame if there is any without any gap before it. * Returns 1 on success. * Returns 0 if there is no further contiguous frame. In that * case *fin is set, if the end of the stream is reached. */ int ossl_sframe_list_peek(const SFRAME_LIST *fl, void **iter, UINT_RANGE *range, const unsigned char **data, int *fin); /* * Drop all frames up to the offset limit. * Also unlocks the head frame if locked. * Returns 1 on success. * Returns 0 when trying to drop frames at offsets that were not * received yet. (ossl_assert() is used to check, so this is an invalid call.) */ int ossl_sframe_list_drop_frames(SFRAME_LIST *fl, uint64_t limit); /* * Locks and returns the head frame of fl if it is readable - read offset is * at the beginning or middle of the frame. * range is set to encompass the not yet read part of the head frame, * data pointer is set to appropriate offset within the frame if the read * offset points in the middle of the frame, * fin is set to 1 if the head frame is also the tail frame. * Returns 1 on success, 0 if there is no readable data or the head * frame is already locked. */ int ossl_sframe_list_lock_head(SFRAME_LIST *fl, UINT_RANGE *range, const unsigned char **data, int *fin); /* * Just returns whether the head frame is locked by previous * ossl_sframe_list_lock_head() call. */ int ossl_sframe_list_is_head_locked(SFRAME_LIST *fl); /* * Callback function type to write stream frame data to some * side storage before the packet containing the frame data * is released. * It should return 1 on success or 0 if there is not enough * space available in the side storage. */ typedef int (sframe_list_write_at_cb)(uint64_t logical_offset, const unsigned char *buf, size_t buf_len, void *cb_arg); /* * Move the frame data in all the stream frames in the list fl * from the packets to the side storage using the write_at_cb * callback. * Returns 1 if all the calls to the callback return 1. * If the callback returns 0, the function stops processing further * frames and returns 0. */ int ossl_sframe_list_move_data(SFRAME_LIST *fl, sframe_list_write_at_cb *write_at_cb, void *cb_arg); # endif #endif
./openssl/include/internal/safe_math.h
/* * Copyright 2021-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_INTERNAL_SAFE_MATH_H # define OSSL_INTERNAL_SAFE_MATH_H # pragma once # include <openssl/e_os2.h> /* For 'ossl_inline' */ # ifndef OPENSSL_NO_BUILTIN_OVERFLOW_CHECKING # ifdef __has_builtin # define has(func) __has_builtin(func) # elif __GNUC__ > 5 # define has(func) 1 # endif # endif /* OPENSSL_NO_BUILTIN_OVERFLOW_CHECKING */ # ifndef has # define has(func) 0 # endif /* * Safe addition helpers */ # if has(__builtin_add_overflow) # define OSSL_SAFE_MATH_ADDS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_add_ ## type_name(type a, \ type b, \ int *err) \ { \ type r; \ \ if (!__builtin_add_overflow(a, b, &r)) \ return r; \ *err |= 1; \ return a < 0 ? min : max; \ } # define OSSL_SAFE_MATH_ADDU(type_name, type, max) \ static ossl_inline ossl_unused type safe_add_ ## type_name(type a, \ type b, \ int *err) \ { \ type r; \ \ if (!__builtin_add_overflow(a, b, &r)) \ return r; \ *err |= 1; \ return a + b; \ } # else /* has(__builtin_add_overflow) */ # define OSSL_SAFE_MATH_ADDS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_add_ ## type_name(type a, \ type b, \ int *err) \ { \ if ((a < 0) ^ (b < 0) \ || (a > 0 && b <= max - a) \ || (a < 0 && b >= min - a) \ || a == 0) \ return a + b; \ *err |= 1; \ return a < 0 ? min : max; \ } # define OSSL_SAFE_MATH_ADDU(type_name, type, max) \ static ossl_inline ossl_unused type safe_add_ ## type_name(type a, \ type b, \ int *err) \ { \ if (b > max - a) \ *err |= 1; \ return a + b; \ } # endif /* has(__builtin_add_overflow) */ /* * Safe subtraction helpers */ # if has(__builtin_sub_overflow) # define OSSL_SAFE_MATH_SUBS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_sub_ ## type_name(type a, \ type b, \ int *err) \ { \ type r; \ \ if (!__builtin_sub_overflow(a, b, &r)) \ return r; \ *err |= 1; \ return a < 0 ? min : max; \ } # else /* has(__builtin_sub_overflow) */ # define OSSL_SAFE_MATH_SUBS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_sub_ ## type_name(type a, \ type b, \ int *err) \ { \ if (!((a < 0) ^ (b < 0)) \ || (b > 0 && a >= min + b) \ || (b < 0 && a <= max + b) \ || b == 0) \ return a - b; \ *err |= 1; \ return a < 0 ? min : max; \ } # endif /* has(__builtin_sub_overflow) */ # define OSSL_SAFE_MATH_SUBU(type_name, type) \ static ossl_inline ossl_unused type safe_sub_ ## type_name(type a, \ type b, \ int *err) \ { \ if (b > a) \ *err |= 1; \ return a - b; \ } /* * Safe multiplication helpers */ # if has(__builtin_mul_overflow) # define OSSL_SAFE_MATH_MULS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_mul_ ## type_name(type a, \ type b, \ int *err) \ { \ type r; \ \ if (!__builtin_mul_overflow(a, b, &r)) \ return r; \ *err |= 1; \ return (a < 0) ^ (b < 0) ? min : max; \ } # define OSSL_SAFE_MATH_MULU(type_name, type, max) \ static ossl_inline ossl_unused type safe_mul_ ## type_name(type a, \ type b, \ int *err) \ { \ type r; \ \ if (!__builtin_mul_overflow(a, b, &r)) \ return r; \ *err |= 1; \ return a * b; \ } # else /* has(__builtin_mul_overflow) */ # define OSSL_SAFE_MATH_MULS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_mul_ ## type_name(type a, \ type b, \ int *err) \ { \ if (a == 0 || b == 0) \ return 0; \ if (a == 1) \ return b; \ if (b == 1) \ return a; \ if (a != min && b != min) { \ const type x = a < 0 ? -a : a; \ const type y = b < 0 ? -b : b; \ \ if (x <= max / y) \ return a * b; \ } \ *err |= 1; \ return (a < 0) ^ (b < 0) ? min : max; \ } # define OSSL_SAFE_MATH_MULU(type_name, type, max) \ static ossl_inline ossl_unused type safe_mul_ ## type_name(type a, \ type b, \ int *err) \ { \ if (b != 0 && a > max / b) \ *err |= 1; \ return a * b; \ } # endif /* has(__builtin_mul_overflow) */ /* * Safe division helpers */ # define OSSL_SAFE_MATH_DIVS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_div_ ## type_name(type a, \ type b, \ int *err) \ { \ if (b == 0) { \ *err |= 1; \ return a < 0 ? min : max; \ } \ if (b == -1 && a == min) { \ *err |= 1; \ return max; \ } \ return a / b; \ } # define OSSL_SAFE_MATH_DIVU(type_name, type, max) \ static ossl_inline ossl_unused type safe_div_ ## type_name(type a, \ type b, \ int *err) \ { \ if (b != 0) \ return a / b; \ *err |= 1; \ return max; \ } /* * Safe modulus helpers */ # define OSSL_SAFE_MATH_MODS(type_name, type, min, max) \ static ossl_inline ossl_unused type safe_mod_ ## type_name(type a, \ type b, \ int *err) \ { \ if (b == 0) { \ *err |= 1; \ return 0; \ } \ if (b == -1 && a == min) { \ *err |= 1; \ return max; \ } \ return a % b; \ } # define OSSL_SAFE_MATH_MODU(type_name, type) \ static ossl_inline ossl_unused type safe_mod_ ## type_name(type a, \ type b, \ int *err) \ { \ if (b != 0) \ return a % b; \ *err |= 1; \ return 0; \ } /* * Safe negation helpers */ # define OSSL_SAFE_MATH_NEGS(type_name, type, min) \ static ossl_inline ossl_unused type safe_neg_ ## type_name(type a, \ int *err) \ { \ if (a != min) \ return -a; \ *err |= 1; \ return min; \ } # define OSSL_SAFE_MATH_NEGU(type_name, type) \ static ossl_inline ossl_unused type safe_neg_ ## type_name(type a, \ int *err) \ { \ if (a == 0) \ return a; \ *err |= 1; \ return 1 + ~a; \ } /* * Safe absolute value helpers */ # define OSSL_SAFE_MATH_ABSS(type_name, type, min) \ static ossl_inline ossl_unused type safe_abs_ ## type_name(type a, \ int *err) \ { \ if (a != min) \ return a < 0 ? -a : a; \ *err |= 1; \ return min; \ } # define OSSL_SAFE_MATH_ABSU(type_name, type) \ static ossl_inline ossl_unused type safe_abs_ ## type_name(type a, \ int *err) \ { \ return a; \ } /* * Safe fused multiply divide helpers * * These are a bit obscure: * . They begin by checking the denominator for zero and getting rid of this * corner case. * * . Second is an attempt to do the multiplication directly, if it doesn't * overflow, the quotient is returned (for signed values there is a * potential problem here which isn't present for unsigned). * * . Finally, the multiplication/division is transformed so that the larger * of the numerators is divided first. This requires a remainder * correction: * * a b / c = (a / c) b + (a mod c) b / c, where a > b * * The individual operations need to be overflow checked (again signed * being more problematic). * * The algorithm used is not perfect but it should be "good enough". */ # define OSSL_SAFE_MATH_MULDIVS(type_name, type, max) \ static ossl_inline ossl_unused type safe_muldiv_ ## type_name(type a, \ type b, \ type c, \ int *err) \ { \ int e2 = 0; \ type q, r, x, y; \ \ if (c == 0) { \ *err |= 1; \ return a == 0 || b == 0 ? 0 : max; \ } \ x = safe_mul_ ## type_name(a, b, &e2); \ if (!e2) \ return safe_div_ ## type_name(x, c, err); \ if (b > a) { \ x = b; \ b = a; \ a = x; \ } \ q = safe_div_ ## type_name(a, c, err); \ r = safe_mod_ ## type_name(a, c, err); \ x = safe_mul_ ## type_name(r, b, err); \ y = safe_mul_ ## type_name(q, b, err); \ q = safe_div_ ## type_name(x, c, err); \ return safe_add_ ## type_name(y, q, err); \ } # define OSSL_SAFE_MATH_MULDIVU(type_name, type, max) \ static ossl_inline ossl_unused type safe_muldiv_ ## type_name(type a, \ type b, \ type c, \ int *err) \ { \ int e2 = 0; \ type x, y; \ \ if (c == 0) { \ *err |= 1; \ return a == 0 || b == 0 ? 0 : max; \ } \ x = safe_mul_ ## type_name(a, b, &e2); \ if (!e2) \ return x / c; \ if (b > a) { \ x = b; \ b = a; \ a = x; \ } \ x = safe_mul_ ## type_name(a % c, b, err); \ y = safe_mul_ ## type_name(a / c, b, err); \ return safe_add_ ## type_name(y, x / c, err); \ } /* * Calculate a / b rounding up: * i.e. a / b + (a % b != 0) * Which is usually (less safely) converted to (a + b - 1) / b * If you *know* that b != 0, then it's safe to ignore err. */ #define OSSL_SAFE_MATH_DIV_ROUND_UP(type_name, type, max) \ static ossl_inline ossl_unused type safe_div_round_up_ ## type_name \ (type a, type b, int *errp) \ { \ type x; \ int *err, err_local = 0; \ \ /* Allow errors to be ignored by callers */ \ err = errp != NULL ? errp : &err_local; \ /* Fast path, both positive */ \ if (b > 0 && a > 0) { \ /* Faster path: no overflow concerns */ \ if (a < max - b) \ return (a + b - 1) / b; \ return a / b + (a % b != 0); \ } \ if (b == 0) { \ *err |= 1; \ return a == 0 ? 0 : max; \ } \ if (a == 0) \ return 0; \ /* Rather slow path because there are negatives involved */ \ x = safe_mod_ ## type_name(a, b, err); \ return safe_add_ ## type_name(safe_div_ ## type_name(a, b, err), \ x != 0, err); \ } /* Calculate ranges of types */ # define OSSL_SAFE_MATH_MINS(type) ((type)1 << (sizeof(type) * 8 - 1)) # define OSSL_SAFE_MATH_MAXS(type) (~OSSL_SAFE_MATH_MINS(type)) # define OSSL_SAFE_MATH_MAXU(type) (~(type)0) /* * Wrapper macros to create all the functions of a given type */ # define OSSL_SAFE_MATH_SIGNED(type_name, type) \ OSSL_SAFE_MATH_ADDS(type_name, type, OSSL_SAFE_MATH_MINS(type), \ OSSL_SAFE_MATH_MAXS(type)) \ OSSL_SAFE_MATH_SUBS(type_name, type, OSSL_SAFE_MATH_MINS(type), \ OSSL_SAFE_MATH_MAXS(type)) \ OSSL_SAFE_MATH_MULS(type_name, type, OSSL_SAFE_MATH_MINS(type), \ OSSL_SAFE_MATH_MAXS(type)) \ OSSL_SAFE_MATH_DIVS(type_name, type, OSSL_SAFE_MATH_MINS(type), \ OSSL_SAFE_MATH_MAXS(type)) \ OSSL_SAFE_MATH_MODS(type_name, type, OSSL_SAFE_MATH_MINS(type), \ OSSL_SAFE_MATH_MAXS(type)) \ OSSL_SAFE_MATH_DIV_ROUND_UP(type_name, type, \ OSSL_SAFE_MATH_MAXS(type)) \ OSSL_SAFE_MATH_MULDIVS(type_name, type, OSSL_SAFE_MATH_MAXS(type)) \ OSSL_SAFE_MATH_NEGS(type_name, type, OSSL_SAFE_MATH_MINS(type)) \ OSSL_SAFE_MATH_ABSS(type_name, type, OSSL_SAFE_MATH_MINS(type)) # define OSSL_SAFE_MATH_UNSIGNED(type_name, type) \ OSSL_SAFE_MATH_ADDU(type_name, type, OSSL_SAFE_MATH_MAXU(type)) \ OSSL_SAFE_MATH_SUBU(type_name, type) \ OSSL_SAFE_MATH_MULU(type_name, type, OSSL_SAFE_MATH_MAXU(type)) \ OSSL_SAFE_MATH_DIVU(type_name, type, OSSL_SAFE_MATH_MAXU(type)) \ OSSL_SAFE_MATH_MODU(type_name, type) \ OSSL_SAFE_MATH_DIV_ROUND_UP(type_name, type, \ OSSL_SAFE_MATH_MAXU(type)) \ OSSL_SAFE_MATH_MULDIVU(type_name, type, OSSL_SAFE_MATH_MAXU(type)) \ OSSL_SAFE_MATH_NEGU(type_name, type) \ OSSL_SAFE_MATH_ABSU(type_name, type) #endif /* OSSL_INTERNAL_SAFE_MATH_H */
./openssl/include/internal/time.h
/* * Copyright 2022-2023 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_INTERNAL_TIME_H # define OSSL_INTERNAL_TIME_H # pragma once # include <openssl/e_os2.h> /* uint64_t */ # include "internal/e_os.h" /* for struct timeval */ # include "internal/safe_math.h" /* * Internal type defining a time. * This should be treated as an opaque structure. * * The time datum is Unix's 1970 and at nanosecond precision, this gives * a range of 584 years roughly. */ typedef struct { uint64_t t; /* Ticks since the epoch */ } OSSL_TIME; /* The precision of times allows this many values per second */ # define OSSL_TIME_SECOND ((uint64_t)1000000000) /* One millisecond. */ # define OSSL_TIME_MS (OSSL_TIME_SECOND / 1000) /* One microsecond. */ # define OSSL_TIME_US (OSSL_TIME_MS / 1000) /* One nanosecond. */ # define OSSL_TIME_NS (OSSL_TIME_US / 1000) #define ossl_seconds2time(s) ossl_ticks2time((s) * OSSL_TIME_SECOND) #define ossl_time2seconds(t) (ossl_time2ticks(t) / OSSL_TIME_SECOND) #define ossl_ms2time(ms) ossl_ticks2time((ms) * OSSL_TIME_MS) #define ossl_time2ms(t) (ossl_time2ticks(t) / OSSL_TIME_MS) #define ossl_us2time(us) ossl_ticks2time((us) * OSSL_TIME_US) #define ossl_time2us(t) (ossl_time2ticks(t) / OSSL_TIME_US) /* * Arithmetic operations on times. * These operations are saturating, in that an overflow or underflow returns * the largest or smallest value respectively. */ OSSL_SAFE_MATH_UNSIGNED(time, uint64_t) /* Convert a tick count into a time */ static ossl_unused ossl_inline OSSL_TIME ossl_ticks2time(uint64_t ticks) { OSSL_TIME r; r.t = ticks; return r; } /* Convert a time to a tick count */ static ossl_unused ossl_inline uint64_t ossl_time2ticks(OSSL_TIME t) { return t.t; } /* Get current time */ OSSL_TIME ossl_time_now(void); /* The beginning and end of the time range */ static ossl_unused ossl_inline OSSL_TIME ossl_time_zero(void) { return ossl_ticks2time(0); } static ossl_unused ossl_inline OSSL_TIME ossl_time_infinite(void) { return ossl_ticks2time(~(uint64_t)0); } /* Convert time to timeval */ static ossl_unused ossl_inline struct timeval ossl_time_to_timeval(OSSL_TIME t) { struct timeval tv; int err = 0; /* * Round up any nano secs which struct timeval doesn't support. Ensures that * we never return a zero time if the input time is non zero */ t.t = safe_add_time(t.t, OSSL_TIME_US - 1, &err); if (err) t = ossl_time_infinite(); #ifdef _WIN32 tv.tv_sec = (long int)(t.t / OSSL_TIME_SECOND); #else tv.tv_sec = (time_t)(t.t / OSSL_TIME_SECOND); #endif tv.tv_usec = (t.t % OSSL_TIME_SECOND) / OSSL_TIME_US; return tv; } /* Convert timeval to time */ static ossl_unused ossl_inline OSSL_TIME ossl_time_from_timeval(struct timeval tv) { OSSL_TIME t; #ifndef __DJGPP__ /* tv_sec is unsigned on djgpp. */ if (tv.tv_sec < 0) return ossl_time_zero(); #endif t.t = tv.tv_sec * OSSL_TIME_SECOND + tv.tv_usec * OSSL_TIME_US; return t; } /* Convert OSSL_TIME to time_t */ static ossl_unused ossl_inline time_t ossl_time_to_time_t(OSSL_TIME t) { return (time_t)(t.t / OSSL_TIME_SECOND); } /* Convert time_t to OSSL_TIME */ static ossl_unused ossl_inline OSSL_TIME ossl_time_from_time_t(time_t t) { OSSL_TIME ot; ot.t = t; ot.t *= OSSL_TIME_SECOND; return ot; } /* Compare two time values, return -1 if less, 1 if greater and 0 if equal */ static ossl_unused ossl_inline int ossl_time_compare(OSSL_TIME a, OSSL_TIME b) { if (a.t > b.t) return 1; if (a.t < b.t) return -1; return 0; } /* Returns true if an OSSL_TIME is ossl_time_zero(). */ static ossl_unused ossl_inline int ossl_time_is_zero(OSSL_TIME t) { return ossl_time_compare(t, ossl_time_zero()) == 0; } /* Returns true if an OSSL_TIME is ossl_time_infinite(). */ static ossl_unused ossl_inline int ossl_time_is_infinite(OSSL_TIME t) { return ossl_time_compare(t, ossl_time_infinite()) == 0; } static ossl_unused ossl_inline OSSL_TIME ossl_time_add(OSSL_TIME a, OSSL_TIME b) { OSSL_TIME r; int err = 0; r.t = safe_add_time(a.t, b.t, &err); return err ? ossl_time_infinite() : r; } static ossl_unused ossl_inline OSSL_TIME ossl_time_subtract(OSSL_TIME a, OSSL_TIME b) { OSSL_TIME r; int err = 0; r.t = safe_sub_time(a.t, b.t, &err); return err ? ossl_time_zero() : r; } /* Returns |a - b|. */ static ossl_unused ossl_inline OSSL_TIME ossl_time_abs_difference(OSSL_TIME a, OSSL_TIME b) { return a.t > b.t ? ossl_time_subtract(a, b) : ossl_time_subtract(b, a); } static ossl_unused ossl_inline OSSL_TIME ossl_time_multiply(OSSL_TIME a, uint64_t b) { OSSL_TIME r; int err = 0; r.t = safe_mul_time(a.t, b, &err); return err ? ossl_time_infinite() : r; } static ossl_unused ossl_inline OSSL_TIME ossl_time_divide(OSSL_TIME a, uint64_t b) { OSSL_TIME r; int err = 0; r.t = safe_div_time(a.t, b, &err); return err ? ossl_time_zero() : r; } static ossl_unused ossl_inline OSSL_TIME ossl_time_muldiv(OSSL_TIME a, uint64_t b, uint64_t c) { OSSL_TIME r; int err = 0; r.t = safe_muldiv_time(a.t, b, c, &err); return err ? ossl_time_zero() : r; } /* Return higher of the two given time values. */ static ossl_unused ossl_inline OSSL_TIME ossl_time_max(OSSL_TIME a, OSSL_TIME b) { return a.t > b.t ? a : b; } /* Return the lower of the two given time values. */ static ossl_unused ossl_inline OSSL_TIME ossl_time_min(OSSL_TIME a, OSSL_TIME b) { return a.t < b.t ? a : b; } #endif
./openssl/include/internal/thread_once.h
/* * Copyright 1995-2021 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_INTERNAL_THREAD_ONCE_H # define OSSL_INTERNAL_THREAD_ONCE_H # pragma once # include <openssl/crypto.h> /* * Initialisation of global data should never happen via "RUN_ONCE" inside the * FIPS module. Global data should instead always be associated with a specific * OSSL_LIB_CTX object. In this way data will get cleaned up correctly when the * module gets unloaded. */ # if !defined(FIPS_MODULE) || defined(ALLOW_RUN_ONCE_IN_FIPS) /* * DEFINE_RUN_ONCE: Define an initialiser function that should be run exactly * once. It takes no arguments and returns an int result (1 for success or * 0 for failure). Typical usage might be: * * DEFINE_RUN_ONCE(myinitfunc) * { * do_some_initialisation(); * if (init_is_successful()) * return 1; * * return 0; * } */ # define DEFINE_RUN_ONCE(init) \ static int init(void); \ int init##_ossl_ret_ = 0; \ void init##_ossl_(void) \ { \ init##_ossl_ret_ = init(); \ } \ static int init(void) /* * DECLARE_RUN_ONCE: Declare an initialiser function that should be run exactly * once that has been defined in another file via DEFINE_RUN_ONCE(). */ # define DECLARE_RUN_ONCE(init) \ extern int init##_ossl_ret_; \ void init##_ossl_(void); /* * DEFINE_RUN_ONCE_STATIC: Define an initialiser function that should be run * exactly once. This function will be declared as static within the file. It * takes no arguments and returns an int result (1 for success or 0 for * failure). Typical usage might be: * * DEFINE_RUN_ONCE_STATIC(myinitfunc) * { * do_some_initialisation(); * if (init_is_successful()) * return 1; * * return 0; * } */ # define DEFINE_RUN_ONCE_STATIC(init) \ static int init(void); \ static int init##_ossl_ret_ = 0; \ static void init##_ossl_(void) \ { \ init##_ossl_ret_ = init(); \ } \ static int init(void) /* * DEFINE_RUN_ONCE_STATIC_ALT: Define an alternative initialiser function. This * function will be declared as static within the file. It takes no arguments * and returns an int result (1 for success or 0 for failure). An alternative * initialiser function is expected to be associated with a primary initialiser * function defined via DEFINE_ONCE_STATIC where both functions use the same * CRYPTO_ONCE object to synchronise. Where an alternative initialiser function * is used only one of the primary or the alternative initialiser function will * ever be called - and that function will be called exactly once. Definition * of an alternative initialiser function MUST occur AFTER the definition of the * primary initialiser function. * * Typical usage might be: * * DEFINE_RUN_ONCE_STATIC(myinitfunc) * { * do_some_initialisation(); * if (init_is_successful()) * return 1; * * return 0; * } * * DEFINE_RUN_ONCE_STATIC_ALT(myaltinitfunc, myinitfunc) * { * do_some_alternative_initialisation(); * if (init_is_successful()) * return 1; * * return 0; * } */ # define DEFINE_RUN_ONCE_STATIC_ALT(initalt, init) \ static int initalt(void); \ static void initalt##_ossl_(void) \ { \ init##_ossl_ret_ = initalt(); \ } \ static int initalt(void) /* * RUN_ONCE - use CRYPTO_THREAD_run_once, and check if the init succeeded * @once: pointer to static object of type CRYPTO_ONCE * @init: function name that was previously given to DEFINE_RUN_ONCE, * DEFINE_RUN_ONCE_STATIC or DECLARE_RUN_ONCE. This function * must return 1 for success or 0 for failure. * * The return value is 1 on success (*) or 0 in case of error. * * (*) by convention, since the init function must return 1 on success. */ # define RUN_ONCE(once, init) \ (CRYPTO_THREAD_run_once(once, init##_ossl_) ? init##_ossl_ret_ : 0) /* * RUN_ONCE_ALT - use CRYPTO_THREAD_run_once, to run an alternative initialiser * function and check if that initialisation succeeded * @once: pointer to static object of type CRYPTO_ONCE * @initalt: alternative initialiser function name that was previously given to * DEFINE_RUN_ONCE_STATIC_ALT. This function must return 1 for * success or 0 for failure. * @init: primary initialiser function name that was previously given to * DEFINE_RUN_ONCE_STATIC. This function must return 1 for success or * 0 for failure. * * The return value is 1 on success (*) or 0 in case of error. * * (*) by convention, since the init function must return 1 on success. */ # define RUN_ONCE_ALT(once, initalt, init) \ (CRYPTO_THREAD_run_once(once, initalt##_ossl_) ? init##_ossl_ret_ : 0) # endif /* FIPS_MODULE */ #endif /* OSSL_INTERNAL_THREAD_ONCE_H */
./openssl/include/internal/packet_quic.h
/* * Copyright 2022-2023 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_INTERNAL_PACKET_QUIC_H # define OSSL_INTERNAL_PACKET_QUIC_H # pragma once # include "internal/packet.h" # include "internal/quic_vlint.h" # ifndef OPENSSL_NO_QUIC /* * Decodes a QUIC variable-length integer in |pkt| and stores the result in * |data|. */ __owur static ossl_inline int PACKET_get_quic_vlint(PACKET *pkt, uint64_t *data) { size_t enclen; if (PACKET_remaining(pkt) < 1) return 0; enclen = ossl_quic_vlint_decode_len(*pkt->curr); if (PACKET_remaining(pkt) < enclen) return 0; *data = ossl_quic_vlint_decode_unchecked(pkt->curr); packet_forward(pkt, enclen); return 1; } /* * Decodes a QUIC variable-length integer in |pkt| and stores the result in * |data|. Unlike PACKET_get_quic_vlint, this does not advance the current * position. If was_minimal is non-NULL, *was_minimal is set to 1 if the integer * was encoded using the minimal possible number of bytes and 0 otherwise. */ __owur static ossl_inline int PACKET_peek_quic_vlint_ex(PACKET *pkt, uint64_t *data, int *was_minimal) { size_t enclen; if (PACKET_remaining(pkt) < 1) return 0; enclen = ossl_quic_vlint_decode_len(*pkt->curr); if (PACKET_remaining(pkt) < enclen) return 0; *data = ossl_quic_vlint_decode_unchecked(pkt->curr); if (was_minimal != NULL) *was_minimal = (enclen == ossl_quic_vlint_encode_len(*data)); return 1; } __owur static ossl_inline int PACKET_peek_quic_vlint(PACKET *pkt, uint64_t *data) { return PACKET_peek_quic_vlint_ex(pkt, data, NULL); } /* * Skips over a QUIC variable-length integer in |pkt| without decoding it. */ __owur static ossl_inline int PACKET_skip_quic_vlint(PACKET *pkt) { size_t enclen; if (PACKET_remaining(pkt) < 1) return 0; enclen = ossl_quic_vlint_decode_len(*pkt->curr); if (PACKET_remaining(pkt) < enclen) return 0; packet_forward(pkt, enclen); return 1; } /* * Reads a variable-length vector prefixed with a QUIC variable-length integer * denoting the length, and stores the contents in |subpkt|. |pkt| can equal * |subpkt|. Data is not copied: the |subpkt| packet will share its underlying * buffer with the original |pkt|, so data wrapped by |pkt| must outlive the * |subpkt|. Upon failure, the original |pkt| and |subpkt| are not modified. */ __owur static ossl_inline int PACKET_get_quic_length_prefixed(PACKET *pkt, PACKET *subpkt) { uint64_t length; const unsigned char *data; PACKET tmp = *pkt; if (!PACKET_get_quic_vlint(&tmp, &length) || length > SIZE_MAX || !PACKET_get_bytes(&tmp, &data, (size_t)length)) { return 0; } *pkt = tmp; subpkt->curr = data; subpkt->remaining = (size_t)length; return 1; } /* * Starts a QUIC sub-packet headed by a QUIC variable-length integer. A 4-byte * representation is used. */ __owur int WPACKET_start_quic_sub_packet(WPACKET *pkt); /* * Starts a QUIC sub-packet headed by a QUIC variable-length integer. max_len * specifies the upper bound for the sub-packet size at the time the sub-packet * is closed, which determines the encoding size for the variable-length * integer header. max_len can be a precise figure or a worst-case bound * if a precise figure is not available. */ __owur int WPACKET_start_quic_sub_packet_bound(WPACKET *pkt, size_t max_len); /* * Allocates a QUIC sub-packet with exactly len bytes of payload, headed by a * QUIC variable-length integer. The pointer to the payload buffer is output and * must be filled by the caller. This function assures optimal selection of * variable-length integer encoding length. */ __owur int WPACKET_quic_sub_allocate_bytes(WPACKET *pkt, size_t len, unsigned char **bytes); /* * Write a QUIC variable-length integer to the packet. */ __owur int WPACKET_quic_write_vlint(WPACKET *pkt, uint64_t v); # endif /* OPENSSL_NO_QUIC */ #endif /* OSSL_INTERNAL_PACKET_QUIC_H */
./openssl/include/internal/common.h
/* * Copyright 1995-2023 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_INTERNAL_COMMON_H # define OSSL_INTERNAL_COMMON_H # pragma once # include <stdlib.h> # include <string.h> # include "openssl/configuration.h" # include "internal/e_os.h" /* ossl_inline in many files */ # include "internal/nelem.h" # if defined(__GNUC__) || defined(__clang__) # define ossl_likely(x) __builtin_expect(!!(x), 1) # define ossl_unlikely(x) __builtin_expect(!!(x), 0) # else # define ossl_likely(x) x # define ossl_unlikely(x) x # endif # if defined(__GNUC__) || defined(__clang__) # define ALIGN32 __attribute((aligned(32))) # define ALIGN64 __attribute((aligned(64))) # elif defined(_MSC_VER) # define ALIGN32 __declspec(align(32)) # define ALIGN64 __declspec(align(64)) # else # define ALIGN32 # define ALIGN64 # endif # ifdef NDEBUG # define ossl_assert(x) ossl_likely((x) != 0) # else __owur static ossl_inline int ossl_assert_int(int expr, const char *exprstr, const char *file, int line) { if (!expr) OPENSSL_die(exprstr, file, line); return expr; } # define ossl_assert(x) ossl_assert_int((x) != 0, "Assertion failed: "#x, \ __FILE__, __LINE__) # endif /* Check if |pre|, which must be a string literal, is a prefix of |str| */ #define HAS_PREFIX(str, pre) (strncmp(str, pre "", sizeof(pre) - 1) == 0) /* As before, and if check succeeds, advance |str| past the prefix |pre| */ #define CHECK_AND_SKIP_PREFIX(str, pre) \ (HAS_PREFIX(str, pre) ? ((str) += sizeof(pre) - 1, 1) : 0) /* Check if the string literal |p| is a case-insensitive prefix of |s| */ #define HAS_CASE_PREFIX(s, p) (OPENSSL_strncasecmp(s, p "", sizeof(p) - 1) == 0) /* As before, and if check succeeds, advance |str| past the prefix |pre| */ #define CHECK_AND_SKIP_CASE_PREFIX(str, pre) \ (HAS_CASE_PREFIX(str, pre) ? ((str) += sizeof(pre) - 1, 1) : 0) /* Check if the string literal |suffix| is a case-insensitive suffix of |str| */ #define HAS_CASE_SUFFIX(str, suffix) (strlen(str) < sizeof(suffix) - 1 ? 0 : \ OPENSSL_strcasecmp(str + strlen(str) - sizeof(suffix) + 1, suffix "") == 0) /* * Use this inside a union with the field that needs to be aligned to a * reasonable boundary for the platform. The most pessimistic alignment * of the listed types will be used by the compiler. */ # define OSSL_UNION_ALIGN \ double align; \ ossl_uintmax_t align_int; \ void *align_ptr # define OPENSSL_CONF "openssl.cnf" # ifndef OPENSSL_SYS_VMS # define X509_CERT_AREA OPENSSLDIR # define X509_CERT_DIR OPENSSLDIR "/certs" # define X509_CERT_FILE OPENSSLDIR "/cert.pem" # define X509_PRIVATE_DIR OPENSSLDIR "/private" # define CTLOG_FILE OPENSSLDIR "/ct_log_list.cnf" # else # define X509_CERT_AREA "OSSL$DATAROOT:[000000]" # define X509_CERT_DIR "OSSL$DATAROOT:[CERTS]" # define X509_CERT_FILE "OSSL$DATAROOT:[000000]cert.pem" # define X509_PRIVATE_DIR "OSSL$DATAROOT:[PRIVATE]" # define CTLOG_FILE "OSSL$DATAROOT:[000000]ct_log_list.cnf" # endif # define X509_CERT_DIR_EVP "SSL_CERT_DIR" # define X509_CERT_FILE_EVP "SSL_CERT_FILE" # define CTLOG_FILE_EVP "CTLOG_FILE" /* size of string representations */ # define DECIMAL_SIZE(type) ((sizeof(type)*8+2)/3+1) # define HEX_SIZE(type) (sizeof(type)*2) # define c2l(c,l) (l = ((unsigned long)(*((c)++))) , \ l|=(((unsigned long)(*((c)++)))<< 8), \ l|=(((unsigned long)(*((c)++)))<<16), \ l|=(((unsigned long)(*((c)++)))<<24)) /* NOTE - c is not incremented as per c2l */ # define c2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c))))<<24; \ case 7: l2|=((unsigned long)(*(--(c))))<<16; \ case 6: l2|=((unsigned long)(*(--(c))))<< 8; \ case 5: l2|=((unsigned long)(*(--(c)))); \ case 4: l1 =((unsigned long)(*(--(c))))<<24; \ case 3: l1|=((unsigned long)(*(--(c))))<<16; \ case 2: l1|=((unsigned long)(*(--(c))))<< 8; \ case 1: l1|=((unsigned long)(*(--(c)))); \ } \ } # define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>>24)&0xff)) # define n2l(c,l) (l =((unsigned long)(*((c)++)))<<24, \ l|=((unsigned long)(*((c)++)))<<16, \ l|=((unsigned long)(*((c)++)))<< 8, \ l|=((unsigned long)(*((c)++)))) # define n2l8(c,l) (l =((uint64_t)(*((c)++)))<<56, \ l|=((uint64_t)(*((c)++)))<<48, \ l|=((uint64_t)(*((c)++)))<<40, \ l|=((uint64_t)(*((c)++)))<<32, \ l|=((uint64_t)(*((c)++)))<<24, \ l|=((uint64_t)(*((c)++)))<<16, \ l|=((uint64_t)(*((c)++)))<< 8, \ l|=((uint64_t)(*((c)++)))) # define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) # define l2n8(l,c) (*((c)++)=(unsigned char)(((l)>>56)&0xff), \ *((c)++)=(unsigned char)(((l)>>48)&0xff), \ *((c)++)=(unsigned char)(((l)>>40)&0xff), \ *((c)++)=(unsigned char)(((l)>>32)&0xff), \ *((c)++)=(unsigned char)(((l)>>24)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) /* NOTE - c is not incremented as per l2c */ # define l2cn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ case 7: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ case 6: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \ case 4: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ case 3: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ case 2: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \ } \ } # define n2s(c,s) ((s=(((unsigned int)((c)[0]))<< 8)| \ (((unsigned int)((c)[1])) )),(c)+=2) # define s2n(s,c) (((c)[0]=(unsigned char)(((s)>> 8)&0xff), \ (c)[1]=(unsigned char)(((s) )&0xff)),(c)+=2) # define n2l3(c,l) ((l =(((unsigned long)((c)[0]))<<16)| \ (((unsigned long)((c)[1]))<< 8)| \ (((unsigned long)((c)[2])) )),(c)+=3) # define l2n3(l,c) (((c)[0]=(unsigned char)(((l)>>16)&0xff), \ (c)[1]=(unsigned char)(((l)>> 8)&0xff), \ (c)[2]=(unsigned char)(((l) )&0xff)),(c)+=3) static ossl_inline int ossl_ends_with_dirsep(const char *path) { if (*path != '\0') path += strlen(path) - 1; # if defined __VMS if (*path == ']' || *path == '>' || *path == ':') return 1; # elif defined _WIN32 if (*path == '\\') return 1; # endif return *path == '/'; } static ossl_inline int ossl_is_absolute_path(const char *path) { # if defined __VMS if (strchr(path, ':') != NULL || ((path[0] == '[' || path[0] == '<') && path[1] != '.' && path[1] != '-' && path[1] != ']' && path[1] != '>')) return 1; # elif defined _WIN32 if (path[0] == '\\' || (path[0] != '\0' && path[1] == ':')) return 1; # endif return path[0] == '/'; } #endif
./openssl/include/internal/quic_ssl.h
/* * Copyright 2022-2023 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_SSL_H # define OSSL_QUIC_SSL_H # include <openssl/ssl.h> # include <openssl/bio.h> # include "internal/quic_record_rx.h" /* OSSL_QRX */ # include "internal/quic_ackm.h" /* OSSL_ACKM */ # include "internal/quic_channel.h" /* QUIC_CHANNEL */ # ifndef OPENSSL_NO_QUIC __owur SSL *ossl_quic_new(SSL_CTX *ctx); __owur int ossl_quic_init(SSL *s); void ossl_quic_deinit(SSL *s); void ossl_quic_free(SSL *s); int ossl_quic_reset(SSL *s); int ossl_quic_clear(SSL *s); __owur int ossl_quic_accept(SSL *s); __owur int ossl_quic_connect(SSL *s); __owur int ossl_quic_read(SSL *s, void *buf, size_t len, size_t *readbytes); __owur int ossl_quic_peek(SSL *s, void *buf, size_t len, size_t *readbytes); __owur int ossl_quic_write(SSL *s, const void *buf, size_t len, size_t *written); __owur long ossl_quic_ctrl(SSL *s, int cmd, long larg, void *parg); __owur long ossl_quic_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg); __owur long ossl_quic_callback_ctrl(SSL *s, int cmd, void (*fp) (void)); __owur long ossl_quic_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void)); __owur size_t ossl_quic_pending(const SSL *s); __owur int ossl_quic_key_update(SSL *s, int update_type); __owur int ossl_quic_get_key_update_type(const SSL *s); __owur const SSL_CIPHER *ossl_quic_get_cipher_by_char(const unsigned char *p); __owur int ossl_quic_num_ciphers(void); __owur const SSL_CIPHER *ossl_quic_get_cipher(unsigned int u); int ossl_quic_renegotiate_check(SSL *ssl, int initok); typedef struct quic_conn_st QUIC_CONNECTION; typedef struct quic_xso_st QUIC_XSO; int ossl_quic_do_handshake(SSL *s); void ossl_quic_set_connect_state(SSL *s); void ossl_quic_set_accept_state(SSL *s); __owur int ossl_quic_has_pending(const SSL *s); __owur int ossl_quic_handle_events(SSL *s); __owur int ossl_quic_get_event_timeout(SSL *s, struct timeval *tv, int *is_infinite); OSSL_TIME ossl_quic_get_event_deadline(SSL *s); __owur int ossl_quic_get_rpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *d); __owur int ossl_quic_get_wpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *d); __owur int ossl_quic_get_net_read_desired(SSL *s); __owur int ossl_quic_get_net_write_desired(SSL *s); __owur int ossl_quic_get_error(const SSL *s, int i); __owur int ossl_quic_want(const SSL *s); __owur int ossl_quic_conn_get_blocking_mode(const SSL *s); __owur int ossl_quic_conn_set_blocking_mode(SSL *s, int blocking); __owur int ossl_quic_conn_shutdown(SSL *s, uint64_t flags, const SSL_SHUTDOWN_EX_ARGS *args, size_t args_len); __owur int ossl_quic_conn_stream_conclude(SSL *s); void ossl_quic_conn_set0_net_rbio(SSL *s, BIO *net_wbio); void ossl_quic_conn_set0_net_wbio(SSL *s, BIO *net_wbio); BIO *ossl_quic_conn_get_net_rbio(const SSL *s); BIO *ossl_quic_conn_get_net_wbio(const SSL *s); __owur int ossl_quic_conn_set_initial_peer_addr(SSL *s, const BIO_ADDR *peer_addr); __owur SSL *ossl_quic_conn_stream_new(SSL *s, uint64_t flags); __owur SSL *ossl_quic_get0_connection(SSL *s); __owur int ossl_quic_get_stream_type(SSL *s); __owur uint64_t ossl_quic_get_stream_id(SSL *s); __owur int ossl_quic_is_stream_local(SSL *s); __owur int ossl_quic_set_default_stream_mode(SSL *s, uint32_t mode); __owur SSL *ossl_quic_detach_stream(SSL *s); __owur int ossl_quic_attach_stream(SSL *conn, SSL *stream); __owur int ossl_quic_set_incoming_stream_policy(SSL *s, int policy, uint64_t aec); __owur SSL *ossl_quic_accept_stream(SSL *s, uint64_t flags); __owur size_t ossl_quic_get_accept_stream_queue_len(SSL *s); __owur int ossl_quic_stream_reset(SSL *ssl, const SSL_STREAM_RESET_ARGS *args, size_t args_len); __owur int ossl_quic_get_stream_read_state(SSL *ssl); __owur int ossl_quic_get_stream_write_state(SSL *ssl); __owur int ossl_quic_get_stream_read_error_code(SSL *ssl, uint64_t *app_error_code); __owur int ossl_quic_get_stream_write_error_code(SSL *ssl, uint64_t *app_error_code); __owur int ossl_quic_get_conn_close_info(SSL *ssl, SSL_CONN_CLOSE_INFO *info, size_t info_len); uint64_t ossl_quic_set_options(SSL *s, uint64_t opts); uint64_t ossl_quic_clear_options(SSL *s, uint64_t opts); uint64_t ossl_quic_get_options(const SSL *s); /* Modifies write buffer size for a stream. */ __owur int ossl_quic_set_write_buffer_size(SSL *s, size_t size); /* * Used to override ossl_time_now() for debug purposes. While this may be * overridden at any time, expect strange results if you change it after * connecting. */ int ossl_quic_conn_set_override_now_cb(SSL *s, OSSL_TIME (*now_cb)(void *arg), void *now_cb_arg); /* * Condvar waiting in the assist thread doesn't support time faking as it relies * on the OS's notion of time, thus this is used in test code to force a * spurious wakeup instead. */ void ossl_quic_conn_force_assist_thread_wake(SSL *s); /* For use by tests only. */ QUIC_CHANNEL *ossl_quic_conn_get_channel(SSL *s); int ossl_quic_has_pending(const SSL *s); int ossl_quic_get_shutdown(const SSL *s); # endif #endif
./openssl/include/internal/quic_port.h
/* * Copyright 2023 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_PORT_H # define OSSL_QUIC_PORT_H # include <openssl/ssl.h> # include "internal/quic_types.h" # include "internal/quic_reactor.h" # include "internal/quic_demux.h" # include "internal/quic_predef.h" # include "internal/thread_arch.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Port * ========= * * A QUIC Port (QUIC_PORT) represents a single UDP network socket and contains * zero or more subsidiary QUIC_CHANNEL instances, each of which represents a * single QUIC connection. All QUIC_CHANNEL instances must belong to a * QUIC_PORT. * * A QUIC port is responsible for managing a set of channels which all use the * same UDP socket, and (in future) for automatically creating new channels when * incoming connections are received. * * In order to retain compatibility with QUIC_TSERVER, it also supports a point * of legacy compatibility where a caller can create an incoming (server role) * channel and that channel will be automatically be bound to the next incoming * connection. In the future this will go away once QUIC_TSERVER is removed. * * All QUIC_PORT instances are created by a QUIC_ENGINE. */ typedef struct quic_port_args_st { /* The engine which the QUIC port is to be a child of. */ QUIC_ENGINE *engine; /* * This SSL_CTX will be used when constructing the handshake layer object * inside newly created channels. */ SSL_CTX *channel_ctx; /* * If 1, this port is to be used for multiple connections, so * non-zero-length CIDs should be used. If 0, this port will only be used * for a single connection, so a zero-length local CID can be used. */ int is_multi_conn; } QUIC_PORT_ARGS; /* Only QUIC_ENGINE should use this function. */ QUIC_PORT *ossl_quic_port_new(const QUIC_PORT_ARGS *args); void ossl_quic_port_free(QUIC_PORT *port); /* * Operations * ========== */ /* Create an outgoing channel using this port. */ QUIC_CHANNEL *ossl_quic_port_create_outgoing(QUIC_PORT *port, SSL *tls); /* * Create an incoming channel using this port. * * TODO(QUIC SERVER): temporary TSERVER use only - will be removed. */ QUIC_CHANNEL *ossl_quic_port_create_incoming(QUIC_PORT *port, SSL *tls); /* * Queries and Accessors * ===================== */ /* Gets/sets the underlying network read and write BIO. */ BIO *ossl_quic_port_get_net_rbio(QUIC_PORT *port); BIO *ossl_quic_port_get_net_wbio(QUIC_PORT *port); int ossl_quic_port_set_net_rbio(QUIC_PORT *port, BIO *net_rbio); int ossl_quic_port_set_net_wbio(QUIC_PORT *port, BIO *net_wbio); /* * Re-poll the network BIOs already set to determine if their support * for polling has changed. */ int ossl_quic_port_update_poll_descriptors(QUIC_PORT *port); /* Gets the engine which this port is a child of. */ QUIC_ENGINE *ossl_quic_port_get0_engine(QUIC_PORT *port); /* Gets the reactor which can be used to tick/poll on the port. */ QUIC_REACTOR *ossl_quic_port_get0_reactor(QUIC_PORT *port); /* Gets the demuxer belonging to the port. */ QUIC_DEMUX *ossl_quic_port_get0_demux(QUIC_PORT *port); /* Gets the mutex used by the port. */ CRYPTO_MUTEX *ossl_quic_port_get0_mutex(QUIC_PORT *port); /* Gets the current time. */ OSSL_TIME ossl_quic_port_get_time(QUIC_PORT *port); int ossl_quic_port_get_rx_short_dcid_len(const QUIC_PORT *port); int ossl_quic_port_get_tx_init_dcid_len(const QUIC_PORT *port); /* Returns 1 if the port is running/healthy, 0 if it has failed. */ int ossl_quic_port_is_running(const QUIC_PORT *port); /* * Restores port-level error to the error stack. To be called only if * the port is no longer running. */ void ossl_quic_port_restore_err_state(const QUIC_PORT *port); /* For use by QUIC_ENGINE. You should not need to call this directly. */ void ossl_quic_port_subtick(QUIC_PORT *port, QUIC_TICK_RESULT *r, uint32_t flags); /* * Events * ====== */ /* * Called if a permanent network error occurs. Terminates all channels * immediately. triggering_ch is an optional argument designating * a channel which encountered the network error. */ void ossl_quic_port_raise_net_error(QUIC_PORT *port, QUIC_CHANNEL *triggering_ch); # endif #endif
./openssl/include/internal/quic_stream.h
/* * Copyright 2022-2023 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_INTERNAL_QUIC_STREAM_H # define OSSL_INTERNAL_QUIC_STREAM_H # pragma once #include "internal/e_os.h" #include "internal/time.h" #include "internal/quic_types.h" #include "internal/quic_predef.h" #include "internal/quic_wire.h" #include "internal/quic_record_tx.h" #include "internal/quic_record_rx.h" #include "internal/quic_fc.h" #include "internal/quic_statm.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Send Stream * ================ * * The QUIC Send Stream Manager (QUIC_SSTREAM) is responsible for: * * - accepting octet strings of stream data; * * - generating corresponding STREAM frames; * * - receiving notifications of lost frames, in order to generate new STREAM * frames for the lost data; * * - receiving notifications of acknowledged frames, in order to internally * reuse memory used to store acknowledged stream data; * * - informing the caller of how much more stream data it can accept into * its internal buffers, so as to ensure that the amount of unacknowledged * data which can be written to a stream is not infinite and to allow the * caller to manifest backpressure conditions to the user. * * The QUIC_SSTREAM is instantiated once for every stream with a send component * (i.e., for a unidirectional send stream or for the send component of a * bidirectional stream). * * Note: The terms 'TX' and 'RX' are used when referring to frames, packets and * datagrams. The terms 'send' and 'receive' are used when referring to the * stream abstraction. Applications send; we transmit. */ /* * Instantiates a new QUIC_SSTREAM. init_buf_size specifies the initial size of * the stream data buffer in bytes, which must be positive. */ QUIC_SSTREAM *ossl_quic_sstream_new(size_t init_buf_size); /* * Frees a QUIC_SSTREAM and associated stream data storage. * * Any iovecs returned by ossl_quic_sstream_get_stream_frame cease to be valid after * calling this function. */ void ossl_quic_sstream_free(QUIC_SSTREAM *qss); /* * (For TX packetizer use.) Retrieves information about application stream data * which is ready for transmission. * * *hdr is filled with the logical offset, maximum possible length of stream * data which can be transmitted, and a pointer to the stream data to be * transmitted. is_fin is set to 1 if hdr->offset + hdr->len is the final size * of the stream and 0 otherwise. hdr->stream_id is not set; the caller must set * it. * * The caller is not obligated to send all of the data. If the caller does not * send all of the data, the caller must reduce hdr->len before serializing the * header structure and must ensure that hdr->is_fin is cleared. * * hdr->has_explicit_len is always set. It is the caller's responsibility to * clear this if it wants to use the optimization of omitting the length field, * as only the caller can know when this optimization can be performed. * * *num_iov must be set to the size of the iov array at call time. When this * function returns successfully, it is updated to the number of iov entries * which have been written. * * The stream data may be split across up to two IOVs due to internal ring * buffer organisation. The sum of the lengths of the IOVs and the value written * to hdr->len will always match. If the caller decides to send less than * hdr->len of stream data, it must adjust the IOVs accordingly. This may be * done by updating hdr->len and then calling the utility function * ossl_quic_sstream_adjust_iov(). * * After committing one or more bytes returned by ossl_quic_sstream_get_stream_frame to a * packet, call ossl_quic_sstream_mark_transmitted with the inclusive range of logical * byte numbers of the transmitted bytes (i.e., hdr->offset, hdr->offset + * hdr->len - 1). If you do not call ossl_quic_sstream_mark_transmitted, the next call to * ossl_quic_sstream_get_stream_frame will return the same data (or potentially the same * and more, if more data has been appended by the application). * * It is the caller's responsibility to clamp the length of data which this * function indicates is available according to other concerns, such as * stream-level flow control, connection-level flow control, or the applicable * maximum datagram payload length (MDPL) for a packet under construction. * * The skip argument can usually be given as zero. If it is non-zero, this * function outputs a range which would be output if it were called again after * calling ossl_quic_sstream_mark_transmitted() with the returned range, repeated 'skip' * times, and so on. This may be useful for callers which wish to enumerate * available stream frames and batch their calls to ossl_quic_sstream_mark_transmitted at * a later time. * * On success, this function will never write *num_iov with a value other than * 0, 1 or 2. A *num_iov value of 0 can only occurs when hdr->is_fin is set (for * example, when a stream is closed after all existing data has been sent, and * without sending any more data); otherwise the function returns 0 as there is * nothing useful to report. * * Returns 1 on success and 0 if there is no stream data available for * transmission, or on other error (such as if the caller provides fewer * than two IOVs.) */ int ossl_quic_sstream_get_stream_frame(QUIC_SSTREAM *qss, size_t skip, OSSL_QUIC_FRAME_STREAM *hdr, OSSL_QTX_IOVEC *iov, size_t *num_iov); /* * Returns 1 if there is data pending transmission. Equivalent to calling * ossl_quic_sstream_get_stream_frame and seeing if it succeeds. */ int ossl_quic_sstream_has_pending(QUIC_SSTREAM *qss); /* * Returns the current size of the stream; i.e., the number of bytes which have * been appended to the stream so far. */ uint64_t ossl_quic_sstream_get_cur_size(QUIC_SSTREAM *qss); /* * (For TX packetizer use.) Marks a logical range of the send stream as having * been transmitted. * * 0 denotes the first byte ever sent on the stream. The start and end values * are both inclusive, therefore all calls to this function always mark at least * one byte as being transmitted; if no bytes have been transmitted, do not call * this function. * * If the STREAM frame sent had the FIN bit set, you must also call * ossl_quic_sstream_mark_transmitted_fin() after calling this function. * * If you sent a zero-length STREAM frame with the FIN bit set, you need only * call ossl_quic_sstream_mark_transmitted_fin() and must not call this function. * * Returns 1 on success and 0 on error (e.g. if end < start). */ int ossl_quic_sstream_mark_transmitted(QUIC_SSTREAM *qss, uint64_t start, uint64_t end); /* * (For TX packetizer use.) Marks a STREAM frame with the FIN bit set as having * been transmitted. final_size is the final size of the stream (i.e., the value * offset + len of the transmitted STREAM frame). * * This function fails returning 0 if ossl_quic_sstream_fin() has not been called or if * final_size is not correct. The final_size argument is not strictly needed by * the QUIC_SSTREAM but is required as a sanity check. */ int ossl_quic_sstream_mark_transmitted_fin(QUIC_SSTREAM *qss, uint64_t final_size); /* * (RX/ACKM use.) Marks a logical range of the send stream as having been lost. * The send stream will return the lost data for retransmission on a future call * to ossl_quic_sstream_get_stream_frame. The start and end values denote logical byte * numbers and are inclusive. * * If the lost frame had the FIN bit set, you must also call * ossl_quic_sstream_mark_lost_fin() after calling this function. * * Returns 1 on success and 0 on error (e.g. if end < start). */ int ossl_quic_sstream_mark_lost(QUIC_SSTREAM *qss, uint64_t start, uint64_t end); /* * (RX/ACKM use.) Informs the QUIC_SSTREAM that a STREAM frame with the FIN bit * set was lost. * * Returns 1 on success and 0 on error. */ int ossl_quic_sstream_mark_lost_fin(QUIC_SSTREAM *qss); /* * (RX/ACKM use.) Marks a logical range of the send stream as having been * acknowledged, meaning that the storage for the data in that range of the * stream can be now recycled and neither that logical range of the stream nor * any subset of it can be retransmitted again. The start and end values are * inclusive. * * If the acknowledged frame had the FIN bit set, you must also call * ossl_quic_sstream_mark_acked_fin() after calling this function. * * Returns 1 on success and 0 on error (e.g. if end < start). */ int ossl_quic_sstream_mark_acked(QUIC_SSTREAM *qss, uint64_t start, uint64_t end); /* * (RX/ACKM use.) Informs the QUIC_SSTREAM that a STREAM frame with the FIN bit * set was acknowledged. * * Returns 1 on success and 0 on error. */ int ossl_quic_sstream_mark_acked_fin(QUIC_SSTREAM *qss); /* * (Front end use.) Appends user data to the stream. The data is copied into the * stream. The amount of data consumed from buf is written to *consumed on * success (short writes are possible). The amount of data which can be written * can be determined in advance by calling the ossl_quic_sstream_get_buffer_avail() * function; data is copied into an internal ring buffer of finite size. * * If the buffer is full, this should be materialised as a backpressure * condition by the front end. This is not considered a failure condition; * *consumed is written as 0 and the function returns 1. * * Returns 1 on success or 0 on failure. */ int ossl_quic_sstream_append(QUIC_SSTREAM *qss, const unsigned char *buf, size_t buf_len, size_t *consumed); /* * Marks a stream as finished. ossl_quic_sstream_append() may not be called anymore * after calling this. */ void ossl_quic_sstream_fin(QUIC_SSTREAM *qss); /* * If the stream has had ossl_quic_sstream_fin() called, returns 1 and writes * the final size to *final_size. Otherwise, returns 0. */ int ossl_quic_sstream_get_final_size(QUIC_SSTREAM *qss, uint64_t *final_size); /* * Returns 1 iff all bytes (and any FIN, if any) which have been appended to the * QUIC_SSTREAM so far, and any FIN (if any), have been both sent and acked. */ int ossl_quic_sstream_is_totally_acked(QUIC_SSTREAM *qss); /* * Resizes the internal ring buffer. All stream data is preserved safely. * * This can be used to expand or contract the ring buffer, but not to contract * the ring buffer below the amount of stream data currently stored in it. * Returns 1 on success and 0 on failure. * * IMPORTANT: Any buffers referenced by iovecs output by * ossl_quic_sstream_get_stream_frame() cease to be valid after calling this function. */ int ossl_quic_sstream_set_buffer_size(QUIC_SSTREAM *qss, size_t num_bytes); /* * Gets the internal ring buffer size in bytes. */ size_t ossl_quic_sstream_get_buffer_size(QUIC_SSTREAM *qss); /* * Gets the number of bytes used in the internal ring buffer. */ size_t ossl_quic_sstream_get_buffer_used(QUIC_SSTREAM *qss); /* * Gets the number of bytes free in the internal ring buffer. */ size_t ossl_quic_sstream_get_buffer_avail(QUIC_SSTREAM *qss); /* * Utility function to ensure the length of an array of iovecs matches the * length given as len. Trailing iovecs have their length values reduced or set * to 0 as necessary. */ void ossl_quic_sstream_adjust_iov(size_t len, OSSL_QTX_IOVEC *iov, size_t num_iov); /* * Sets flag to cleanse the buffered data when it is acked. */ void ossl_quic_sstream_set_cleanse(QUIC_SSTREAM *qss, int cleanse); /* * QUIC Receive Stream Manager * =========================== * * The QUIC Receive Stream Manager (QUIC_RSTREAM) is responsible for * storing the received stream data frames until the application * is able to read the data. * * The QUIC_RSTREAM is instantiated once for every stream that can receive data. * (i.e., for a unidirectional receiving stream or for the receiving component * of a bidirectional stream). */ /* * Create a new instance of QUIC_RSTREAM with pointers to the flow * controller and statistics module. They can be NULL for unit testing. * If they are non-NULL, the `rxfc` is called when receive stream data * is read by application. `statm` is queried for current rtt. * `rbuf_size` is the initial size of the ring buffer to be used * when ossl_quic_rstream_move_to_rbuf() is called. */ QUIC_RSTREAM *ossl_quic_rstream_new(QUIC_RXFC *rxfc, OSSL_STATM *statm, size_t rbuf_size); /* * Frees a QUIC_RSTREAM and any associated storage. */ void ossl_quic_rstream_free(QUIC_RSTREAM *qrs); /* * Adds received stream frame data to `qrs`. The `pkt_wrap` refcount is * incremented if the `data` is queued directly without copying. * It can be NULL for unit-testing purposes, i.e. if `data` is static or * never released before calling ossl_quic_rstream_free(). * The `offset` is the absolute offset of the data in the stream. * `data_len` can be 0 - can be useful for indicating `fin` for empty stream. * Or to indicate `fin` without any further data added to the stream. */ int ossl_quic_rstream_queue_data(QUIC_RSTREAM *qrs, OSSL_QRX_PKT *pkt, uint64_t offset, const unsigned char *data, uint64_t data_len, int fin); /* * Copies the data from the stream storage to buffer `buf` of size `size`. * `readbytes` is set to the number of bytes actually copied. * `fin` is set to 1 if all the data from the stream were read so the * stream is finished. It is set to 0 otherwise. */ int ossl_quic_rstream_read(QUIC_RSTREAM *qrs, unsigned char *buf, size_t size, size_t *readbytes, int *fin); /* * Peeks at the data in the stream storage. It copies them to buffer `buf` * of size `size` and sets `readbytes` to the number of bytes actually copied. * `fin` is set to 1 if the copied data reach end of the stream. * It is set to 0 otherwise. */ int ossl_quic_rstream_peek(QUIC_RSTREAM *qrs, unsigned char *buf, size_t size, size_t *readbytes, int *fin); /* * Returns the size of the data available for reading. `fin` is set to 1 if * after reading all the available data the stream will be finished, * set to 0 otherwise. */ int ossl_quic_rstream_available(QUIC_RSTREAM *qrs, size_t *avail, int *fin); /* * Sets *record to the beginning of the first readable stream data chunk and * *reclen to the size of the chunk. *fin is set to 1 if the end of the * chunk is the last of the stream data chunks. * If there is no record available *record is set to NULL and *rec_len to 0; * ossl_quic_rstream_release_record() should not be called in that case. * Returns 1 on success (including calls if no record is available, or * after end of the stream - in that case *fin will be set to 1 and * *rec_len to 0), 0 on error. * It is an error to call ossl_quic_rstream_get_record() multiple times * without calling ossl_quic_rstream_release_record() in between. */ int ossl_quic_rstream_get_record(QUIC_RSTREAM *qrs, const unsigned char **record, size_t *rec_len, int *fin); /* * Releases (possibly partially) the record returned by * previous ossl_quic_rstream_get_record() call. * read_len between previously returned *rec_len and SIZE_MAX indicates * release of the whole record. Otherwise only part of the record is * released. The remaining part of the record is unlocked, another * call to ossl_quic_rstream_get_record() is needed to obtain further * stream data. * Returns 1 on success, 0 on error. * It is an error to call ossl_quic_rstream_release_record() multiple * times without calling ossl_quic_rstream_get_record() in between. */ int ossl_quic_rstream_release_record(QUIC_RSTREAM *qrs, size_t read_len); /* * Moves received frame data from decrypted packets to ring buffer. * This should be called when there are too many decrypted packets allocated. * Returns 1 on success, 0 when it was not possible to release all * referenced packets due to an insufficient size of the ring buffer. * Exception is the packet from the record returned previously by * ossl_quic_rstream_get_record() - that one will be always skipped. */ int ossl_quic_rstream_move_to_rbuf(QUIC_RSTREAM *qrs); /* * Resizes the internal ring buffer to a new `rbuf_size` size. * Returns 1 on success, 0 on error. * Possible error conditions are an allocation failure, trying to resize * the ring buffer when ossl_quic_rstream_get_record() was called and * not yet released, or trying to resize the ring buffer to a smaller size * than currently occupied. */ int ossl_quic_rstream_resize_rbuf(QUIC_RSTREAM *qrs, size_t rbuf_size); /* * Sets flag to cleanse the buffered data when user reads it. */ void ossl_quic_rstream_set_cleanse(QUIC_RSTREAM *qrs, int cleanse); # endif #endif
./openssl/include/internal/quic_srt_gen.h
/* * Copyright 2023 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_INTERNAL_QUIC_SRT_GEN_H # define OSSL_INTERNAL_QUIC_SRT_GEN_H # pragma once # include "internal/e_os.h" # include "internal/time.h" # include "internal/quic_types.h" # include "internal/quic_wire.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Stateless Reset Token Generator * ==================================== * * This generates 16-byte QUIC Stateless Reset Tokens given a secret symmetric * key and a DCID. Because the output is deterministic with regards to these * inputs, assuming the same key is used between invocations of a process, we * are able to generate the same stateless reset token in a subsequent process, * thereby allowing us to achieve stateless reset of a peer which still thinks * it is connected to a past process at the same UDP address. */ typedef struct quic_srt_gen_st QUIC_SRT_GEN; /* * Create a new stateless reset token generator using the given key as input. * The key may be of arbitrary length. * * The caller is responsible for performing domain separation with regards to * the key; i.e., the caller is responsible for ensuring the key is never used * in any other context. */ QUIC_SRT_GEN *ossl_quic_srt_gen_new(OSSL_LIB_CTX *libctx, const char *propq, const unsigned char *key, size_t key_len); /* Free the stateless reset token generator. No-op if srt_gen is NULL. */ void ossl_quic_srt_gen_free(QUIC_SRT_GEN *srt_gen); /* * Calculates a token using the given DCID and writes it to *token. Returns 0 on * failure. */ int ossl_quic_srt_gen_calculate_token(QUIC_SRT_GEN *srt_gen, const QUIC_CONN_ID *dcid, QUIC_STATELESS_RESET_TOKEN *token); # endif #endif
./openssl/include/internal/quic_record_rx.h
/* * Copyright 2022-2023 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_predef.h" # include "internal/quic_record_util.h" # include "internal/quic_demux.h" # ifndef OPENSSL_NO_QUIC /* * 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 which owns the URXEs passed to us. */ QUIC_DEMUX *demux; /* Length of connection IDs used in short-header packets in bytes. */ size_t short_conn_id_len; /* * Maximum number of deferred datagrams buffered at any one time. * Suggested value: 32. */ size_t max_deferred; /* Initial reference PN used for RX. */ QUIC_PN init_largest_pn[QUIC_PN_SPACE_NUM]; /* Initial key phase. For debugging use only; always 0 in real use. */ unsigned char init_key_phase_bit; } 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); /* Setters for the msg_callback and msg_callback_arg */ void ossl_qrx_set_msg_callback(OSSL_QRX *qrx, ossl_msg_cb msg_callback, SSL *msg_callback_ssl); void ossl_qrx_set_msg_callback_arg(OSSL_QRX *qrx, void *msg_callback_arg); /* * 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_quic_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_quic_provide_initial_secret * 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_quic_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 QRL_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, except for the INITIAL * EL, which can need rekeying when a connection retry occurs. Subsequent calls * for non-INITIAL ELs fail, as do calls made after a corresponding call to * ossl_qrx_discard_enc_level for that EL. The secret for a non-INITIAL 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 semi-automatically by the QRX but do require some caller handling * (see below). * * 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. */ struct ossl_qrx_pkt_st { /* * 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; /* The PN which was decoded for the packet, if the packet has a PN field. */ QUIC_PN pn; /* * Time the packet was received, or ossl_time_zero() if the demuxer is not * using a now() function. */ OSSL_TIME time; /* The QRX which was used to receive the packet. */ OSSL_QRX *qrx; /* * The key epoch the packet was received with. Always 0 for non-1-RTT * packets. */ uint64_t key_epoch; }; /* * Tries to read a new decrypted packet from the QRX. * * On success, *pkt points to a OSSL_QRX_PKT structure. The structure should be * freed when no longer needed by calling ossl_qrx_pkt_release(). The structure * is refcounted; to gain extra references, call ossl_qrx_pkt_up_ref(). This * will cause a corresponding number of calls to ossl_qrx_pkt_release() to be * ignored. * * The resources referenced by (*pkt)->hdr, (*pkt)->hdr->data and (*pkt)->peer * have the same lifetime as *pkt. * * Returns 1 on success and 0 on failure. */ int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT **pkt); /* * Decrement the reference count for the given packet and frees it if the * reference count drops to zero. No-op if pkt is NULL. */ void ossl_qrx_pkt_release(OSSL_QRX_PKT *pkt); /* Increments the reference count for the given packet. */ void ossl_qrx_pkt_up_ref(OSSL_QRX_PKT *pkt); /* * 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 are 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 after packet body * decryption and authentication to prevent exposing side channels. 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 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_late_validation_cb)(QUIC_PN pn, int pn_space, void *arg); int ossl_qrx_set_late_validation_cb(OSSL_QRX *qrx, ossl_qrx_late_validation_cb *cb, void *cb_arg); /* * Forcibly injects a URXE which has been issued by the DEMUX into the QRX for * processing. This can be used to pass a received datagram to the QRX if it * would not be correctly routed to the QRX via standard DCID-based routing; for * example, when handling an incoming Initial packet which is attempting to * establish a new connection. */ void ossl_qrx_inject_urxe(OSSL_QRX *qrx, QUIC_URXE *e); /* * Decryption of 1-RTT packets must be explicitly enabled by calling this * function. This is to comply with the requirement that we not process 1-RTT * packets until the handshake is complete, even if we already have 1-RTT * secrets. Even if a 1-RTT secret is provisioned for the QRX, incoming 1-RTT * packets will be handled as though no key is available until this function is * called. Calling this function will then requeue any such deferred packets for * processing. */ void ossl_qrx_allow_1rtt_processing(OSSL_QRX *qrx); /* * 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 * keys, 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 <----------\ |------> DISCARDED * | | | | * | | | | * | v | | * | UPDATING | | * | | | | * | | | | * | 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 UPDATING 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 UPDATING 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 UPDATING 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 UPDATING 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: * * Epoch Exp KP Uses Keys KS0 KS1 If Non-Expected KP Bit * ----- ------ --------- ------ ----- ---------------------- * NORMAL 0 0 Keyset 0 Gen 0 Gen 1 → UPDATING * UPDATING 1 1 Keyset 1 Gen 0 Gen 1 Use Keyset 0 * COOLDOWN 1 1 Keyset 1 Erased Gen 1 Ignore Packet (*) * * NORMAL 1 1 Keyset 1 Gen 2 Gen 1 → UPDATING * UPDATING 2 0 Keyset 0 Gen 2 Gen 1 Use Keyset 1 * COOLDOWN 2 0 Keyset 0 Gen 2 Erased Ignore Packet (*) * * (*) Actually implemented by attempting to decrypt the packet with the * wrong keys (which ultimately has the same outcome), as recommended * by RFC 9001 to avoid creating timing channels. * * 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, UPDATING, 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 DISCARDED state, which is * the terminal state. * * Note that non-1RTT ELs cannot undergo key update, therefore a non-1RTT EL is * always in the NORMAL substate if it is in the PROVISIONED state. */ /* * Return the current RX key epoch for the 1-RTT encryption level. This is * initially zero and is incremented by one for every Key Update successfully * signalled by the peer. If the 1-RTT EL has not yet been provisioned or has * been discarded, returns UINT64_MAX. * * 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 UPDATING state discussed above. */ uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx); /* * Sets an optional callback which will be called when the key epoch changes. * * The callback is optional and can be unset by passing NULL for cb. * cb_arg is an opaque value passed to cb. pn is the PN of the packet. * Since key update is only supported for 1-RTT packets, the PN is always * in the Application Data PN space. */ typedef void (ossl_qrx_key_update_cb)(QUIC_PN pn, void *arg); int ossl_qrx_set_key_update_cb(OSSL_QRX *qrx, ossl_qrx_key_update_cb *cb, void *cb_arg); /* * Relates to the 1-RTT encryption level. The caller should call this after the * UPDATING state is reached, after a timeout to be determined by the caller. * * This transitions from the UPDATING state to the COOLDOWN state (if * still in the UPDATING 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. Returns 0 if the 1-RTT EL has not been provisioned or * has been dropped. * * 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() for a given EL, all further * received encrypted packets for that EL will be discarded without processing. * * Note that the forged packet limit is for the connection lifetime, thus it is * not reset by a key update. It is suggested that the caller terminate the * connection a reasonable margin before the limit is reached. However, the * exact limit imposed does vary by EL due to the possibility that different ELs * use different AEADs. */ uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX *qrx); /* * Returns the maximum number of forged packets which the record layer will * permit to be verified using this QRX instance. */ uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX *qrx, uint32_t enc_level); # endif #endif
./openssl/include/internal/quic_txp.h
/* * Copyright 2022-2023 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_TXP_H # define OSSL_QUIC_TXP_H # include <openssl/ssl.h> # include "internal/quic_types.h" # include "internal/quic_predef.h" # include "internal/quic_record_tx.h" # include "internal/quic_cfq.h" # include "internal/quic_txpim.h" # include "internal/quic_stream.h" # include "internal/quic_stream_map.h" # include "internal/quic_fc.h" # include "internal/bio_addr.h" # include "internal/time.h" # ifndef OPENSSL_NO_QUIC /* * QUIC TX Packetiser * ================== */ typedef struct ossl_quic_tx_packetiser_args_st { /* Configuration Settings */ QUIC_CONN_ID cur_scid; /* Current Source Connection ID we use. */ QUIC_CONN_ID cur_dcid; /* Current Destination Connection ID we use. */ BIO_ADDR peer; /* Current destination L4 address we use. */ uint32_t ack_delay_exponent; /* ACK delay exponent used when encoding. */ /* Injected Dependencies */ OSSL_QTX *qtx; /* QUIC Record Layer TX we are using */ QUIC_TXPIM *txpim; /* QUIC TX'd Packet Information Manager */ QUIC_CFQ *cfq; /* QUIC Control Frame Queue */ OSSL_ACKM *ackm; /* QUIC Acknowledgement Manager */ QUIC_STREAM_MAP *qsm; /* QUIC Streams Map */ QUIC_TXFC *conn_txfc; /* QUIC Connection-Level TX Flow Controller */ QUIC_RXFC *conn_rxfc; /* QUIC Connection-Level RX Flow Controller */ QUIC_RXFC *max_streams_bidi_rxfc; /* QUIC RXFC for MAX_STREAMS generation */ QUIC_RXFC *max_streams_uni_rxfc; const OSSL_CC_METHOD *cc_method; /* QUIC Congestion Controller */ OSSL_CC_DATA *cc_data; /* QUIC Congestion Controller Instance */ OSSL_TIME (*now)(void *arg); /* Callback to get current time. */ void *now_arg; /* * Injected dependencies - crypto streams. * * Note: There is no crypto stream for the 0-RTT EL. * crypto[QUIC_PN_SPACE_APP] is the 1-RTT crypto stream. */ QUIC_SSTREAM *crypto[QUIC_PN_SPACE_NUM]; } OSSL_QUIC_TX_PACKETISER_ARGS; OSSL_QUIC_TX_PACKETISER *ossl_quic_tx_packetiser_new(const OSSL_QUIC_TX_PACKETISER_ARGS *args); typedef void (ossl_quic_initial_token_free_fn)(const unsigned char *buf, size_t buf_len, void *arg); void ossl_quic_tx_packetiser_free(OSSL_QUIC_TX_PACKETISER *txp); /* * When in the closing state we need to maintain a count of received bytes * so that we can limit the number of close connection frames we send. * Refer RFC 9000 s. 10.2.1 Closing Connection State. */ void ossl_quic_tx_packetiser_record_received_closing_bytes( OSSL_QUIC_TX_PACKETISER *txp, size_t n); /* * Generates a datagram by polling the various ELs to determine if they want to * generate any frames, and generating a datagram which coalesces packets for * any ELs which do. * * Returns 0 on failure (e.g. allocation error or other errors), 1 otherwise. * * *status is filled with status information about the generated packet. * It is always filled even in case of failure. In particular, packets can be * sent even if failure is later returned. * See QUIC_TXP_STATUS for details. */ typedef struct quic_txp_status_st { int sent_ack_eliciting; /* Was an ACK-eliciting packet sent? */ int sent_handshake; /* Was a Handshake packet sent? */ size_t sent_pkt; /* Number of packets sent (0 if nothing was sent) */ } QUIC_TXP_STATUS; int ossl_quic_tx_packetiser_generate(OSSL_QUIC_TX_PACKETISER *txp, QUIC_TXP_STATUS *status); /* * Returns a deadline after which a call to ossl_quic_tx_packetiser_generate() * might succeed even if it did not previously. This may return * ossl_time_infinite() if there is no such deadline currently applicable. It * returns ossl_time_zero() if there is (potentially) more data to be generated * immediately. The value returned is liable to change after any call to * ossl_quic_tx_packetiser_generate() (or after ACKM or CC state changes). Note * that ossl_quic_tx_packetiser_generate() can also start to succeed for other * non-chronological reasons, such as changes to send stream buffers, etc. */ OSSL_TIME ossl_quic_tx_packetiser_get_deadline(OSSL_QUIC_TX_PACKETISER *txp); /* * Set the token used in Initial packets. The callback is called when the buffer * is no longer needed; for example, when the TXP is freed or when this function * is called again with a new buffer. Fails returning 0 if the token is too big * to ever be reasonably encapsulated in an outgoing packet based on our current * understanding of our PMTU. */ int ossl_quic_tx_packetiser_set_initial_token(OSSL_QUIC_TX_PACKETISER *txp, const unsigned char *token, size_t token_len, ossl_quic_initial_token_free_fn *free_cb, void *free_cb_arg); /* Change the DCID the TXP uses to send outgoing packets. */ int ossl_quic_tx_packetiser_set_cur_dcid(OSSL_QUIC_TX_PACKETISER *txp, const QUIC_CONN_ID *dcid); /* Change the SCID the TXP uses to send outgoing (long) packets. */ int ossl_quic_tx_packetiser_set_cur_scid(OSSL_QUIC_TX_PACKETISER *txp, const QUIC_CONN_ID *scid); /* * Change the destination L4 address the TXP uses to send datagrams. Specify * NULL (or AF_UNSPEC) to disable use of addressed mode. */ int ossl_quic_tx_packetiser_set_peer(OSSL_QUIC_TX_PACKETISER *txp, const BIO_ADDR *peer); /* * Inform the TX packetiser that an EL has been discarded. Idempotent. * * This does not inform the QTX as well; the caller must also inform the QTX. * * The TXP will no longer reference the crypto[enc_level] QUIC_SSTREAM which was * provided in the TXP arguments. However, it is the callers responsibility to * free that QUIC_SSTREAM if desired. */ int ossl_quic_tx_packetiser_discard_enc_level(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level); /* * Informs the TX packetiser that the handshake is complete. The TX packetiser * will not send 1-RTT application data until the handshake is complete, * as the authenticity of the peer is not confirmed until the handshake * complete event occurs. */ void ossl_quic_tx_packetiser_notify_handshake_complete(OSSL_QUIC_TX_PACKETISER *txp); /* Asks the TXP to generate a HANDSHAKE_DONE frame in the next 1-RTT packet. */ void ossl_quic_tx_packetiser_schedule_handshake_done(OSSL_QUIC_TX_PACKETISER *txp); /* Asks the TXP to ensure the next packet in the given PN space is ACK-eliciting. */ void ossl_quic_tx_packetiser_schedule_ack_eliciting(OSSL_QUIC_TX_PACKETISER *txp, uint32_t pn_space); /* * Asks the TXP to ensure an ACK is put in the next packet in the given PN * space. */ void ossl_quic_tx_packetiser_schedule_ack(OSSL_QUIC_TX_PACKETISER *txp, uint32_t pn_space); /* * Schedules a connection close. *f and f->reason are copied. This operation is * irreversible and causes all further packets generated by the TXP to contain a * CONNECTION_CLOSE frame. This function fails if it has already been called * successfully; the information in *f cannot be changed after the first * successful call to this function. */ int ossl_quic_tx_packetiser_schedule_conn_close(OSSL_QUIC_TX_PACKETISER *txp, const OSSL_QUIC_FRAME_CONN_CLOSE *f); /* Setters for the msg_callback and msg_callback_arg */ void ossl_quic_tx_packetiser_set_msg_callback(OSSL_QUIC_TX_PACKETISER *txp, ossl_msg_cb msg_callback, SSL *msg_callback_ssl); void ossl_quic_tx_packetiser_set_msg_callback_arg(OSSL_QUIC_TX_PACKETISER *txp, void *msg_callback_arg); /* * Determines the next PN which will be used for a given PN space. */ QUIC_PN ossl_quic_tx_packetiser_get_next_pn(OSSL_QUIC_TX_PACKETISER *txp, uint32_t pn_space); /* * Sets a callback which is called whenever TXP sends an ACK frame. The callee * must not modify the ACK frame data. Can be used to snoop on PNs being ACKed. */ void ossl_quic_tx_packetiser_set_ack_tx_cb(OSSL_QUIC_TX_PACKETISER *txp, void (*cb)(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space, void *arg), void *cb_arg); # endif #endif
./openssl/include/internal/ktls.h
/* * Copyright 2018-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 */ #if defined(OPENSSL_SYS_LINUX) # ifndef OPENSSL_NO_KTLS # include <linux/version.h> # if LINUX_VERSION_CODE < KERNEL_VERSION(4, 13, 0) # define OPENSSL_NO_KTLS # ifndef PEDANTIC # warning "KTLS requires Kernel Headers >= 4.13.0" # warning "Skipping Compilation of KTLS" # endif # endif # endif #endif #ifndef HEADER_INTERNAL_KTLS # define HEADER_INTERNAL_KTLS # pragma once # ifndef OPENSSL_NO_KTLS # if defined(__FreeBSD__) # include <sys/types.h> # include <sys/socket.h> # include <sys/ktls.h> # include <netinet/in.h> # include <netinet/tcp.h> # include <openssl/ssl3.h> # ifndef TCP_RXTLS_ENABLE # define OPENSSL_NO_KTLS_RX # endif # define OPENSSL_KTLS_AES_GCM_128 # define OPENSSL_KTLS_AES_GCM_256 # define OPENSSL_KTLS_TLS13 # ifdef TLS_CHACHA20_IV_LEN # ifndef OPENSSL_NO_CHACHA # define OPENSSL_KTLS_CHACHA20_POLY1305 # endif # endif typedef struct tls_enable ktls_crypto_info_t; /* * FreeBSD does not require any additional steps to enable KTLS before * setting keys. */ static ossl_inline int ktls_enable(int fd) { return 1; } /* * The TCP_TXTLS_ENABLE socket option marks the outgoing socket buffer * as using TLS. If successful, then data sent using this socket will * be encrypted and encapsulated in TLS records using the tls_en * provided here. * * The TCP_RXTLS_ENABLE socket option marks the incoming socket buffer * as using TLS. If successful, then data received for this socket will * be authenticated and decrypted using the tls_en provided here. */ static ossl_inline int ktls_start(int fd, ktls_crypto_info_t *tls_en, int is_tx) { if (is_tx) return setsockopt(fd, IPPROTO_TCP, TCP_TXTLS_ENABLE, tls_en, sizeof(*tls_en)) ? 0 : 1; # ifndef OPENSSL_NO_KTLS_RX return setsockopt(fd, IPPROTO_TCP, TCP_RXTLS_ENABLE, tls_en, sizeof(*tls_en)) ? 0 : 1; # else return 0; # endif } /* Not supported on FreeBSD */ static ossl_inline int ktls_enable_tx_zerocopy_sendfile(int fd) { return 0; } /* * Send a TLS record using the tls_en provided in ktls_start and use * record_type instead of the default SSL3_RT_APPLICATION_DATA. * When the socket is non-blocking, then this call either returns EAGAIN or * the entire record is pushed to TCP. It is impossible to send a partial * record using this control message. */ static ossl_inline int ktls_send_ctrl_message(int fd, unsigned char record_type, const void *data, size_t length) { struct msghdr msg = { 0 }; int cmsg_len = sizeof(record_type); struct cmsghdr *cmsg; char buf[CMSG_SPACE(cmsg_len)]; struct iovec msg_iov; /* Vector of data to send/receive into */ msg.msg_control = buf; msg.msg_controllen = sizeof(buf); cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = IPPROTO_TCP; cmsg->cmsg_type = TLS_SET_RECORD_TYPE; cmsg->cmsg_len = CMSG_LEN(cmsg_len); *((unsigned char *)CMSG_DATA(cmsg)) = record_type; msg.msg_controllen = cmsg->cmsg_len; msg_iov.iov_base = (void *)data; msg_iov.iov_len = length; msg.msg_iov = &msg_iov; msg.msg_iovlen = 1; return sendmsg(fd, &msg, 0); } # ifdef OPENSSL_NO_KTLS_RX static ossl_inline int ktls_read_record(int fd, void *data, size_t length) { return -1; } # else /* !defined(OPENSSL_NO_KTLS_RX) */ /* * Receive a TLS record using the tls_en provided in ktls_start. The * kernel strips any explicit IV and authentication tag, but provides * the TLS record header via a control message. If there is an error * with the TLS record such as an invalid header, invalid padding, or * authentication failure recvmsg() will fail with an error. */ static ossl_inline int ktls_read_record(int fd, void *data, size_t length) { struct msghdr msg = { 0 }; int cmsg_len = sizeof(struct tls_get_record); struct tls_get_record *tgr; struct cmsghdr *cmsg; char buf[CMSG_SPACE(cmsg_len)]; struct iovec msg_iov; /* Vector of data to send/receive into */ int ret; unsigned char *p = data; const size_t prepend_length = SSL3_RT_HEADER_LENGTH; if (length <= prepend_length) { errno = EINVAL; return -1; } msg.msg_control = buf; msg.msg_controllen = sizeof(buf); msg_iov.iov_base = p + prepend_length; msg_iov.iov_len = length - prepend_length; msg.msg_iov = &msg_iov; msg.msg_iovlen = 1; ret = recvmsg(fd, &msg, 0); if (ret <= 0) return ret; if ((msg.msg_flags & (MSG_EOR | MSG_CTRUNC)) != MSG_EOR) { errno = EMSGSIZE; return -1; } if (msg.msg_controllen == 0) { errno = EBADMSG; return -1; } cmsg = CMSG_FIRSTHDR(&msg); if (cmsg->cmsg_level != IPPROTO_TCP || cmsg->cmsg_type != TLS_GET_RECORD || cmsg->cmsg_len != CMSG_LEN(cmsg_len)) { errno = EBADMSG; return -1; } tgr = (struct tls_get_record *)CMSG_DATA(cmsg); p[0] = tgr->tls_type; p[1] = tgr->tls_vmajor; p[2] = tgr->tls_vminor; *(uint16_t *)(p + 3) = htons(ret); return ret + prepend_length; } # endif /* OPENSSL_NO_KTLS_RX */ /* * KTLS enables the sendfile system call to send data from a file over * TLS. */ static ossl_inline ossl_ssize_t ktls_sendfile(int s, int fd, off_t off, size_t size, int flags) { off_t sbytes = 0; int ret; ret = sendfile(fd, s, off, size, NULL, &sbytes, flags); if (ret == -1 && sbytes == 0) return -1; return sbytes; } # endif /* __FreeBSD__ */ # if defined(OPENSSL_SYS_LINUX) # include <linux/tls.h> # if LINUX_VERSION_CODE < KERNEL_VERSION(4, 17, 0) # define OPENSSL_NO_KTLS_RX # ifndef PEDANTIC # warning "KTLS requires Kernel Headers >= 4.17.0 for receiving" # warning "Skipping Compilation of KTLS receive data path" # endif # endif # if LINUX_VERSION_CODE < KERNEL_VERSION(5, 19, 0) # define OPENSSL_NO_KTLS_ZC_TX # ifndef PEDANTIC # warning "KTLS requires Kernel Headers >= 5.19.0 for zerocopy sendfile" # warning "Skipping Compilation of KTLS zerocopy sendfile" # endif # endif # define OPENSSL_KTLS_AES_GCM_128 # if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0) # define OPENSSL_KTLS_AES_GCM_256 # define OPENSSL_KTLS_TLS13 # if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 2, 0) # define OPENSSL_KTLS_AES_CCM_128 # if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 11, 0) # ifndef OPENSSL_NO_CHACHA # define OPENSSL_KTLS_CHACHA20_POLY1305 # endif # endif # endif # endif # include <sys/sendfile.h> # include <netinet/tcp.h> # include <linux/socket.h> # include <openssl/ssl3.h> # include <openssl/tls1.h> # include <openssl/evp.h> # ifndef SOL_TLS # define SOL_TLS 282 # endif # ifndef TCP_ULP # define TCP_ULP 31 # endif # ifndef TLS_RX # define TLS_RX 2 # endif struct tls_crypto_info_all { union { # ifdef OPENSSL_KTLS_AES_GCM_128 struct tls12_crypto_info_aes_gcm_128 gcm128; # endif # ifdef OPENSSL_KTLS_AES_GCM_256 struct tls12_crypto_info_aes_gcm_256 gcm256; # endif # ifdef OPENSSL_KTLS_AES_CCM_128 struct tls12_crypto_info_aes_ccm_128 ccm128; # endif # ifdef OPENSSL_KTLS_CHACHA20_POLY1305 struct tls12_crypto_info_chacha20_poly1305 chacha20poly1305; # endif }; size_t tls_crypto_info_len; }; typedef struct tls_crypto_info_all ktls_crypto_info_t; /* * When successful, this socket option doesn't change the behaviour of the * TCP socket, except changing the TCP setsockopt handler to enable the * processing of SOL_TLS socket options. All other functionality remains the * same. */ static ossl_inline int ktls_enable(int fd) { return setsockopt(fd, SOL_TCP, TCP_ULP, "tls", sizeof("tls")) ? 0 : 1; } /* * The TLS_TX socket option changes the send/sendmsg handlers of the TCP socket. * If successful, then data sent using this socket will be encrypted and * encapsulated in TLS records using the crypto_info provided here. * The TLS_RX socket option changes the recv/recvmsg handlers of the TCP socket. * If successful, then data received using this socket will be decrypted, * authenticated and decapsulated using the crypto_info provided here. */ static ossl_inline int ktls_start(int fd, ktls_crypto_info_t *crypto_info, int is_tx) { return setsockopt(fd, SOL_TLS, is_tx ? TLS_TX : TLS_RX, crypto_info, crypto_info->tls_crypto_info_len) ? 0 : 1; } static ossl_inline int ktls_enable_tx_zerocopy_sendfile(int fd) { #ifndef OPENSSL_NO_KTLS_ZC_TX int enable = 1; return setsockopt(fd, SOL_TLS, TLS_TX_ZEROCOPY_RO, &enable, sizeof(enable)) ? 0 : 1; #else return 0; #endif } /* * Send a TLS record using the crypto_info provided in ktls_start and use * record_type instead of the default SSL3_RT_APPLICATION_DATA. * When the socket is non-blocking, then this call either returns EAGAIN or * the entire record is pushed to TCP. It is impossible to send a partial * record using this control message. */ static ossl_inline int ktls_send_ctrl_message(int fd, unsigned char record_type, const void *data, size_t length) { struct msghdr msg; int cmsg_len = sizeof(record_type); struct cmsghdr *cmsg; union { struct cmsghdr hdr; char buf[CMSG_SPACE(sizeof(unsigned char))]; } cmsgbuf; struct iovec msg_iov; /* Vector of data to send/receive into */ memset(&msg, 0, sizeof(msg)); msg.msg_control = cmsgbuf.buf; msg.msg_controllen = sizeof(cmsgbuf.buf); cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_TLS; cmsg->cmsg_type = TLS_SET_RECORD_TYPE; cmsg->cmsg_len = CMSG_LEN(cmsg_len); *((unsigned char *)CMSG_DATA(cmsg)) = record_type; msg.msg_controllen = cmsg->cmsg_len; msg_iov.iov_base = (void *)data; msg_iov.iov_len = length; msg.msg_iov = &msg_iov; msg.msg_iovlen = 1; return sendmsg(fd, &msg, 0); } /* * KTLS enables the sendfile system call to send data from a file over TLS. * @flags are ignored on Linux. (placeholder for FreeBSD sendfile) * */ static ossl_inline ossl_ssize_t ktls_sendfile(int s, int fd, off_t off, size_t size, int flags) { return sendfile(s, fd, &off, size); } # ifdef OPENSSL_NO_KTLS_RX static ossl_inline int ktls_read_record(int fd, void *data, size_t length) { return -1; } # else /* !defined(OPENSSL_NO_KTLS_RX) */ /* * Receive a TLS record using the crypto_info provided in ktls_start. * The kernel strips the TLS record header, IV and authentication tag, * returning only the plaintext data or an error on failure. * We add the TLS record header here to satisfy routines in rec_layer_s3.c */ static ossl_inline int ktls_read_record(int fd, void *data, size_t length) { struct msghdr msg; struct cmsghdr *cmsg; union { struct cmsghdr hdr; char buf[CMSG_SPACE(sizeof(unsigned char))]; } cmsgbuf; struct iovec msg_iov; int ret; unsigned char *p = data; const size_t prepend_length = SSL3_RT_HEADER_LENGTH; if (length < prepend_length + EVP_GCM_TLS_TAG_LEN) { errno = EINVAL; return -1; } memset(&msg, 0, sizeof(msg)); msg.msg_control = cmsgbuf.buf; msg.msg_controllen = sizeof(cmsgbuf.buf); msg_iov.iov_base = p + prepend_length; msg_iov.iov_len = length - prepend_length - EVP_GCM_TLS_TAG_LEN; msg.msg_iov = &msg_iov; msg.msg_iovlen = 1; ret = recvmsg(fd, &msg, 0); if (ret < 0) return ret; if (msg.msg_controllen > 0) { cmsg = CMSG_FIRSTHDR(&msg); if (cmsg->cmsg_type == TLS_GET_RECORD_TYPE) { p[0] = *((unsigned char *)CMSG_DATA(cmsg)); p[1] = TLS1_2_VERSION_MAJOR; p[2] = TLS1_2_VERSION_MINOR; /* returned length is limited to msg_iov.iov_len above */ p[3] = (ret >> 8) & 0xff; p[4] = ret & 0xff; ret += prepend_length; } } return ret; } # endif /* OPENSSL_NO_KTLS_RX */ # endif /* OPENSSL_SYS_LINUX */ # endif /* OPENSSL_NO_KTLS */ #endif /* HEADER_INTERNAL_KTLS */
./openssl/include/internal/params.h
/* * Copyright 2023 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 <stddef.h> #include <openssl/params.h> /* * Extract the parameter into an allocated buffer. * Any existing allocation in *out is cleared and freed. * * Returns 1 on success, 0 on failure and -1 if there are no matching params. * * *out and *out_len are guaranteed to be untouched if this function * doesn't return success. */ int ossl_param_get1_octet_string(const OSSL_PARAM *params, const char *name, unsigned char **out, size_t *out_len); /* * Concatenate all of the matching params together. * *out will point to an allocated buffer on successful return. * Any existing allocation in *out is cleared and freed. * * Passing 0 for maxsize means unlimited size output. * * Returns 1 on success, 0 on failure and -1 if there are no matching params. * * *out and *out_len are guaranteed to be untouched if this function * doesn't return success. */ int ossl_param_get1_concat_octet_string(const OSSL_PARAM *params, const char *name, unsigned char **out, size_t *out_len, size_t maxsize);
./openssl/include/internal/statem.h
/* * Copyright 2015-2023 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_INTERNAL_STATEM_H # define OSSL_INTERNAL_STATEM_H /***************************************************************************** * * * These enums should be considered PRIVATE to the state machine. No * * non-state machine code should need to use these * * * *****************************************************************************/ /* * Valid return codes used for functions performing work prior to or after * sending or receiving a message */ typedef enum { /* Something went wrong */ WORK_ERROR, /* We're done working and there shouldn't be anything else to do after */ WORK_FINISHED_STOP, /* We're done working move onto the next thing */ WORK_FINISHED_CONTINUE, /* We're working on phase A */ WORK_MORE_A, /* We're working on phase B */ WORK_MORE_B, /* We're working on phase C */ WORK_MORE_C } WORK_STATE; /* Write transition return codes */ typedef enum { /* Something went wrong */ WRITE_TRAN_ERROR, /* A transition was successfully completed and we should continue */ WRITE_TRAN_CONTINUE, /* There is no more write work to be done */ WRITE_TRAN_FINISHED } WRITE_TRAN; /* Message flow states */ typedef enum { /* No handshake in progress */ MSG_FLOW_UNINITED, /* A permanent error with this connection */ MSG_FLOW_ERROR, /* We are reading messages */ MSG_FLOW_READING, /* We are writing messages */ MSG_FLOW_WRITING, /* Handshake has finished */ MSG_FLOW_FINISHED } MSG_FLOW_STATE; /* Read states */ typedef enum { READ_STATE_HEADER, READ_STATE_BODY, READ_STATE_POST_PROCESS } READ_STATE; /* Write states */ typedef enum { WRITE_STATE_TRANSITION, WRITE_STATE_PRE_WORK, WRITE_STATE_SEND, WRITE_STATE_POST_WORK } WRITE_STATE; typedef enum { CON_FUNC_ERROR = 0, CON_FUNC_SUCCESS, CON_FUNC_DONT_SEND } CON_FUNC_RETURN; typedef int (*ossl_statem_mutate_handshake_cb)(const unsigned char *msgin, size_t inlen, unsigned char **msgout, size_t *outlen, void *arg); typedef void (*ossl_statem_finish_mutate_handshake_cb)(void *arg); /***************************************************************************** * * * This structure should be considered "opaque" to anything outside of the * * state machine. No non-state machine code should be accessing the members * * of this structure. * * * *****************************************************************************/ struct ossl_statem_st { MSG_FLOW_STATE state; WRITE_STATE write_state; WORK_STATE write_state_work; READ_STATE read_state; WORK_STATE read_state_work; OSSL_HANDSHAKE_STATE hand_state; /* The handshake state requested by an API call (e.g. HelloRequest) */ OSSL_HANDSHAKE_STATE request_state; int in_init; int read_state_first_init; /* true when we are actually in SSL_accept() or SSL_connect() */ int in_handshake; /* * True when are processing a "real" handshake that needs cleaning up (not * just a HelloRequest or similar). */ int cleanuphand; /* Should we skip the CertificateVerify message? */ unsigned int no_cert_verify; int use_timer; /* Test harness message mutator callbacks */ ossl_statem_mutate_handshake_cb mutate_handshake_cb; ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb; void *mutatearg; unsigned int write_in_progress : 1; }; typedef struct ossl_statem_st OSSL_STATEM; /***************************************************************************** * * * The following macros/functions represent the libssl internal API to the * * state machine. Any libssl code may call these functions/macros * * * *****************************************************************************/ typedef struct ssl_connection_st SSL_CONNECTION; __owur int ossl_statem_accept(SSL *s); __owur int ossl_statem_connect(SSL *s); OSSL_HANDSHAKE_STATE ossl_statem_get_state(SSL_CONNECTION *s); void ossl_statem_clear(SSL_CONNECTION *s); void ossl_statem_set_renegotiate(SSL_CONNECTION *s); void ossl_statem_send_fatal(SSL_CONNECTION *s, int al); void ossl_statem_fatal(SSL_CONNECTION *s, int al, int reason, const char *fmt, ...); # define SSLfatal_alert(s, al) ossl_statem_send_fatal((s), (al)) # define SSLfatal(s, al, r) SSLfatal_data((s), (al), (r), NULL) # define SSLfatal_data \ (ERR_new(), \ ERR_set_debug(OPENSSL_FILE, OPENSSL_LINE, OPENSSL_FUNC), \ ossl_statem_fatal) int ossl_statem_in_error(const SSL_CONNECTION *s); void ossl_statem_set_in_init(SSL_CONNECTION *s, int init); int ossl_statem_get_in_handshake(SSL_CONNECTION *s); void ossl_statem_set_in_handshake(SSL_CONNECTION *s, int inhand); __owur int ossl_statem_skip_early_data(SSL_CONNECTION *s); void ossl_statem_check_finish_init(SSL_CONNECTION *s, int send); void ossl_statem_set_hello_verify_done(SSL_CONNECTION *s); __owur int ossl_statem_app_data_allowed(SSL_CONNECTION *s); __owur int ossl_statem_export_allowed(SSL_CONNECTION *s); __owur int ossl_statem_export_early_allowed(SSL_CONNECTION *s); /* Flush the write BIO */ int statem_flush(SSL_CONNECTION *s); int ossl_statem_set_mutator(SSL *s, ossl_statem_mutate_handshake_cb mutate_handshake_cb, ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb, void *mutatearg); #endif
./openssl/include/internal/e_os.h
/* * Copyright 1995-2023 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_E_OS_H # define OSSL_E_OS_H # include <limits.h> # include <openssl/opensslconf.h> # include <openssl/e_os2.h> # include <openssl/crypto.h> # include "internal/numbers.h" /* Ensure the definition of SIZE_MAX */ /* * <openssl/e_os2.h> contains what we can justify to make visible to the * outside; this file e_os.h is not part of the exported interface. */ # if defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI) # define NO_CHMOD # define NO_SYSLOG # endif # define get_last_sys_error() errno # define clear_sys_error() errno=0 # define set_sys_error(e) errno=(e) /******************************************************************** The Microsoft section ********************************************************************/ # if defined(OPENSSL_SYS_WIN32) && !defined(WIN32) # define WIN32 # endif # if defined(OPENSSL_SYS_WINDOWS) && !defined(WINDOWS) # define WINDOWS # endif # if defined(OPENSSL_SYS_MSDOS) && !defined(MSDOS) # define MSDOS # endif # ifdef WIN32 # undef get_last_sys_error # undef clear_sys_error # undef set_sys_error # define get_last_sys_error() GetLastError() # define clear_sys_error() SetLastError(0) # define set_sys_error(e) SetLastError(e) # if !defined(WINNT) # define WIN_CONSOLE_BUG # endif # else # endif # if (defined(WINDOWS) || defined(MSDOS)) # ifdef __DJGPP__ # include <unistd.h> # include <sys/stat.h> # define _setmode setmode # define _O_TEXT O_TEXT # define _O_BINARY O_BINARY # undef DEVRANDOM_EGD /* Neither MS-DOS nor FreeDOS provide 'egd' sockets. */ # undef DEVRANDOM # define DEVRANDOM "/dev/urandom\x24" # endif /* __DJGPP__ */ # ifndef S_IFDIR # define S_IFDIR _S_IFDIR # endif # ifndef S_IFMT # define S_IFMT _S_IFMT # endif # if !defined(WINNT) && !defined(__DJGPP__) # define NO_SYSLOG # endif # ifdef WINDOWS # if !defined(_WIN32_WCE) && !defined(_WIN32_WINNT) /* * Defining _WIN32_WINNT here in e_os.h implies certain "discipline." * Most notably we ought to check for availability of each specific * routine that was introduced after denoted _WIN32_WINNT with * GetProcAddress(). Normally newer functions are masked with higher * _WIN32_WINNT in SDK headers. So that if you wish to use them in * some module, you'd need to override _WIN32_WINNT definition in * the target module in order to "reach for" prototypes, but replace * calls to new functions with indirect calls. Alternatively it * might be possible to achieve the goal by /DELAYLOAD-ing .DLLs * and check for current OS version instead. */ # define _WIN32_WINNT 0x0501 # endif # if defined(_WIN32_WINNT) || defined(_WIN32_WCE) /* * Just like defining _WIN32_WINNT including winsock2.h implies * certain "discipline" for maintaining [broad] binary compatibility. * As long as structures are invariant among Winsock versions, * it's sufficient to check for specific Winsock2 API availability * at run-time [DSO_global_lookup is recommended]... */ # include <winsock2.h> # include <ws2tcpip.h> /* * Clang-based C++Builder 10.3.3 toolchains cannot find C inline * definitions at link-time. This header defines WspiapiLoad() as an * __inline function. https://quality.embarcadero.com/browse/RSP-33806 */ # if !defined(__BORLANDC__) || !defined(__clang__) # include <wspiapi.h> # endif /* yes, they have to be #included prior to <windows.h> */ # endif # include <windows.h> # include <stdio.h> # include <stddef.h> # include <errno.h> # if defined(_WIN32_WCE) && !defined(EACCES) # define EACCES 13 # endif # include <string.h> # ifdef _WIN64 # define strlen(s) _strlen31(s) /* cut strings to 2GB */ static __inline unsigned int _strlen31(const char *str) { unsigned int len = 0; while (*str && len < 0x80000000U) str++, len++; return len & 0x7FFFFFFF; } # endif # include <malloc.h> # if defined(_MSC_VER) && !defined(_WIN32_WCE) && !defined(_DLL) && defined(stdin) # if _MSC_VER>=1300 && _MSC_VER<1600 # undef stdin # undef stdout # undef stderr FILE *__iob_func(void); # define stdin (&__iob_func()[0]) # define stdout (&__iob_func()[1]) # define stderr (&__iob_func()[2]) # endif # endif # endif # include <io.h> # include <fcntl.h> # ifdef OPENSSL_SYS_WINCE # define OPENSSL_NO_POSIX_IO # endif # define EXIT(n) exit(n) # define LIST_SEPARATOR_CHAR ';' # ifndef W_OK # define W_OK 2 # endif # ifndef R_OK # define R_OK 4 # endif # ifdef OPENSSL_SYS_WINCE # define DEFAULT_HOME "" # else # define DEFAULT_HOME "C:" # endif /* Avoid Visual Studio 13 GetVersion deprecated problems */ # if defined(_MSC_VER) && _MSC_VER>=1800 # define check_winnt() (1) # define check_win_minplat(x) (1) # else # define check_winnt() (GetVersion() < 0x80000000) # define check_win_minplat(x) (LOBYTE(LOWORD(GetVersion())) >= (x)) # endif # else /* The non-microsoft world */ # if defined(OPENSSL_SYS_VXWORKS) # include <time.h> # else # include <sys/time.h> # endif # ifdef OPENSSL_SYS_VMS # define VMS 1 /* * some programs don't include stdlib, so exit() and others give implicit * function warnings */ # include <stdlib.h> # if defined(__DECC) # include <unistd.h> # else # include <unixlib.h> # endif # define LIST_SEPARATOR_CHAR ',' /* We don't have any well-defined random devices on VMS, yet... */ # undef DEVRANDOM /*- We need to do this since VMS has the following coding on status codes: Bits 0-2: status type: 0 = warning, 1 = success, 2 = error, 3 = info ... The important thing to know is that odd numbers are considered good, while even ones are considered errors. Bits 3-15: actual status number Bits 16-27: facility number. 0 is considered "unknown" Bits 28-31: control bits. If bit 28 is set, the shell won't try to output the message (which, for random codes, just looks ugly) So, what we do here is to change 0 to 1 to get the default success status, and everything else is shifted up to fit into the status number field, and the status is tagged as an error, which is what is wanted here. Finally, we add the VMS C facility code 0x35a000, because there are some programs, such as Perl, that will reinterpret the code back to something POSIX. 'man perlvms' explains it further. NOTE: the perlvms manual wants to turn all codes 2 to 255 into success codes (status type = 1). I couldn't disagree more. Fortunately, the status type doesn't seem to bother Perl. -- Richard Levitte */ # define EXIT(n) exit((n) ? (((n) << 3) | 2 | 0x10000000 | 0x35a000) : 1) # define DEFAULT_HOME "SYS$LOGIN:" # else /* !defined VMS */ # include <unistd.h> # include <sys/types.h> # ifdef OPENSSL_SYS_WIN32_CYGWIN # include <io.h> # include <fcntl.h> # endif # define LIST_SEPARATOR_CHAR ':' # define EXIT(n) exit(n) # endif # endif /***********************************************/ # if defined(OPENSSL_SYS_WINDOWS) # if defined(_MSC_VER) && (_MSC_VER >= 1310) && !defined(_WIN32_WCE) # define open _open # define fdopen _fdopen # define close _close # ifndef strdup # define strdup _strdup # endif # define unlink _unlink # define fileno _fileno # endif # else # include <strings.h> # endif /* vxworks */ # if defined(OPENSSL_SYS_VXWORKS) # include <ioLib.h> # include <tickLib.h> # include <sysLib.h> # include <vxWorks.h> # include <sockLib.h> # include <taskLib.h> # define TTY_STRUCT int # define sleep(a) taskDelay((a) * sysClkRateGet()) /* * NOTE: these are implemented by helpers in database app! if the database is * not linked, we need to implement them elsewhere */ struct hostent *gethostbyname(const char *name); struct hostent *gethostbyaddr(const char *addr, int length, int type); struct servent *getservbyname(const char *name, const char *proto); # endif /* end vxworks */ /* ----------------------------- HP NonStop -------------------------------- */ /* Required to support platform variant without getpid() and pid_t. */ # if defined(__TANDEM) && defined(_GUARDIAN_TARGET) # include <strings.h> # include <netdb.h> # define getservbyname(name,proto) getservbyname((char*)name,proto) # define gethostbyname(name) gethostbyname((char*)name) # define ioctlsocket(a,b,c) ioctl(a,b,c) # ifdef NO_GETPID inline int nssgetpid(void); # ifndef NSSGETPID_MACRO # define NSSGETPID_MACRO # include <cextdecs.h(PROCESSHANDLE_GETMINE_)> # include <cextdecs.h(PROCESSHANDLE_DECOMPOSE_)> inline int nssgetpid(void) { short phandle[10]={0}; union pseudo_pid { struct { short cpu; short pin; } cpu_pin ; int ppid; } ppid = { 0 }; PROCESSHANDLE_GETMINE_(phandle); PROCESSHANDLE_DECOMPOSE_(phandle, &ppid.cpu_pin.cpu, &ppid.cpu_pin.pin); return ppid.ppid; } # define getpid(a) nssgetpid(a) # endif /* NSSGETPID_MACRO */ # endif /* NO_GETPID */ /*# define setsockopt(a,b,c,d,f) setsockopt(a,b,c,(char*)d,f)*/ /*# define getsockopt(a,b,c,d,f) getsockopt(a,b,c,(char*)d,f)*/ /*# define connect(a,b,c) connect(a,(struct sockaddr *)b,c)*/ /*# define bind(a,b,c) bind(a,(struct sockaddr *)b,c)*/ /*# define sendto(a,b,c,d,e,f) sendto(a,(char*)b,c,d,(struct sockaddr *)e,f)*/ # if defined(OPENSSL_THREADS) && !defined(_PUT_MODEL_) /* * HPNS SPT threads */ # define SPT_THREAD_SIGNAL 1 # define SPT_THREAD_AWARE 1 # include <spthread.h> # undef close # define close spt_close /* # define get_last_socket_error() errno # define clear_socket_error() errno=0 # define ioctlsocket(a,b,c) ioctl(a,b,c) # define closesocket(s) close(s) # define readsocket(s,b,n) read((s),(char*)(b),(n)) # define writesocket(s,b,n) write((s),(char*)(b),(n) */ # define accept(a,b,c) accept(a,(struct sockaddr *)b,c) # define recvfrom(a,b,c,d,e,f) recvfrom(a,b,(socklen_t)c,d,e,f) # endif # endif # ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION # define CRYPTO_memcmp memcmp # endif # ifndef OPENSSL_NO_SECURE_MEMORY /* unistd.h defines _POSIX_VERSION */ # if (defined(OPENSSL_SYS_UNIX) \ && ( (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) \ || defined(__sun) || defined(__hpux) || defined(__sgi) \ || defined(__osf__) )) \ || defined(_WIN32) /* secure memory is implemented */ # else # define OPENSSL_NO_SECURE_MEMORY # endif # endif /* * str[n]casecmp_l is defined in POSIX 2008-01. Value is taken accordingly * https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html * There are also equivalent functions on Windows. * There is no locale_t on NONSTOP. */ # if defined(OPENSSL_SYS_WINDOWS) # define locale_t _locale_t # define freelocale _free_locale # define strcasecmp_l _stricmp_l # define strncasecmp_l _strnicmp_l # define strcasecmp _stricmp # define strncasecmp _strnicmp # elif !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 200809L \ || defined(OPENSSL_SYS_TANDEM) # ifndef OPENSSL_NO_LOCALE # define OPENSSL_NO_LOCALE # endif # endif #endif
./openssl/include/internal/provider.h
/* * Copyright 2019-2023 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_INTERNAL_PROVIDER_H # define OSSL_INTERNAL_PROVIDER_H # pragma once # include <openssl/core.h> # include <openssl/core_dispatch.h> # include "internal/dso.h" # include "internal/symhacks.h" # ifdef __cplusplus extern "C" { # endif /* * namespaces: * * ossl_provider_ Provider Object internal API * OSSL_PROVIDER Provider Object */ /* Provider Object finder, constructor and destructor */ OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name, int noconfig); OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name, OSSL_provider_init_fn *init_function, OSSL_PARAM *params, int noconfig); int ossl_provider_up_ref(OSSL_PROVIDER *prov); void ossl_provider_free(OSSL_PROVIDER *prov); /* Setters */ int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path); int ossl_provider_add_parameter(OSSL_PROVIDER *prov, const char *name, const char *value); int ossl_provider_is_child(const OSSL_PROVIDER *prov); int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle); const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov); int ossl_provider_up_ref_parent(OSSL_PROVIDER *prov, int activate); int ossl_provider_free_parent(OSSL_PROVIDER *prov, int deactivate); int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx, const char *props); /* Disable fallback loading */ int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx); /* * Activate the Provider * If the Provider is a module, the module will be loaded */ int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild); int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren); int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov, int retain_fallbacks); /* Return pointer to the provider's context */ void *ossl_provider_ctx(const OSSL_PROVIDER *prov); /* Iterate over all loaded providers */ int ossl_provider_doall_activated(OSSL_LIB_CTX *, int (*cb)(OSSL_PROVIDER *provider, void *cbdata), void *cbdata); /* Getters for other library functions */ const char *ossl_provider_name(const OSSL_PROVIDER *prov); const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov); const char *ossl_provider_module_name(const OSSL_PROVIDER *prov); const char *ossl_provider_module_path(const OSSL_PROVIDER *prov); void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov); const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov); OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov); /* Thin wrappers around calls to the provider */ void ossl_provider_teardown(const OSSL_PROVIDER *prov); const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov); int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[]); int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov, const char *capability, OSSL_CALLBACK *cb, void *arg); int ossl_provider_self_test(const OSSL_PROVIDER *prov); const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov, int operation_id, int *no_cache); void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov, int operation_id, const OSSL_ALGORITHM *algs); /* * Cache of bits to see if we already added methods for an operation in * the "permanent" method store. * They should never be called for temporary method stores! */ int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum); int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum, int *result); /* Configuration */ void ossl_provider_add_conf_module(void); /* Child providers */ int ossl_provider_init_as_child(OSSL_LIB_CTX *ctx, const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in); void ossl_provider_deinit_child(OSSL_LIB_CTX *ctx); # ifdef __cplusplus } # endif #endif
./openssl/include/internal/dso.h
/* * Copyright 2000-2021 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_INTERNAL_DSO_H # define OSSL_INTERNAL_DSO_H # pragma once # include <openssl/crypto.h> # include "internal/dsoerr.h" /* These values are used as commands to DSO_ctrl() */ # define DSO_CTRL_GET_FLAGS 1 # define DSO_CTRL_SET_FLAGS 2 # define DSO_CTRL_OR_FLAGS 3 /* * By default, DSO_load() will translate the provided filename into a form * typical for the platform using the dso_name_converter function of the * method. Eg. win32 will transform "blah" into "blah.dll", and dlfcn will * transform it into "libblah.so". This callback could even utilise the * DSO_METHOD's converter too if it only wants to override behaviour for * one or two possible DSO methods. However, the following flag can be * set in a DSO to prevent *any* native name-translation at all - eg. if * the caller has prompted the user for a path to a driver library so the * filename should be interpreted as-is. */ # define DSO_FLAG_NO_NAME_TRANSLATION 0x01 /* * An extra flag to give if only the extension should be added as * translation. This is obviously only of importance on Unix and other * operating systems where the translation also may prefix the name with * something, like 'lib', and ignored everywhere else. This flag is also * ignored if DSO_FLAG_NO_NAME_TRANSLATION is used at the same time. */ # define DSO_FLAG_NAME_TRANSLATION_EXT_ONLY 0x02 /* * Don't unload the DSO when we call DSO_free() */ # define DSO_FLAG_NO_UNLOAD_ON_FREE 0x04 /* * This flag loads the library with public symbols. Meaning: The exported * symbols of this library are public to all libraries loaded after this * library. At the moment only implemented in unix. */ # define DSO_FLAG_GLOBAL_SYMBOLS 0x20 typedef void (*DSO_FUNC_TYPE) (void); typedef struct dso_st DSO; typedef struct dso_meth_st DSO_METHOD; /* * The function prototype used for method functions (or caller-provided * callbacks) that transform filenames. They are passed a DSO structure * pointer (or NULL if they are to be used independently of a DSO object) and * a filename to transform. They should either return NULL (if there is an * error condition) or a newly allocated string containing the transformed * form that the caller will need to free with OPENSSL_free() when done. */ typedef char *(*DSO_NAME_CONVERTER_FUNC)(DSO *, const char *); /* * The function prototype used for method functions (or caller-provided * callbacks) that merge two file specifications. They are passed a DSO * structure pointer (or NULL if they are to be used independently of a DSO * object) and two file specifications to merge. They should either return * NULL (if there is an error condition) or a newly allocated string * containing the result of merging that the caller will need to free with * OPENSSL_free() when done. Here, merging means that bits and pieces are * taken from each of the file specifications and added together in whatever * fashion that is sensible for the DSO method in question. The only rule * that really applies is that if the two specification contain pieces of the * same type, the copy from the first string takes priority. One could see * it as the first specification is the one given by the user and the second * being a bunch of defaults to add on if they're missing in the first. */ typedef char *(*DSO_MERGER_FUNC)(DSO *, const char *, const char *); DSO *DSO_new(void); int DSO_free(DSO *dso); int DSO_flags(DSO *dso); int DSO_up_ref(DSO *dso); long DSO_ctrl(DSO *dso, int cmd, long larg, void *parg); /* * These functions can be used to get/set the platform-independent filename * used for a DSO. NB: set will fail if the DSO is already loaded. */ const char *DSO_get_filename(DSO *dso); int DSO_set_filename(DSO *dso, const char *filename); /* * This function will invoke the DSO's name_converter callback to translate a * filename, or if the callback isn't set it will instead use the DSO_METHOD's * converter. If "filename" is NULL, the "filename" in the DSO itself will be * used. If the DSO_FLAG_NO_NAME_TRANSLATION flag is set, then the filename is * simply duplicated. NB: This function is usually called from within a * DSO_METHOD during the processing of a DSO_load() call, and is exposed so * that caller-created DSO_METHODs can do the same thing. A non-NULL return * value will need to be OPENSSL_free()'d. */ char *DSO_convert_filename(DSO *dso, const char *filename); /* * This function will invoke the DSO's merger callback to merge two file * specifications, or if the callback isn't set it will instead use the * DSO_METHOD's merger. A non-NULL return value will need to be * OPENSSL_free()'d. */ char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2); /* * The all-singing all-dancing load function, you normally pass NULL for the * first and third parameters. Use DSO_up_ref and DSO_free for subsequent * reference count handling. Any flags passed in will be set in the * constructed DSO after its init() function but before the load operation. * If 'dso' is non-NULL, 'flags' is ignored. */ DSO *DSO_load(DSO *dso, const char *filename, DSO_METHOD *meth, int flags); /* This function binds to a function inside a shared library. */ DSO_FUNC_TYPE DSO_bind_func(DSO *dso, const char *symname); /* * This method is the default, but will beg, borrow, or steal whatever method * should be the default on any particular platform (including * DSO_METH_null() if necessary). */ DSO_METHOD *DSO_METHOD_openssl(void); /* * This function writes null-terminated pathname of DSO module containing * 'addr' into 'sz' large caller-provided 'path' and returns the number of * characters [including trailing zero] written to it. If 'sz' is 0 or * negative, 'path' is ignored and required amount of characters [including * trailing zero] to accommodate pathname is returned. If 'addr' is NULL, then * pathname of cryptolib itself is returned. Negative or zero return value * denotes error. */ int DSO_pathbyaddr(void *addr, char *path, int sz); /* * Like DSO_pathbyaddr() but instead returns a handle to the DSO for the symbol * or NULL on error. */ DSO *DSO_dsobyaddr(void *addr, int flags); /* * This function should be used with caution! It looks up symbols in *all* * loaded modules and if module gets unloaded by somebody else attempt to * dereference the pointer is doomed to have fatal consequences. Primary * usage for this function is to probe *core* system functionality, e.g. * check if getnameinfo(3) is available at run-time without bothering about * OS-specific details such as libc.so.versioning or where does it actually * reside: in libc itself or libsocket. */ void *DSO_global_lookup(const char *name); #endif
./openssl/include/internal/quic_rcidm.h
/* * Copyright 2023 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_INTERNAL_QUIC_RCIDM_H # define OSSL_INTERNAL_QUIC_RCIDM_H # pragma once # include "internal/e_os.h" # include "internal/time.h" # include "internal/quic_types.h" # include "internal/quic_wire.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Remote Connection ID Manager * ================================= * * This manages connection IDs for the TX side. The RCIDM tracks remote CIDs * (RCIDs) which a peer has issued to us and which we can use as the DCID of * packets we transmit. It is entirely separate from the LCIDM, which handles * routing received packets by their DCIDs. * * RCIDs fall into four categories: * * 1. A client's Initial ODCID (0..1) * 2. A peer's Initial SCID (1) * 3. A server's Retry SCID (0..1) * 4. A CID issued via a NEW_CONNECTION_ID frame (n) * * Unlike a LCIDM, which is per port, a RCIDM is per connection, as there is no * need for routing of outgoing packets. */ typedef struct quic_rcidm_st QUIC_RCIDM; /* * Creates a new RCIDM. Returns NULL on failure. * * For a client, initial_odcid is the client's Initial ODCID. * For a server, initial_odcid is NULL. */ QUIC_RCIDM *ossl_quic_rcidm_new(const QUIC_CONN_ID *initial_odcid); /* Frees a RCIDM. */ void ossl_quic_rcidm_free(QUIC_RCIDM *rcidm); /* * CID Events * ========== */ /* * To be called by a client when a server responds to the first Initial packet * sent with its own Initial packet with its own SCID; or to be called by a * server when we first get an Initial packet from a client with the client's * supplied SCID. The added RCID implicitly has a sequence number of 0. * * We immediately switch to using this SCID as our preferred RCID. This SCID * must be enrolled using this function. May only be called once. */ int ossl_quic_rcidm_add_from_initial(QUIC_RCIDM *rcidm, const QUIC_CONN_ID *rcid); /* * To be called by a client when a server responds to the first Initial packet * sent with a Retry packet with its own SCID (the "Retry ODCID"). We * immediately switch to using this SCID as our preferred RCID when conducting * the retry. This SCID must be enrolled using this function. May only be called * once. The added RCID has no sequence number associated with it as it is * essentially a new ODCID (hereafter a Retry ODCID). * * Not for server use. */ int ossl_quic_rcidm_add_from_server_retry(QUIC_RCIDM *rcidm, const QUIC_CONN_ID *retry_odcid); /* * Processes an incoming NEW_CONN_ID frame, recording the new CID as a potential * RCID. The RCIDM retirement mechanism is ratcheted according to the * ncid->retire_prior_to field. The stateless_reset field is ignored; the caller * is responsible for handling it separately. */ int ossl_quic_rcidm_add_from_ncid(QUIC_RCIDM *rcidm, const OSSL_QUIC_FRAME_NEW_CONN_ID *ncid); /* * Other Events * ============ */ /* * Notifies the RCIDM that the handshake for a connection is complete. * Should only be called once; further calls are ignored. * * This may influence the RCIDM's RCID change policy. */ void ossl_quic_rcidm_on_handshake_complete(QUIC_RCIDM *rcidm); /* * Notifies the RCIDM that one or more packets have been sent. * * This may influence the RCIDM's RCID change policy. */ void ossl_quic_rcidm_on_packet_sent(QUIC_RCIDM *rcidm, uint64_t num_packets); /* * Manually request switching to a new RCID as soon as possible. */ void ossl_quic_rcidm_request_roll(QUIC_RCIDM *rcidm); /* * Queries * ======= */ /* * The RCIDM decides when it will never use a given RCID again. When it does * this, it outputs the sequence number of that RCID using this function, which * pops from a logical queue of retired RCIDs. The caller is responsible * for polling this function and generating Retire CID frames from the result. * * If nothing needs doing and the queue is empty, this function returns 0. If * there is an RCID which needs retiring, the sequence number of that RCID is * written to *seq_num (if seq_num is non-NULL) and this function returns 1. The * queue entry is popped (and the caller is thus assumed to have taken * responsibility for transmitting the necessary Retire CID frame). * * Note that the caller should not transmit a Retire CID frame immediately as * packets using the RCID may still be in flight. The caller must determine an * appropriate delay using knowledge of network conditions (RTT, etc.) which is * outside the scope of the RCIDM. The caller is responsible for implementing * this delay based on the last time a packet was transmitted using the RCID * being retired. */ int ossl_quic_rcidm_pop_retire_seq_num(QUIC_RCIDM *rcid, uint64_t *seq_num); /* * Like ossl_quic_rcidm_pop_retire_seq_num, but does not pop the item from the * queue. If this call succeeds, the next call to * ossl_quic_rcidm_pop_retire_seq_num is guaranteed to output the same sequence * number. */ int ossl_quic_rcidm_peek_retire_seq_num(QUIC_RCIDM *rcid, uint64_t *seq_num); /* * Writes the DCID preferred for a newly transmitted packet at this time to * *tx_dcid. This function should be called to determine what DCID to use when * transmitting a packet to the peer. The RCIDM may implement arbitrary policy * to decide when to change the preferred RCID. * * Returns 1 on success and 0 on failure. */ int ossl_quic_rcidm_get_preferred_tx_dcid(QUIC_RCIDM *rcidm, QUIC_CONN_ID *tx_dcid); /* * Returns 1 if the value output by ossl_quic_rcidm_get_preferred_tx_dcid() has * changed since the last call to this function with clear set. If clear is set, * clears the changed flag. Returns the old value of the changed flag. */ int ossl_quic_rcidm_get_preferred_tx_dcid_changed(QUIC_RCIDM *rcidm, int clear); /* * Returns the number of active numbered RCIDs we have. Note that this includes * RCIDs on the retir*ing* queue accessed via * ossl_quic_rcidm_pop_retire_seq_num() as these are still active until actually * retired. */ size_t ossl_quic_rcidm_get_num_active(const QUIC_RCIDM *rcidm); /* * Returns the number of retir*ing* numbered RCIDs we have. */ size_t ossl_quic_rcidm_get_num_retiring(const QUIC_RCIDM *rcidm); # endif #endif
./openssl/include/internal/ssl3_cbc.h
/* * Copyright 2022-2023 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 <openssl/evp.h> /* tls_pad.c */ int ssl3_cbc_remove_padding_and_mac(size_t *reclen, size_t origreclen, unsigned char *recdata, unsigned char **mac, int *alloced, size_t block_size, size_t mac_size, OSSL_LIB_CTX *libctx); int tls1_cbc_remove_padding_and_mac(size_t *reclen, size_t origreclen, unsigned char *recdata, unsigned char **mac, int *alloced, size_t block_size, size_t mac_size, int aead, OSSL_LIB_CTX *libctx); /* ssl3_cbc.c */ __owur char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx); __owur int ssl3_cbc_digest_record(const EVP_MD *md, unsigned char *md_out, size_t *md_out_size, const unsigned char *header, const unsigned char *data, size_t data_size, size_t data_plus_mac_plus_padding_size, const unsigned char *mac_secret, size_t mac_secret_length, char is_sslv3);
./openssl/include/internal/quic_tserver.h
/* * Copyright 2022-2023 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_TSERVER_H # define OSSL_QUIC_TSERVER_H # include <openssl/ssl.h> # include <openssl/bio.h> # include "internal/quic_stream.h" # include "internal/quic_channel.h" # include "internal/statem.h" # include "internal/time.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Test Server Module * ======================= * * This implements a QUIC test server. Since full QUIC server support is not yet * implemented this server is limited in features and scope. It exists to * provide a target for our QUIC client to talk to for testing purposes. * * A given QUIC test server instance supports only one client at a time. * * Note that this test server is not suitable for production use because it does * not implement address verification, anti-amplification or retry logic. */ typedef struct quic_tserver_st QUIC_TSERVER; typedef struct quic_tserver_args_st { OSSL_LIB_CTX *libctx; const char *propq; SSL_CTX *ctx; BIO *net_rbio, *net_wbio; OSSL_TIME (*now_cb)(void *arg); void *now_cb_arg; const unsigned char *alpn; size_t alpnlen; } QUIC_TSERVER_ARGS; QUIC_TSERVER *ossl_quic_tserver_new(const QUIC_TSERVER_ARGS *args, const char *certfile, const char *keyfile); void ossl_quic_tserver_free(QUIC_TSERVER *srv); /* Set mutator callbacks for test framework support */ int ossl_quic_tserver_set_plain_packet_mutator(QUIC_TSERVER *srv, ossl_mutate_packet_cb mutatecb, ossl_finish_mutate_cb finishmutatecb, void *mutatearg); int ossl_quic_tserver_set_handshake_mutator(QUIC_TSERVER *srv, ossl_statem_mutate_handshake_cb mutate_handshake_cb, ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb, void *mutatearg); /* Advances the state machine. */ int ossl_quic_tserver_tick(QUIC_TSERVER *srv); /* Returns 1 if we have a (non-terminated) client. */ int ossl_quic_tserver_is_connected(QUIC_TSERVER *srv); /* * Returns 1 if we have finished the TLS handshake */ int ossl_quic_tserver_is_handshake_confirmed(const QUIC_TSERVER *srv); /* Returns 1 if the server is in any terminating or terminated state */ int ossl_quic_tserver_is_term_any(const QUIC_TSERVER *srv); const QUIC_TERMINATE_CAUSE * ossl_quic_tserver_get_terminate_cause(const QUIC_TSERVER *srv); /* Returns 1 if the server is in a terminated state */ int ossl_quic_tserver_is_terminated(const QUIC_TSERVER *srv); /* * Attempts to read from stream 0. Writes the number of bytes read to * *bytes_read and returns 1 on success. If no bytes are available, 0 is written * to *bytes_read and 1 is returned (this is considered a success case). * * Returns 0 if connection is not currently active. If the receive part of * the stream has reached the end of stream condition, returns 0; call * ossl_quic_tserver_has_read_ended() to identify this condition. */ int ossl_quic_tserver_read(QUIC_TSERVER *srv, uint64_t stream_id, unsigned char *buf, size_t buf_len, size_t *bytes_read); /* * Returns 1 if the read part of the stream has ended normally. */ int ossl_quic_tserver_has_read_ended(QUIC_TSERVER *srv, uint64_t stream_id); /* * Attempts to write to the given stream. Writes the number of bytes consumed to * *bytes_written and returns 1 on success. If there is no space currently * available to write any bytes, 0 is written to *consumed and 1 is returned * (this is considered a success case). * * Note that unlike libssl public APIs, this API always works in a 'partial * write' mode. * * Returns 0 if connection is not currently active. */ int ossl_quic_tserver_write(QUIC_TSERVER *srv, uint64_t stream_id, const unsigned char *buf, size_t buf_len, size_t *bytes_written); /* * Signals normal end of the stream. */ int ossl_quic_tserver_conclude(QUIC_TSERVER *srv, uint64_t stream_id); /* * Create a server-initiated stream. The stream ID of the newly * created stream is written to *stream_id. */ int ossl_quic_tserver_stream_new(QUIC_TSERVER *srv, int is_uni, uint64_t *stream_id); BIO *ossl_quic_tserver_get0_rbio(QUIC_TSERVER *srv); SSL_CTX *ossl_quic_tserver_get0_ssl_ctx(QUIC_TSERVER *srv); /* * Returns 1 if the peer has sent a STOP_SENDING frame for a stream. * app_error_code is written if this returns 1. */ int ossl_quic_tserver_stream_has_peer_stop_sending(QUIC_TSERVER *srv, uint64_t stream_id, uint64_t *app_error_code); /* * Returns 1 if the peer has sent a RESET_STREAM frame for a stream. * app_error_code is written if this returns 1. */ int ossl_quic_tserver_stream_has_peer_reset_stream(QUIC_TSERVER *srv, uint64_t stream_id, uint64_t *app_error_code); /* * Replaces existing local connection ID in the underlying QUIC_CHANNEL. */ int ossl_quic_tserver_set_new_local_cid(QUIC_TSERVER *srv, const QUIC_CONN_ID *conn_id); /* * Returns the stream ID of the next incoming stream, or UINT64_MAX if there * currently is none. */ uint64_t ossl_quic_tserver_pop_incoming_stream(QUIC_TSERVER *srv); /* * Returns 1 if all data sent on the given stream_id has been acked by the peer. */ int ossl_quic_tserver_is_stream_totally_acked(QUIC_TSERVER *srv, uint64_t stream_id); /* Returns 1 if we are currently interested in reading data from the network */ int ossl_quic_tserver_get_net_read_desired(QUIC_TSERVER *srv); /* Returns 1 if we are currently interested in writing data to the network */ int ossl_quic_tserver_get_net_write_desired(QUIC_TSERVER *srv); /* Returns the next event deadline */ OSSL_TIME ossl_quic_tserver_get_deadline(QUIC_TSERVER *srv); /* * Shutdown the QUIC connection. Returns 1 if the connection is terminated and * 0 otherwise. */ int ossl_quic_tserver_shutdown(QUIC_TSERVER *srv, uint64_t app_error_code); /* Force generation of an ACK-eliciting packet. */ int ossl_quic_tserver_ping(QUIC_TSERVER *srv); /* Set tracing callback on channel. */ void ossl_quic_tserver_set_msg_callback(QUIC_TSERVER *srv, void (*f)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg), void *arg); /* * This is similar to ossl_quic_conn_get_channel; it should be used for test * instrumentation only and not to bypass QUIC_TSERVER for 'normal' operations. */ QUIC_CHANNEL *ossl_quic_tserver_get_channel(QUIC_TSERVER *srv); /* Send a TLS new session ticket */ int ossl_quic_tserver_new_ticket(QUIC_TSERVER *srv); /* * Set the max_early_data value to be sent in NewSessionTickets. Only the * values 0 and 0xffffffff are valid for use in QUIC. */ int ossl_quic_tserver_set_max_early_data(QUIC_TSERVER *srv, uint32_t max_early_data); /* Set the find session callback for getting a server PSK */ void ossl_quic_tserver_set_psk_find_session_cb(QUIC_TSERVER *srv, SSL_psk_find_session_cb_func cb); # endif #endif
./openssl/include/internal/thread_arch.h
/* * Copyright 2019-2023 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_INTERNAL_THREAD_ARCH_H # define OSSL_INTERNAL_THREAD_ARCH_H # include <openssl/configuration.h> # include <openssl/e_os2.h> # include "internal/time.h" # if defined(_WIN32) # include <windows.h> # endif # if defined(OPENSSL_THREADS) && defined(OPENSSL_SYS_UNIX) # define OPENSSL_THREADS_POSIX # elif defined(OPENSSL_THREADS) && defined(OPENSSL_SYS_VMS) # define OPENSSL_THREADS_POSIX # elif defined(OPENSSL_THREADS) && defined(OPENSSL_SYS_WINDOWS) && \ defined(_WIN32_WINNT) # if _WIN32_WINNT >= 0x0600 # define OPENSSL_THREADS_WINNT # elif _WIN32_WINNT >= 0x0501 # define OPENSSL_THREADS_WINNT # define OPENSSL_THREADS_WINNT_LEGACY # else # define OPENSSL_THREADS_NONE # endif # else # define OPENSSL_THREADS_NONE # endif # include <openssl/crypto.h> typedef void CRYPTO_MUTEX; typedef void CRYPTO_CONDVAR; CRYPTO_MUTEX *ossl_crypto_mutex_new(void); void ossl_crypto_mutex_lock(CRYPTO_MUTEX *mutex); int ossl_crypto_mutex_try_lock(CRYPTO_MUTEX *mutex); void ossl_crypto_mutex_unlock(CRYPTO_MUTEX *mutex); void ossl_crypto_mutex_free(CRYPTO_MUTEX **mutex); CRYPTO_CONDVAR *ossl_crypto_condvar_new(void); void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex); void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex, OSSL_TIME deadline); void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv); void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv); void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv); typedef uint32_t CRYPTO_THREAD_RETVAL; typedef CRYPTO_THREAD_RETVAL (*CRYPTO_THREAD_ROUTINE)(void *); typedef CRYPTO_THREAD_RETVAL (*CRYPTO_THREAD_ROUTINE_CB)(void *, void (**)(void *), void **); # define CRYPTO_THREAD_NO_STATE 0UL # define CRYPTO_THREAD_FINISHED (1UL << 0) # define CRYPTO_THREAD_JOIN_AWAIT (1UL << 1) # define CRYPTO_THREAD_JOINED (1UL << 2) # define CRYPTO_THREAD_GET_STATE(THREAD, FLAG) ((THREAD)->state & (FLAG)) # define CRYPTO_THREAD_GET_ERROR(THREAD, FLAG) (((THREAD)->state >> 16) & (FLAG)) typedef struct crypto_thread_st { uint32_t state; void *data; CRYPTO_THREAD_ROUTINE routine; CRYPTO_THREAD_RETVAL retval; void *handle; CRYPTO_MUTEX *lock; CRYPTO_MUTEX *statelock; CRYPTO_CONDVAR *condvar; unsigned long thread_id; int joinable; OSSL_LIB_CTX *ctx; } CRYPTO_THREAD; # if defined(OPENSSL_THREADS) # define CRYPTO_THREAD_UNSET_STATE(THREAD, FLAG) \ do { \ (THREAD)->state &= ~(FLAG); \ } while ((void)0, 0) # define CRYPTO_THREAD_SET_STATE(THREAD, FLAG) \ do { \ (THREAD)->state |= (FLAG); \ } while ((void)0, 0) # define CRYPTO_THREAD_SET_ERROR(THREAD, FLAG) \ do { \ (THREAD)->state |= ((FLAG) << 16); \ } while ((void)0, 0) # define CRYPTO_THREAD_UNSET_ERROR(THREAD, FLAG) \ do { \ (THREAD)->state &= ~((FLAG) << 16); \ } while ((void)0, 0) # else # define CRYPTO_THREAD_UNSET_STATE(THREAD, FLAG) # define CRYPTO_THREAD_SET_STATE(THREAD, FLAG) # define CRYPTO_THREAD_SET_ERROR(THREAD, FLAG) # define CRYPTO_THREAD_UNSET_ERROR(THREAD, FLAG) # endif /* defined(OPENSSL_THREADS) */ CRYPTO_THREAD * ossl_crypto_thread_native_start(CRYPTO_THREAD_ROUTINE routine, void *data, int joinable); int ossl_crypto_thread_native_spawn(CRYPTO_THREAD *thread); int ossl_crypto_thread_native_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval); int ossl_crypto_thread_native_perform_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval); int ossl_crypto_thread_native_exit(void); int ossl_crypto_thread_native_is_self(CRYPTO_THREAD *thread); int ossl_crypto_thread_native_clean(CRYPTO_THREAD *thread); #endif /* OSSL_INTERNAL_THREAD_ARCH_H */
./openssl/include/internal/priority_queue.h
/* * 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_INTERNAL_PRIORITY_QUEUE_H # define OSSL_INTERNAL_PRIORITY_QUEUE_H # pragma once # include <stdlib.h> # include <openssl/e_os2.h> # define PRIORITY_QUEUE_OF(type) OSSL_PRIORITY_QUEUE_ ## type # define DEFINE_PRIORITY_QUEUE_OF_INTERNAL(type, ctype) \ typedef struct ossl_priority_queue_st_ ## type PRIORITY_QUEUE_OF(type); \ static ossl_unused ossl_inline PRIORITY_QUEUE_OF(type) * \ ossl_pqueue_##type##_new(int (*compare)(const ctype *, const ctype *)) \ { \ return (PRIORITY_QUEUE_OF(type) *)ossl_pqueue_new( \ (int (*)(const void *, const void *))compare); \ } \ static ossl_unused ossl_inline void \ ossl_pqueue_##type##_free(PRIORITY_QUEUE_OF(type) *pq) \ { \ ossl_pqueue_free((OSSL_PQUEUE *)pq); \ } \ static ossl_unused ossl_inline void \ ossl_pqueue_##type##_pop_free(PRIORITY_QUEUE_OF(type) *pq, \ void (*freefunc)(ctype *)) \ { \ ossl_pqueue_pop_free((OSSL_PQUEUE *)pq, (void (*)(void *))freefunc);\ } \ static ossl_unused ossl_inline int \ ossl_pqueue_##type##_reserve(PRIORITY_QUEUE_OF(type) *pq, size_t n) \ { \ return ossl_pqueue_reserve((OSSL_PQUEUE *)pq, n); \ } \ static ossl_unused ossl_inline size_t \ ossl_pqueue_##type##_num(const PRIORITY_QUEUE_OF(type) *pq) \ { \ return ossl_pqueue_num((OSSL_PQUEUE *)pq); \ } \ static ossl_unused ossl_inline int \ ossl_pqueue_##type##_push(PRIORITY_QUEUE_OF(type) *pq, \ ctype *data, size_t *elem) \ { \ return ossl_pqueue_push((OSSL_PQUEUE *)pq, (void *)data, elem); \ } \ static ossl_unused ossl_inline ctype * \ ossl_pqueue_##type##_peek(const PRIORITY_QUEUE_OF(type) *pq) \ { \ return (type *)ossl_pqueue_peek((OSSL_PQUEUE *)pq); \ } \ static ossl_unused ossl_inline ctype * \ ossl_pqueue_##type##_pop(PRIORITY_QUEUE_OF(type) *pq) \ { \ return (type *)ossl_pqueue_pop((OSSL_PQUEUE *)pq); \ } \ static ossl_unused ossl_inline ctype * \ ossl_pqueue_##type##_remove(PRIORITY_QUEUE_OF(type) *pq, \ size_t elem) \ { \ return (type *)ossl_pqueue_remove((OSSL_PQUEUE *)pq, elem); \ } \ struct ossl_priority_queue_st_ ## type # define DEFINE_PRIORITY_QUEUE_OF(type) \ DEFINE_PRIORITY_QUEUE_OF_INTERNAL(type, type) typedef struct ossl_pqueue_st OSSL_PQUEUE; OSSL_PQUEUE *ossl_pqueue_new(int (*compare)(const void *, const void *)); void ossl_pqueue_free(OSSL_PQUEUE *pq); void ossl_pqueue_pop_free(OSSL_PQUEUE *pq, void (*freefunc)(void *)); int ossl_pqueue_reserve(OSSL_PQUEUE *pq, size_t n); size_t ossl_pqueue_num(const OSSL_PQUEUE *pq); int ossl_pqueue_push(OSSL_PQUEUE *pq, void *data, size_t *elem); void *ossl_pqueue_peek(const OSSL_PQUEUE *pq); void *ossl_pqueue_pop(OSSL_PQUEUE *pq); void *ossl_pqueue_remove(OSSL_PQUEUE *pq, size_t elem); #endif
./openssl/include/internal/quic_record_tx.h
/* * Copyright 2022-2023 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_predef.h" # include "internal/quic_record_util.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Record Layer - TX * ====================== */ typedef struct ossl_qtx_iovec_st { const unsigned char *buf; size_t buf_len; } OSSL_QTX_IOVEC; typedef struct ossl_qtx_st OSSL_QTX; typedef int (*ossl_mutate_packet_cb)(const QUIC_PKT_HDR *hdrin, const OSSL_QTX_IOVEC *iovecin, size_t numin, QUIC_PKT_HDR **hdrout, const OSSL_QTX_IOVEC **iovecout, size_t *numout, void *arg); typedef void (*ossl_finish_mutate_cb)(void *arg); 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); /* Set mutator callbacks for test framework support */ void ossl_qtx_set_mutator(OSSL_QTX *qtx, ossl_mutate_packet_cb mutatecb, ossl_finish_mutate_cb finishmutatecb, void *mutatearg); /* Setters for the msg_callback and the msg_callback_arg */ void ossl_qtx_set_msg_callback(OSSL_QTX *qtx, ossl_msg_cb msg_callback, SSL *msg_callback_ssl); void ossl_qtx_set_msg_callback_arg(OSSL_QTX *qtx, void *msg_callback_arg); /* * 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, except for the INITIAL * EL, as the INITIAL EL can need to be rekeyed if connection retry occurs. * Subsequent calls for non-INITIAL ELs fail. Calls made after a corresponding * call to ossl_qtx_discard_enc_level for a given EL also fail, including for * the INITIAL EL. The secret for a non-INITIAL 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); /* Returns 1 if the given encryption level is provisioned. */ int ossl_qtx_is_enc_level_provisioned(OSSL_QTX *qtx, uint32_t enc_level); /* * Given the value ciphertext_len representing an encrypted packet payload * length in bytes, determines how many plaintext bytes it will decrypt to. * Returns 0 if the specified EL is not provisioned or ciphertext_len is too * small. The result is written to *plaintext_len. */ int ossl_qtx_calculate_plaintext_payload_len(OSSL_QTX *qtx, uint32_t enc_level, size_t ciphertext_len, size_t *plaintext_len); /* * Given the value plaintext_len represented a plaintext packet payload length * in bytes, determines how many ciphertext bytes it will encrypt to. The value * output does not include packet headers. Returns 0 if the specified EL is not * provisioned. The result is written to *ciphertext_len. */ int ossl_qtx_calculate_ciphertext_payload_len(OSSL_QTX *qtx, uint32_t enc_level, size_t plaintext_len, size_t *ciphertext_len); uint32_t ossl_qrl_get_suite_cipher_tag_len(uint32_t suite_id); /* * Packet Transmission * ------------------- */ 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; }; /* * 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. * * Note that 1-RTT packets do not have a DCID Length field, therefore the DCID * length must be understood contextually. This function assumes the caller * knows what it is doing and will serialize a DCID of whatever length is given. * It is the caller's responsibility to ensure it uses a consistent DCID length * for communication with any given set of remote peers. * * The packet is queued regardless of whether it is able to be sent immediately. * This enables packets to be batched and sent at once on systems which support * system calls to send multiple datagrams in a single system call (see * BIO_sendmmsg). To flush queued datagrams to the network, see * ossl_qtx_flush_net(). * * 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(). * * Returns one of the following values: * * QTX_FLUSH_NET_RES_OK * Either no packets are currently queued for transmission, * or at least one packet was successfully submitted. * * QTX_FLUSH_NET_RES_TRANSIENT_FAIL * The underlying network write BIO indicated a transient error * (e.g. buffers full). * * QTX_FLUSH_NET_RES_PERMANENT_FAIL * Internal error (e.g. assertion or allocation error) * or the underlying network write BIO indicated a non-transient * error. */ #define QTX_FLUSH_NET_RES_OK 1 #define QTX_FLUSH_NET_RES_TRANSIENT_FAIL (-1) #define QTX_FLUSH_NET_RES_PERMANENT_FAIL (-2) int 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. Does not up-ref the BIO; the caller is responsible * for ensuring the lifetime of the BIO exceeds the lifetime of the QTX. */ void ossl_qtx_set_bio(OSSL_QTX *qtx, BIO *bio); /* Changes the MDPL. */ int ossl_qtx_set_mdpl(OSSL_QTX *qtx, size_t mdpl); /* Retrieves the current MDPL. */ size_t ossl_qtx_get_mdpl(OSSL_QTX *qtx); /* * 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); /* * Get the 1-RTT EL key epoch number for the QTX. This is intended for * diagnostic purposes. Returns 0 if 1-RTT EL is not provisioned yet. */ uint64_t ossl_qtx_get_key_epoch(OSSL_QTX *qtx); # endif #endif
./openssl/include/internal/sockets.h
/* * Copyright 1995-2023 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_INTERNAL_SOCKETS_H # define OSSL_INTERNAL_SOCKETS_H # pragma once # include <openssl/opensslconf.h> # if defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI) # define NO_SYS_PARAM_H # endif # ifdef WIN32 # define NO_SYS_UN_H # endif # ifdef OPENSSL_SYS_VMS # define NO_SYS_PARAM_H # define NO_SYS_UN_H # endif # ifdef OPENSSL_NO_SOCK # elif defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) # if defined(__DJGPP__) # define WATT32 # define WATT32_NO_OLDIES # include <sys/socket.h> # include <sys/un.h> # include <tcp.h> # include <netdb.h> # include <arpa/inet.h> # include <netinet/tcp.h> # elif defined(_WIN32_WCE) && _WIN32_WCE<410 # define getservbyname _masked_declaration_getservbyname # endif # if !defined(IPPROTO_IP) /* winsock[2].h was included already? */ # include <winsock.h> # endif # ifdef getservbyname /* this is used to be wcecompat/include/winsock_extras.h */ # undef getservbyname struct servent *PASCAL getservbyname(const char *, const char *); # endif # ifdef _WIN64 /* * Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because * the value constitutes an index in per-process table of limited size * and not a real pointer. And we also depend on fact that all processors * Windows run on happen to be two's-complement, which allows to * interchange INVALID_SOCKET and -1. */ # define socket(d,t,p) ((int)socket(d,t,p)) # define accept(s,f,l) ((int)accept(s,f,l)) # endif /* Windows have other names for shutdown() reasons */ # ifndef SHUT_RD # define SHUT_RD SD_RECEIVE # endif # ifndef SHUT_WR # define SHUT_WR SD_SEND # endif # ifndef SHUT_RDWR # define SHUT_RDWR SD_BOTH # endif # else # if defined(__APPLE__) /* * This must be defined before including <netinet/in6.h> to get * IPV6_RECVPKTINFO */ # define __APPLE_USE_RFC_3542 # endif # ifndef NO_SYS_PARAM_H # include <sys/param.h> # endif # ifdef OPENSSL_SYS_VXWORKS # include <time.h> # endif # include <netdb.h> # if defined(OPENSSL_SYS_VMS) typedef size_t socklen_t; /* Currently appears to be missing on VMS */ # endif # if defined(OPENSSL_SYS_VMS_NODECC) # include <socket.h> # include <in.h> # include <inet.h> # else # include <sys/socket.h> # if !defined(NO_SYS_UN_H) && defined(AF_UNIX) && !defined(OPENSSL_NO_UNIX_SOCK) # include <sys/un.h> # ifndef UNIX_PATH_MAX # define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)NULL)->sun_path) # endif # endif # ifdef FILIO_H # include <sys/filio.h> /* FIONBIO in some SVR4, e.g. unixware, solaris */ # endif # include <netinet/in.h> # include <arpa/inet.h> # include <netinet/tcp.h> # endif # ifdef OPENSSL_SYS_AIX # include <sys/select.h> # endif # ifdef OPENSSL_SYS_UNIX # ifndef OPENSSL_SYS_TANDEM # include <poll.h> # endif # include <errno.h> # endif # ifndef VMS # include <sys/ioctl.h> # else # if !defined(TCPIP_TYPE_SOCKETSHR) && defined(__VMS_VER) && (__VMS_VER > 70000000) /* ioctl is only in VMS > 7.0 and when socketshr is not used */ # include <sys/ioctl.h> # endif # include <unixio.h> # if defined(TCPIP_TYPE_SOCKETSHR) # include <socketshr.h> # endif # endif # ifndef INVALID_SOCKET # define INVALID_SOCKET (-1) # endif # endif /* * Some IPv6 implementations are broken, you can disable them in known * bad versions. */ # if !defined(OPENSSL_USE_IPV6) # if defined(AF_INET6) # define OPENSSL_USE_IPV6 1 # else # define OPENSSL_USE_IPV6 0 # endif # endif /* * Some platforms define AF_UNIX, but don't support it */ # if !defined(OPENSSL_NO_UNIX_SOCK) # if !defined(AF_UNIX) || defined(NO_SYS_UN_H) # define OPENSSL_NO_UNIX_SOCK # endif # endif # define get_last_socket_error() errno # define clear_socket_error() errno=0 # define get_last_socket_error_is_eintr() (get_last_socket_error() == EINTR) # if defined(OPENSSL_SYS_WINDOWS) # undef get_last_socket_error # undef clear_socket_error # undef get_last_socket_error_is_eintr # define get_last_socket_error() WSAGetLastError() # define clear_socket_error() WSASetLastError(0) # define get_last_socket_error_is_eintr() (get_last_socket_error() == WSAEINTR) # define readsocket(s,b,n) recv((s),(b),(n),0) # define writesocket(s,b,n) send((s),(b),(n),0) # elif defined(__DJGPP__) # define closesocket(s) close_s(s) # define readsocket(s,b,n) read_s(s,b,n) # define writesocket(s,b,n) send(s,b,n,0) # elif defined(OPENSSL_SYS_VMS) # define ioctlsocket(a,b,c) ioctl(a,b,c) # define closesocket(s) close(s) # define readsocket(s,b,n) recv((s),(b),(n),0) # define writesocket(s,b,n) send((s),(b),(n),0) # elif defined(OPENSSL_SYS_VXWORKS) # define ioctlsocket(a,b,c) ioctl((a),(b),(int)(c)) # define closesocket(s) close(s) # define readsocket(s,b,n) read((s),(b),(n)) # define writesocket(s,b,n) write((s),(char *)(b),(n)) # elif defined(OPENSSL_SYS_TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_read, floss_write)> # define readsocket(s,b,n) floss_read((s),(b),(n)) # define writesocket(s,b,n) floss_write((s),(b),(n)) # else # define readsocket(s,b,n) read((s),(b),(n)) # define writesocket(s,b,n) write((s),(b),(n)) # endif # define ioctlsocket(a,b,c) ioctl(a,b,c) # define closesocket(s) close(s) # else # define ioctlsocket(a,b,c) ioctl(a,b,c) # define closesocket(s) close(s) # define readsocket(s,b,n) read((s),(b),(n)) # define writesocket(s,b,n) write((s),(b),(n)) # endif /* also in apps/include/apps.h */ # if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WINCE) # define openssl_fdset(a, b) FD_SET((unsigned int)(a), b) # else # define openssl_fdset(a, b) FD_SET(a, b) # endif #endif
./openssl/include/internal/quic_rx_depack.h
/* * Copyright 2022-2023 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_RX_DEPACK_H # define OSSL_QUIC_RX_DEPACK_H # include "internal/quic_channel.h" # ifndef OPENSSL_NO_QUIC int ossl_quic_handle_frames(QUIC_CHANNEL *qc, OSSL_QRX_PKT *qpacket); # endif #endif
./openssl/include/crypto/cmperr.h
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 2020-2023 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_CRYPTO_CMPERR_H # define OSSL_CRYPTO_CMPERR_H # pragma once # include <openssl/opensslconf.h> # include <openssl/symhacks.h> # ifdef __cplusplus extern "C" { # endif # ifndef OPENSSL_NO_CMP int ossl_err_load_CMP_strings(void); # endif # ifdef __cplusplus } # endif #endif
./openssl/include/crypto/cmll_platform.h
/* * Copyright 2019-2021 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_CMLL_PLATFORM_H # define OSSL_CMLL_PLATFORM_H # pragma once # if defined(CMLL_ASM) && (defined(__sparc) || defined(__sparc__)) /* Fujitsu SPARC64 X support */ # include "crypto/sparc_arch.h" # ifndef OPENSSL_NO_CAMELLIA # define SPARC_CMLL_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_CAMELLIA) # include <openssl/camellia.h> void cmll_t4_set_key(const unsigned char *key, int bits, CAMELLIA_KEY *ks); void cmll_t4_encrypt(const unsigned char *in, unsigned char *out, const CAMELLIA_KEY *key); void cmll_t4_decrypt(const unsigned char *in, unsigned char *out, const CAMELLIA_KEY *key); void cmll128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const CAMELLIA_KEY *key, unsigned char *ivec, int /*unused*/); void cmll128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out, size_t len, const CAMELLIA_KEY *key, unsigned char *ivec, int /*unused*/); void cmll256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const CAMELLIA_KEY *key, unsigned char *ivec, int /*unused*/); void cmll256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out, size_t len, const CAMELLIA_KEY *key, unsigned char *ivec, int /*unused*/); void cmll128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const CAMELLIA_KEY *key, unsigned char *ivec); void cmll256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out, size_t blocks, const CAMELLIA_KEY *key, unsigned char *ivec); # endif /* OPENSSL_NO_CAMELLIA */ # endif /* CMLL_ASM && sparc */ #endif /* OSSL_CRYPTO_CIPHERMODE_PLATFORM_H */
./openssl/include/crypto/sparse_array.h
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. 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_CRYPTO_SPARSE_ARRAY_H # define OSSL_CRYPTO_SPARSE_ARRAY_H # pragma once # include <openssl/e_os2.h> # ifdef __cplusplus extern "C" { # endif # define SPARSE_ARRAY_OF(type) struct sparse_array_st_ ## type # define DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, ctype) \ SPARSE_ARRAY_OF(type); \ static ossl_unused ossl_inline SPARSE_ARRAY_OF(type) * \ ossl_sa_##type##_new(void) \ { \ return (SPARSE_ARRAY_OF(type) *)ossl_sa_new(); \ } \ static ossl_unused ossl_inline void \ ossl_sa_##type##_free(SPARSE_ARRAY_OF(type) *sa) \ { \ ossl_sa_free((OPENSSL_SA *)sa); \ } \ static ossl_unused ossl_inline void \ ossl_sa_##type##_free_leaves(SPARSE_ARRAY_OF(type) *sa) \ { \ ossl_sa_free_leaves((OPENSSL_SA *)sa); \ } \ static ossl_unused ossl_inline size_t \ ossl_sa_##type##_num(const SPARSE_ARRAY_OF(type) *sa) \ { \ return ossl_sa_num((OPENSSL_SA *)sa); \ } \ static ossl_unused ossl_inline void \ ossl_sa_##type##_doall(const SPARSE_ARRAY_OF(type) *sa, \ void (*leaf)(ossl_uintmax_t, type *)) \ { \ ossl_sa_doall((OPENSSL_SA *)sa, \ (void (*)(ossl_uintmax_t, void *))leaf); \ } \ static ossl_unused ossl_inline void \ ossl_sa_##type##_doall_arg(const SPARSE_ARRAY_OF(type) *sa, \ void (*leaf)(ossl_uintmax_t, type *, void *), \ void *arg) \ { \ ossl_sa_doall_arg((OPENSSL_SA *)sa, \ (void (*)(ossl_uintmax_t, void *, void *))leaf, arg); \ } \ static ossl_unused ossl_inline ctype \ *ossl_sa_##type##_get(const SPARSE_ARRAY_OF(type) *sa, ossl_uintmax_t n) \ { \ return (type *)ossl_sa_get((OPENSSL_SA *)sa, n); \ } \ static ossl_unused ossl_inline int \ ossl_sa_##type##_set(SPARSE_ARRAY_OF(type) *sa, \ ossl_uintmax_t n, ctype *val) \ { \ return ossl_sa_set((OPENSSL_SA *)sa, n, (void *)val); \ } \ SPARSE_ARRAY_OF(type) # define DEFINE_SPARSE_ARRAY_OF(type) \ DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, type) # define DEFINE_SPARSE_ARRAY_OF_CONST(type) \ DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, const type) typedef struct sparse_array_st OPENSSL_SA; OPENSSL_SA *ossl_sa_new(void); void ossl_sa_free(OPENSSL_SA *sa); void ossl_sa_free_leaves(OPENSSL_SA *sa); size_t ossl_sa_num(const OPENSSL_SA *sa); void ossl_sa_doall(const OPENSSL_SA *sa, void (*leaf)(ossl_uintmax_t, void *)); void ossl_sa_doall_arg(const OPENSSL_SA *sa, void (*leaf)(ossl_uintmax_t, void *, void *), void *); void *ossl_sa_get(const OPENSSL_SA *sa, ossl_uintmax_t n); int ossl_sa_set(OPENSSL_SA *sa, ossl_uintmax_t n, void *val); # ifdef __cplusplus } # endif #endif
./openssl/include/crypto/sparc_arch.h
/* * Copyright 2012-2021 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_CRYPTO_SPARC_ARCH_H # define OSSL_CRYPTO_SPARC_ARCH_H # define SPARCV9_TICK_PRIVILEGED (1<<0) # define SPARCV9_PREFER_FPU (1<<1) # define SPARCV9_VIS1 (1<<2) # define SPARCV9_VIS2 (1<<3)/* reserved */ # define SPARCV9_FMADD (1<<4) # define SPARCV9_BLK (1<<5)/* VIS1 block copy */ # define SPARCV9_VIS3 (1<<6) # define SPARCV9_RANDOM (1<<7) # define SPARCV9_64BIT_STACK (1<<8) # define SPARCV9_FJAESX (1<<9)/* Fujitsu SPARC64 X AES */ # define SPARCV9_FJDESX (1<<10)/* Fujitsu SPARC64 X DES, reserved */ # define SPARCV9_FJHPCACE (1<<11)/* Fujitsu HPC-ACE, reserved */ # define SPARCV9_IMA (1<<13)/* reserved */ # define SPARCV9_VIS4 (1<<14)/* reserved */ /* * OPENSSL_sparcv9cap_P[1] is copy of Compatibility Feature Register, * %asr26, SPARC-T4 and later. There is no SPARCV9_CFR bit in * OPENSSL_sparcv9cap_P[0], as %cfr copy is sufficient... */ # define CFR_AES 0x00000001/* Supports AES opcodes */ # define CFR_DES 0x00000002/* Supports DES opcodes */ # define CFR_KASUMI 0x00000004/* Supports KASUMI opcodes */ # define CFR_CAMELLIA 0x00000008/* Supports CAMELLIA opcodes */ # define CFR_MD5 0x00000010/* Supports MD5 opcodes */ # define CFR_SHA1 0x00000020/* Supports SHA1 opcodes */ # define CFR_SHA256 0x00000040/* Supports SHA256 opcodes */ # define CFR_SHA512 0x00000080/* Supports SHA512 opcodes */ # define CFR_MPMUL 0x00000100/* Supports MPMUL opcodes */ # define CFR_MONTMUL 0x00000200/* Supports MONTMUL opcodes */ # define CFR_MONTSQR 0x00000400/* Supports MONTSQR opcodes */ # define CFR_CRC32C 0x00000800/* Supports CRC32C opcodes */ # define CFR_XMPMUL 0x00001000/* Supports XMPMUL opcodes */ # define CFR_XMONTMUL 0x00002000/* Supports XMONTMUL opcodes */ # define CFR_XMONTSQR 0x00004000/* Supports XMONTSQR opcodes */ # if defined(OPENSSL_PIC) && !defined(__PIC__) # define __PIC__ # endif # if defined(__SUNPRO_C) && defined(__sparcv9) && !defined(__arch64__) # define __arch64__ # endif # define SPARC_PIC_THUNK(reg) \ .align 32; \ .Lpic_thunk: \ jmp %o7 + 8; \ add %o7, reg, reg; # define SPARC_PIC_THUNK_CALL(reg) \ sethi %hi(_GLOBAL_OFFSET_TABLE_-4), reg; \ call .Lpic_thunk; \ or reg, %lo(_GLOBAL_OFFSET_TABLE_+4), reg; # if 1 # define SPARC_SETUP_GOT_REG(reg) SPARC_PIC_THUNK_CALL(reg) # else # define SPARC_SETUP_GOT_REG(reg) \ sethi %hi(_GLOBAL_OFFSET_TABLE_-4), reg; \ call .+8; \ or reg,%lo(_GLOBAL_OFFSET_TABLE_+4), reg; \ add %o7, reg, reg # endif # if defined(__arch64__) # define SPARC_LOAD_ADDRESS(SYM, reg) \ setx SYM, %o7, reg; # define LDPTR ldx # define SIZE_T_CC %xcc # define STACK_FRAME 192 # define STACK_BIAS 2047 # define STACK_7thARG (STACK_BIAS+176) # else # define SPARC_LOAD_ADDRESS(SYM, reg) \ set SYM, reg; # define LDPTR ld # define SIZE_T_CC %icc # define STACK_FRAME 112 # define STACK_BIAS 0 # define STACK_7thARG 92 # define SPARC_LOAD_ADDRESS_LEAF(SYM,reg,tmp) SPARC_LOAD_ADDRESS(SYM,reg) # endif # ifdef __PIC__ # undef SPARC_LOAD_ADDRESS # undef SPARC_LOAD_ADDRESS_LEAF # define SPARC_LOAD_ADDRESS(SYM, reg) \ SPARC_SETUP_GOT_REG(reg); \ sethi %hi(SYM), %o7; \ or %o7, %lo(SYM), %o7; \ LDPTR [reg + %o7], reg; # endif # ifndef SPARC_LOAD_ADDRESS_LEAF # define SPARC_LOAD_ADDRESS_LEAF(SYM, reg, tmp) \ mov %o7, tmp; \ SPARC_LOAD_ADDRESS(SYM, reg) \ mov tmp, %o7; # endif # ifndef __ASSEMBLER__ extern unsigned int OPENSSL_sparcv9cap_P[2]; # endif #endif /* OSSL_CRYPTO_SPARC_ARCH_H */
./openssl/include/crypto/ess.h
/* * Copyright 2019-2021 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_CRYPTO_ESS_H # define OSSL_CRYPTO_ESS_H # pragma once /*- * IssuerSerial ::= SEQUENCE { * issuer GeneralNames, * serialNumber CertificateSerialNumber * } */ struct ESS_issuer_serial { STACK_OF(GENERAL_NAME) *issuer; ASN1_INTEGER *serial; }; /*- * ESSCertID ::= SEQUENCE { * certHash Hash, * issuerSerial IssuerSerial OPTIONAL * } */ struct ESS_cert_id { ASN1_OCTET_STRING *hash; /* Always SHA-1 digest. */ ESS_ISSUER_SERIAL *issuer_serial; }; /*- * SigningCertificate ::= SEQUENCE { * certs SEQUENCE OF ESSCertID, * policies SEQUENCE OF PolicyInformation OPTIONAL * } */ struct ESS_signing_cert { STACK_OF(ESS_CERT_ID) *cert_ids; STACK_OF(POLICYINFO) *policy_info; }; /*- * ESSCertIDv2 ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier DEFAULT id-sha256, * certHash Hash, * issuerSerial IssuerSerial OPTIONAL * } */ struct ESS_cert_id_v2_st { X509_ALGOR *hash_alg; /* Default: SHA-256 */ ASN1_OCTET_STRING *hash; ESS_ISSUER_SERIAL *issuer_serial; }; /*- * SigningCertificateV2 ::= SEQUENCE { * certs SEQUENCE OF ESSCertIDv2, * policies SEQUENCE OF PolicyInformation OPTIONAL * } */ struct ESS_signing_cert_v2_st { STACK_OF(ESS_CERT_ID_V2) *cert_ids; STACK_OF(POLICYINFO) *policy_info; }; #endif /* OSSL_CRYPTO_ESS_H */
./openssl/include/crypto/riscv_arch.h
/* * Copyright 2022-2023 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_CRYPTO_RISCV_ARCH_H # define OSSL_CRYPTO_RISCV_ARCH_H # include <ctype.h> # include <stdint.h> # define RISCV_DEFINE_CAP(NAME, INDEX, BIT_INDEX) +1 extern uint32_t OPENSSL_riscvcap_P[ (( # include "riscv_arch.def" ) + sizeof(uint32_t) - 1) / sizeof(uint32_t) ]; # ifdef OPENSSL_RISCVCAP_IMPL # define RISCV_DEFINE_CAP(NAME, INDEX, BIT_INDEX) +1 uint32_t OPENSSL_riscvcap_P[ (( # include "riscv_arch.def" ) + sizeof(uint32_t) - 1) / sizeof(uint32_t) ]; # endif # define RISCV_DEFINE_CAP(NAME, INDEX, BIT_INDEX) \ static inline int RISCV_HAS_##NAME(void) \ { \ return (OPENSSL_riscvcap_P[INDEX] & (1 << BIT_INDEX)) != 0; \ } # include "riscv_arch.def" struct RISCV_capability_s { const char *name; size_t index; size_t bit_offset; }; # define RISCV_DEFINE_CAP(NAME, INDEX, BIT_INDEX) +1 extern const struct RISCV_capability_s RISCV_capabilities[ # include "riscv_arch.def" ]; # ifdef OPENSSL_RISCVCAP_IMPL # define RISCV_DEFINE_CAP(NAME, INDEX, BIT_INDEX) \ { #NAME, INDEX, BIT_INDEX }, const struct RISCV_capability_s RISCV_capabilities[] = { # include "riscv_arch.def" }; # endif # define RISCV_DEFINE_CAP(NAME, INDEX, BIT_INDEX) +1 static const size_t kRISCVNumCaps = # include "riscv_arch.def" ; /* Extension combination tests. */ #define RISCV_HAS_ZBB_AND_ZBC() (RISCV_HAS_ZBB() && RISCV_HAS_ZBC()) #define RISCV_HAS_ZBKB_AND_ZKND_AND_ZKNE() (RISCV_HAS_ZBKB() && RISCV_HAS_ZKND() && RISCV_HAS_ZKNE()) #define RISCV_HAS_ZKND_AND_ZKNE() (RISCV_HAS_ZKND() && RISCV_HAS_ZKNE()) /* * The ZVBB is the superset of ZVKB extension. We use macro here to replace the * `RISCV_HAS_ZVKB()` with `RISCV_HAS_ZVBB() || RISCV_HAS_ZVKB()`. */ #define RISCV_HAS_ZVKB() (RISCV_HAS_ZVBB() || RISCV_HAS_ZVKB()) #define RISCV_HAS_ZVKB_AND_ZVKNHA() (RISCV_HAS_ZVKB() && RISCV_HAS_ZVKNHA()) #define RISCV_HAS_ZVKB_AND_ZVKNHB() (RISCV_HAS_ZVKB() && RISCV_HAS_ZVKNHB()) #define RISCV_HAS_ZVKB_AND_ZVKSED() (RISCV_HAS_ZVKB() && RISCV_HAS_ZVKSED()) #define RISCV_HAS_ZVKB_AND_ZVKSH() (RISCV_HAS_ZVKB() && RISCV_HAS_ZVKSH()) /* * Get the size of a vector register in bits (VLEN). * If RISCV_HAS_V() is false, then this returns 0. */ size_t riscv_vlen(void); #endif
./openssl/include/crypto/randerr.h
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 2020-2023 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_CRYPTO_RANDERR_H # define OSSL_CRYPTO_RANDERR_H # pragma once # include <openssl/opensslconf.h> # include <openssl/symhacks.h> # ifdef __cplusplus extern "C" { # endif int ossl_err_load_RAND_strings(void); # ifdef __cplusplus } # endif #endif
./openssl/include/crypto/poly1305.h
/* * Copyright 2015-2021 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_CRYPTO_POLY1305_H # define OSSL_CRYPTO_POLY1305_H # pragma once #include <stddef.h> #define POLY1305_BLOCK_SIZE 16 #define POLY1305_DIGEST_SIZE 16 #define POLY1305_KEY_SIZE 32 typedef struct poly1305_context POLY1305; typedef void (*poly1305_blocks_f) (void *ctx, const unsigned char *inp, size_t len, unsigned int padbit); typedef void (*poly1305_emit_f) (void *ctx, unsigned char mac[16], const unsigned int nonce[4]); struct poly1305_context { double opaque[24]; /* large enough to hold internal state, declared * 'double' to ensure at least 64-bit invariant * alignment across all platforms and * configurations */ unsigned int nonce[4]; unsigned char data[POLY1305_BLOCK_SIZE]; size_t num; struct { poly1305_blocks_f blocks; poly1305_emit_f emit; } func; }; size_t Poly1305_ctx_size(void); void Poly1305_Init(POLY1305 *ctx, const unsigned char key[32]); void Poly1305_Update(POLY1305 *ctx, const unsigned char *inp, size_t len); void Poly1305_Final(POLY1305 *ctx, unsigned char mac[16]); #endif /* OSSL_CRYPTO_POLY1305_H */
./openssl/include/crypto/storeerr.h
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 2020-2021 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_CRYPTO_STOREERR_H # define OSSL_CRYPTO_STOREERR_H # pragma once # include <openssl/opensslconf.h> # include <openssl/symhacks.h> # ifdef __cplusplus extern "C" { # endif int ossl_err_load_OSSL_STORE_strings(void); # ifdef __cplusplus } # endif #endif
./openssl/include/crypto/objectserr.h
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 2020-2021 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_CRYPTO_OBJECTSERR_H # define OSSL_CRYPTO_OBJECTSERR_H # pragma once # include <openssl/opensslconf.h> # include <openssl/symhacks.h> # ifdef __cplusplus extern "C" { # endif int ossl_err_load_OBJ_strings(void); # ifdef __cplusplus } # endif #endif
./openssl/include/crypto/cmserr.h
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 2020-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_CRYPTO_CMSERR_H # define OSSL_CRYPTO_CMSERR_H # pragma once # include <openssl/opensslconf.h> # include <openssl/symhacks.h> # ifdef __cplusplus extern "C" { # endif # ifndef OPENSSL_NO_CMS int ossl_err_load_CMS_strings(void); # endif # ifdef __cplusplus } # endif #endif
./openssl/include/crypto/ec.h
/* * Copyright 2018-2021 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 */ /* Internal EC functions for other submodules: not for application use */ #ifndef OSSL_CRYPTO_EC_H # define OSSL_CRYPTO_EC_H # pragma once # include <openssl/opensslconf.h> # include <openssl/evp.h> int ossl_ec_curve_name2nid(const char *name); const char *ossl_ec_curve_nid2nist_int(int nid); int ossl_ec_curve_nist2nid_int(const char *name); int evp_pkey_ctx_set_ec_param_enc_prov(EVP_PKEY_CTX *ctx, int param_enc); # ifndef OPENSSL_NO_EC # include <openssl/core.h> # include <openssl/ec.h> # include "crypto/types.h" /*- * Computes the multiplicative inverse of x in the range * [1,EC_GROUP::order), where EC_GROUP::order is the cardinality of the * subgroup generated by the generator G: * * res := x^(-1) (mod EC_GROUP::order). * * This function expects the following two conditions to hold: * - the EC_GROUP order is prime, and * - x is included in the range [1, EC_GROUP::order). * * This function returns 1 on success, 0 on error. * * If the EC_GROUP order is even, this function explicitly returns 0 as * an error. * In case any of the two conditions stated above is not satisfied, * the correctness of its output is not guaranteed, even if the return * value could still be 1 (as primality testing and a conditional modular * reduction round on the input can be omitted by the underlying * implementations for better SCA properties on regular input values). */ __owur int ossl_ec_group_do_inverse_ord(const EC_GROUP *group, BIGNUM *res, const BIGNUM *x, BN_CTX *ctx); /*- * ECDH Key Derivation Function as defined in ANSI X9.63 */ int ossl_ecdh_kdf_X9_63(unsigned char *out, size_t outlen, const unsigned char *Z, size_t Zlen, const unsigned char *sinfo, size_t sinfolen, const EVP_MD *md, OSSL_LIB_CTX *libctx, const char *propq); int ossl_ec_key_public_check(const EC_KEY *eckey, BN_CTX *ctx); int ossl_ec_key_public_check_quick(const EC_KEY *eckey, BN_CTX *ctx); int ossl_ec_key_private_check(const EC_KEY *eckey); int ossl_ec_key_pairwise_check(const EC_KEY *eckey, BN_CTX *ctx); OSSL_LIB_CTX *ossl_ec_key_get_libctx(const EC_KEY *eckey); const char *ossl_ec_key_get0_propq(const EC_KEY *eckey); void ossl_ec_key_set0_libctx(EC_KEY *key, OSSL_LIB_CTX *libctx); /* Backend support */ int ossl_ec_group_todata(const EC_GROUP *group, OSSL_PARAM_BLD *tmpl, OSSL_PARAM params[], OSSL_LIB_CTX *libctx, const char *propq, BN_CTX *bnctx, unsigned char **genbuf); int ossl_ec_group_fromdata(EC_KEY *ec, const OSSL_PARAM params[]); int ossl_ec_group_set_params(EC_GROUP *group, const OSSL_PARAM params[]); int ossl_ec_key_fromdata(EC_KEY *ecx, const OSSL_PARAM params[], int include_private); int ossl_ec_key_otherparams_fromdata(EC_KEY *ec, const OSSL_PARAM params[]); int ossl_ec_key_is_foreign(const EC_KEY *ec); EC_KEY *ossl_ec_key_dup(const EC_KEY *key, int selection); int ossl_x509_algor_is_sm2(const X509_ALGOR *palg); EC_KEY *ossl_ec_key_param_from_x509_algor(const X509_ALGOR *palg, OSSL_LIB_CTX *libctx, const char *propq); EC_KEY *ossl_ec_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq); int ossl_ec_set_ecdh_cofactor_mode(EC_KEY *ec, int mode); int ossl_ec_encoding_name2id(const char *name); int ossl_ec_encoding_param2id(const OSSL_PARAM *p, int *id); int ossl_ec_pt_format_name2id(const char *name); int ossl_ec_pt_format_param2id(const OSSL_PARAM *p, int *id); char *ossl_ec_pt_format_id2name(int id); char *ossl_ec_check_group_type_id2name(int flags); int ossl_ec_set_check_group_type_from_name(EC_KEY *ec, const char *name); int ossl_ec_generate_key_dhkem(EC_KEY *eckey, const unsigned char *ikm, size_t ikmlen); int ossl_ecdsa_deterministic_sign(const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, EC_KEY *eckey, unsigned int nonce_type, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq); # endif /* OPENSSL_NO_EC */ #endif
./openssl/include/crypto/context.h
/* * Copyright 2022-2023 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 <openssl/core.h> void *ossl_provider_store_new(OSSL_LIB_CTX *); void *ossl_property_string_data_new(OSSL_LIB_CTX *); void *ossl_stored_namemap_new(OSSL_LIB_CTX *); void *ossl_property_defns_new(OSSL_LIB_CTX *); void *ossl_ctx_global_properties_new(OSSL_LIB_CTX *); void *ossl_rand_ctx_new(OSSL_LIB_CTX *); void *ossl_prov_conf_ctx_new(OSSL_LIB_CTX *); void *ossl_bio_core_globals_new(OSSL_LIB_CTX *); void *ossl_child_prov_ctx_new(OSSL_LIB_CTX *); void *ossl_prov_drbg_nonce_ctx_new(OSSL_LIB_CTX *); void *ossl_self_test_set_callback_new(OSSL_LIB_CTX *); void *ossl_rand_crng_ctx_new(OSSL_LIB_CTX *); int ossl_thread_register_fips(OSSL_LIB_CTX *); void *ossl_thread_event_ctx_new(OSSL_LIB_CTX *); void *ossl_fips_prov_ossl_ctx_new(OSSL_LIB_CTX *); #if defined(OPENSSL_THREADS) void *ossl_threads_ctx_new(OSSL_LIB_CTX *); #endif void ossl_provider_store_free(void *); void ossl_property_string_data_free(void *); void ossl_stored_namemap_free(void *); void ossl_property_defns_free(void *); void ossl_ctx_global_properties_free(void *); void ossl_rand_ctx_free(void *); void ossl_prov_conf_ctx_free(void *); void ossl_bio_core_globals_free(void *); void ossl_child_prov_ctx_free(void *); void ossl_prov_drbg_nonce_ctx_free(void *); void ossl_self_test_set_callback_free(void *); void ossl_rand_crng_ctx_free(void *); void ossl_thread_event_ctx_free(void *); void ossl_fips_prov_ossl_ctx_free(void *); void ossl_release_default_drbg_ctx(void); #if defined(OPENSSL_THREADS) void ossl_threads_ctx_free(void *); #endif
./openssl/include/crypto/crmferr.h
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 2020-2021 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_CRYPTO_CRMFERR_H # define OSSL_CRYPTO_CRMFERR_H # pragma once # include <openssl/opensslconf.h> # include <openssl/symhacks.h> # ifdef __cplusplus extern "C" { # endif # ifndef OPENSSL_NO_CRMF int ossl_err_load_CRMF_strings(void); # endif # ifdef __cplusplus } # endif #endif
./openssl/include/crypto/types.h
/* * Copyright 2020-2023 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 */ /* When removal is simulated, we still need the type internally */ #ifndef OSSL_CRYPTO_TYPES_H # define OSSL_CRYPTO_TYPES_H # pragma once # ifdef OPENSSL_NO_DEPRECATED_3_0 typedef struct rsa_st RSA; typedef struct rsa_meth_st RSA_METHOD; # ifndef OPENSSL_NO_EC typedef struct ec_key_st EC_KEY; typedef struct ec_key_method_st EC_KEY_METHOD; # endif # ifndef OPENSSL_NO_DSA typedef struct dsa_st DSA; # endif # endif # ifndef OPENSSL_NO_EC typedef struct ecx_key_st ECX_KEY; # endif #endif
./openssl/include/crypto/decoder.h
/* * Copyright 2020-2023 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_CRYPTO_DECODER_H # define OSSL_CRYPTO_DECODER_H # pragma once # include <openssl/decoder.h> /* * These are specially made for the 'file:' provider-native loader, which * uses this to install a DER to anything decoder, which doesn't do much * except read a DER blob and pass it on as a provider object abstraction * (provider-object(7)). */ void *ossl_decoder_from_algorithm(int id, const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov); OSSL_DECODER_INSTANCE * ossl_decoder_instance_new(OSSL_DECODER *decoder, void *decoderctx); void ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst); OSSL_DECODER_INSTANCE *ossl_decoder_instance_dup(const OSSL_DECODER_INSTANCE *src); int ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx, OSSL_DECODER_INSTANCE *di); int ossl_decoder_get_number(const OSSL_DECODER *encoder); int ossl_decoder_store_cache_flush(OSSL_LIB_CTX *libctx); int ossl_decoder_store_remove_all_provided(const OSSL_PROVIDER *prov); void *ossl_decoder_cache_new(OSSL_LIB_CTX *ctx); void ossl_decoder_cache_free(void *vcache); int ossl_decoder_cache_flush(OSSL_LIB_CTX *libctx); #endif
./openssl/include/crypto/security_bits.h
/* * Copyright 2019-2021 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_SECURITY_BITS_H # define OSSL_SECURITY_BITS_H # pragma once uint16_t ossl_ifc_ffc_compute_security_bits(int n); #endif