file_path
stringlengths
19
75
code
stringlengths
279
1.37M
./openssl/ssl/quic/quic_record_rx.c
/* * 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/ssl.h> #include "internal/quic_record_rx.h" #include "quic_record_shared.h" #include "internal/common.h" #include "internal/list.h" #include "../ssl_local.h" /* * Mark a packet in a bitfield. * * pkt_idx: index of packet within datagram. */ static ossl_inline void pkt_mark(uint64_t *bitf, size_t pkt_idx) { assert(pkt_idx < QUIC_MAX_PKT_PER_URXE); *bitf |= ((uint64_t)1) << pkt_idx; } /* Returns 1 if a packet is in the bitfield. */ static ossl_inline int pkt_is_marked(const uint64_t *bitf, size_t pkt_idx) { assert(pkt_idx < QUIC_MAX_PKT_PER_URXE); return (*bitf & (((uint64_t)1) << pkt_idx)) != 0; } /* * RXE * === * * RX Entries (RXEs) store processed (i.e., decrypted) data received from the * network. One RXE is used per received QUIC packet. */ typedef struct rxe_st RXE; struct rxe_st { OSSL_QRX_PKT pkt; OSSL_LIST_MEMBER(rxe, RXE); size_t data_len, alloc_len, refcount; /* Extra fields for per-packet information. */ QUIC_PKT_HDR hdr; /* data/len are decrypted payload */ /* Decoded packet number. */ QUIC_PN pn; /* Addresses copied from URXE. */ BIO_ADDR peer, local; /* Time we received the packet (not when we processed it). */ OSSL_TIME time; /* Total length of the datagram which contained this packet. */ size_t datagram_len; /* * The key epoch the packet was received with. Always 0 for non-1-RTT * packets. */ uint64_t key_epoch; /* * alloc_len allocated bytes (of which data_len bytes are valid) follow this * structure. */ }; DEFINE_LIST_OF(rxe, RXE); typedef OSSL_LIST(rxe) RXE_LIST; static ossl_inline unsigned char *rxe_data(const RXE *e) { return (unsigned char *)(e + 1); } /* * QRL * === */ struct ossl_qrx_st { OSSL_LIB_CTX *libctx; const char *propq; /* Demux to receive datagrams from. */ QUIC_DEMUX *demux; /* Length of connection IDs used in short-header packets in bytes. */ size_t short_conn_id_len; /* Maximum number of deferred datagrams buffered at any one time. */ size_t max_deferred; /* Current count of deferred datagrams. */ size_t num_deferred; /* * List of URXEs which are filled with received encrypted data. * These are returned to the DEMUX's free list as they are processed. */ QUIC_URXE_LIST urx_pending; /* * List of URXEs which we could not decrypt immediately and which are being * kept in case they can be decrypted later. */ QUIC_URXE_LIST urx_deferred; /* * List of RXEs which are not currently in use. These are moved * to the pending list as they are filled. */ RXE_LIST rx_free; /* * List of RXEs which are filled with decrypted packets ready to be passed * to the user. A RXE is removed from all lists inside the QRL when passed * to the user, then returned to the free list when the user returns it. */ RXE_LIST rx_pending; /* Largest PN we have received and processed in a given PN space. */ QUIC_PN largest_pn[QUIC_PN_SPACE_NUM]; /* Per encryption-level state. */ OSSL_QRL_ENC_LEVEL_SET el_set; /* Bytes we have received since this counter was last cleared. */ uint64_t bytes_received; /* * Number of forged packets we have received since the QRX was instantiated. * Note that as per RFC 9001, this is connection-level state; it is not per * EL and is not reset by a key update. */ uint64_t forged_pkt_count; /* * The PN the current key epoch started at, inclusive. */ uint64_t cur_epoch_start_pn; /* Validation callback. */ ossl_qrx_late_validation_cb *validation_cb; void *validation_cb_arg; /* Key update callback. */ ossl_qrx_key_update_cb *key_update_cb; void *key_update_cb_arg; /* Initial key phase. For debugging use only; always 0 in real use. */ unsigned char init_key_phase_bit; /* Are we allowed to process 1-RTT packets yet? */ unsigned char allow_1rtt; /* Message callback related arguments */ ossl_msg_cb msg_callback; void *msg_callback_arg; SSL *msg_callback_ssl; }; OSSL_QRX *ossl_qrx_new(const OSSL_QRX_ARGS *args) { OSSL_QRX *qrx; size_t i; if (args->demux == NULL || args->max_deferred == 0) return NULL; qrx = OPENSSL_zalloc(sizeof(OSSL_QRX)); if (qrx == NULL) return NULL; for (i = 0; i < OSSL_NELEM(qrx->largest_pn); ++i) qrx->largest_pn[i] = args->init_largest_pn[i]; qrx->libctx = args->libctx; qrx->propq = args->propq; qrx->demux = args->demux; qrx->short_conn_id_len = args->short_conn_id_len; qrx->init_key_phase_bit = args->init_key_phase_bit; qrx->max_deferred = args->max_deferred; return qrx; } static void qrx_cleanup_rxl(RXE_LIST *l) { RXE *e, *enext; for (e = ossl_list_rxe_head(l); e != NULL; e = enext) { enext = ossl_list_rxe_next(e); ossl_list_rxe_remove(l, e); OPENSSL_free(e); } } static void qrx_cleanup_urxl(OSSL_QRX *qrx, QUIC_URXE_LIST *l) { QUIC_URXE *e, *enext; for (e = ossl_list_urxe_head(l); e != NULL; e = enext) { enext = ossl_list_urxe_next(e); ossl_list_urxe_remove(l, e); ossl_quic_demux_release_urxe(qrx->demux, e); } } void ossl_qrx_free(OSSL_QRX *qrx) { uint32_t i; if (qrx == NULL) return; /* Free RXE queue data. */ qrx_cleanup_rxl(&qrx->rx_free); qrx_cleanup_rxl(&qrx->rx_pending); qrx_cleanup_urxl(qrx, &qrx->urx_pending); qrx_cleanup_urxl(qrx, &qrx->urx_deferred); /* Drop keying material and crypto resources. */ for (i = 0; i < QUIC_ENC_LEVEL_NUM; ++i) ossl_qrl_enc_level_set_discard(&qrx->el_set, i); OPENSSL_free(qrx); } void ossl_qrx_inject_urxe(OSSL_QRX *qrx, QUIC_URXE *urxe) { /* Initialize our own fields inside the URXE and add to the pending list. */ urxe->processed = 0; urxe->hpr_removed = 0; urxe->deferred = 0; ossl_list_urxe_insert_tail(&qrx->urx_pending, urxe); if (qrx->msg_callback != NULL) qrx->msg_callback(0, OSSL_QUIC1_VERSION, SSL3_RT_QUIC_DATAGRAM, urxe + 1, urxe->data_len, qrx->msg_callback_ssl, qrx->msg_callback_arg); } static void qrx_requeue_deferred(OSSL_QRX *qrx) { QUIC_URXE *e; while ((e = ossl_list_urxe_head(&qrx->urx_deferred)) != NULL) { ossl_list_urxe_remove(&qrx->urx_deferred, e); ossl_list_urxe_insert_tail(&qrx->urx_pending, e); } } 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) { if (enc_level >= QUIC_ENC_LEVEL_NUM) return 0; if (!ossl_qrl_enc_level_set_provide_secret(&qrx->el_set, qrx->libctx, qrx->propq, enc_level, suite_id, md, secret, secret_len, qrx->init_key_phase_bit, /*is_tx=*/0)) return 0; /* * Any packets we previously could not decrypt, we may now be able to * decrypt, so move any datagrams containing deferred packets from the * deferred to the pending queue. */ qrx_requeue_deferred(qrx); return 1; } int ossl_qrx_discard_enc_level(OSSL_QRX *qrx, uint32_t enc_level) { if (enc_level >= QUIC_ENC_LEVEL_NUM) return 0; ossl_qrl_enc_level_set_discard(&qrx->el_set, enc_level); return 1; } /* Returns 1 if there are one or more pending RXEs. */ int ossl_qrx_processed_read_pending(OSSL_QRX *qrx) { return !ossl_list_rxe_is_empty(&qrx->rx_pending); } /* Returns 1 if there are yet-unprocessed packets. */ int ossl_qrx_unprocessed_read_pending(OSSL_QRX *qrx) { return !ossl_list_urxe_is_empty(&qrx->urx_pending) || !ossl_list_urxe_is_empty(&qrx->urx_deferred); } /* Pop the next pending RXE. Returns NULL if no RXE is pending. */ static RXE *qrx_pop_pending_rxe(OSSL_QRX *qrx) { RXE *rxe = ossl_list_rxe_head(&qrx->rx_pending); if (rxe == NULL) return NULL; ossl_list_rxe_remove(&qrx->rx_pending, rxe); return rxe; } /* Allocate a new RXE. */ static RXE *qrx_alloc_rxe(size_t alloc_len) { RXE *rxe; if (alloc_len >= SIZE_MAX - sizeof(RXE)) return NULL; rxe = OPENSSL_malloc(sizeof(RXE) + alloc_len); if (rxe == NULL) return NULL; ossl_list_rxe_init_elem(rxe); rxe->alloc_len = alloc_len; rxe->data_len = 0; rxe->refcount = 0; return rxe; } /* * Ensures there is at least one RXE in the RX free list, allocating a new entry * if necessary. The returned RXE is in the RX free list; it is not popped. * * alloc_len is a hint which may be used to determine the RXE size if allocation * is necessary. Returns NULL on allocation failure. */ static RXE *qrx_ensure_free_rxe(OSSL_QRX *qrx, size_t alloc_len) { RXE *rxe; if (ossl_list_rxe_head(&qrx->rx_free) != NULL) return ossl_list_rxe_head(&qrx->rx_free); rxe = qrx_alloc_rxe(alloc_len); if (rxe == NULL) return NULL; ossl_list_rxe_insert_tail(&qrx->rx_free, rxe); return rxe; } /* * Resize the data buffer attached to an RXE to be n bytes in size. The address * of the RXE might change; the new address is returned, or NULL on failure, in * which case the original RXE remains valid. */ static RXE *qrx_resize_rxe(RXE_LIST *rxl, RXE *rxe, size_t n) { RXE *rxe2, *p; /* Should never happen. */ if (rxe == NULL) return NULL; if (n >= SIZE_MAX - sizeof(RXE)) return NULL; /* Remove the item from the list to avoid accessing freed memory */ p = ossl_list_rxe_prev(rxe); ossl_list_rxe_remove(rxl, rxe); /* Should never resize an RXE which has been handed out. */ if (!ossl_assert(rxe->refcount == 0)) return NULL; /* * NOTE: We do not clear old memory, although it does contain decrypted * data. */ rxe2 = OPENSSL_realloc(rxe, sizeof(RXE) + n); if (rxe2 == NULL) { /* Resize failed, restore old allocation. */ if (p == NULL) ossl_list_rxe_insert_head(rxl, rxe); else ossl_list_rxe_insert_after(rxl, p, rxe); return NULL; } if (p == NULL) ossl_list_rxe_insert_head(rxl, rxe2); else ossl_list_rxe_insert_after(rxl, p, rxe2); rxe2->alloc_len = n; return rxe2; } /* * Ensure the data buffer attached to an RXE is at least n bytes in size. * Returns NULL on failure. */ static RXE *qrx_reserve_rxe(RXE_LIST *rxl, RXE *rxe, size_t n) { if (rxe->alloc_len >= n) return rxe; return qrx_resize_rxe(rxl, rxe, n); } /* Return a RXE handed out to the user back to our freelist. */ static void qrx_recycle_rxe(OSSL_QRX *qrx, RXE *rxe) { /* RXE should not be in any list */ assert(ossl_list_rxe_prev(rxe) == NULL && ossl_list_rxe_next(rxe) == NULL); rxe->pkt.hdr = NULL; rxe->pkt.peer = NULL; rxe->pkt.local = NULL; ossl_list_rxe_insert_tail(&qrx->rx_free, rxe); } /* * Given a pointer to a pointer pointing to a buffer and the size of that * buffer, copy the buffer into *prxe, expanding the RXE if necessary (its * pointer may change due to realloc). *pi is the offset in bytes to copy the * buffer to, and on success is updated to be the offset pointing after the * copied buffer. *pptr is updated to point to the new location of the buffer. */ static int qrx_relocate_buffer(OSSL_QRX *qrx, RXE **prxe, size_t *pi, const unsigned char **pptr, size_t buf_len) { RXE *rxe; unsigned char *dst; if (!buf_len) return 1; if ((rxe = qrx_reserve_rxe(&qrx->rx_free, *prxe, *pi + buf_len)) == NULL) return 0; *prxe = rxe; dst = (unsigned char *)rxe_data(rxe) + *pi; memcpy(dst, *pptr, buf_len); *pi += buf_len; *pptr = dst; return 1; } static uint32_t qrx_determine_enc_level(const QUIC_PKT_HDR *hdr) { switch (hdr->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: assert(0); case QUIC_PKT_TYPE_RETRY: case QUIC_PKT_TYPE_VERSION_NEG: return QUIC_ENC_LEVEL_INITIAL; /* not used */ } } static uint32_t rxe_determine_pn_space(RXE *rxe) { uint32_t enc_level; enc_level = qrx_determine_enc_level(&rxe->hdr); return ossl_quic_enc_level_to_pn_space(enc_level); } static int qrx_validate_hdr_early(OSSL_QRX *qrx, RXE *rxe, const QUIC_CONN_ID *first_dcid) { /* Ensure version is what we want. */ if (rxe->hdr.version != QUIC_VERSION_1 && rxe->hdr.version != QUIC_VERSION_NONE) return 0; /* Clients should never receive 0-RTT packets. */ if (rxe->hdr.type == QUIC_PKT_TYPE_0RTT) return 0; /* Version negotiation and retry packets must be the first packet. */ if (first_dcid != NULL && !ossl_quic_pkt_type_can_share_dgram(rxe->hdr.type)) return 0; /* * If this is not the first packet in a datagram, the destination connection * ID must match the one in that packet. */ if (first_dcid != NULL) { if (!ossl_assert(first_dcid->id_len < QUIC_MAX_CONN_ID_LEN) || !ossl_quic_conn_id_eq(first_dcid, &rxe->hdr.dst_conn_id)) return 0; } return 1; } /* Validate header and decode PN. */ static int qrx_validate_hdr(OSSL_QRX *qrx, RXE *rxe) { int pn_space = rxe_determine_pn_space(rxe); if (!ossl_quic_wire_decode_pkt_hdr_pn(rxe->hdr.pn, rxe->hdr.pn_len, qrx->largest_pn[pn_space], &rxe->pn)) return 0; return 1; } /* Late packet header validation. */ static int qrx_validate_hdr_late(OSSL_QRX *qrx, RXE *rxe) { int pn_space = rxe_determine_pn_space(rxe); /* * Allow our user to decide whether to discard the packet before we try and * decrypt it. */ if (qrx->validation_cb != NULL && !qrx->validation_cb(rxe->pn, pn_space, qrx->validation_cb_arg)) return 0; return 1; } /* * Retrieves the correct cipher context for an EL and key phase. Writes the key * epoch number actually used for packet decryption to *rx_key_epoch. */ static size_t qrx_get_cipher_ctx_idx(OSSL_QRX *qrx, OSSL_QRL_ENC_LEVEL *el, uint32_t enc_level, unsigned char key_phase_bit, uint64_t *rx_key_epoch, int *is_old_key) { size_t idx; *is_old_key = 0; if (enc_level != QUIC_ENC_LEVEL_1RTT) { *rx_key_epoch = 0; return 0; } if (!ossl_assert(key_phase_bit <= 1)) return SIZE_MAX; /* * RFC 9001 requires that we not create timing channels which could reveal * the decrypted value of the Key Phase bit. We usually handle this by * keeping the cipher contexts for both the current and next key epochs * around, so that we just select a cipher context blindly using the key * phase bit, which is time-invariant. * * In the COOLDOWN state, we only have one keyslot/cipher context. RFC 9001 * suggests an implementation strategy to avoid creating a timing channel in * this case: * * Endpoints can use randomized packet protection keys in place of * discarded keys when key updates are not yet permitted. * * Rather than use a randomised key, we simply use our existing key as it * will fail AEAD verification anyway. This avoids the need to keep around a * dedicated garbage key. * * Note: Accessing different cipher contexts is technically not * timing-channel safe due to microarchitectural side channels, but this is * the best we can reasonably do and appears to be directly suggested by the * RFC. */ idx = (el->state == QRL_EL_STATE_PROV_COOLDOWN ? el->key_epoch & 1 : key_phase_bit); /* * We also need to determine the key epoch number which this index * corresponds to. This is so we can report the key epoch number in the * OSSL_QRX_PKT structure, which callers need to validate whether it was OK * for a packet to be sent using a given key epoch's keys. */ switch (el->state) { case QRL_EL_STATE_PROV_NORMAL: /* * If we are in the NORMAL state, usually the KP bit will match the LSB * of our key epoch, meaning no new key update is being signalled. If it * does not match, this means the packet (purports to) belong to * the next key epoch. * * IMPORTANT: The AEAD tag has not been verified yet when this function * is called, so this code must be timing-channel safe, hence use of * XOR. Moreover, the value output below is not yet authenticated. */ *rx_key_epoch = el->key_epoch + ((el->key_epoch & 1) ^ (uint64_t)key_phase_bit); break; case QRL_EL_STATE_PROV_UPDATING: /* * If we are in the UPDATING state, usually the KP bit will match the * LSB of our key epoch. If it does not match, this means that the * packet (purports to) belong to the previous key epoch. * * As above, must be timing-channel safe. */ *is_old_key = (el->key_epoch & 1) ^ (uint64_t)key_phase_bit; *rx_key_epoch = el->key_epoch - (uint64_t)*is_old_key; break; case QRL_EL_STATE_PROV_COOLDOWN: /* * If we are in COOLDOWN, there is only one key epoch we can possibly * decrypt with, so just try that. If AEAD decryption fails, the * value we output here isn't used anyway. */ *rx_key_epoch = el->key_epoch; break; } return idx; } /* * Tries to decrypt a packet payload. * * Returns 1 on success or 0 on failure (which is permanent). The payload is * decrypted from src and written to dst. The buffer dst must be of at least * src_len bytes in length. The actual length of the output in bytes is written * to *dec_len on success, which will always be equal to or less than (usually * less than) src_len. */ static int qrx_decrypt_pkt_body(OSSL_QRX *qrx, unsigned char *dst, const unsigned char *src, size_t src_len, size_t *dec_len, const unsigned char *aad, size_t aad_len, QUIC_PN pn, uint32_t enc_level, unsigned char key_phase_bit, uint64_t *rx_key_epoch) { int l = 0, l2 = 0, is_old_key, nonce_len; unsigned char nonce[EVP_MAX_IV_LENGTH]; size_t i, cctx_idx; OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set, enc_level, 1); EVP_CIPHER_CTX *cctx; if (src_len > INT_MAX || aad_len > INT_MAX) return 0; /* We should not have been called if we do not have key material. */ if (!ossl_assert(el != NULL)) return 0; if (el->tag_len >= src_len) return 0; /* * If we have failed to authenticate a certain number of ciphertexts, refuse * to decrypt any more ciphertexts. */ if (qrx->forged_pkt_count >= ossl_qrl_get_suite_max_forged_pkt(el->suite_id)) return 0; cctx_idx = qrx_get_cipher_ctx_idx(qrx, el, enc_level, key_phase_bit, rx_key_epoch, &is_old_key); if (!ossl_assert(cctx_idx < OSSL_NELEM(el->cctx))) return 0; if (is_old_key && pn >= qrx->cur_epoch_start_pn) /* * RFC 9001 s. 5.5: Once an endpoint successfully receives a packet with * a given PN, it MUST discard all packets in the same PN space with * higher PNs if they cannot be successfully unprotected with the same * key, or -- if there is a key update -- a subsequent packet protection * key. * * In other words, once a PN x triggers a KU, it is invalid for us to * receive a packet with a newer PN y (y > x) using the old keys. */ return 0; cctx = el->cctx[cctx_idx]; /* Construct nonce (nonce=IV ^ PN). */ nonce_len = EVP_CIPHER_CTX_get_iv_length(cctx); if (!ossl_assert(nonce_len >= (int)sizeof(QUIC_PN))) return 0; memcpy(nonce, el->iv[cctx_idx], nonce_len); for (i = 0; i < sizeof(QUIC_PN); ++i) nonce[nonce_len - i - 1] ^= (unsigned char)(pn >> (i * 8)); /* type and key will already have been setup; feed the IV. */ if (EVP_CipherInit_ex(cctx, NULL, NULL, NULL, nonce, /*enc=*/0) != 1) return 0; /* Feed the AEAD tag we got so the cipher can validate it. */ if (EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_SET_TAG, el->tag_len, (unsigned char *)src + src_len - el->tag_len) != 1) return 0; /* Feed AAD data. */ if (EVP_CipherUpdate(cctx, NULL, &l, aad, aad_len) != 1) return 0; /* Feed encrypted packet body. */ if (EVP_CipherUpdate(cctx, dst, &l, src, src_len - el->tag_len) != 1) return 0; #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION /* * Throw away what we just decrypted and just use the ciphertext instead * (which should be unencrypted) */ memcpy(dst, src, l); /* Pretend to authenticate the tag but ignore it */ if (EVP_CipherFinal_ex(cctx, NULL, &l2) != 1) { /* We don't care */ } #else /* Ensure authentication succeeded. */ if (EVP_CipherFinal_ex(cctx, NULL, &l2) != 1) { /* Authentication failed, increment failed auth counter. */ ++qrx->forged_pkt_count; return 0; } #endif *dec_len = l; return 1; } static ossl_inline void ignore_res(int x) { /* No-op. */ } static void qrx_key_update_initiated(OSSL_QRX *qrx, QUIC_PN pn) { if (!ossl_qrl_enc_level_set_key_update(&qrx->el_set, QUIC_ENC_LEVEL_1RTT)) /* We are already in RXKU, so we don't call the callback again. */ return; qrx->cur_epoch_start_pn = pn; if (qrx->key_update_cb != NULL) qrx->key_update_cb(pn, qrx->key_update_cb_arg); } /* Process a single packet in a datagram. */ static int qrx_process_pkt(OSSL_QRX *qrx, QUIC_URXE *urxe, PACKET *pkt, size_t pkt_idx, QUIC_CONN_ID *first_dcid, size_t datagram_len) { RXE *rxe; const unsigned char *eop = NULL; size_t i, aad_len = 0, dec_len = 0; PACKET orig_pkt = *pkt; const unsigned char *sop = PACKET_data(pkt); unsigned char *dst; char need_second_decode = 0, already_processed = 0; QUIC_PKT_HDR_PTRS ptrs; uint32_t pn_space, enc_level; OSSL_QRL_ENC_LEVEL *el = NULL; uint64_t rx_key_epoch = UINT64_MAX; /* * Get a free RXE. If we need to allocate a new one, use the packet length * as a good ballpark figure. */ rxe = qrx_ensure_free_rxe(qrx, PACKET_remaining(pkt)); if (rxe == NULL) return 0; /* Have we already processed this packet? */ if (pkt_is_marked(&urxe->processed, pkt_idx)) already_processed = 1; /* * Decode the header into the RXE structure. We first decrypt and read the * unprotected part of the packet header (unless we already removed header * protection, in which case we decode all of it). */ need_second_decode = !pkt_is_marked(&urxe->hpr_removed, pkt_idx); if (!ossl_quic_wire_decode_pkt_hdr(pkt, qrx->short_conn_id_len, need_second_decode, 0, &rxe->hdr, &ptrs)) goto malformed; /* * Our successful decode above included an intelligible length and the * PACKET is now pointing to the end of the QUIC packet. */ eop = PACKET_data(pkt); /* * Make a note of the first packet's DCID so we can later ensure the * destination connection IDs of all packets in a datagram match. */ if (pkt_idx == 0) *first_dcid = rxe->hdr.dst_conn_id; /* * Early header validation. Since we now know the packet length, we can also * now skip over it if we already processed it. */ if (already_processed || !qrx_validate_hdr_early(qrx, rxe, pkt_idx == 0 ? NULL : first_dcid)) /* * Already processed packets are handled identically to malformed * packets; i.e., they are ignored. */ goto malformed; if (!ossl_quic_pkt_type_is_encrypted(rxe->hdr.type)) { /* * Version negotiation and retry packets are a special case. They do not * contain a payload which needs decrypting and have no header * protection. */ /* Just copy the payload from the URXE to the RXE. */ if ((rxe = qrx_reserve_rxe(&qrx->rx_free, rxe, rxe->hdr.len)) == NULL) /* * Allocation failure. EOP will be pointing to the end of the * datagram so processing of this datagram will end here. */ goto malformed; /* We are now committed to returning the packet. */ memcpy(rxe_data(rxe), rxe->hdr.data, rxe->hdr.len); pkt_mark(&urxe->processed, pkt_idx); rxe->hdr.data = rxe_data(rxe); rxe->pn = QUIC_PN_INVALID; rxe->data_len = rxe->hdr.len; rxe->datagram_len = datagram_len; rxe->key_epoch = 0; rxe->peer = urxe->peer; rxe->local = urxe->local; rxe->time = urxe->time; /* Move RXE to pending. */ ossl_list_rxe_remove(&qrx->rx_free, rxe); ossl_list_rxe_insert_tail(&qrx->rx_pending, rxe); return 0; /* success, did not defer */ } /* Determine encryption level of packet. */ enc_level = qrx_determine_enc_level(&rxe->hdr); /* If we do not have keying material for this encryption level yet, defer. */ switch (ossl_qrl_enc_level_set_have_el(&qrx->el_set, enc_level)) { case 1: /* We have keys. */ if (enc_level == QUIC_ENC_LEVEL_1RTT && !qrx->allow_1rtt) /* * But we cannot process 1-RTT packets until the handshake is * completed (RFC 9000 s. 5.7). */ goto cannot_decrypt; break; case 0: /* No keys yet. */ goto cannot_decrypt; default: /* We already discarded keys for this EL, we will never process this.*/ goto malformed; } /* * We will copy any token included in the packet to the start of our RXE * data buffer (so that we don't reference the URXE buffer any more and can * recycle it). Track our position in the RXE buffer by index instead of * pointer as the pointer may change as reallocs occur. */ i = 0; /* * rxe->hdr.data is now pointing at the (encrypted) packet payload. rxe->hdr * also has fields pointing into the PACKET buffer which will be going away * soon (the URXE will be reused for another incoming packet). * * Firstly, relocate some of these fields into the RXE as needed. * * Relocate token buffer and fix pointer. */ if (rxe->hdr.type == QUIC_PKT_TYPE_INITIAL) { const unsigned char *token = rxe->hdr.token; /* * This may change the value of rxe and change the value of the token * pointer as well. So we must make a temporary copy of the pointer to * the token, and then copy it back into the new location of the rxe */ if (!qrx_relocate_buffer(qrx, &rxe, &i, &token, rxe->hdr.token_len)) goto malformed; rxe->hdr.token = token; } /* Now remove header protection. */ *pkt = orig_pkt; el = ossl_qrl_enc_level_set_get(&qrx->el_set, enc_level, 1); assert(el != NULL); /* Already checked above */ if (need_second_decode) { if (!ossl_quic_hdr_protector_decrypt(&el->hpr, &ptrs)) goto malformed; /* * We have removed header protection, so don't attempt to do it again if * the packet gets deferred and processed again. */ pkt_mark(&urxe->hpr_removed, pkt_idx); /* Decode the now unprotected header. */ if (ossl_quic_wire_decode_pkt_hdr(pkt, qrx->short_conn_id_len, 0, 0, &rxe->hdr, NULL) != 1) goto malformed; } /* Validate header and decode PN. */ if (!qrx_validate_hdr(qrx, rxe)) goto malformed; if (qrx->msg_callback != NULL) qrx->msg_callback(0, OSSL_QUIC1_VERSION, SSL3_RT_QUIC_PACKET, sop, eop - sop - rxe->hdr.len, qrx->msg_callback_ssl, qrx->msg_callback_arg); /* * The AAD data is the entire (unprotected) packet header including the PN. * The packet header has been unprotected in place, so we can just reuse the * PACKET buffer. The header ends where the payload begins. */ aad_len = rxe->hdr.data - sop; /* Ensure the RXE buffer size is adequate for our payload. */ if ((rxe = qrx_reserve_rxe(&qrx->rx_free, rxe, rxe->hdr.len + i)) == NULL) { /* * Allocation failure, treat as malformed and do not bother processing * any further packets in the datagram as they are likely to also * encounter allocation failures. */ eop = NULL; goto malformed; } /* * We decrypt the packet body to immediately after the token at the start of * the RXE buffer (where present). * * Do the decryption from the PACKET (which points into URXE memory) to our * RXE payload (single-copy decryption), then fixup the pointers in the * header to point to our new buffer. * * If decryption fails this is considered a permanent error; we defer * packets we don't yet have decryption keys for above, so if this fails, * something has gone wrong with the handshake process or a packet has been * corrupted. */ dst = (unsigned char *)rxe_data(rxe) + i; if (!qrx_decrypt_pkt_body(qrx, dst, rxe->hdr.data, rxe->hdr.len, &dec_len, sop, aad_len, rxe->pn, enc_level, rxe->hdr.key_phase, &rx_key_epoch)) goto malformed; /* * ----------------------------------------------------- * IMPORTANT: ANYTHING ABOVE THIS LINE IS UNVERIFIED * AND MUST BE TIMING-CHANNEL SAFE. * ----------------------------------------------------- * * At this point, we have successfully authenticated the AEAD tag and no * longer need to worry about exposing the PN, PN length or Key Phase bit in * timing channels. Invoke any configured validation callback to allow for * rejection of duplicate PNs. */ if (!qrx_validate_hdr_late(qrx, rxe)) goto malformed; /* Check for a Key Phase bit differing from our expectation. */ if (rxe->hdr.type == QUIC_PKT_TYPE_1RTT && rxe->hdr.key_phase != (el->key_epoch & 1)) qrx_key_update_initiated(qrx, rxe->pn); /* * We have now successfully decrypted the packet payload. If there are * additional packets in the datagram, it is possible we will fail to * decrypt them and need to defer them until we have some key material we * don't currently possess. If this happens, the URXE will be moved to the * deferred queue. Since a URXE corresponds to one datagram, which may * contain multiple packets, we must ensure any packets we have already * processed in the URXE are not processed again (this is an RFC * requirement). We do this by marking the nth packet in the datagram as * processed. * * We are now committed to returning this decrypted packet to the user, * meaning we now consider the packet processed and must mark it * accordingly. */ pkt_mark(&urxe->processed, pkt_idx); /* * Update header to point to the decrypted buffer, which may be shorter * due to AEAD tags, block padding, etc. */ rxe->hdr.data = dst; rxe->hdr.len = dec_len; rxe->data_len = dec_len; rxe->datagram_len = datagram_len; rxe->key_epoch = rx_key_epoch; /* We processed the PN successfully, so update largest processed PN. */ pn_space = rxe_determine_pn_space(rxe); if (rxe->pn > qrx->largest_pn[pn_space]) qrx->largest_pn[pn_space] = rxe->pn; /* Copy across network addresses and RX time from URXE to RXE. */ rxe->peer = urxe->peer; rxe->local = urxe->local; rxe->time = urxe->time; /* Move RXE to pending. */ ossl_list_rxe_remove(&qrx->rx_free, rxe); ossl_list_rxe_insert_tail(&qrx->rx_pending, rxe); return 0; /* success, did not defer; not distinguished from failure */ cannot_decrypt: /* * We cannot process this packet right now (but might be able to later). We * MUST attempt to process any other packets in the datagram, so defer it * and skip over it. */ assert(eop != NULL && eop >= PACKET_data(pkt)); /* * We don't care if this fails as it will just result in the packet being at * the end of the datagram buffer. */ ignore_res(PACKET_forward(pkt, eop - PACKET_data(pkt))); return 1; /* deferred */ malformed: if (eop != NULL) { /* * This packet cannot be processed and will never be processable. We * were at least able to decode its header and determine its length, so * we can skip over it and try to process any subsequent packets in the * datagram. * * Mark as processed as an optimization. */ assert(eop >= PACKET_data(pkt)); pkt_mark(&urxe->processed, pkt_idx); /* We don't care if this fails (see above) */ ignore_res(PACKET_forward(pkt, eop - PACKET_data(pkt))); } else { /* * This packet cannot be processed and will never be processable. * Because even its header is not intelligible, we cannot examine any * further packets in the datagram because its length cannot be * discerned. * * Advance over the entire remainder of the datagram, and mark it as * processed as an optimization. */ pkt_mark(&urxe->processed, pkt_idx); /* We don't care if this fails (see above) */ ignore_res(PACKET_forward(pkt, PACKET_remaining(pkt))); } return 0; /* failure, did not defer; not distinguished from success */ } /* Process a datagram which was received. */ static int qrx_process_datagram(OSSL_QRX *qrx, QUIC_URXE *e, const unsigned char *data, size_t data_len) { int have_deferred = 0; PACKET pkt; size_t pkt_idx = 0; QUIC_CONN_ID first_dcid = { 255 }; qrx->bytes_received += data_len; if (!PACKET_buf_init(&pkt, data, data_len)) return 0; for (; PACKET_remaining(&pkt) > 0; ++pkt_idx) { /* * A packet smaller than the minimum possible QUIC packet size is not * considered valid. We also ignore more than a certain number of * packets within the same datagram. */ if (PACKET_remaining(&pkt) < QUIC_MIN_VALID_PKT_LEN || pkt_idx >= QUIC_MAX_PKT_PER_URXE) break; /* * We note whether packet processing resulted in a deferral since * this means we need to move the URXE to the deferred list rather * than the free list after we're finished dealing with it for now. * * However, we don't otherwise care here whether processing succeeded or * failed, as the RFC says even if a packet in a datagram is malformed, * we should still try to process any packets following it. * * In the case where the packet is so malformed we can't determine its * length, qrx_process_pkt will take care of advancing to the end of * the packet, so we will exit the loop automatically in this case. */ if (qrx_process_pkt(qrx, e, &pkt, pkt_idx, &first_dcid, data_len)) have_deferred = 1; } /* Only report whether there were any deferrals. */ return have_deferred; } /* Process a single pending URXE. */ static int qrx_process_one_urxe(OSSL_QRX *qrx, QUIC_URXE *e) { int was_deferred; /* The next URXE we process should be at the head of the pending list. */ if (!ossl_assert(e == ossl_list_urxe_head(&qrx->urx_pending))) return 0; /* * Attempt to process the datagram. The return value indicates only if * processing of the datagram was deferred. If we failed to process the * datagram, we do not attempt to process it again and silently eat the * error. */ was_deferred = qrx_process_datagram(qrx, e, ossl_quic_urxe_data(e), e->data_len); /* * Remove the URXE from the pending list and return it to * either the free or deferred list. */ ossl_list_urxe_remove(&qrx->urx_pending, e); if (was_deferred > 0 && (e->deferred || qrx->num_deferred < qrx->max_deferred)) { ossl_list_urxe_insert_tail(&qrx->urx_deferred, e); if (!e->deferred) { e->deferred = 1; ++qrx->num_deferred; } } else { if (e->deferred) { e->deferred = 0; --qrx->num_deferred; } ossl_quic_demux_release_urxe(qrx->demux, e); } return 1; } /* Process any pending URXEs to generate pending RXEs. */ static int qrx_process_pending_urxl(OSSL_QRX *qrx) { QUIC_URXE *e; while ((e = ossl_list_urxe_head(&qrx->urx_pending)) != NULL) if (!qrx_process_one_urxe(qrx, e)) return 0; return 1; } int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT **ppkt) { RXE *rxe; if (!ossl_qrx_processed_read_pending(qrx)) { if (!qrx_process_pending_urxl(qrx)) return 0; if (!ossl_qrx_processed_read_pending(qrx)) return 0; } rxe = qrx_pop_pending_rxe(qrx); if (!ossl_assert(rxe != NULL)) return 0; assert(rxe->refcount == 0); rxe->refcount = 1; rxe->pkt.hdr = &rxe->hdr; rxe->pkt.pn = rxe->pn; rxe->pkt.time = rxe->time; rxe->pkt.datagram_len = rxe->datagram_len; rxe->pkt.peer = BIO_ADDR_family(&rxe->peer) != AF_UNSPEC ? &rxe->peer : NULL; rxe->pkt.local = BIO_ADDR_family(&rxe->local) != AF_UNSPEC ? &rxe->local : NULL; rxe->pkt.key_epoch = rxe->key_epoch; rxe->pkt.qrx = qrx; *ppkt = &rxe->pkt; return 1; } void ossl_qrx_pkt_release(OSSL_QRX_PKT *pkt) { RXE *rxe; if (pkt == NULL) return; rxe = (RXE *)pkt; assert(rxe->refcount > 0); if (--rxe->refcount == 0) qrx_recycle_rxe(pkt->qrx, rxe); } void ossl_qrx_pkt_up_ref(OSSL_QRX_PKT *pkt) { RXE *rxe = (RXE *)pkt; assert(rxe->refcount > 0); ++rxe->refcount; } uint64_t ossl_qrx_get_bytes_received(OSSL_QRX *qrx, int clear) { uint64_t v = qrx->bytes_received; if (clear) qrx->bytes_received = 0; return v; } int ossl_qrx_set_late_validation_cb(OSSL_QRX *qrx, ossl_qrx_late_validation_cb *cb, void *cb_arg) { qrx->validation_cb = cb; qrx->validation_cb_arg = cb_arg; return 1; } int ossl_qrx_set_key_update_cb(OSSL_QRX *qrx, ossl_qrx_key_update_cb *cb, void *cb_arg) { qrx->key_update_cb = cb; qrx->key_update_cb_arg = cb_arg; return 1; } uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set, QUIC_ENC_LEVEL_1RTT, 1); return el == NULL ? UINT64_MAX : el->key_epoch; } int ossl_qrx_key_update_timeout(OSSL_QRX *qrx, int normal) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set, QUIC_ENC_LEVEL_1RTT, 1); if (el == NULL) return 0; if (el->state == QRL_EL_STATE_PROV_UPDATING && !ossl_qrl_enc_level_set_key_update_done(&qrx->el_set, QUIC_ENC_LEVEL_1RTT)) return 0; if (normal && el->state == QRL_EL_STATE_PROV_COOLDOWN && !ossl_qrl_enc_level_set_key_cooldown_done(&qrx->el_set, QUIC_ENC_LEVEL_1RTT)) return 0; return 1; } uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX *qrx) { return qrx->forged_pkt_count; } uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX *qrx, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set, enc_level, 1); return el == NULL ? UINT64_MAX : ossl_qrl_get_suite_max_forged_pkt(el->suite_id); } void ossl_qrx_allow_1rtt_processing(OSSL_QRX *qrx) { if (qrx->allow_1rtt) return; qrx->allow_1rtt = 1; qrx_requeue_deferred(qrx); } void ossl_qrx_set_msg_callback(OSSL_QRX *qrx, ossl_msg_cb msg_callback, SSL *msg_callback_ssl) { qrx->msg_callback = msg_callback; qrx->msg_callback_ssl = msg_callback_ssl; } void ossl_qrx_set_msg_callback_arg(OSSL_QRX *qrx, void *msg_callback_arg) { qrx->msg_callback_arg = msg_callback_arg; }
./openssl/ssl/quic/quic_local.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_LOCAL_H # define OSSL_QUIC_LOCAL_H # include <openssl/ssl.h> # include "internal/quic_ssl.h" /* QUIC_CONNECTION */ # include "internal/quic_txp.h" # include "internal/quic_statm.h" # include "internal/quic_demux.h" # include "internal/quic_record_rx.h" # include "internal/quic_tls.h" # include "internal/quic_fc.h" # include "internal/quic_stream.h" # include "internal/quic_channel.h" # include "internal/quic_reactor.h" # include "internal/quic_thread_assist.h" # include "../ssl_local.h" # ifndef OPENSSL_NO_QUIC /* * QUIC stream SSL object (QSSO) type. This implements the API personality layer * for QSSO objects, wrapping the QUIC-native QUIC_STREAM object and tracking * state required by the libssl API personality. */ struct quic_xso_st { /* SSL object common header. */ struct ssl_st ssl; /* The connection this stream is associated with. Always non-NULL. */ QUIC_CONNECTION *conn; /* The stream object. Always non-NULL for as long as the XSO exists. */ QUIC_STREAM *stream; /* * Has this stream been logically configured into blocking mode? Only * meaningful if desires_blocking_set is 1. Ignored if blocking is not * currently possible given QUIC_CONNECTION configuration. */ unsigned int desires_blocking : 1; /* * Has SSL_set_blocking_mode been called on this stream? If not set, we * inherit from the QUIC_CONNECTION blocking state. */ unsigned int desires_blocking_set : 1; /* * This state tracks SSL_write all-or-nothing (AON) write semantics * emulation. * * Example chronology: * * t=0: aon_write_in_progress=0 * t=1: SSL_write(ssl, b1, l1) called; * too big to enqueue into sstream at once, SSL_ERROR_WANT_WRITE; * aon_write_in_progress=1; aon_buf_base=b1; aon_buf_len=l1; * aon_buf_pos < l1 (depends on how much room was in sstream); * t=2: SSL_write(ssl, b2, l2); * b2 must equal b1 (validated unless ACCEPT_MOVING_WRITE_BUFFER) * l2 must equal l1 (always validated) * append into sstream from [b2 + aon_buf_pos, b2 + aon_buf_len) * if done, aon_write_in_progress=0 * */ /* Is an AON write in progress? */ unsigned int aon_write_in_progress : 1; /* * The base buffer pointer the caller passed us for the initial AON write * call. We use this for validation purposes unless * ACCEPT_MOVING_WRITE_BUFFER is enabled. * * NOTE: We never dereference this, as the caller might pass a different * (but identical) buffer if using ACCEPT_MOVING_WRITE_BUFFER. It is for * validation by pointer comparison only. */ const unsigned char *aon_buf_base; /* The total length of the AON buffer being sent, in bytes. */ size_t aon_buf_len; /* * The position in the AON buffer up to which we have successfully sent data * so far. */ size_t aon_buf_pos; /* SSL_set_mode */ uint32_t ssl_mode; /* SSL_set_options */ uint64_t ssl_options; /* * Last 'normal' error during an app-level I/O operation, used by * SSL_get_error(); used to track data-path errors like SSL_ERROR_WANT_READ * and SSL_ERROR_WANT_WRITE. */ int last_error; }; struct quic_conn_st { /* * ssl_st is a common header for ordinary SSL objects, QUIC connection * objects and QUIC stream objects, allowing objects of these different * types to be disambiguated at runtime and providing some common fields. * * Note: This must come first in the QUIC_CONNECTION structure. */ struct ssl_st ssl; SSL *tls; /* The QUIC engine representing the QUIC event domain. */ QUIC_ENGINE *engine; /* The QUIC port representing the QUIC listener and socket. */ QUIC_PORT *port; /* * The QUIC channel providing the core QUIC connection implementation. Note * that this is not instantiated until we actually start trying to do the * handshake. This is to allow us to gather information like whether we are * going to be in client or server mode before committing to instantiating * the channel, since we want to determine the channel arguments based on * that. * * The channel remains available after connection termination until the SSL * object is freed, thus (ch != NULL) iff (started == 1). */ QUIC_CHANNEL *ch; /* * The mutex used to synchronise access to the QUIC_CHANNEL. We own this but * provide it to the channel. */ CRYPTO_MUTEX *mutex; /* * If we have a default stream attached, this is the internal XSO * object. If there is no default stream, this is NULL. */ QUIC_XSO *default_xso; /* The network read and write BIOs. */ BIO *net_rbio, *net_wbio; /* Initial peer L4 address. */ BIO_ADDR init_peer_addr; # ifndef OPENSSL_NO_QUIC_THREAD_ASSIST /* Manages thread for QUIC thread assisted mode. */ QUIC_THREAD_ASSIST thread_assist; # endif /* If non-NULL, used instead of ossl_time_now(). Used for testing. */ OSSL_TIME (*override_now_cb)(void *arg); void *override_now_cb_arg; /* Number of XSOs allocated. Includes the default XSO, if any. */ size_t num_xso; /* Have we started? */ unsigned int started : 1; /* * This is 1 if we were instantiated using a QUIC server method * (for future use). */ unsigned int as_server : 1; /* * Has the application called SSL_set_accept_state? We require this to be * congruent with the value of as_server. */ unsigned int as_server_state : 1; /* Are we using thread assisted mode? Never changes after init. */ unsigned int is_thread_assisted : 1; /* Do connection-level operations (e.g. handshakes) run in blocking mode? */ unsigned int blocking : 1; /* Does the application want blocking mode? */ unsigned int desires_blocking : 1; /* Have we created a default XSO yet? */ unsigned int default_xso_created : 1; /* * Pre-TERMINATING shutdown phase in which we are flushing streams. * Monotonically transitions to 1. * New streams cannot be created in this state. */ unsigned int shutting_down : 1; /* Have we probed the BIOs for addressing support? */ unsigned int addressing_probe_done : 1; /* Are we using addressed mode (BIO_sendmmsg with non-NULL peer)? */ unsigned int addressed_mode_w : 1; unsigned int addressed_mode_r : 1; /* Default stream type. Defaults to SSL_DEFAULT_STREAM_MODE_AUTO_BIDI. */ uint32_t default_stream_mode; /* SSL_set_mode. This is not used directly but inherited by new XSOs. */ uint32_t default_ssl_mode; /* SSL_set_options. This is not used directly but inherited by new XSOs. */ uint64_t default_ssl_options; /* SSL_set_incoming_stream_policy. */ int incoming_stream_policy; uint64_t incoming_stream_aec; /* * Last 'normal' error during an app-level I/O operation, used by * SSL_get_error(); used to track data-path errors like SSL_ERROR_WANT_READ * and SSL_ERROR_WANT_WRITE. */ int last_error; }; /* Internal calls to the QUIC CSM which come from various places. */ int ossl_quic_conn_on_handshake_confirmed(QUIC_CONNECTION *qc); /* * To be called when a protocol violation occurs. The connection is torn down * with the given error code, which should be a QUIC_ERR_* value. Reason string * is optional and copied if provided. frame_type should be 0 if not applicable. */ void ossl_quic_conn_raise_protocol_error(QUIC_CONNECTION *qc, uint64_t error_code, uint64_t frame_type, const char *reason); void ossl_quic_conn_on_remote_conn_close(QUIC_CONNECTION *qc, OSSL_QUIC_FRAME_CONN_CLOSE *f); int ossl_quic_trace(int write_p, int version, int content_type, const void *buf, size_t msglen, SSL *ssl, void *arg); # define OSSL_QUIC_ANY_VERSION 0xFFFFF # define IS_QUIC_METHOD(m) \ ((m) == OSSL_QUIC_client_method() || \ (m) == OSSL_QUIC_client_thread_method()) # define IS_QUIC_CTX(ctx) IS_QUIC_METHOD((ctx)->method) # define QUIC_CONNECTION_FROM_SSL_int(ssl, c) \ ((ssl) == NULL ? NULL \ : ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \ ? (c QUIC_CONNECTION *)(ssl) \ : NULL)) # define QUIC_XSO_FROM_SSL_int(ssl, c) \ ((ssl) == NULL \ ? NULL \ : (((ssl)->type == SSL_TYPE_QUIC_XSO \ ? (c QUIC_XSO *)(ssl) \ : ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \ ? (c QUIC_XSO *)((QUIC_CONNECTION *)(ssl))->default_xso \ : NULL)))) # define SSL_CONNECTION_FROM_QUIC_SSL_int(ssl, c) \ ((ssl) == NULL ? NULL \ : ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \ ? (c SSL_CONNECTION *)((c QUIC_CONNECTION *)(ssl))->tls \ : NULL)) # define IS_QUIC(ssl) ((ssl) != NULL \ && ((ssl)->type == SSL_TYPE_QUIC_CONNECTION \ || (ssl)->type == SSL_TYPE_QUIC_XSO)) # else # define QUIC_CONNECTION_FROM_SSL_int(ssl, c) NULL # define QUIC_XSO_FROM_SSL_int(ssl, c) NULL # define SSL_CONNECTION_FROM_QUIC_SSL_int(ssl, c) NULL # define IS_QUIC(ssl) 0 # define IS_QUIC_CTX(ctx) 0 # define IS_QUIC_METHOD(m) 0 # endif # define QUIC_CONNECTION_FROM_SSL(ssl) \ QUIC_CONNECTION_FROM_SSL_int(ssl, SSL_CONNECTION_NO_CONST) # define QUIC_CONNECTION_FROM_CONST_SSL(ssl) \ QUIC_CONNECTION_FROM_SSL_int(ssl, const) # define QUIC_XSO_FROM_SSL(ssl) \ QUIC_XSO_FROM_SSL_int(ssl, SSL_CONNECTION_NO_CONST) # define QUIC_XSO_FROM_CONST_SSL(ssl) \ QUIC_XSO_FROM_SSL_int(ssl, const) # define SSL_CONNECTION_FROM_QUIC_SSL(ssl) \ SSL_CONNECTION_FROM_QUIC_SSL_int(ssl, SSL_CONNECTION_NO_CONST) # define SSL_CONNECTION_FROM_CONST_QUIC_SSL(ssl) \ SSL_CONNECTION_FROM_CONST_QUIC_SSL_int(ssl, const) # define IMPLEMENT_quic_meth_func(version, func_name, q_accept, \ q_connect, enc_data) \ const SSL_METHOD *func_name(void) \ { \ static const SSL_METHOD func_name##_data= { \ version, \ 0, \ 0, \ ossl_quic_new, \ ossl_quic_free, \ ossl_quic_reset, \ ossl_quic_init, \ NULL /* clear */, \ ossl_quic_deinit, \ q_accept, \ q_connect, \ ossl_quic_read, \ ossl_quic_peek, \ ossl_quic_write, \ NULL /* shutdown */, \ NULL /* renegotiate */, \ ossl_quic_renegotiate_check, \ NULL /* read_bytes */, \ NULL /* write_bytes */, \ NULL /* dispatch_alert */, \ ossl_quic_ctrl, \ ossl_quic_ctx_ctrl, \ ossl_quic_get_cipher_by_char, \ NULL /* put_cipher_by_char */, \ ossl_quic_pending, \ ossl_quic_num_ciphers, \ ossl_quic_get_cipher, \ tls1_default_timeout, \ &enc_data, \ ssl_undefined_void_function, \ ossl_quic_callback_ctrl, \ ossl_quic_ctx_callback_ctrl, \ }; \ return &func_name##_data; \ } #endif
./openssl/ssl/quic/quic_record_shared.c
#include "quic_record_shared.h" #include "internal/quic_record_util.h" #include "internal/common.h" #include "../ssl_local.h" /* Constants used for key derivation in QUIC v1. */ static const unsigned char quic_v1_iv_label[] = { 0x71, 0x75, 0x69, 0x63, 0x20, 0x69, 0x76 /* "quic iv" */ }; static const unsigned char quic_v1_key_label[] = { 0x71, 0x75, 0x69, 0x63, 0x20, 0x6b, 0x65, 0x79 /* "quic key" */ }; static const unsigned char quic_v1_hp_label[] = { 0x71, 0x75, 0x69, 0x63, 0x20, 0x68, 0x70 /* "quic hp" */ }; static const unsigned char quic_v1_ku_label[] = { 0x71, 0x75, 0x69, 0x63, 0x20, 0x6b, 0x75 /* "quic ku" */ }; OSSL_QRL_ENC_LEVEL *ossl_qrl_enc_level_set_get(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level, int require_prov) { OSSL_QRL_ENC_LEVEL *el; if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_NUM)) return NULL; el = &els->el[enc_level]; if (require_prov) switch (el->state) { case QRL_EL_STATE_PROV_NORMAL: case QRL_EL_STATE_PROV_UPDATING: case QRL_EL_STATE_PROV_COOLDOWN: break; default: return NULL; } return el; } int ossl_qrl_enc_level_set_have_el(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); switch (el->state) { case QRL_EL_STATE_UNPROV: return 0; case QRL_EL_STATE_PROV_NORMAL: case QRL_EL_STATE_PROV_UPDATING: case QRL_EL_STATE_PROV_COOLDOWN: return 1; default: case QRL_EL_STATE_DISCARDED: return -1; } } int ossl_qrl_enc_level_set_has_keyslot(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level, unsigned char tgt_state, size_t keyslot) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); if (!ossl_assert(el != NULL && keyslot < 2)) return 0; switch (tgt_state) { case QRL_EL_STATE_PROV_NORMAL: case QRL_EL_STATE_PROV_UPDATING: return enc_level == QUIC_ENC_LEVEL_1RTT || keyslot == 0; case QRL_EL_STATE_PROV_COOLDOWN: assert(enc_level == QUIC_ENC_LEVEL_1RTT); return keyslot == (el->key_epoch & 1); default: return 0; } } static void el_teardown_keyslot(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level, size_t keyslot) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); if (!ossl_qrl_enc_level_set_has_keyslot(els, enc_level, el->state, keyslot)) return; if (el->cctx[keyslot] != NULL) { EVP_CIPHER_CTX_free(el->cctx[keyslot]); el->cctx[keyslot] = NULL; } OPENSSL_cleanse(el->iv[keyslot], sizeof(el->iv[keyslot])); } static int el_setup_keyslot(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level, unsigned char tgt_state, size_t keyslot, const unsigned char *secret, size_t secret_len) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); unsigned char key[EVP_MAX_KEY_LENGTH]; size_t key_len = 0, iv_len = 0; const char *cipher_name = NULL; EVP_CIPHER *cipher = NULL; EVP_CIPHER_CTX *cctx = NULL; if (!ossl_assert(el != NULL && ossl_qrl_enc_level_set_has_keyslot(els, enc_level, tgt_state, keyslot))) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } cipher_name = ossl_qrl_get_suite_cipher_name(el->suite_id); iv_len = ossl_qrl_get_suite_cipher_iv_len(el->suite_id); key_len = ossl_qrl_get_suite_cipher_key_len(el->suite_id); if (cipher_name == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } if (secret_len != ossl_qrl_get_suite_secret_len(el->suite_id) || secret_len > EVP_MAX_KEY_LENGTH) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } assert(el->cctx[keyslot] == NULL); /* Derive "quic iv" key. */ if (!tls13_hkdf_expand_ex(el->libctx, el->propq, el->md, secret, quic_v1_iv_label, sizeof(quic_v1_iv_label), NULL, 0, el->iv[keyslot], iv_len, 1)) goto err; /* Derive "quic key" key. */ if (!tls13_hkdf_expand_ex(el->libctx, el->propq, el->md, secret, quic_v1_key_label, sizeof(quic_v1_key_label), NULL, 0, key, key_len, 1)) goto err; /* Create and initialise cipher context. */ if ((cipher = EVP_CIPHER_fetch(el->libctx, cipher_name, el->propq)) == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); goto err; } if ((cctx = EVP_CIPHER_CTX_new()) == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); goto err; } if (!ossl_assert(iv_len == (size_t)EVP_CIPHER_get_iv_length(cipher)) || !ossl_assert(key_len == (size_t)EVP_CIPHER_get_key_length(cipher))) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); goto err; } /* IV will be changed on RX/TX so we don't need to use a real value here. */ if (!EVP_CipherInit_ex(cctx, cipher, NULL, key, el->iv[keyslot], 0)) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); goto err; } el->cctx[keyslot] = cctx; /* Zeroize intermediate keys. */ OPENSSL_cleanse(key, sizeof(key)); EVP_CIPHER_free(cipher); return 1; err: EVP_CIPHER_CTX_free(cctx); EVP_CIPHER_free(cipher); OPENSSL_cleanse(el->iv[keyslot], sizeof(el->iv[keyslot])); OPENSSL_cleanse(key, sizeof(key)); return 0; } int ossl_qrl_enc_level_set_provide_secret(OSSL_QRL_ENC_LEVEL_SET *els, OSSL_LIB_CTX *libctx, const char *propq, uint32_t enc_level, uint32_t suite_id, EVP_MD *md, const unsigned char *secret, size_t secret_len, unsigned char init_key_phase_bit, int is_tx) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); unsigned char ku_key[EVP_MAX_KEY_LENGTH], hpr_key[EVP_MAX_KEY_LENGTH]; int have_ks0 = 0, have_ks1 = 0, own_md = 0; const char *md_name = ossl_qrl_get_suite_md_name(suite_id); size_t hpr_key_len, init_keyslot; if (el == NULL || md_name == NULL || init_key_phase_bit > 1 || is_tx < 0 || is_tx > 1 || (init_key_phase_bit > 0 && enc_level != QUIC_ENC_LEVEL_1RTT)) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (enc_level == QUIC_ENC_LEVEL_INITIAL && el->state == QRL_EL_STATE_PROV_NORMAL) { /* * Sometimes the INITIAL EL needs to be reprovisioned, namely if a * connection retry occurs. Exceptionally, if the caller wants to * reprovision the INITIAL EL, tear it down as usual and then override * the state so it can be provisioned again. */ ossl_qrl_enc_level_set_discard(els, enc_level); el->state = QRL_EL_STATE_UNPROV; } if (el->state != QRL_EL_STATE_UNPROV) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } init_keyslot = is_tx ? 0 : init_key_phase_bit; hpr_key_len = ossl_qrl_get_suite_hdr_prot_key_len(suite_id); if (hpr_key_len == 0) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } if (md == NULL) { md = EVP_MD_fetch(libctx, md_name, propq); if (md == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); return 0; } own_md = 1; } el->libctx = libctx; el->propq = propq; el->md = md; el->suite_id = suite_id; el->tag_len = ossl_qrl_get_suite_cipher_tag_len(suite_id); el->op_count = 0; el->key_epoch = (uint64_t)init_key_phase_bit; el->is_tx = (unsigned char)is_tx; /* Derive "quic hp" key. */ if (!tls13_hkdf_expand_ex(libctx, propq, md, secret, quic_v1_hp_label, sizeof(quic_v1_hp_label), NULL, 0, hpr_key, hpr_key_len, 1)) goto err; /* Setup KS0 (or KS1 if init_key_phase_bit), our initial keyslot. */ if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL, init_keyslot, secret, secret_len)) goto err; have_ks0 = 1; if (enc_level == QUIC_ENC_LEVEL_1RTT) { /* Derive "quic ku" key (the epoch 1 secret). */ if (!tls13_hkdf_expand_ex(libctx, propq, md, secret, quic_v1_ku_label, sizeof(quic_v1_ku_label), NULL, 0, is_tx ? el->ku : ku_key, secret_len, 1)) goto err; if (!is_tx) { /* Setup KS1 (or KS0 if init_key_phase_bit), our next keyslot. */ if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL, !init_keyslot, ku_key, secret_len)) goto err; have_ks1 = 1; /* Derive NEXT "quic ku" key (the epoch 2 secret). */ if (!tls13_hkdf_expand_ex(libctx, propq, md, ku_key, quic_v1_ku_label, sizeof(quic_v1_ku_label), NULL, 0, el->ku, secret_len, 1)) goto err; } } /* Setup header protection context. */ if (!ossl_quic_hdr_protector_init(&el->hpr, libctx, propq, ossl_qrl_get_suite_hdr_prot_cipher_id(suite_id), hpr_key, hpr_key_len)) goto err; /* * We are now provisioned: KS0 has our current key (for key epoch 0), KS1 * has our next key (for key epoch 1, in the case of the 1-RTT EL only), and * el->ku has the secret which will be used to generate keys for key epoch * 2. */ OPENSSL_cleanse(hpr_key, sizeof(hpr_key)); OPENSSL_cleanse(ku_key, sizeof(ku_key)); el->state = QRL_EL_STATE_PROV_NORMAL; return 1; err: el->suite_id = 0; el->md = NULL; OPENSSL_cleanse(hpr_key, sizeof(hpr_key)); OPENSSL_cleanse(ku_key, sizeof(ku_key)); OPENSSL_cleanse(el->ku, sizeof(el->ku)); if (have_ks0) el_teardown_keyslot(els, enc_level, init_keyslot); if (have_ks1) el_teardown_keyslot(els, enc_level, !init_keyslot); if (own_md) EVP_MD_free(md); return 0; } int ossl_qrl_enc_level_set_key_update(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); size_t secret_len; unsigned char new_ku[EVP_MAX_KEY_LENGTH]; if (el == NULL || !ossl_assert(enc_level == QUIC_ENC_LEVEL_1RTT)) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (el->state != QRL_EL_STATE_PROV_NORMAL) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } if (!el->is_tx) { /* * We already have the key for the next epoch, so just move to using it. */ ++el->key_epoch; el->state = QRL_EL_STATE_PROV_UPDATING; return 1; } /* * TX case. For the TX side we use only keyslot 0; it replaces the old key * immediately. */ secret_len = ossl_qrl_get_suite_secret_len(el->suite_id); /* Derive NEXT "quic ku" key (the epoch n+1 secret). */ if (!tls13_hkdf_expand_ex(el->libctx, el->propq, el->md, el->ku, quic_v1_ku_label, sizeof(quic_v1_ku_label), NULL, 0, new_ku, secret_len, 1)) return 0; el_teardown_keyslot(els, enc_level, 0); /* Setup keyslot for CURRENT "quic ku" key. */ if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL, 0, el->ku, secret_len)) return 0; ++el->key_epoch; el->op_count = 0; memcpy(el->ku, new_ku, secret_len); /* Remain in PROV_NORMAL state */ return 1; } /* Transitions from PROV_UPDATING to PROV_COOLDOWN. */ int ossl_qrl_enc_level_set_key_update_done(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); if (el == NULL || !ossl_assert(enc_level == QUIC_ENC_LEVEL_1RTT)) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* No new key yet, but erase key material to aid PFS. */ el_teardown_keyslot(els, enc_level, ~el->key_epoch & 1); el->state = QRL_EL_STATE_PROV_COOLDOWN; return 1; } /* * Transitions from PROV_COOLDOWN to PROV_NORMAL. (If in PROV_UPDATING, * auto-transitions to PROV_COOLDOWN first.) */ int ossl_qrl_enc_level_set_key_cooldown_done(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); size_t secret_len; unsigned char new_ku[EVP_MAX_KEY_LENGTH]; if (el == NULL || !ossl_assert(enc_level == QUIC_ENC_LEVEL_1RTT)) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (el->state == QRL_EL_STATE_PROV_UPDATING && !ossl_qrl_enc_level_set_key_update_done(els, enc_level)) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } if (el->state != QRL_EL_STATE_PROV_COOLDOWN) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } secret_len = ossl_qrl_get_suite_secret_len(el->suite_id); if (!el_setup_keyslot(els, enc_level, QRL_EL_STATE_PROV_NORMAL, ~el->key_epoch & 1, el->ku, secret_len)) return 0; /* Derive NEXT "quic ku" key (the epoch n+1 secret). */ if (!tls13_hkdf_expand_ex(el->libctx, el->propq, el->md, el->ku, quic_v1_ku_label, sizeof(quic_v1_ku_label), NULL, 0, new_ku, secret_len, 1)) { el_teardown_keyslot(els, enc_level, ~el->key_epoch & 1); return 0; } memcpy(el->ku, new_ku, secret_len); el->state = QRL_EL_STATE_PROV_NORMAL; return 1; } /* * Discards keying material for a given encryption level. Transitions from any * state to DISCARDED. */ void ossl_qrl_enc_level_set_discard(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(els, enc_level, 0); if (el == NULL || el->state == QRL_EL_STATE_DISCARDED) return; if (ossl_qrl_enc_level_set_have_el(els, enc_level) == 1) { ossl_quic_hdr_protector_cleanup(&el->hpr); el_teardown_keyslot(els, enc_level, 0); el_teardown_keyslot(els, enc_level, 1); } EVP_MD_free(el->md); el->md = NULL; el->state = QRL_EL_STATE_DISCARDED; }
./openssl/ssl/quic/quic_statm.c
/* * 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 "internal/quic_statm.h" void ossl_statm_update_rtt(OSSL_STATM *statm, OSSL_TIME ack_delay, OSSL_TIME override_latest_rtt) { OSSL_TIME adjusted_rtt, latest_rtt = override_latest_rtt; /* Use provided RTT value, or else last RTT value. */ if (ossl_time_is_zero(latest_rtt)) latest_rtt = statm->latest_rtt; else statm->latest_rtt = latest_rtt; if (!statm->have_first_sample) { statm->min_rtt = latest_rtt; statm->smoothed_rtt = latest_rtt; statm->rtt_variance = ossl_time_divide(latest_rtt, 2); statm->have_first_sample = 1; return; } /* Update minimum RTT. */ if (ossl_time_compare(latest_rtt, statm->min_rtt) < 0) statm->min_rtt = latest_rtt; /* * Enforcement of max_ack_delay is the responsibility of * the caller as it is context-dependent. */ adjusted_rtt = latest_rtt; if (ossl_time_compare(latest_rtt, ossl_time_add(statm->min_rtt, ack_delay)) >= 0) adjusted_rtt = ossl_time_subtract(latest_rtt, ack_delay); statm->rtt_variance = ossl_time_divide(ossl_time_add(ossl_time_multiply(statm->rtt_variance, 3), ossl_time_abs_difference(statm->smoothed_rtt, adjusted_rtt)), 4); statm->smoothed_rtt = ossl_time_divide(ossl_time_add(ossl_time_multiply(statm->smoothed_rtt, 7), adjusted_rtt), 8); } /* RFC 9002 kInitialRtt value. RFC recommended value. */ #define K_INITIAL_RTT ossl_ms2time(333) int ossl_statm_init(OSSL_STATM *statm) { statm->smoothed_rtt = K_INITIAL_RTT; statm->latest_rtt = ossl_time_zero(); statm->min_rtt = ossl_time_infinite(); statm->rtt_variance = ossl_time_divide(K_INITIAL_RTT, 2); statm->have_first_sample = 0; return 1; } void ossl_statm_destroy(OSSL_STATM *statm) { /* No-op. */ } void ossl_statm_get_rtt_info(OSSL_STATM *statm, OSSL_RTT_INFO *rtt_info) { rtt_info->min_rtt = statm->min_rtt; rtt_info->latest_rtt = statm->latest_rtt; rtt_info->smoothed_rtt = statm->smoothed_rtt; rtt_info->rtt_variance = statm->rtt_variance; }
./openssl/ssl/quic/quic_engine.c
/* * 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 "internal/quic_engine.h" #include "internal/quic_port.h" #include "quic_engine_local.h" #include "quic_port_local.h" #include "../ssl_local.h" /* * QUIC Engine * =========== */ static int qeng_init(QUIC_ENGINE *qeng); static void qeng_cleanup(QUIC_ENGINE *qeng); static void qeng_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags); DEFINE_LIST_OF_IMPL(port, QUIC_PORT); QUIC_ENGINE *ossl_quic_engine_new(const QUIC_ENGINE_ARGS *args) { QUIC_ENGINE *qeng; if ((qeng = OPENSSL_zalloc(sizeof(QUIC_ENGINE))) == NULL) return NULL; qeng->libctx = args->libctx; qeng->propq = args->propq; qeng->mutex = args->mutex; qeng->now_cb = args->now_cb; qeng->now_cb_arg = args->now_cb_arg; if (!qeng_init(qeng)) { OPENSSL_free(qeng); return NULL; } return qeng; } void ossl_quic_engine_free(QUIC_ENGINE *qeng) { if (qeng == NULL) return; qeng_cleanup(qeng); OPENSSL_free(qeng); } static int qeng_init(QUIC_ENGINE *qeng) { ossl_quic_reactor_init(&qeng->rtor, qeng_tick, qeng, ossl_time_zero()); return 1; } static void qeng_cleanup(QUIC_ENGINE *qeng) { assert(ossl_list_port_num(&qeng->port_list) == 0); } QUIC_REACTOR *ossl_quic_engine_get0_reactor(QUIC_ENGINE *qeng) { return &qeng->rtor; } CRYPTO_MUTEX *ossl_quic_engine_get0_mutex(QUIC_ENGINE *qeng) { return qeng->mutex; } OSSL_TIME ossl_quic_engine_get_time(QUIC_ENGINE *qeng) { if (qeng->now_cb == NULL) return ossl_time_now(); return qeng->now_cb(qeng->now_cb_arg); } void ossl_quic_engine_set_inhibit_tick(QUIC_ENGINE *qeng, int inhibit) { qeng->inhibit_tick = (inhibit != 0); } /* * QUIC Engine: Child Object Lifecycle Management * ============================================== */ QUIC_PORT *ossl_quic_engine_create_port(QUIC_ENGINE *qeng, const QUIC_PORT_ARGS *args) { QUIC_PORT_ARGS largs = *args; if (ossl_list_port_num(&qeng->port_list) > 0) /* TODO(QUIC MULTIPORT): We currently support only one port. */ return NULL; if (largs.engine != NULL) return NULL; largs.engine = qeng; return ossl_quic_port_new(&largs); } /* * QUIC Engine: Ticker-Mutator * ========================== */ /* * The central ticker function called by the reactor. This does everything, or * at least everything network I/O related. Best effort - not allowed to fail * "loudly". */ static void qeng_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags) { QUIC_ENGINE *qeng = arg; QUIC_PORT *port; res->net_read_desired = 0; res->net_write_desired = 0; res->tick_deadline = ossl_time_infinite(); if (qeng->inhibit_tick) return; /* Iterate through all ports and service them. */ LIST_FOREACH(port, port, &qeng->port_list) { QUIC_TICK_RESULT subr = {0}; ossl_quic_port_subtick(port, &subr, flags); ossl_quic_tick_result_merge_into(res, &subr); } }
./openssl/ssl/quic/quic_port.c
/* * 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 "internal/quic_port.h" #include "internal/quic_channel.h" #include "internal/quic_lcidm.h" #include "internal/quic_srtm.h" #include "quic_port_local.h" #include "quic_channel_local.h" #include "quic_engine_local.h" #include "../ssl_local.h" /* * QUIC Port Structure * =================== */ #define INIT_DCID_LEN 8 static int port_init(QUIC_PORT *port); static void port_cleanup(QUIC_PORT *port); static OSSL_TIME get_time(void *arg); static void port_default_packet_handler(QUIC_URXE *e, void *arg, const QUIC_CONN_ID *dcid); static void port_rx_pre(QUIC_PORT *port); DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL); DEFINE_LIST_OF_IMPL(port, QUIC_PORT); QUIC_PORT *ossl_quic_port_new(const QUIC_PORT_ARGS *args) { QUIC_PORT *port; if ((port = OPENSSL_zalloc(sizeof(QUIC_PORT))) == NULL) return NULL; port->engine = args->engine; port->channel_ctx = args->channel_ctx; port->is_multi_conn = args->is_multi_conn; if (!port_init(port)) { OPENSSL_free(port); return NULL; } return port; } void ossl_quic_port_free(QUIC_PORT *port) { if (port == NULL) return; port_cleanup(port); OPENSSL_free(port); } static int port_init(QUIC_PORT *port) { size_t rx_short_dcid_len = (port->is_multi_conn ? INIT_DCID_LEN : 0); if (port->engine == NULL || port->channel_ctx == NULL) goto err; if ((port->err_state = OSSL_ERR_STATE_new()) == NULL) goto err; if ((port->demux = ossl_quic_demux_new(/*BIO=*/NULL, /*Short CID Len=*/rx_short_dcid_len, get_time, port)) == NULL) goto err; ossl_quic_demux_set_default_handler(port->demux, port_default_packet_handler, port); if ((port->srtm = ossl_quic_srtm_new(port->engine->libctx, port->engine->propq)) == NULL) goto err; if ((port->lcidm = ossl_quic_lcidm_new(port->engine->libctx, rx_short_dcid_len)) == NULL) goto err; port->rx_short_dcid_len = (unsigned char)rx_short_dcid_len; port->tx_init_dcid_len = INIT_DCID_LEN; port->state = QUIC_PORT_STATE_RUNNING; ossl_list_port_insert_tail(&port->engine->port_list, port); port->on_engine_list = 1; return 1; err: port_cleanup(port); return 0; } static void port_cleanup(QUIC_PORT *port) { assert(ossl_list_ch_num(&port->channel_list) == 0); ossl_quic_demux_free(port->demux); port->demux = NULL; ossl_quic_srtm_free(port->srtm); port->srtm = NULL; ossl_quic_lcidm_free(port->lcidm); port->lcidm = NULL; OSSL_ERR_STATE_free(port->err_state); port->err_state = NULL; if (port->on_engine_list) { ossl_list_port_remove(&port->engine->port_list, port); port->on_engine_list = 0; } } static void port_transition_failed(QUIC_PORT *port) { if (port->state == QUIC_PORT_STATE_FAILED) return; port->state = QUIC_PORT_STATE_FAILED; } int ossl_quic_port_is_running(const QUIC_PORT *port) { return port->state == QUIC_PORT_STATE_RUNNING; } QUIC_ENGINE *ossl_quic_port_get0_engine(QUIC_PORT *port) { return port->engine; } QUIC_REACTOR *ossl_quic_port_get0_reactor(QUIC_PORT *port) { return ossl_quic_engine_get0_reactor(port->engine); } QUIC_DEMUX *ossl_quic_port_get0_demux(QUIC_PORT *port) { return port->demux; } CRYPTO_MUTEX *ossl_quic_port_get0_mutex(QUIC_PORT *port) { return ossl_quic_engine_get0_mutex(port->engine); } OSSL_TIME ossl_quic_port_get_time(QUIC_PORT *port) { return ossl_quic_engine_get_time(port->engine); } static OSSL_TIME get_time(void *port) { return ossl_quic_port_get_time((QUIC_PORT *)port); } int ossl_quic_port_get_rx_short_dcid_len(const QUIC_PORT *port) { return port->rx_short_dcid_len; } int ossl_quic_port_get_tx_init_dcid_len(const QUIC_PORT *port) { return port->tx_init_dcid_len; } /* * QUIC Port: Network BIO Configuration * ==================================== */ /* Determines whether we can support a given poll descriptor. */ static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d) { if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } return 1; } BIO *ossl_quic_port_get_net_rbio(QUIC_PORT *port) { return port->net_rbio; } BIO *ossl_quic_port_get_net_wbio(QUIC_PORT *port) { return port->net_wbio; } static int port_update_poll_desc(QUIC_PORT *port, BIO *net_bio, int for_write) { BIO_POLL_DESCRIPTOR d = {0}; if (net_bio == NULL || (!for_write && !BIO_get_rpoll_descriptor(net_bio, &d)) || (for_write && !BIO_get_wpoll_descriptor(net_bio, &d))) /* Non-pollable BIO */ d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE; if (!validate_poll_descriptor(&d)) return 0; /* * TODO(QUIC MULTIPORT): We currently only support one port per * engine/domain. This is necessitated because QUIC_REACTOR only supports a * single pollable currently. In the future, once complete polling * infrastructure has been implemented, this limitation can be removed. * * For now, just update the descriptor on the the engine's reactor as we are * guaranteed to be the only port under it. */ if (for_write) ossl_quic_reactor_set_poll_w(&port->engine->rtor, &d); else ossl_quic_reactor_set_poll_r(&port->engine->rtor, &d); return 1; } int ossl_quic_port_update_poll_descriptors(QUIC_PORT *port) { int ok = 1; if (!port_update_poll_desc(port, port->net_rbio, /*for_write=*/0)) ok = 0; if (!port_update_poll_desc(port, port->net_wbio, /*for_write=*/1)) ok = 0; return ok; } /* * QUIC_PORT does not ref any BIO it is provided with, nor is any ref * transferred to it. The caller (e.g., QUIC_CONNECTION) is responsible for * ensuring the BIO lasts until the channel is freed or the BIO is switched out * for another BIO by a subsequent successful call to this function. */ int ossl_quic_port_set_net_rbio(QUIC_PORT *port, BIO *net_rbio) { if (port->net_rbio == net_rbio) return 1; if (!port_update_poll_desc(port, net_rbio, /*for_write=*/0)) return 0; ossl_quic_demux_set_bio(port->demux, net_rbio); port->net_rbio = net_rbio; return 1; } int ossl_quic_port_set_net_wbio(QUIC_PORT *port, BIO *net_wbio) { QUIC_CHANNEL *ch; if (port->net_wbio == net_wbio) return 1; if (!port_update_poll_desc(port, net_wbio, /*for_write=*/1)) return 0; LIST_FOREACH(ch, ch, &port->channel_list) ossl_qtx_set_bio(ch->qtx, net_wbio); port->net_wbio = net_wbio; return 1; } /* * QUIC Port: Channel Lifecycle * ============================ */ static SSL *port_new_handshake_layer(QUIC_PORT *port) { SSL *tls = NULL; SSL_CONNECTION *tls_conn = NULL; tls = ossl_ssl_connection_new_int(port->channel_ctx, TLS_method()); if (tls == NULL || (tls_conn = SSL_CONNECTION_FROM_SSL(tls)) == NULL) return NULL; /* Override the user_ssl of the inner connection. */ tls_conn->s3.flags |= TLS1_FLAGS_QUIC; /* Restrict options derived from the SSL_CTX. */ tls_conn->options &= OSSL_QUIC_PERMITTED_OPTIONS_CONN; tls_conn->pha_enabled = 0; return tls; } static QUIC_CHANNEL *port_make_channel(QUIC_PORT *port, SSL *tls, int is_server) { QUIC_CHANNEL_ARGS args = {0}; QUIC_CHANNEL *ch; args.port = port; args.is_server = is_server; args.tls = (tls != NULL ? tls : port_new_handshake_layer(port)); args.lcidm = port->lcidm; args.srtm = port->srtm; if (args.tls == NULL) return NULL; ch = ossl_quic_channel_new(&args); if (ch == NULL) { if (tls == NULL) SSL_free(args.tls); return NULL; } return ch; } QUIC_CHANNEL *ossl_quic_port_create_outgoing(QUIC_PORT *port, SSL *tls) { return port_make_channel(port, tls, /*is_server=*/0); } QUIC_CHANNEL *ossl_quic_port_create_incoming(QUIC_PORT *port, SSL *tls) { QUIC_CHANNEL *ch; assert(port->tserver_ch == NULL); ch = port_make_channel(port, tls, /*is_server=*/1); port->tserver_ch = ch; port->is_server = 1; return ch; } /* * QUIC Port: Ticker-Mutator * ========================= */ /* * Tick function for this port. This does everything related to network I/O for * this port's network BIOs, and services child channels. */ void ossl_quic_port_subtick(QUIC_PORT *port, QUIC_TICK_RESULT *res, uint32_t flags) { QUIC_CHANNEL *ch; res->net_read_desired = 0; res->net_write_desired = 0; res->tick_deadline = ossl_time_infinite(); if (!port->engine->inhibit_tick) { /* Handle any incoming data from network. */ if (ossl_quic_port_is_running(port)) port_rx_pre(port); /* Iterate through all channels and service them. */ LIST_FOREACH(ch, ch, &port->channel_list) { QUIC_TICK_RESULT subr = {0}; ossl_quic_channel_subtick(ch, &subr, flags); ossl_quic_tick_result_merge_into(res, &subr); } } } /* Process incoming datagrams, if any. */ static void port_rx_pre(QUIC_PORT *port) { int ret; /* * Originally, this check (don't RX before we have sent anything if we are * not a server, because there can't be anything) was just intended as a * minor optimisation. However, it is actually required on Windows, and * removing this check will cause Windows to break. * * The reason is that under Win32, recvfrom() does not work on a UDP socket * which has not had bind() called (???). However, calling sendto() will * automatically bind an unbound UDP socket. Therefore, if we call a Winsock * recv-type function before calling a Winsock send-type function, that call * will fail with WSAEINVAL, which we will regard as a permanent network * error. * * Therefore, this check is essential as we do not require our API users to * bind a socket first when using the API in client mode. */ if (!port->is_server && !port->have_sent_any_pkt) return; /* * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams * to the appropriate QRX instances. */ ret = ossl_quic_demux_pump(port->demux); if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL) /* * We don't care about transient failure, but permanent failure means we * should tear down the port. All connections skip straight to the * Terminated state as there is no point trying to send CONNECTION_CLOSE * frames if the network BIO is not operating correctly. */ ossl_quic_port_raise_net_error(port, NULL); } /* * Handles an incoming connection request and potentially decides to make a * connection from it. If a new connection is made, the new channel is written * to *new_ch. */ static void port_on_new_conn(QUIC_PORT *port, const BIO_ADDR *peer, const QUIC_CONN_ID *scid, const QUIC_CONN_ID *dcid, QUIC_CHANNEL **new_ch) { if (port->tserver_ch != NULL) { /* Specially assign to existing channel */ if (!ossl_quic_channel_on_new_conn(port->tserver_ch, peer, scid, dcid)) return; *new_ch = port->tserver_ch; port->tserver_ch = NULL; return; } } static int port_try_handle_stateless_reset(QUIC_PORT *port, const QUIC_URXE *e) { size_t i; const unsigned char *data = ossl_quic_urxe_data(e); void *opaque = NULL; /* * Perform some fast and cheap checks for a packet not being a stateless * reset token. RFC 9000 s. 10.3 specifies this layout for stateless * reset packets: * * Stateless Reset { * Fixed Bits (2) = 1, * Unpredictable Bits (38..), * Stateless Reset Token (128), * } * * It also specifies: * However, endpoints MUST treat any packet ending in a valid * stateless reset token as a Stateless Reset, as other QUIC * versions might allow the use of a long header. * * We can rapidly check for the minimum length and that the first pair * of bits in the first byte are 01 or 11. * * The function returns 1 if it is a stateless reset packet, 0 if it isn't * and -1 if an error was encountered. */ if (e->data_len < QUIC_STATELESS_RESET_TOKEN_LEN + 5 || (0100 & *data) != 0100) return 0; for (i = 0;; ++i) { if (!ossl_quic_srtm_lookup(port->srtm, (QUIC_STATELESS_RESET_TOKEN *)(data + e->data_len - sizeof(QUIC_STATELESS_RESET_TOKEN)), i, &opaque, NULL)) break; assert(opaque != NULL); ossl_quic_channel_on_stateless_reset((QUIC_CHANNEL *)opaque); } return i > 0; } /* * This is called by the demux when we get a packet not destined for any known * DCID. */ static void port_default_packet_handler(QUIC_URXE *e, void *arg, const QUIC_CONN_ID *dcid) { QUIC_PORT *port = arg; PACKET pkt; QUIC_PKT_HDR hdr; QUIC_CHANNEL *ch = NULL, *new_ch = NULL; /* Don't handle anything if we are no longer running. */ if (!ossl_quic_port_is_running(port)) goto undesirable; if (dcid != NULL && ossl_quic_lcidm_lookup(port->lcidm, dcid, NULL, (void **)&ch)) { assert(ch != NULL); ossl_quic_channel_inject(ch, e); return; } if (port_try_handle_stateless_reset(port, e)) goto undesirable; /* * If we have an incoming packet which doesn't match any existing connection * we assume this is an attempt to make a new connection. Currently we * require our caller to have precreated a latent 'incoming' channel via * TSERVER which then gets turned into the new connection. * * TODO(QUIC SERVER): In the future we will construct channels dynamically * in this case. */ if (port->tserver_ch == NULL) goto undesirable; /* * We have got a packet for an unknown DCID. This might be an attempt to * open a new connection. */ if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN) goto undesirable; if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len)) goto undesirable; /* * We set short_conn_id_len to SIZE_MAX here which will cause the decode * operation to fail if we get a 1-RTT packet. This is fine since we only * care about Initial packets. */ if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, 0, &hdr, NULL)) goto undesirable; switch (hdr.version) { case QUIC_VERSION_1: break; case QUIC_VERSION_NONE: default: /* Unknown version or proactive version negotiation request, bail. */ /* TODO(QUIC SERVER): Handle version negotiation on server side */ goto undesirable; } /* * We only care about Initial packets which might be trying to establish a * connection. */ if (hdr.type != QUIC_PKT_TYPE_INITIAL) goto undesirable; /* * Try to process this as a valid attempt to initiate a connection. * * The channel will do all the LCID registration needed, but as an * optimization inject this packet directly into the channel's QRX for * processing without going through the DEMUX again. */ port_on_new_conn(port, &e->peer, &hdr.src_conn_id, &hdr.dst_conn_id, &new_ch); if (new_ch != NULL) ossl_qrx_inject_urxe(new_ch->qrx, e); return; undesirable: ossl_quic_demux_release_urxe(port->demux, e); } void ossl_quic_port_raise_net_error(QUIC_PORT *port, QUIC_CHANNEL *triggering_ch) { QUIC_CHANNEL *ch; if (!ossl_quic_port_is_running(port)) return; /* * Immediately capture any triggering error on the error stack, with a * cover error. */ ERR_raise_data(ERR_LIB_SSL, SSL_R_QUIC_NETWORK_ERROR, "port failed due to network BIO I/O error"); OSSL_ERR_STATE_save(port->err_state); port_transition_failed(port); /* Give the triggering channel (if any) the first notification. */ if (triggering_ch != NULL) ossl_quic_channel_raise_net_error(triggering_ch); LIST_FOREACH(ch, ch, &port->channel_list) if (ch != triggering_ch) ossl_quic_channel_raise_net_error(ch); } void ossl_quic_port_restore_err_state(const QUIC_PORT *port) { ERR_clear_error(); OSSL_ERR_STATE_restore(port->err_state); }
./openssl/ssl/quic/quic_txp.c
/* * 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 "internal/quic_txp.h" #include "internal/quic_fifd.h" #include "internal/quic_stream_map.h" #include "internal/quic_error.h" #include "internal/common.h" #include <openssl/err.h> #define MIN_CRYPTO_HDR_SIZE 3 #define MIN_FRAME_SIZE_HANDSHAKE_DONE 1 #define MIN_FRAME_SIZE_MAX_DATA 2 #define MIN_FRAME_SIZE_ACK 5 #define MIN_FRAME_SIZE_CRYPTO (MIN_CRYPTO_HDR_SIZE + 1) #define MIN_FRAME_SIZE_STREAM 3 /* minimum useful size (for non-FIN) */ #define MIN_FRAME_SIZE_MAX_STREAMS_BIDI 2 #define MIN_FRAME_SIZE_MAX_STREAMS_UNI 2 /* * Packet Archetypes * ================= */ /* Generate normal packets containing most frame types, subject to EL. */ #define TX_PACKETISER_ARCHETYPE_NORMAL 0 /* * A probe packet is different in that: * - It bypasses CC, but *is* counted as in flight for purposes of CC; * - It must be ACK-eliciting. */ #define TX_PACKETISER_ARCHETYPE_PROBE 1 /* * An ACK-only packet is different in that: * - It bypasses CC, and is considered a 'non-inflight' packet; * - It may not contain anything other than an ACK frame, not even padding. */ #define TX_PACKETISER_ARCHETYPE_ACK_ONLY 2 #define TX_PACKETISER_ARCHETYPE_NUM 3 struct ossl_quic_tx_packetiser_st { OSSL_QUIC_TX_PACKETISER_ARGS args; /* * Opaque initial token blob provided by caller. TXP frees using the * callback when it is no longer needed. */ const unsigned char *initial_token; size_t initial_token_len; ossl_quic_initial_token_free_fn *initial_token_free_cb; void *initial_token_free_cb_arg; /* Subcomponents of the TXP that we own. */ QUIC_FIFD fifd; /* QUIC Frame-in-Flight Dispatcher */ /* Internal state. */ uint64_t next_pn[QUIC_PN_SPACE_NUM]; /* Next PN to use in given PN space. */ OSSL_TIME last_tx_time; /* Last time a packet was generated, or 0. */ /* Internal state - frame (re)generation flags. */ unsigned int want_handshake_done : 1; unsigned int want_max_data : 1; unsigned int want_max_streams_bidi : 1; unsigned int want_max_streams_uni : 1; /* Internal state - frame (re)generation flags - per PN space. */ unsigned int want_ack : QUIC_PN_SPACE_NUM; unsigned int force_ack_eliciting : QUIC_PN_SPACE_NUM; /* * Internal state - connection close terminal state. * Once this is set, it is not unset unlike other want_ flags - we keep * sending it in every packet. */ unsigned int want_conn_close : 1; /* Has the handshake been completed? */ unsigned int handshake_complete : 1; OSSL_QUIC_FRAME_CONN_CLOSE conn_close_frame; /* * Counts of the number of bytes received and sent while in the closing * state. */ uint64_t closing_bytes_recv; uint64_t closing_bytes_xmit; /* Internal state - packet assembly. */ struct txp_el { unsigned char *scratch; /* scratch buffer for packet assembly */ size_t scratch_len; /* number of bytes allocated for scratch */ OSSL_QTX_IOVEC *iovec; /* scratch iovec array for use with QTX */ size_t alloc_iovec; /* size of iovec array */ } el[QUIC_ENC_LEVEL_NUM]; /* Message callback related arguments */ ossl_msg_cb msg_callback; void *msg_callback_arg; SSL *msg_callback_ssl; /* Callbacks. */ void (*ack_tx_cb)(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space, void *arg); void *ack_tx_cb_arg; }; /* * The TX helper records state used while generating frames into packets. It * enables serialization into the packet to be done "transactionally" where * serialization of a frame can be rolled back if it fails midway (e.g. if it * does not fit). */ struct tx_helper { OSSL_QUIC_TX_PACKETISER *txp; /* * The Maximum Packet Payload Length in bytes. This is the amount of * space we have to generate frames into. */ size_t max_ppl; /* * Number of bytes we have generated so far. */ size_t bytes_appended; /* * Number of scratch bytes in txp->scratch we have used so far. Some iovecs * will reference this scratch buffer. When we need to use more of it (e.g. * when we need to put frame headers somewhere), we append to the scratch * buffer, resizing if necessary, and increase this accordingly. */ size_t scratch_bytes; /* * Bytes reserved in the MaxPPL budget. We keep this number of bytes spare * until reserve_allowed is set to 1. Currently this is always at most 1, as * a PING frame takes up one byte and this mechanism is only used to ensure * we can encode a PING frame if we have been asked to ensure a packet is * ACK-eliciting and we are unusure if we are going to add any other * ACK-eliciting frames before we reach our MaxPPL budget. */ size_t reserve; /* * Number of iovecs we have currently appended. This is the number of * entries valid in txp->iovec. */ size_t num_iovec; /* The EL this TX helper is being used for. */ uint32_t enc_level; /* * Whether we are allowed to make use of the reserve bytes in our MaxPPL * budget. This is used to ensure we have room to append a PING frame later * if we need to. Once we know we will not need to append a PING frame, this * is set to 1. */ unsigned int reserve_allowed : 1; /* * Set to 1 if we have appended a STREAM frame with an implicit length. If * this happens we should never append another frame after that frame as it * cannot be validly encoded. This is just a safety check. */ unsigned int done_implicit : 1; struct { /* * The fields in this structure are valid if active is set, which means * that a serialization transaction is currently in progress. */ unsigned char *data; WPACKET wpkt; unsigned int active : 1; } txn; }; static void tx_helper_rollback(struct tx_helper *h); static int txp_el_ensure_iovec(struct txp_el *el, size_t num); /* Initialises the TX helper. */ static int tx_helper_init(struct tx_helper *h, OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level, size_t max_ppl, size_t reserve) { if (reserve > max_ppl) return 0; h->txp = txp; h->enc_level = enc_level; h->max_ppl = max_ppl; h->reserve = reserve; h->num_iovec = 0; h->bytes_appended = 0; h->scratch_bytes = 0; h->reserve_allowed = 0; h->done_implicit = 0; h->txn.data = NULL; h->txn.active = 0; if (max_ppl > h->txp->el[enc_level].scratch_len) { unsigned char *scratch; scratch = OPENSSL_realloc(h->txp->el[enc_level].scratch, max_ppl); if (scratch == NULL) return 0; h->txp->el[enc_level].scratch = scratch; h->txp->el[enc_level].scratch_len = max_ppl; } return 1; } static void tx_helper_cleanup(struct tx_helper *h) { if (h->txn.active) tx_helper_rollback(h); h->txp = NULL; } static void tx_helper_unrestrict(struct tx_helper *h) { h->reserve_allowed = 1; } /* * Append an extent of memory to the iovec list. The memory must remain * allocated until we finish generating the packet and call the QTX. * * In general, the buffers passed to this function will be from one of two * ranges: * * - Application data contained in stream buffers managed elsewhere * in the QUIC stack; or * * - Control frame data appended into txp->scratch using tx_helper_begin and * tx_helper_commit. * */ static int tx_helper_append_iovec(struct tx_helper *h, const unsigned char *buf, size_t buf_len) { struct txp_el *el = &h->txp->el[h->enc_level]; if (buf_len == 0) return 1; if (!ossl_assert(!h->done_implicit)) return 0; if (!txp_el_ensure_iovec(el, h->num_iovec + 1)) return 0; el->iovec[h->num_iovec].buf = buf; el->iovec[h->num_iovec].buf_len = buf_len; ++h->num_iovec; h->bytes_appended += buf_len; return 1; } /* * How many more bytes of space do we have left in our plaintext packet payload? */ static size_t tx_helper_get_space_left(struct tx_helper *h) { return h->max_ppl - (h->reserve_allowed ? 0 : h->reserve) - h->bytes_appended; } /* * Begin a control frame serialization transaction. This allows the * serialization of the control frame to be backed out if it turns out it won't * fit. Write the control frame to the returned WPACKET. Ensure you always * call tx_helper_rollback or tx_helper_commit (or tx_helper_cleanup). Returns * NULL on failure. */ static WPACKET *tx_helper_begin(struct tx_helper *h) { size_t space_left, len; unsigned char *data; struct txp_el *el = &h->txp->el[h->enc_level]; if (!ossl_assert(!h->txn.active)) return NULL; if (!ossl_assert(!h->done_implicit)) return NULL; data = (unsigned char *)el->scratch + h->scratch_bytes; len = el->scratch_len - h->scratch_bytes; space_left = tx_helper_get_space_left(h); if (!ossl_assert(space_left <= len)) return NULL; if (!WPACKET_init_static_len(&h->txn.wpkt, data, len, 0)) return NULL; if (!WPACKET_set_max_size(&h->txn.wpkt, space_left)) { WPACKET_cleanup(&h->txn.wpkt); return NULL; } h->txn.data = data; h->txn.active = 1; return &h->txn.wpkt; } static void tx_helper_end(struct tx_helper *h, int success) { if (success) WPACKET_finish(&h->txn.wpkt); else WPACKET_cleanup(&h->txn.wpkt); h->txn.active = 0; h->txn.data = NULL; } /* Abort a control frame serialization transaction. */ static void tx_helper_rollback(struct tx_helper *h) { if (!h->txn.active) return; tx_helper_end(h, 0); } /* Commit a control frame. */ static int tx_helper_commit(struct tx_helper *h) { size_t l = 0; if (!h->txn.active) return 0; if (!WPACKET_get_total_written(&h->txn.wpkt, &l)) { tx_helper_end(h, 0); return 0; } if (!tx_helper_append_iovec(h, h->txn.data, l)) { tx_helper_end(h, 0); return 0; } if (h->txp->msg_callback != NULL && l > 0) { uint64_t ftype; int ctype = SSL3_RT_QUIC_FRAME_FULL; PACKET pkt; if (!PACKET_buf_init(&pkt, h->txn.data, l) || !ossl_quic_wire_peek_frame_header(&pkt, &ftype, NULL)) { tx_helper_end(h, 0); return 0; } if (ftype == OSSL_QUIC_FRAME_TYPE_PADDING) ctype = SSL3_RT_QUIC_FRAME_PADDING; else if (OSSL_QUIC_FRAME_TYPE_IS_STREAM(ftype) || ftype == OSSL_QUIC_FRAME_TYPE_CRYPTO) ctype = SSL3_RT_QUIC_FRAME_HEADER; h->txp->msg_callback(1, OSSL_QUIC1_VERSION, ctype, h->txn.data, l, h->txp->msg_callback_ssl, h->txp->msg_callback_arg); } h->scratch_bytes += l; tx_helper_end(h, 1); return 1; } struct archetype_data { unsigned int allow_ack : 1; unsigned int allow_ping : 1; unsigned int allow_crypto : 1; unsigned int allow_handshake_done : 1; unsigned int allow_path_challenge : 1; unsigned int allow_path_response : 1; unsigned int allow_new_conn_id : 1; unsigned int allow_retire_conn_id : 1; unsigned int allow_stream_rel : 1; unsigned int allow_conn_fc : 1; unsigned int allow_conn_close : 1; unsigned int allow_cfq_other : 1; unsigned int allow_new_token : 1; unsigned int allow_force_ack_eliciting : 1; unsigned int allow_padding : 1; unsigned int require_ack_eliciting : 1; unsigned int bypass_cc : 1; }; struct txp_pkt_geom { size_t cmpl, cmppl, hwm, pkt_overhead; uint32_t archetype; struct archetype_data adata; }; struct txp_pkt { struct tx_helper h; int h_valid; QUIC_TXPIM_PKT *tpkt; QUIC_STREAM *stream_head; QUIC_PKT_HDR phdr; struct txp_pkt_geom geom; int force_pad; }; static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space, void *arg); static void on_regen_notify(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg); static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg); static void on_sstream_updated(uint64_t stream_id, void *arg); static int sstream_is_pending(QUIC_SSTREAM *sstream); static int txp_should_try_staging(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level, uint32_t archetype, uint64_t cc_limit, uint32_t *conn_close_enc_level); static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp); static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp, size_t pl, uint32_t enc_level, size_t hdr_len, size_t *r); static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp); static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, int chosen_for_conn_close); static int txp_pkt_init(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level, uint32_t archetype, size_t running_total); static void txp_pkt_cleanup(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp); static int txp_pkt_postgen_update_pkt_overhead(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp); static int txp_pkt_append_padding(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp, size_t num_bytes); static int txp_pkt_commit(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, uint32_t archetype, int *txpim_pkt_reffed); static uint32_t txp_determine_archetype(OSSL_QUIC_TX_PACKETISER *txp, uint64_t cc_limit); OSSL_QUIC_TX_PACKETISER *ossl_quic_tx_packetiser_new(const OSSL_QUIC_TX_PACKETISER_ARGS *args) { OSSL_QUIC_TX_PACKETISER *txp; if (args == NULL || args->qtx == NULL || args->txpim == NULL || args->cfq == NULL || args->ackm == NULL || args->qsm == NULL || args->conn_txfc == NULL || args->conn_rxfc == NULL || args->max_streams_bidi_rxfc == NULL || args->max_streams_uni_rxfc == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return NULL; } txp = OPENSSL_zalloc(sizeof(*txp)); if (txp == NULL) return NULL; txp->args = *args; txp->last_tx_time = ossl_time_zero(); if (!ossl_quic_fifd_init(&txp->fifd, txp->args.cfq, txp->args.ackm, txp->args.txpim, get_sstream_by_id, txp, on_regen_notify, txp, on_confirm_notify, txp, on_sstream_updated, txp)) { OPENSSL_free(txp); return NULL; } return txp; } void ossl_quic_tx_packetiser_free(OSSL_QUIC_TX_PACKETISER *txp) { uint32_t enc_level; if (txp == NULL) return; ossl_quic_tx_packetiser_set_initial_token(txp, NULL, 0, NULL, NULL); ossl_quic_fifd_cleanup(&txp->fifd); OPENSSL_free(txp->conn_close_frame.reason); for (enc_level = QUIC_ENC_LEVEL_INITIAL; enc_level < QUIC_ENC_LEVEL_NUM; ++enc_level) { OPENSSL_free(txp->el[enc_level].iovec); OPENSSL_free(txp->el[enc_level].scratch); } OPENSSL_free(txp); } /* * Determine if an Initial packet token length is reasonable based on the * current MDPL, returning 1 if it is OK. * * The real PMTU to the peer could differ from our (pessimistic) understanding * of the PMTU, therefore it is possible we could receive an Initial token from * a server in a Retry packet which is bigger than the MDPL. In this case it is * impossible for us ever to make forward progress and we need to error out * and fail the connection attempt. * * The specific boundary condition is complex: for example, after the size of * the Initial token, there are the Initial packet header overheads and then * encryption/AEAD tag overheads. After that, the minimum room for frame data in * order to guarantee forward progress must be guaranteed. For example, a crypto * stream needs to always be able to serialize at least one byte in a CRYPTO * frame in order to make forward progress. Because the offset field of a CRYPTO * frame uses a variable-length integer, the number of bytes needed to ensure * this also varies. * * Rather than trying to get this boundary condition check actually right, * require a reasonable amount of slack to avoid pathological behaviours. (After * all, transmitting a CRYPTO stream one byte at a time is probably not * desirable anyway.) * * We choose 160 bytes as the required margin, which is double the rough * estimation of the minimum we would require to guarantee forward progress * under worst case packet overheads. */ #define TXP_REQUIRED_TOKEN_MARGIN 160 static int txp_check_token_len(size_t token_len, size_t mdpl) { if (token_len == 0) return 1; if (token_len >= mdpl) return 0; if (TXP_REQUIRED_TOKEN_MARGIN >= mdpl) /* (should not be possible because MDPL must be at least 1200) */ return 0; if (token_len > mdpl - TXP_REQUIRED_TOKEN_MARGIN) return 0; return 1; } 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) { if (!txp_check_token_len(token_len, txp_get_mdpl(txp))) return 0; if (txp->initial_token != NULL && txp->initial_token_free_cb != NULL) txp->initial_token_free_cb(txp->initial_token, txp->initial_token_len, txp->initial_token_free_cb_arg); txp->initial_token = token; txp->initial_token_len = token_len; txp->initial_token_free_cb = free_cb; txp->initial_token_free_cb_arg = free_cb_arg; return 1; } int ossl_quic_tx_packetiser_set_cur_dcid(OSSL_QUIC_TX_PACKETISER *txp, const QUIC_CONN_ID *dcid) { if (dcid == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return 0; } txp->args.cur_dcid = *dcid; return 1; } int ossl_quic_tx_packetiser_set_cur_scid(OSSL_QUIC_TX_PACKETISER *txp, const QUIC_CONN_ID *scid) { if (scid == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER); return 0; } txp->args.cur_scid = *scid; return 1; } /* Change the destination L4 address the TXP uses to send datagrams. */ int ossl_quic_tx_packetiser_set_peer(OSSL_QUIC_TX_PACKETISER *txp, const BIO_ADDR *peer) { if (peer == NULL) { BIO_ADDR_clear(&txp->args.peer); return 1; } txp->args.peer = *peer; return 1; } 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) { txp->ack_tx_cb = cb; txp->ack_tx_cb_arg = cb_arg; } int ossl_quic_tx_packetiser_discard_enc_level(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level) { if (enc_level >= QUIC_ENC_LEVEL_NUM) { ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (enc_level != QUIC_ENC_LEVEL_0RTT) txp->args.crypto[ossl_quic_enc_level_to_pn_space(enc_level)] = NULL; return 1; } void ossl_quic_tx_packetiser_notify_handshake_complete(OSSL_QUIC_TX_PACKETISER *txp) { txp->handshake_complete = 1; } void ossl_quic_tx_packetiser_schedule_handshake_done(OSSL_QUIC_TX_PACKETISER *txp) { txp->want_handshake_done = 1; } void ossl_quic_tx_packetiser_schedule_ack_eliciting(OSSL_QUIC_TX_PACKETISER *txp, uint32_t pn_space) { txp->force_ack_eliciting |= (1UL << pn_space); } void ossl_quic_tx_packetiser_schedule_ack(OSSL_QUIC_TX_PACKETISER *txp, uint32_t pn_space) { txp->want_ack |= (1UL << pn_space); } #define TXP_ERR_INTERNAL 0 /* Internal (e.g. alloc) error */ #define TXP_ERR_SUCCESS 1 /* Success */ #define TXP_ERR_SPACE 2 /* Not enough room for another packet */ #define TXP_ERR_INPUT 3 /* Invalid/malformed input */ /* * 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. */ int ossl_quic_tx_packetiser_generate(OSSL_QUIC_TX_PACKETISER *txp, QUIC_TXP_STATUS *status) { /* * Called to generate one or more datagrams, each containing one or more * packets. * * There are some tricky things to note here: * * - The TXP is only concerned with generating encrypted packets; * other packets use a different path. * * - Any datagram containing an Initial packet must have a payload length * (DPL) of at least 1200 bytes. This padding need not necessarily be * found in the Initial packet. * * - It is desirable to be able to coalesce an Initial packet * with a Handshake packet. Since, before generating the Handshake * packet, we do not know how long it will be, we cannot know the * correct amount of padding to ensure a DPL of at least 1200 bytes. * Thus this padding must added to the Handshake packet (or whatever * packet is the last in the datagram). * * - However, at the time that we generate the Initial packet, * we do not actually know for sure that we will be followed * in the datagram by another packet. For example, suppose we have * some queued data (e.g. crypto stream data for the HANDSHAKE EL) * it looks like we will want to send on the HANDSHAKE EL. * We could assume padding will be placed in the Handshake packet * subsequently and avoid adding any padding to the Initial packet * (which would leave no room for the Handshake packet in the * datagram). * * However, this is not actually a safe assumption. Suppose that we * are using a link with a MDPL of 1200 bytes, the minimum allowed by * QUIC. Suppose that the Initial packet consumes 1195 bytes in total. * Since it is not possible to fit a Handshake packet in just 5 bytes, * upon trying to add a Handshake packet after generating the Initial * packet, we will discover we have no room to fit it! This is not a * problem in itself as another datagram can be sent subsequently, but * it is a problem because we were counting to use that packet to hold * the essential padding. But if we have already finished encrypting * the Initial packet, we cannot go and add padding to it anymore. * This leaves us stuck. * * Because of this, we have to plan multiple packets simultaneously, such * that we can start generating a Handshake (or 0-RTT or 1-RTT, or so on) * packet while still having the option to go back and add padding to the * Initial packet if it turns out to be needed. * * Trying to predict ahead of time (e.g. during Initial packet generation) * whether we will successfully generate a subsequent packet is fraught with * error as it relies on a large number of variables: * * - Do we have room to fit a packet header? (Consider that due to * variable-length integer encoding this is highly variable and can even * depend on payload length due to a variable-length Length field.) * * - Can we fit even a single one of the frames we want to put in this * packet in the packet? (Each frame type has a bespoke encoding. While * our encodings of some frame types are adaptive based on the available * room - e.g. STREAM frames - ultimately all frame types have some * absolute minimum number of bytes to be successfully encoded. For * example, if after an Initial packet there is enough room to encode * only one byte of frame data, it is quite likely we can't send any of * the frames we wanted to send.) While this is not strictly a problem * because we could just fill the packet with padding frames, this is a * pointless packet and is wasteful. * * Thus we adopt a multi-phase architecture: * * 1. Archetype Selection: Determine desired packet archetype. * * 2. Packet Staging: Generation of packet information and packet payload * data (frame data) into staging areas. * * 3. Packet Adjustment: Adjustment of staged packets, adding padding to * the staged packets if needed. * * 4. Commit: The packets are sent to the QTX and recorded as having been * sent to the FIFM. * */ int res = 0, rc; uint32_t archetype, enc_level; uint32_t conn_close_enc_level = QUIC_ENC_LEVEL_NUM; struct txp_pkt pkt[QUIC_ENC_LEVEL_NUM]; size_t pkts_done = 0; uint64_t cc_limit = txp->args.cc_method->get_tx_allowance(txp->args.cc_data); int need_padding = 0, txpim_pkt_reffed; for (enc_level = QUIC_ENC_LEVEL_INITIAL; enc_level < QUIC_ENC_LEVEL_NUM; ++enc_level) pkt[enc_level].h_valid = 0; memset(status, 0, sizeof(*status)); /* * Should not be needed, but a sanity check in case anyone else has been * using the QTX. */ ossl_qtx_finish_dgram(txp->args.qtx); /* 1. Archetype Selection */ archetype = txp_determine_archetype(txp, cc_limit); /* 2. Packet Staging */ for (enc_level = QUIC_ENC_LEVEL_INITIAL; enc_level < QUIC_ENC_LEVEL_NUM; ++enc_level) { size_t running_total = (enc_level > QUIC_ENC_LEVEL_INITIAL) ? pkt[enc_level - 1].geom.hwm : 0; pkt[enc_level].geom.hwm = running_total; if (!txp_should_try_staging(txp, enc_level, archetype, cc_limit, &conn_close_enc_level)) continue; if (!txp_pkt_init(&pkt[enc_level], txp, enc_level, archetype, running_total)) /* * If this fails this is not a fatal error - it means the geometry * planning determined there was not enough space for another * packet. So just proceed with what we've already planned for. */ break; rc = txp_generate_for_el(txp, &pkt[enc_level], conn_close_enc_level == enc_level); if (rc != TXP_ERR_SUCCESS) goto out; if (pkt[enc_level].force_pad) /* * txp_generate_for_el emitted a frame which forces packet padding. */ need_padding = 1; pkt[enc_level].geom.hwm = running_total + pkt[enc_level].h.bytes_appended + pkt[enc_level].geom.pkt_overhead; } /* 3. Packet Adjustment */ if (pkt[QUIC_ENC_LEVEL_INITIAL].h_valid && pkt[QUIC_ENC_LEVEL_INITIAL].h.bytes_appended > 0) /* * We have an Initial packet in this datagram, so we need to make sure * the total size of the datagram is adequate. */ need_padding = 1; if (need_padding) { size_t total_dgram_size = 0; const size_t min_dpl = QUIC_MIN_INITIAL_DGRAM_LEN; uint32_t pad_el = QUIC_ENC_LEVEL_NUM; for (enc_level = QUIC_ENC_LEVEL_INITIAL; enc_level < QUIC_ENC_LEVEL_NUM; ++enc_level) if (pkt[enc_level].h_valid && pkt[enc_level].h.bytes_appended > 0) { if (pad_el == QUIC_ENC_LEVEL_NUM /* * We might not be able to add padding, for example if we * are using the ACK_ONLY archetype. */ && pkt[enc_level].geom.adata.allow_padding && !pkt[enc_level].h.done_implicit) pad_el = enc_level; txp_pkt_postgen_update_pkt_overhead(&pkt[enc_level], txp); total_dgram_size += pkt[enc_level].geom.pkt_overhead + pkt[enc_level].h.bytes_appended; } if (pad_el != QUIC_ENC_LEVEL_NUM && total_dgram_size < min_dpl) { size_t deficit = min_dpl - total_dgram_size; if (!txp_pkt_append_padding(&pkt[pad_el], txp, deficit)) goto out; total_dgram_size += deficit; /* * Padding frames make a packet ineligible for being a non-inflight * packet. */ pkt[pad_el].tpkt->ackm_pkt.is_inflight = 1; } /* * If we have failed to make a datagram of adequate size, for example * because we have a padding requirement but are using the ACK_ONLY * archetype (because we are CC limited), which precludes us from * sending padding, give up on generating the datagram - there is * nothing we can do. */ if (total_dgram_size < min_dpl) { res = 1; goto out; } } /* 4. Commit */ for (enc_level = QUIC_ENC_LEVEL_INITIAL; enc_level < QUIC_ENC_LEVEL_NUM; ++enc_level) { if (!pkt[enc_level].h_valid) /* Did not attempt to generate a packet for this EL. */ continue; if (pkt[enc_level].h.bytes_appended == 0) /* Nothing was generated for this EL, so skip. */ continue; rc = txp_pkt_commit(txp, &pkt[enc_level], archetype, &txpim_pkt_reffed); if (rc) { status->sent_ack_eliciting = status->sent_ack_eliciting || pkt[enc_level].tpkt->ackm_pkt.is_ack_eliciting; if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE) status->sent_handshake = (pkt[enc_level].h_valid && pkt[enc_level].h.bytes_appended > 0); } if (txpim_pkt_reffed) pkt[enc_level].tpkt = NULL; /* don't free */ if (!rc) goto out; ++pkts_done; } /* Flush & Cleanup */ res = 1; out: ossl_qtx_finish_dgram(txp->args.qtx); for (enc_level = QUIC_ENC_LEVEL_INITIAL; enc_level < QUIC_ENC_LEVEL_NUM; ++enc_level) txp_pkt_cleanup(&pkt[enc_level], txp); status->sent_pkt = pkts_done; return res; } static const struct archetype_data archetypes[QUIC_ENC_LEVEL_NUM][TX_PACKETISER_ARCHETYPE_NUM] = { /* EL 0(INITIAL) */ { /* EL 0(INITIAL) - Archetype 0(NORMAL) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 1, /*allow_crypto =*/ 1, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 0, }, /* EL 0(INITIAL) - Archetype 1(PROBE) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 1, /*allow_crypto =*/ 1, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 1, /*bypass_cc =*/ 1, }, /* EL 0(INITIAL) - Archetype 2(ACK_ONLY) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 0, /*allow_crypto =*/ 0, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 0, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 0, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 1, }, }, /* EL 1(HANDSHAKE) */ { /* EL 1(HANDSHAKE) - Archetype 0(NORMAL) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 1, /*allow_crypto =*/ 1, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 0, }, /* EL 1(HANDSHAKE) - Archetype 1(PROBE) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 1, /*allow_crypto =*/ 1, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 1, /*bypass_cc =*/ 1, }, /* EL 1(HANDSHAKE) - Archetype 2(ACK_ONLY) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 0, /*allow_crypto =*/ 0, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 0, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 0, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 1, }, }, /* EL 2(0RTT) */ { /* EL 2(0RTT) - Archetype 0(NORMAL) */ { /*allow_ack =*/ 0, /*allow_ping =*/ 1, /*allow_crypto =*/ 0, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 1, /*allow_retire_conn_id =*/ 1, /*allow_stream_rel =*/ 1, /*allow_conn_fc =*/ 1, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 0, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 0, }, /* EL 2(0RTT) - Archetype 1(PROBE) */ { /*allow_ack =*/ 0, /*allow_ping =*/ 1, /*allow_crypto =*/ 0, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 1, /*allow_retire_conn_id =*/ 1, /*allow_stream_rel =*/ 1, /*allow_conn_fc =*/ 1, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 0, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 1, /*bypass_cc =*/ 1, }, /* EL 2(0RTT) - Archetype 2(ACK_ONLY) */ { /*allow_ack =*/ 0, /*allow_ping =*/ 0, /*allow_crypto =*/ 0, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 0, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 0, /*allow_padding =*/ 0, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 1, }, }, /* EL 3(1RTT) */ { /* EL 3(1RTT) - Archetype 0(NORMAL) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 1, /*allow_crypto =*/ 1, /*allow_handshake_done =*/ 1, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 1, /*allow_new_conn_id =*/ 1, /*allow_retire_conn_id =*/ 1, /*allow_stream_rel =*/ 1, /*allow_conn_fc =*/ 1, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 1, /*allow_new_token =*/ 1, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 0, }, /* EL 3(1RTT) - Archetype 1(PROBE) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 1, /*allow_crypto =*/ 1, /*allow_handshake_done =*/ 1, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 1, /*allow_new_conn_id =*/ 1, /*allow_retire_conn_id =*/ 1, /*allow_stream_rel =*/ 1, /*allow_conn_fc =*/ 1, /*allow_conn_close =*/ 1, /*allow_cfq_other =*/ 1, /*allow_new_token =*/ 1, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 1, /*require_ack_eliciting =*/ 1, /*bypass_cc =*/ 1, }, /* EL 3(1RTT) - Archetype 2(ACK_ONLY) */ { /*allow_ack =*/ 1, /*allow_ping =*/ 0, /*allow_crypto =*/ 0, /*allow_handshake_done =*/ 0, /*allow_path_challenge =*/ 0, /*allow_path_response =*/ 0, /*allow_new_conn_id =*/ 0, /*allow_retire_conn_id =*/ 0, /*allow_stream_rel =*/ 0, /*allow_conn_fc =*/ 0, /*allow_conn_close =*/ 0, /*allow_cfq_other =*/ 0, /*allow_new_token =*/ 0, /*allow_force_ack_eliciting =*/ 1, /*allow_padding =*/ 0, /*require_ack_eliciting =*/ 0, /*bypass_cc =*/ 1, } } }; static int txp_get_archetype_data(uint32_t enc_level, uint32_t archetype, struct archetype_data *a) { if (enc_level >= QUIC_ENC_LEVEL_NUM || archetype >= TX_PACKETISER_ARCHETYPE_NUM) return 0; /* No need to avoid copying this as it should not exceed one int in size. */ *a = archetypes[enc_level][archetype]; return 1; } static int txp_determine_geometry(OSSL_QUIC_TX_PACKETISER *txp, uint32_t archetype, uint32_t enc_level, size_t running_total, QUIC_PKT_HDR *phdr, struct txp_pkt_geom *geom) { size_t mdpl, cmpl, hdr_len; /* Get information about packet archetype. */ if (!txp_get_archetype_data(enc_level, archetype, &geom->adata)) return 0; /* Assemble packet header. */ phdr->type = ossl_quic_enc_level_to_pkt_type(enc_level); phdr->spin_bit = 0; phdr->pn_len = txp_determine_pn_len(txp); phdr->partial = 0; phdr->fixed = 1; phdr->reserved = 0; phdr->version = QUIC_VERSION_1; phdr->dst_conn_id = txp->args.cur_dcid; phdr->src_conn_id = txp->args.cur_scid; /* * We need to know the length of the payload to get an accurate header * length for non-1RTT packets, because the Length field found in * Initial/Handshake/0-RTT packets uses a variable-length encoding. However, * we don't have a good idea of the length of our payload, because the * length of the payload depends on the room in the datagram after fitting * the header, which depends on the size of the header. * * In general, it does not matter if a packet is slightly shorter (because * e.g. we predicted use of a 2-byte length field, but ended up only needing * a 1-byte length field). However this does matter for Initial packets * which must be at least 1200 bytes, which is also the assumed default MTU; * therefore in many cases Initial packets will be padded to 1200 bytes, * which means if we overestimated the header size, we will be short by a * few bytes and the server will ignore the packet for being too short. In * this case, however, such packets always *will* be padded to meet 1200 * bytes, which requires a 2-byte length field, so we don't actually need to * worry about this. Thus we estimate the header length assuming a 2-byte * length field here, which should in practice work well in all cases. */ phdr->len = OSSL_QUIC_VLINT_2B_MAX - phdr->pn_len; if (enc_level == QUIC_ENC_LEVEL_INITIAL) { phdr->token = txp->initial_token; phdr->token_len = txp->initial_token_len; } else { phdr->token = NULL; phdr->token_len = 0; } hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(phdr->dst_conn_id.id_len, phdr); if (hdr_len == 0) return 0; /* MDPL: Maximum datagram payload length. */ mdpl = txp_get_mdpl(txp); /* * CMPL: Maximum encoded packet size we can put into this datagram given any * previous packets coalesced into it. */ if (running_total > mdpl) /* Should not be possible, but if it happens: */ cmpl = 0; else cmpl = mdpl - running_total; /* CMPPL: Maximum amount we can put into the current packet payload */ if (!txp_determine_ppl_from_pl(txp, cmpl, enc_level, hdr_len, &geom->cmppl)) return 0; geom->cmpl = cmpl; geom->pkt_overhead = cmpl - geom->cmppl; geom->archetype = archetype; return 1; } static uint32_t txp_determine_archetype(OSSL_QUIC_TX_PACKETISER *txp, uint64_t cc_limit) { OSSL_ACKM_PROBE_INFO *probe_info = ossl_ackm_get0_probe_request(txp->args.ackm); uint32_t pn_space; /* * If ACKM has requested probe generation (e.g. due to PTO), we generate a * Probe-archetype packet. Actually, we determine archetype on a * per-datagram basis, so if any EL wants a probe, do a pass in which * we try and generate a probe (if needed) for all ELs. */ if (probe_info->anti_deadlock_initial > 0 || probe_info->anti_deadlock_handshake > 0) return TX_PACKETISER_ARCHETYPE_PROBE; for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) if (probe_info->pto[pn_space] > 0) return TX_PACKETISER_ARCHETYPE_PROBE; /* * If we are out of CC budget, we cannot send a normal packet, * but we can do an ACK-only packet (potentially, if we * want to send an ACK). */ if (cc_limit == 0) return TX_PACKETISER_ARCHETYPE_ACK_ONLY; /* All other packets. */ return TX_PACKETISER_ARCHETYPE_NORMAL; } static int txp_should_try_staging(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level, uint32_t archetype, uint64_t cc_limit, uint32_t *conn_close_enc_level) { struct archetype_data a; uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level); QUIC_CFQ_ITEM *cfq_item; if (!ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level)) return 0; if (!txp_get_archetype_data(enc_level, archetype, &a)) return 0; if (!a.bypass_cc && cc_limit == 0) /* CC not allowing us to send. */ return 0; /* * We can produce CONNECTION_CLOSE frames on any EL in principle, which * means we need to choose which EL we would prefer to use. After a * connection is fully established we have only one provisioned EL and this * is a non-issue. Where multiple ELs are provisioned, it is possible the * peer does not have the keys for the EL yet, which suggests in general it * is preferable to use the lowest EL which is still provisioned. * * However (RFC 9000 s. 10.2.3 & 12.5) we are also required to not send * application CONNECTION_CLOSE frames in non-1-RTT ELs, so as to not * potentially leak application data on a connection which has yet to be * authenticated. Thus when we have an application CONNECTION_CLOSE frame * queued and need to send it on a non-1-RTT EL, we have to convert it * into a transport CONNECTION_CLOSE frame which contains no application * data. Since this loses information, it suggests we should use the 1-RTT * EL to avoid this if possible, even if a lower EL is also available. * * At the same time, just because we have the 1-RTT EL provisioned locally * does not necessarily mean the peer does, for example if a handshake * CRYPTO frame has been lost. It is fairly important that CONNECTION_CLOSE * is signalled in a way we know our peer can decrypt, as we stop processing * connection retransmission logic for real after connection close and * simply 'blindly' retransmit the same CONNECTION_CLOSE frame. * * This is not a major concern for clients, since if a client has a 1-RTT EL * provisioned the server is guaranteed to also have a 1-RTT EL provisioned. * * TODO(QUIC SERVER): Revisit this when server support is added. */ if (*conn_close_enc_level > enc_level && *conn_close_enc_level != QUIC_ENC_LEVEL_1RTT) *conn_close_enc_level = enc_level; /* Do we need to send a PTO probe? */ if (a.allow_force_ack_eliciting) { OSSL_ACKM_PROBE_INFO *probe_info = ossl_ackm_get0_probe_request(txp->args.ackm); if ((enc_level == QUIC_ENC_LEVEL_INITIAL && probe_info->anti_deadlock_initial > 0) || (enc_level == QUIC_ENC_LEVEL_HANDSHAKE && probe_info->anti_deadlock_handshake > 0) || probe_info->pto[pn_space] > 0) return 1; } /* Does the crypto stream for this EL want to produce anything? */ if (a.allow_crypto && sstream_is_pending(txp->args.crypto[pn_space])) return 1; /* Does the ACKM for this PN space want to produce anything? */ if (a.allow_ack && (ossl_ackm_is_ack_desired(txp->args.ackm, pn_space) || (txp->want_ack & (1UL << pn_space)) != 0)) return 1; /* Do we need to force emission of an ACK-eliciting packet? */ if (a.allow_force_ack_eliciting && (txp->force_ack_eliciting & (1UL << pn_space)) != 0) return 1; /* Does the connection-level RXFC want to produce a frame? */ if (a.allow_conn_fc && (txp->want_max_data || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0))) return 1; /* Do we want to produce a MAX_STREAMS frame? */ if (a.allow_conn_fc && (txp->want_max_streams_bidi || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 0) || txp->want_max_streams_uni || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 0))) return 1; /* Do we want to produce a HANDSHAKE_DONE frame? */ if (a.allow_handshake_done && txp->want_handshake_done) return 1; /* Do we want to produce a CONNECTION_CLOSE frame? */ if (a.allow_conn_close && txp->want_conn_close && *conn_close_enc_level == enc_level) /* * This is a bit of a special case since CONNECTION_CLOSE can appear in * most packet types, and when we decide we want to send it this status * isn't tied to a specific EL. So if we want to send it, we send it * only on the lowest non-dropped EL. */ return 1; /* Does the CFQ have any frames queued for this PN space? */ if (enc_level != QUIC_ENC_LEVEL_0RTT) for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space); cfq_item != NULL; cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) { uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item); switch (frame_type) { case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID: if (a.allow_new_conn_id) return 1; break; case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID: if (a.allow_retire_conn_id) return 1; break; case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN: if (a.allow_new_token) return 1; break; case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE: if (a.allow_path_response) return 1; break; default: if (a.allow_cfq_other) return 1; break; } } if (a.allow_stream_rel && txp->handshake_complete) { QUIC_STREAM_ITER it; /* If there are any active streams, 0/1-RTT wants to produce a packet. * Whether a stream is on the active list is required to be precise * (i.e., a stream is never on the active list if we cannot produce a * frame for it), and all stream-related frames are governed by * a.allow_stream_rel (i.e., if we can send one type of stream-related * frame, we can send any of them), so we don't need to inspect * individual streams on the active list, just confirm that the active * list is non-empty. */ ossl_quic_stream_iter_init(&it, txp->args.qsm, 0); if (it.stream != NULL) return 1; } return 0; } static int sstream_is_pending(QUIC_SSTREAM *sstream) { OSSL_QUIC_FRAME_STREAM hdr; OSSL_QTX_IOVEC iov[2]; size_t num_iov = OSSL_NELEM(iov); return ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov); } /* Determine how many bytes we should use for the encoded PN. */ static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp) { return 4; /* TODO(QUIC FUTURE) */ } /* Determine plaintext packet payload length from payload length. */ static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp, size_t pl, uint32_t enc_level, size_t hdr_len, size_t *r) { if (pl < hdr_len) return 0; pl -= hdr_len; if (!ossl_qtx_calculate_plaintext_payload_len(txp->args.qtx, enc_level, pl, &pl)) return 0; *r = pl; return 1; } static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp) { return ossl_qtx_get_mdpl(txp->args.qtx); } static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space, void *arg) { OSSL_QUIC_TX_PACKETISER *txp = arg; QUIC_STREAM *s; if (stream_id == UINT64_MAX) return txp->args.crypto[pn_space]; s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id); if (s == NULL) return NULL; return s->sstream; } static void on_regen_notify(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg) { OSSL_QUIC_TX_PACKETISER *txp = arg; switch (frame_type) { case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE: txp->want_handshake_done = 1; break; case OSSL_QUIC_FRAME_TYPE_MAX_DATA: txp->want_max_data = 1; break; case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI: txp->want_max_streams_bidi = 1; break; case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI: txp->want_max_streams_uni = 1; break; case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN: txp->want_ack |= (1UL << pkt->ackm_pkt.pkt_space); break; case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA: { QUIC_STREAM *s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id); if (s == NULL) return; s->want_max_stream_data = 1; ossl_quic_stream_map_update_state(txp->args.qsm, s); } break; case OSSL_QUIC_FRAME_TYPE_STOP_SENDING: { QUIC_STREAM *s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id); if (s == NULL) return; ossl_quic_stream_map_schedule_stop_sending(txp->args.qsm, s); } break; case OSSL_QUIC_FRAME_TYPE_RESET_STREAM: { QUIC_STREAM *s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id); if (s == NULL) return; s->want_reset_stream = 1; ossl_quic_stream_map_update_state(txp->args.qsm, s); } break; default: assert(0); break; } } static int txp_pkt_init(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level, uint32_t archetype, size_t running_total) { if (!txp_determine_geometry(txp, archetype, enc_level, running_total, &pkt->phdr, &pkt->geom)) return 0; /* * Initialise TX helper. If we must be ACK eliciting, reserve 1 byte for * PING. */ if (!tx_helper_init(&pkt->h, txp, enc_level, pkt->geom.cmppl, pkt->geom.adata.require_ack_eliciting ? 1 : 0)) return 0; pkt->h_valid = 1; pkt->tpkt = NULL; pkt->stream_head = NULL; pkt->force_pad = 0; return 1; } static void txp_pkt_cleanup(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp) { if (!pkt->h_valid) return; tx_helper_cleanup(&pkt->h); pkt->h_valid = 0; if (pkt->tpkt != NULL) { ossl_quic_txpim_pkt_release(txp->args.txpim, pkt->tpkt); pkt->tpkt = NULL; } } static int txp_pkt_postgen_update_pkt_overhead(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp) { /* * After we have staged and generated our packets, but before we commit * them, it is possible for the estimated packet overhead (packet header + * AEAD tag size) to shrink slightly because we generated a short packet * whose which can be represented in fewer bytes as a variable-length * integer than we were (pessimistically) budgeting for. We need to account * for this to ensure that we get our padding calculation exactly right. * * Update pkt_overhead to be accurate now that we know how much data is * going in a packet. */ size_t hdr_len, ciphertext_len; if (pkt->h.enc_level == QUIC_ENC_LEVEL_INITIAL) /* * Don't update overheads for the INITIAL EL - we have not finished * appending padding to it and would potentially miscalculate the * correct padding if we now update the pkt_overhead field to switch to * e.g. a 1-byte length field in the packet header. Since we are padding * to QUIC_MIN_INITIAL_DGRAM_LEN which requires a 2-byte length field, * this is guaranteed to be moot anyway. See comment in * txp_determine_geometry for more information. */ return 1; if (!ossl_qtx_calculate_ciphertext_payload_len(txp->args.qtx, pkt->h.enc_level, pkt->h.bytes_appended, &ciphertext_len)) return 0; pkt->phdr.len = ciphertext_len; hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(pkt->phdr.dst_conn_id.id_len, &pkt->phdr); pkt->geom.pkt_overhead = hdr_len + ciphertext_len - pkt->h.bytes_appended; return 1; } static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id, QUIC_TXPIM_PKT *pkt, void *arg) { OSSL_QUIC_TX_PACKETISER *txp = arg; switch (frame_type) { case OSSL_QUIC_FRAME_TYPE_STOP_SENDING: { QUIC_STREAM *s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id); if (s == NULL) return; s->acked_stop_sending = 1; ossl_quic_stream_map_update_state(txp->args.qsm, s); } break; case OSSL_QUIC_FRAME_TYPE_RESET_STREAM: { QUIC_STREAM *s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id); if (s == NULL) return; /* * We must already be in RESET_SENT or RESET_RECVD if we are * here, so we don't need to check state here. */ ossl_quic_stream_map_notify_reset_stream_acked(txp->args.qsm, s); ossl_quic_stream_map_update_state(txp->args.qsm, s); } break; default: assert(0); break; } } static int txp_pkt_append_padding(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp, size_t num_bytes) { WPACKET *wpkt; if (num_bytes == 0) return 1; if (!ossl_assert(pkt->h_valid)) return 0; if (!ossl_assert(pkt->tpkt != NULL)) return 0; wpkt = tx_helper_begin(&pkt->h); if (wpkt == NULL) return 0; if (!ossl_quic_wire_encode_padding(wpkt, num_bytes)) { tx_helper_rollback(&pkt->h); return 0; } if (!tx_helper_commit(&pkt->h)) return 0; pkt->tpkt->ackm_pkt.num_bytes += num_bytes; /* Cannot be non-inflight if we have a PADDING frame */ pkt->tpkt->ackm_pkt.is_inflight = 1; return 1; } static void on_sstream_updated(uint64_t stream_id, void *arg) { OSSL_QUIC_TX_PACKETISER *txp = arg; QUIC_STREAM *s; s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id); if (s == NULL) return; ossl_quic_stream_map_update_state(txp->args.qsm, s); } /* * Returns 1 if we can send that many bytes in closing state, 0 otherwise. * Also maintains the bytes sent state if it returns a success. */ static int try_commit_conn_close(OSSL_QUIC_TX_PACKETISER *txp, size_t n) { int res; /* We can always send the first connection close frame */ if (txp->closing_bytes_recv == 0) return 1; /* * RFC 9000 s. 10.2.1 Closing Connection State: * To avoid being used for an amplification attack, such * endpoints MUST limit the cumulative size of packets it sends * to three times the cumulative size of the packets that are * received and attributed to the connection. * and: * An endpoint in the closing state MUST either discard packets * received from an unvalidated address or limit the cumulative * size of packets it sends to an unvalidated address to three * times the size of packets it receives from that address. */ res = txp->closing_bytes_xmit + n <= txp->closing_bytes_recv * 3; /* * Attribute the bytes to the connection, if we are allowed to send them * and this isn't the first closing frame. */ if (res && txp->closing_bytes_recv != 0) txp->closing_bytes_xmit += n; return res; } void ossl_quic_tx_packetiser_record_received_closing_bytes( OSSL_QUIC_TX_PACKETISER *txp, size_t n) { txp->closing_bytes_recv += n; } static int txp_generate_pre_token(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, int chosen_for_conn_close, int *can_be_non_inflight) { const uint32_t enc_level = pkt->h.enc_level; const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level); const struct archetype_data *a = &pkt->geom.adata; QUIC_TXPIM_PKT *tpkt = pkt->tpkt; struct tx_helper *h = &pkt->h; const OSSL_QUIC_FRAME_ACK *ack; OSSL_QUIC_FRAME_ACK ack2; tpkt->ackm_pkt.largest_acked = QUIC_PN_INVALID; /* ACK Frames (Regenerate) */ if (a->allow_ack && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_ACK && (((txp->want_ack & (1UL << pn_space)) != 0) || ossl_ackm_is_ack_desired(txp->args.ackm, pn_space)) && (ack = ossl_ackm_get_ack_frame(txp->args.ackm, pn_space)) != NULL) { WPACKET *wpkt = tx_helper_begin(h); if (wpkt == NULL) return 0; /* We do not currently support ECN */ ack2 = *ack; ack2.ecn_present = 0; if (ossl_quic_wire_encode_frame_ack(wpkt, txp->args.ack_delay_exponent, &ack2)) { if (!tx_helper_commit(h)) return 0; tpkt->had_ack_frame = 1; if (ack->num_ack_ranges > 0) tpkt->ackm_pkt.largest_acked = ack->ack_ranges[0].end; if (txp->ack_tx_cb != NULL) txp->ack_tx_cb(&ack2, pn_space, txp->ack_tx_cb_arg); } else { tx_helper_rollback(h); } } /* CONNECTION_CLOSE Frames (Regenerate) */ if (a->allow_conn_close && txp->want_conn_close && chosen_for_conn_close) { WPACKET *wpkt = tx_helper_begin(h); OSSL_QUIC_FRAME_CONN_CLOSE f, *pf = &txp->conn_close_frame; size_t l; if (wpkt == NULL) return 0; /* * Application CONNECTION_CLOSE frames may only be sent in the * Application PN space, as otherwise they may be sent before a * connection is authenticated and leak application data. Therefore, if * we need to send a CONNECTION_CLOSE frame in another PN space and were * given an application CONNECTION_CLOSE frame, convert it into a * transport CONNECTION_CLOSE frame, removing any sensitive application * data. * * RFC 9000 s. 10.2.3: "A CONNECTION_CLOSE of type 0x1d MUST be replaced * by a CONNECTION_CLOSE of type 0x1c when sending the frame in Initial * or Handshake packets. Otherwise, information about the application * state might be revealed. Endpoints MUST clear the value of the Reason * Phrase field and SHOULD use the APPLICATION_ERROR code when * converting to a CONNECTION_CLOSE of type 0x1c." */ if (pn_space != QUIC_PN_SPACE_APP && pf->is_app) { pf = &f; pf->is_app = 0; pf->frame_type = 0; pf->error_code = QUIC_ERR_APPLICATION_ERROR; pf->reason = NULL; pf->reason_len = 0; } if (ossl_quic_wire_encode_frame_conn_close(wpkt, pf) && WPACKET_get_total_written(wpkt, &l) && try_commit_conn_close(txp, l)) { if (!tx_helper_commit(h)) return 0; tpkt->had_conn_close = 1; *can_be_non_inflight = 0; } else { tx_helper_rollback(h); } } return 1; } static int try_len(size_t space_left, size_t orig_len, size_t base_hdr_len, size_t lenbytes, uint64_t maxn, size_t *hdr_len, size_t *payload_len) { size_t n; size_t maxn_ = maxn > SIZE_MAX ? SIZE_MAX : (size_t)maxn; *hdr_len = base_hdr_len + lenbytes; if (orig_len == 0 && space_left >= *hdr_len) { *payload_len = 0; return 1; } n = orig_len; if (n > maxn_) n = maxn_; if (n + *hdr_len > space_left) n = (space_left >= *hdr_len) ? space_left - *hdr_len : 0; *payload_len = n; return n > 0; } static int determine_len(size_t space_left, size_t orig_len, size_t base_hdr_len, uint64_t *hlen, uint64_t *len) { int ok = 0; size_t chosen_payload_len = 0; size_t chosen_hdr_len = 0; size_t payload_len[4], hdr_len[4]; int i, valid[4] = {0}; valid[0] = try_len(space_left, orig_len, base_hdr_len, 1, OSSL_QUIC_VLINT_1B_MAX, &hdr_len[0], &payload_len[0]); valid[1] = try_len(space_left, orig_len, base_hdr_len, 2, OSSL_QUIC_VLINT_2B_MAX, &hdr_len[1], &payload_len[1]); valid[2] = try_len(space_left, orig_len, base_hdr_len, 4, OSSL_QUIC_VLINT_4B_MAX, &hdr_len[2], &payload_len[2]); valid[3] = try_len(space_left, orig_len, base_hdr_len, 8, OSSL_QUIC_VLINT_8B_MAX, &hdr_len[3], &payload_len[3]); for (i = OSSL_NELEM(valid) - 1; i >= 0; --i) if (valid[i] && payload_len[i] >= chosen_payload_len) { chosen_payload_len = payload_len[i]; chosen_hdr_len = hdr_len[i]; ok = 1; } *hlen = chosen_hdr_len; *len = chosen_payload_len; return ok; } /* * Given a CRYPTO frame header with accurate chdr->len and a budget * (space_left), try to find the optimal value of chdr->len to fill as much of * the budget as possible. This is slightly hairy because larger values of * chdr->len cause larger encoded sizes of the length field of the frame, which * in turn mean less space available for payload data. We check all possible * encodings and choose the optimal encoding. */ static int determine_crypto_len(struct tx_helper *h, OSSL_QUIC_FRAME_CRYPTO *chdr, size_t space_left, uint64_t *hlen, uint64_t *len) { size_t orig_len; size_t base_hdr_len; /* CRYPTO header length without length field */ if (chdr->len > SIZE_MAX) return 0; orig_len = (size_t)chdr->len; chdr->len = 0; base_hdr_len = ossl_quic_wire_get_encoded_frame_len_crypto_hdr(chdr); chdr->len = orig_len; if (base_hdr_len == 0) return 0; --base_hdr_len; return determine_len(space_left, orig_len, base_hdr_len, hlen, len); } static int determine_stream_len(struct tx_helper *h, OSSL_QUIC_FRAME_STREAM *shdr, size_t space_left, uint64_t *hlen, uint64_t *len) { size_t orig_len; size_t base_hdr_len; /* STREAM header length without length field */ if (shdr->len > SIZE_MAX) return 0; orig_len = (size_t)shdr->len; shdr->len = 0; base_hdr_len = ossl_quic_wire_get_encoded_frame_len_stream_hdr(shdr); shdr->len = orig_len; if (base_hdr_len == 0) return 0; if (shdr->has_explicit_len) --base_hdr_len; return determine_len(space_left, orig_len, base_hdr_len, hlen, len); } static int txp_generate_crypto_frames(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, int *have_ack_eliciting) { const uint32_t enc_level = pkt->h.enc_level; const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level); QUIC_TXPIM_PKT *tpkt = pkt->tpkt; struct tx_helper *h = &pkt->h; size_t num_stream_iovec; OSSL_QUIC_FRAME_STREAM shdr = {0}; OSSL_QUIC_FRAME_CRYPTO chdr = {0}; OSSL_QTX_IOVEC iov[2]; uint64_t hdr_bytes; WPACKET *wpkt; QUIC_TXPIM_CHUNK chunk = {0}; size_t i, space_left; for (i = 0;; ++i) { space_left = tx_helper_get_space_left(h); if (space_left < MIN_FRAME_SIZE_CRYPTO) return 1; /* no point trying */ /* Do we have any CRYPTO data waiting? */ num_stream_iovec = OSSL_NELEM(iov); if (!ossl_quic_sstream_get_stream_frame(txp->args.crypto[pn_space], i, &shdr, iov, &num_stream_iovec)) return 1; /* nothing to do */ /* Convert STREAM frame header to CRYPTO frame header */ chdr.offset = shdr.offset; chdr.len = shdr.len; if (chdr.len == 0) return 1; /* nothing to do */ /* Find best fit (header length, payload length) combination. */ if (!determine_crypto_len(h, &chdr, space_left, &hdr_bytes, &chdr.len)) return 1; /* can't fit anything */ /* * Truncate IOVs to match our chosen length. * * The length cannot be more than SIZE_MAX because this length comes * from our send stream buffer. */ ossl_quic_sstream_adjust_iov((size_t)chdr.len, iov, num_stream_iovec); /* * Ensure we have enough iovecs allocated (1 for the header, up to 2 for * the stream data.) */ if (!txp_el_ensure_iovec(&txp->el[enc_level], h->num_iovec + 3)) return 0; /* alloc error */ /* Encode the header. */ wpkt = tx_helper_begin(h); if (wpkt == NULL) return 0; /* alloc error */ if (!ossl_quic_wire_encode_frame_crypto_hdr(wpkt, &chdr)) { tx_helper_rollback(h); return 1; /* can't fit */ } if (!tx_helper_commit(h)) return 0; /* alloc error */ /* Add payload iovecs to the helper (infallible). */ for (i = 0; i < num_stream_iovec; ++i) tx_helper_append_iovec(h, iov[i].buf, iov[i].buf_len); *have_ack_eliciting = 1; tx_helper_unrestrict(h); /* no longer need PING */ /* Log chunk to TXPIM. */ chunk.stream_id = UINT64_MAX; /* crypto stream */ chunk.start = chdr.offset; chunk.end = chdr.offset + chdr.len - 1; chunk.has_fin = 0; /* Crypto stream never ends */ if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk)) return 0; /* alloc error */ } } struct chunk_info { OSSL_QUIC_FRAME_STREAM shdr; uint64_t orig_len; OSSL_QTX_IOVEC iov[2]; size_t num_stream_iovec; int valid; }; static int txp_plan_stream_chunk(OSSL_QUIC_TX_PACKETISER *txp, struct tx_helper *h, QUIC_SSTREAM *sstream, QUIC_TXFC *stream_txfc, size_t skip, struct chunk_info *chunk, uint64_t consumed) { uint64_t fc_credit, fc_swm, fc_limit; chunk->num_stream_iovec = OSSL_NELEM(chunk->iov); chunk->valid = ossl_quic_sstream_get_stream_frame(sstream, skip, &chunk->shdr, chunk->iov, &chunk->num_stream_iovec); if (!chunk->valid) return 1; if (!ossl_assert(chunk->shdr.len > 0 || chunk->shdr.is_fin)) /* Should only have 0-length chunk if FIN */ return 0; chunk->orig_len = chunk->shdr.len; /* Clamp according to connection and stream-level TXFC. */ fc_credit = ossl_quic_txfc_get_credit(stream_txfc, consumed); fc_swm = ossl_quic_txfc_get_swm(stream_txfc); fc_limit = fc_swm + fc_credit; if (chunk->shdr.len > 0 && chunk->shdr.offset + chunk->shdr.len > fc_limit) { chunk->shdr.len = (fc_limit <= chunk->shdr.offset) ? 0 : fc_limit - chunk->shdr.offset; chunk->shdr.is_fin = 0; } if (chunk->shdr.len == 0 && !chunk->shdr.is_fin) { /* * Nothing to do due to TXFC. Since SSTREAM returns chunks in ascending * order of offset we don't need to check any later chunks, so stop * iterating here. */ chunk->valid = 0; return 1; } return 1; } /* * Returns 0 on fatal error (e.g. allocation failure), 1 on success. * *packet_full is set to 1 if there is no longer enough room for another STREAM * frame. */ static int txp_generate_stream_frames(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, uint64_t id, QUIC_SSTREAM *sstream, QUIC_TXFC *stream_txfc, QUIC_STREAM *next_stream, int *have_ack_eliciting, int *packet_full, uint64_t *new_credit_consumed, uint64_t conn_consumed) { int rc = 0; struct chunk_info chunks[2] = {0}; const uint32_t enc_level = pkt->h.enc_level; QUIC_TXPIM_PKT *tpkt = pkt->tpkt; struct tx_helper *h = &pkt->h; OSSL_QUIC_FRAME_STREAM *shdr; WPACKET *wpkt; QUIC_TXPIM_CHUNK chunk; size_t i, j, space_left; int can_fill_payload, use_explicit_len; int could_have_following_chunk; uint64_t orig_len; uint64_t hdr_len_implicit, payload_len_implicit; uint64_t hdr_len_explicit, payload_len_explicit; uint64_t fc_swm, fc_new_hwm; fc_swm = ossl_quic_txfc_get_swm(stream_txfc); fc_new_hwm = fc_swm; /* * Load the first two chunks if any offered by the send stream. We retrieve * the next chunk in advance so we can determine if we need to send any more * chunks from the same stream after this one, which is needed when * determining when we can use an implicit length in a STREAM frame. */ for (i = 0; i < 2; ++i) { if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i, &chunks[i], conn_consumed)) goto err; if (i == 0 && !chunks[i].valid) { /* No chunks, nothing to do. */ rc = 1; goto err; } } for (i = 0;; ++i) { space_left = tx_helper_get_space_left(h); if (!chunks[i % 2].valid) { /* Out of chunks; we're done. */ rc = 1; goto err; } if (space_left < MIN_FRAME_SIZE_STREAM) { *packet_full = 1; rc = 1; goto err; } if (!ossl_assert(!h->done_implicit)) /* * Logic below should have ensured we didn't append an * implicit-length unless we filled the packet or didn't have * another stream to handle, so this should not be possible. */ goto err; shdr = &chunks[i % 2].shdr; orig_len = chunks[i % 2].orig_len; if (i > 0) /* Load next chunk for lookahead. */ if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i + 1, &chunks[(i + 1) % 2], conn_consumed)) goto err; /* * Find best fit (header length, payload length) combination for if we * use an implicit length. */ shdr->has_explicit_len = 0; hdr_len_implicit = payload_len_implicit = 0; if (!determine_stream_len(h, shdr, space_left, &hdr_len_implicit, &payload_len_implicit)) { *packet_full = 1; rc = 1; goto err; /* can't fit anything */ } /* * If there is a next stream, we don't use the implicit length so we can * add more STREAM frames after this one, unless there is enough data * for this STREAM frame to fill the packet. */ can_fill_payload = (hdr_len_implicit + payload_len_implicit >= space_left); /* * Is there is a stream after this one, or another chunk pending * transmission in this stream? */ could_have_following_chunk = (next_stream != NULL || chunks[(i + 1) % 2].valid); /* Choose between explicit or implicit length representations. */ use_explicit_len = !((can_fill_payload || !could_have_following_chunk) && !pkt->force_pad); if (use_explicit_len) { /* * Find best fit (header length, payload length) combination for if * we use an explicit length. */ shdr->has_explicit_len = 1; hdr_len_explicit = payload_len_explicit = 0; if (!determine_stream_len(h, shdr, space_left, &hdr_len_explicit, &payload_len_explicit)) { *packet_full = 1; rc = 1; goto err; /* can't fit anything */ } shdr->len = payload_len_explicit; } else { *packet_full = 1; shdr->has_explicit_len = 0; shdr->len = payload_len_implicit; } /* If this is a FIN, don't keep filling the packet with more FINs. */ if (shdr->is_fin) chunks[(i + 1) % 2].valid = 0; /* * We are now committed to our length (shdr->len can't change). * If we truncated the chunk, clear the FIN bit. */ if (shdr->len < orig_len) shdr->is_fin = 0; /* Truncate IOVs to match our chosen length. */ ossl_quic_sstream_adjust_iov((size_t)shdr->len, chunks[i % 2].iov, chunks[i % 2].num_stream_iovec); /* * Ensure we have enough iovecs allocated (1 for the header, up to 2 for * the stream data.) */ if (!txp_el_ensure_iovec(&txp->el[enc_level], h->num_iovec + 3)) goto err; /* alloc error */ /* Encode the header. */ wpkt = tx_helper_begin(h); if (wpkt == NULL) goto err; /* alloc error */ shdr->stream_id = id; if (!ossl_assert(ossl_quic_wire_encode_frame_stream_hdr(wpkt, shdr))) { /* (Should not be possible.) */ tx_helper_rollback(h); *packet_full = 1; rc = 1; goto err; /* can't fit */ } if (!tx_helper_commit(h)) goto err; /* alloc error */ /* Add payload iovecs to the helper (infallible). */ for (j = 0; j < chunks[i % 2].num_stream_iovec; ++j) tx_helper_append_iovec(h, chunks[i % 2].iov[j].buf, chunks[i % 2].iov[j].buf_len); *have_ack_eliciting = 1; tx_helper_unrestrict(h); /* no longer need PING */ if (!shdr->has_explicit_len) h->done_implicit = 1; /* Log new TXFC credit which was consumed. */ if (shdr->len > 0 && shdr->offset + shdr->len > fc_new_hwm) fc_new_hwm = shdr->offset + shdr->len; /* Log chunk to TXPIM. */ chunk.stream_id = shdr->stream_id; chunk.start = shdr->offset; chunk.end = shdr->offset + shdr->len - 1; chunk.has_fin = shdr->is_fin; chunk.has_stop_sending = 0; chunk.has_reset_stream = 0; if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk)) goto err; /* alloc error */ if (shdr->len < orig_len) { /* * If we did not serialize all of this chunk we definitely do not * want to try the next chunk */ rc = 1; goto err; } } err: *new_credit_consumed = fc_new_hwm - fc_swm; return rc; } static void txp_enlink_tmp(QUIC_STREAM **tmp_head, QUIC_STREAM *stream) { stream->txp_next = *tmp_head; *tmp_head = stream; } static int txp_generate_stream_related(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, int *have_ack_eliciting, QUIC_STREAM **tmp_head) { QUIC_STREAM_ITER it; WPACKET *wpkt; uint64_t cwm; QUIC_STREAM *stream, *snext; struct tx_helper *h = &pkt->h; uint64_t conn_consumed = 0; for (ossl_quic_stream_iter_init(&it, txp->args.qsm, 1); it.stream != NULL;) { stream = it.stream; ossl_quic_stream_iter_next(&it); snext = it.stream; stream->txp_sent_fc = 0; stream->txp_sent_stop_sending = 0; stream->txp_sent_reset_stream = 0; stream->txp_blocked = 0; stream->txp_txfc_new_credit_consumed = 0; /* Stream Abort Frames (STOP_SENDING, RESET_STREAM) */ if (stream->want_stop_sending) { OSSL_QUIC_FRAME_STOP_SENDING f; wpkt = tx_helper_begin(h); if (wpkt == NULL) return 0; /* alloc error */ f.stream_id = stream->id; f.app_error_code = stream->stop_sending_aec; if (!ossl_quic_wire_encode_frame_stop_sending(wpkt, &f)) { tx_helper_rollback(h); /* can't fit */ txp_enlink_tmp(tmp_head, stream); break; } if (!tx_helper_commit(h)) return 0; /* alloc error */ *have_ack_eliciting = 1; tx_helper_unrestrict(h); /* no longer need PING */ stream->txp_sent_stop_sending = 1; } if (stream->want_reset_stream) { OSSL_QUIC_FRAME_RESET_STREAM f; if (!ossl_assert(stream->send_state == QUIC_SSTREAM_STATE_RESET_SENT)) return 0; wpkt = tx_helper_begin(h); if (wpkt == NULL) return 0; /* alloc error */ f.stream_id = stream->id; f.app_error_code = stream->reset_stream_aec; if (!ossl_quic_stream_send_get_final_size(stream, &f.final_size)) return 0; /* should not be possible */ if (!ossl_quic_wire_encode_frame_reset_stream(wpkt, &f)) { tx_helper_rollback(h); /* can't fit */ txp_enlink_tmp(tmp_head, stream); break; } if (!tx_helper_commit(h)) return 0; /* alloc error */ *have_ack_eliciting = 1; tx_helper_unrestrict(h); /* no longer need PING */ stream->txp_sent_reset_stream = 1; /* * The final size of the stream as indicated by RESET_STREAM is used * to ensure a consistent view of flow control state by both * parties; if we happen to send a RESET_STREAM that consumes more * flow control credit, make sure we account for that. */ if (!ossl_assert(f.final_size <= ossl_quic_txfc_get_swm(&stream->txfc))) return 0; stream->txp_txfc_new_credit_consumed = f.final_size - ossl_quic_txfc_get_swm(&stream->txfc); } /* * Stream Flow Control Frames (MAX_STREAM_DATA) * * RFC 9000 s. 13.3: "An endpoint SHOULD stop sending MAX_STREAM_DATA * frames when the receiving part of the stream enters a "Size Known" or * "Reset Recvd" state." -- In practice, RECV is the only state * in which it makes sense to generate more MAX_STREAM_DATA frames. */ if (stream->recv_state == QUIC_RSTREAM_STATE_RECV && (stream->want_max_stream_data || ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 0))) { wpkt = tx_helper_begin(h); if (wpkt == NULL) return 0; /* alloc error */ cwm = ossl_quic_rxfc_get_cwm(&stream->rxfc); if (!ossl_quic_wire_encode_frame_max_stream_data(wpkt, stream->id, cwm)) { tx_helper_rollback(h); /* can't fit */ txp_enlink_tmp(tmp_head, stream); break; } if (!tx_helper_commit(h)) return 0; /* alloc error */ *have_ack_eliciting = 1; tx_helper_unrestrict(h); /* no longer need PING */ stream->txp_sent_fc = 1; } /* * Stream Data Frames (STREAM) * * RFC 9000 s. 3.3: A sender MUST NOT send a STREAM [...] frame for a * stream in the "Reset Sent" state [or any terminal state]. We don't * send any more STREAM frames if we are sending, have sent, or are * planning to send, RESET_STREAM. The other terminal state is Data * Recvd, but txp_generate_stream_frames() is guaranteed to generate * nothing in this case. */ if (ossl_quic_stream_has_send_buffer(stream) && !ossl_quic_stream_send_is_reset(stream)) { int packet_full = 0; if (!ossl_assert(!stream->want_reset_stream)) return 0; if (!txp_generate_stream_frames(txp, pkt, stream->id, stream->sstream, &stream->txfc, snext, have_ack_eliciting, &packet_full, &stream->txp_txfc_new_credit_consumed, conn_consumed)) { /* Fatal error (allocation, etc.) */ txp_enlink_tmp(tmp_head, stream); return 0; } conn_consumed += stream->txp_txfc_new_credit_consumed; if (packet_full) { txp_enlink_tmp(tmp_head, stream); break; } } txp_enlink_tmp(tmp_head, stream); } return 1; } static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, int chosen_for_conn_close) { int rc = TXP_ERR_SUCCESS; const uint32_t enc_level = pkt->h.enc_level; const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level); int have_ack_eliciting = 0, done_pre_token = 0; const struct archetype_data a = pkt->geom.adata; /* * Cleared if we encode any non-ACK-eliciting frame type which rules out the * packet being a non-inflight frame. This means any non-ACK ACK-eliciting * frame, even PADDING frames. ACK eliciting frames always cause a packet to * become ineligible for non-inflight treatment so it is not necessary to * clear this in cases where have_ack_eliciting is set, as it is ignored in * that case. */ int can_be_non_inflight = 1; QUIC_CFQ_ITEM *cfq_item; QUIC_TXPIM_PKT *tpkt = NULL; struct tx_helper *h = &pkt->h; /* Maximum PN reached? */ if (!ossl_quic_pn_valid(txp->next_pn[pn_space])) goto fatal_err; if (!ossl_assert(pkt->tpkt == NULL)) goto fatal_err; if ((pkt->tpkt = tpkt = ossl_quic_txpim_pkt_alloc(txp->args.txpim)) == NULL) goto fatal_err; /* * Frame Serialization * =================== * * We now serialize frames into the packet in descending order of priority. */ /* HANDSHAKE_DONE (Regenerate) */ if (a.allow_handshake_done && txp->want_handshake_done && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_HANDSHAKE_DONE) { WPACKET *wpkt = tx_helper_begin(h); if (wpkt == NULL) goto fatal_err; if (ossl_quic_wire_encode_frame_handshake_done(wpkt)) { tpkt->had_handshake_done_frame = 1; have_ack_eliciting = 1; if (!tx_helper_commit(h)) goto fatal_err; tx_helper_unrestrict(h); /* no longer need PING */ } else { tx_helper_rollback(h); } } /* MAX_DATA (Regenerate) */ if (a.allow_conn_fc && (txp->want_max_data || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0)) && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_DATA) { WPACKET *wpkt = tx_helper_begin(h); uint64_t cwm = ossl_quic_rxfc_get_cwm(txp->args.conn_rxfc); if (wpkt == NULL) goto fatal_err; if (ossl_quic_wire_encode_frame_max_data(wpkt, cwm)) { tpkt->had_max_data_frame = 1; have_ack_eliciting = 1; if (!tx_helper_commit(h)) goto fatal_err; tx_helper_unrestrict(h); /* no longer need PING */ } else { tx_helper_rollback(h); } } /* MAX_STREAMS_BIDI (Regenerate) */ if (a.allow_conn_fc && (txp->want_max_streams_bidi || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 0)) && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_STREAMS_BIDI) { WPACKET *wpkt = tx_helper_begin(h); uint64_t max_streams = ossl_quic_rxfc_get_cwm(txp->args.max_streams_bidi_rxfc); if (wpkt == NULL) goto fatal_err; if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/0, max_streams)) { tpkt->had_max_streams_bidi_frame = 1; have_ack_eliciting = 1; if (!tx_helper_commit(h)) goto fatal_err; tx_helper_unrestrict(h); /* no longer need PING */ } else { tx_helper_rollback(h); } } /* MAX_STREAMS_UNI (Regenerate) */ if (a.allow_conn_fc && (txp->want_max_streams_uni || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 0)) && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_STREAMS_UNI) { WPACKET *wpkt = tx_helper_begin(h); uint64_t max_streams = ossl_quic_rxfc_get_cwm(txp->args.max_streams_uni_rxfc); if (wpkt == NULL) goto fatal_err; if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/1, max_streams)) { tpkt->had_max_streams_uni_frame = 1; have_ack_eliciting = 1; if (!tx_helper_commit(h)) goto fatal_err; tx_helper_unrestrict(h); /* no longer need PING */ } else { tx_helper_rollback(h); } } /* GCR Frames */ for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space); cfq_item != NULL; cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) { uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item); const unsigned char *encoded = ossl_quic_cfq_item_get_encoded(cfq_item); size_t encoded_len = ossl_quic_cfq_item_get_encoded_len(cfq_item); switch (frame_type) { case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID: if (!a.allow_new_conn_id) continue; break; case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID: if (!a.allow_retire_conn_id) continue; break; case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN: if (!a.allow_new_token) continue; /* * NEW_TOKEN frames are handled via GCR, but some * Regenerate-strategy frames should come before them (namely * ACK, CONNECTION_CLOSE, PATH_CHALLENGE and PATH_RESPONSE). If * we find a NEW_TOKEN frame, do these now. If there are no * NEW_TOKEN frames in the GCR queue we will handle these below. */ if (!done_pre_token) if (txp_generate_pre_token(txp, pkt, chosen_for_conn_close, &can_be_non_inflight)) done_pre_token = 1; break; case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE: if (!a.allow_path_response) continue; /* * RFC 9000 s. 8.2.2: An endpoint MUST expand datagrams that * contain a PATH_RESPONSE frame to at least the smallest * allowed maximum datagram size of 1200 bytes. */ pkt->force_pad = 1; break; default: if (!a.allow_cfq_other) continue; break; } /* * If the frame is too big, don't try to schedule any more GCR frames in * this packet rather than sending subsequent ones out of order. */ if (encoded_len > tx_helper_get_space_left(h)) break; if (!tx_helper_append_iovec(h, encoded, encoded_len)) goto fatal_err; ossl_quic_txpim_pkt_add_cfq_item(tpkt, cfq_item); if (ossl_quic_frame_type_is_ack_eliciting(frame_type)) { have_ack_eliciting = 1; tx_helper_unrestrict(h); /* no longer need PING */ } } /* * If we didn't generate ACK, CONNECTION_CLOSE, PATH_CHALLENGE or * PATH_RESPONSE (as desired) before, do so now. */ if (!done_pre_token) if (txp_generate_pre_token(txp, pkt, chosen_for_conn_close, &can_be_non_inflight)) done_pre_token = 1; /* CRYPTO Frames */ if (a.allow_crypto) if (!txp_generate_crypto_frames(txp, pkt, &have_ack_eliciting)) goto fatal_err; /* Stream-specific frames */ if (a.allow_stream_rel && txp->handshake_complete) if (!txp_generate_stream_related(txp, pkt, &have_ack_eliciting, &pkt->stream_head)) goto fatal_err; /* PING */ tx_helper_unrestrict(h); if ((a.require_ack_eliciting || (txp->force_ack_eliciting & (1UL << pn_space)) != 0) && !have_ack_eliciting && a.allow_ping) { WPACKET *wpkt; wpkt = tx_helper_begin(h); if (wpkt == NULL) goto fatal_err; if (!ossl_quic_wire_encode_frame_ping(wpkt) || !tx_helper_commit(h)) /* * We treat a request to be ACK-eliciting as a requirement, so this * is an error. */ goto fatal_err; have_ack_eliciting = 1; } /* PADDING is added by ossl_quic_tx_packetiser_generate(). */ /* * ACKM Data * ========= */ if (have_ack_eliciting) can_be_non_inflight = 0; /* ACKM Data */ tpkt->ackm_pkt.num_bytes = h->bytes_appended + pkt->geom.pkt_overhead; tpkt->ackm_pkt.pkt_num = txp->next_pn[pn_space]; /* largest_acked is set in txp_generate_pre_token */ tpkt->ackm_pkt.pkt_space = pn_space; tpkt->ackm_pkt.is_inflight = !can_be_non_inflight; tpkt->ackm_pkt.is_ack_eliciting = have_ack_eliciting; tpkt->ackm_pkt.is_pto_probe = 0; tpkt->ackm_pkt.is_mtu_probe = 0; tpkt->ackm_pkt.time = txp->args.now(txp->args.now_arg); /* Done. */ return rc; fatal_err: /* * Handler for fatal errors, i.e. errors causing us to abort the entire * packet rather than just one frame. Examples of such errors include * allocation errors. */ if (tpkt != NULL) { ossl_quic_txpim_pkt_release(txp->args.txpim, tpkt); pkt->tpkt = NULL; } return TXP_ERR_INTERNAL; } /* * Commits and queues a packet for transmission. There is no backing out after * this. * * This: * * - Sends the packet to the QTX for encryption and transmission; * * - Records the packet as having been transmitted in FIFM. ACKM is informed, * etc. and the TXPIM record is filed. * * - Informs various subsystems of frames that were sent and clears frame * wanted flags so that we do not generate the same frames again. * * Assumptions: * * - pkt is a txp_pkt for the correct EL; * * - pkt->tpkt is valid; * * - pkt->tpkt->ackm_pkt has been fully filled in; * * - Stream chunk records have been appended to pkt->tpkt for STREAM and * CRYPTO frames, but not for RESET_STREAM or STOP_SENDING frames; * * - The chosen stream list for the packet can be fully walked from * pkt->stream_head using stream->txp_next; * * - pkt->has_ack_eliciting is set correctly. * */ static int txp_pkt_commit(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt, uint32_t archetype, int *txpim_pkt_reffed) { int rc = 1; uint32_t enc_level = pkt->h.enc_level; uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level); QUIC_TXPIM_PKT *tpkt = pkt->tpkt; QUIC_STREAM *stream; OSSL_QTX_PKT txpkt; struct archetype_data a; *txpim_pkt_reffed = 0; /* Cannot send a packet with an empty payload. */ if (pkt->h.bytes_appended == 0) return 0; if (!txp_get_archetype_data(enc_level, archetype, &a)) return 0; /* Packet Information for QTX */ txpkt.hdr = &pkt->phdr; txpkt.iovec = txp->el[enc_level].iovec; txpkt.num_iovec = pkt->h.num_iovec; txpkt.local = NULL; txpkt.peer = BIO_ADDR_family(&txp->args.peer) == AF_UNSPEC ? NULL : &txp->args.peer; txpkt.pn = txp->next_pn[pn_space]; txpkt.flags = OSSL_QTX_PKT_FLAG_COALESCE; /* always try to coalesce */ /* Generate TXPIM chunks representing STOP_SENDING and RESET_STREAM frames. */ for (stream = pkt->stream_head; stream != NULL; stream = stream->txp_next) if (stream->txp_sent_stop_sending || stream->txp_sent_reset_stream) { /* Log STOP_SENDING/RESET_STREAM chunk to TXPIM. */ QUIC_TXPIM_CHUNK chunk; chunk.stream_id = stream->id; chunk.start = UINT64_MAX; chunk.end = 0; chunk.has_fin = 0; chunk.has_stop_sending = stream->txp_sent_stop_sending; chunk.has_reset_stream = stream->txp_sent_reset_stream; if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk)) return 0; /* alloc error */ } /* Dispatch to FIFD. */ if (!ossl_quic_fifd_pkt_commit(&txp->fifd, tpkt)) return 0; /* * Transmission and Post-Packet Generation Bookkeeping * =================================================== * * No backing out anymore - at this point the ACKM has recorded the packet * as having been sent, so we need to increment our next PN counter, or * the ACKM will complain when we try to record a duplicate packet with * the same PN later. At this point actually sending the packet may still * fail. In this unlikely event it will simply be handled as though it * were a lost packet. */ ++txp->next_pn[pn_space]; *txpim_pkt_reffed = 1; /* Send the packet. */ if (!ossl_qtx_write_pkt(txp->args.qtx, &txpkt)) return 0; /* * Record FC and stream abort frames as sent; deactivate streams which no * longer have anything to do. */ for (stream = pkt->stream_head; stream != NULL; stream = stream->txp_next) { if (stream->txp_sent_fc) { stream->want_max_stream_data = 0; ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 1); } if (stream->txp_sent_stop_sending) stream->want_stop_sending = 0; if (stream->txp_sent_reset_stream) stream->want_reset_stream = 0; if (stream->txp_txfc_new_credit_consumed > 0) { if (!ossl_assert(ossl_quic_txfc_consume_credit(&stream->txfc, stream->txp_txfc_new_credit_consumed))) /* * Should not be possible, but we should continue with our * bookkeeping as we have already committed the packet to the * FIFD. Just change the value we return. */ rc = 0; stream->txp_txfc_new_credit_consumed = 0; } /* * If we no longer need to generate any flow control (MAX_STREAM_DATA), * STOP_SENDING or RESET_STREAM frames, nor any STREAM frames (because * the stream is drained of data or TXFC-blocked), we can mark the * stream as inactive. */ ossl_quic_stream_map_update_state(txp->args.qsm, stream); if (ossl_quic_stream_has_send_buffer(stream) && !ossl_quic_sstream_has_pending(stream->sstream) && ossl_quic_sstream_get_final_size(stream->sstream, NULL)) /* * Transition to DATA_SENT if stream has a final size and we have * sent all data. */ ossl_quic_stream_map_notify_all_data_sent(txp->args.qsm, stream); } /* We have now sent the packet, so update state accordingly. */ if (tpkt->ackm_pkt.is_ack_eliciting) txp->force_ack_eliciting &= ~(1UL << pn_space); if (tpkt->had_handshake_done_frame) txp->want_handshake_done = 0; if (tpkt->had_max_data_frame) { txp->want_max_data = 0; ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 1); } if (tpkt->had_max_streams_bidi_frame) { txp->want_max_streams_bidi = 0; ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 1); } if (tpkt->had_max_streams_uni_frame) { txp->want_max_streams_uni = 0; ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 1); } if (tpkt->had_ack_frame) txp->want_ack &= ~(1UL << pn_space); if (tpkt->had_conn_close) txp->want_conn_close = 0; /* * Decrement probe request counts if we have sent a packet that meets * the requirement of a probe, namely being ACK-eliciting. */ if (tpkt->ackm_pkt.is_ack_eliciting) { OSSL_ACKM_PROBE_INFO *probe_info = ossl_ackm_get0_probe_request(txp->args.ackm); if (enc_level == QUIC_ENC_LEVEL_INITIAL && probe_info->anti_deadlock_initial > 0) --probe_info->anti_deadlock_initial; if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE && probe_info->anti_deadlock_handshake > 0) --probe_info->anti_deadlock_handshake; if (a.allow_force_ack_eliciting /* (i.e., not for 0-RTT) */ && probe_info->pto[pn_space] > 0) --probe_info->pto[pn_space]; } return rc; } /* Ensure the iovec array is at least num elements long. */ static int txp_el_ensure_iovec(struct txp_el *el, size_t num) { OSSL_QTX_IOVEC *iovec; if (el->alloc_iovec >= num) return 1; num = el->alloc_iovec != 0 ? el->alloc_iovec * 2 : 8; iovec = OPENSSL_realloc(el->iovec, sizeof(OSSL_QTX_IOVEC) * num); if (iovec == NULL) return 0; el->iovec = iovec; el->alloc_iovec = num; return 1; } int ossl_quic_tx_packetiser_schedule_conn_close(OSSL_QUIC_TX_PACKETISER *txp, const OSSL_QUIC_FRAME_CONN_CLOSE *f) { char *reason = NULL; size_t reason_len = f->reason_len; size_t max_reason_len = txp_get_mdpl(txp) / 2; if (txp->want_conn_close) return 0; /* * Arbitrarily limit the length of the reason length string to half of the * MDPL. */ if (reason_len > max_reason_len) reason_len = max_reason_len; if (reason_len > 0) { reason = OPENSSL_memdup(f->reason, reason_len); if (reason == NULL) return 0; } txp->conn_close_frame = *f; txp->conn_close_frame.reason = reason; txp->conn_close_frame.reason_len = reason_len; txp->want_conn_close = 1; return 1; } void ossl_quic_tx_packetiser_set_msg_callback(OSSL_QUIC_TX_PACKETISER *txp, ossl_msg_cb msg_callback, SSL *msg_callback_ssl) { txp->msg_callback = msg_callback; txp->msg_callback_ssl = msg_callback_ssl; } void ossl_quic_tx_packetiser_set_msg_callback_arg(OSSL_QUIC_TX_PACKETISER *txp, void *msg_callback_arg) { txp->msg_callback_arg = msg_callback_arg; } QUIC_PN ossl_quic_tx_packetiser_get_next_pn(OSSL_QUIC_TX_PACKETISER *txp, uint32_t pn_space) { if (pn_space >= QUIC_PN_SPACE_NUM) return UINT64_MAX; return txp->next_pn[pn_space]; } OSSL_TIME ossl_quic_tx_packetiser_get_deadline(OSSL_QUIC_TX_PACKETISER *txp) { /* * TXP-specific deadline computations which rely on TXP innards. This is in * turn relied on by the QUIC_CHANNEL code to determine the channel event * handling deadline. */ OSSL_TIME deadline = ossl_time_infinite(); uint32_t enc_level, pn_space; /* * ACK generation is not CC-gated - packets containing only ACKs are allowed * to bypass CC. We want to generate ACK frames even if we are currently * restricted by CC so the peer knows we have received data. The generate * call will take care of selecting the correct packet archetype. */ for (enc_level = QUIC_ENC_LEVEL_INITIAL; enc_level < QUIC_ENC_LEVEL_NUM; ++enc_level) if (ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level)) { pn_space = ossl_quic_enc_level_to_pn_space(enc_level); deadline = ossl_time_min(deadline, ossl_ackm_get_ack_deadline(txp->args.ackm, pn_space)); } /* When will CC let us send more? */ if (txp->args.cc_method->get_tx_allowance(txp->args.cc_data) == 0) deadline = ossl_time_min(deadline, txp->args.cc_method->get_wakeup_deadline(txp->args.cc_data)); return deadline; }
./openssl/ssl/quic/quic_impl.c
/* * 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/macros.h> #include <openssl/objects.h> #include <openssl/sslerr.h> #include <crypto/rand.h> #include "quic_local.h" #include "internal/quic_tls.h" #include "internal/quic_rx_depack.h" #include "internal/quic_error.h" #include "internal/quic_engine.h" #include "internal/quic_port.h" #include "internal/time.h" typedef struct qctx_st QCTX; static void aon_write_finish(QUIC_XSO *xso); static int create_channel(QUIC_CONNECTION *qc); static QUIC_XSO *create_xso_from_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs); static int qc_try_create_default_xso_for_write(QCTX *ctx); static int qc_wait_for_default_xso_for_read(QCTX *ctx); static void quic_lock(QUIC_CONNECTION *qc); static void quic_unlock(QUIC_CONNECTION *qc); static void quic_lock_for_io(QCTX *ctx); static int quic_do_handshake(QCTX *ctx); static void qc_update_reject_policy(QUIC_CONNECTION *qc); static void qc_touch_default_xso(QUIC_CONNECTION *qc); static void qc_set_default_xso(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch); static void qc_set_default_xso_keep_ref(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch, QUIC_XSO **old_xso); static SSL *quic_conn_stream_new(QCTX *ctx, uint64_t flags, int need_lock); static int quic_validate_for_write(QUIC_XSO *xso, int *err); static int quic_mutation_allowed(QUIC_CONNECTION *qc, int req_active); static int qc_blocking_mode(const QUIC_CONNECTION *qc); static int xso_blocking_mode(const QUIC_XSO *xso); /* * QUIC Front-End I/O API: Common Utilities * ======================================== */ /* * Block until a predicate is met. * * Precondition: Must have a channel. * Precondition: Must hold channel lock (unchecked). */ QUIC_NEEDS_LOCK static int block_until_pred(QUIC_CONNECTION *qc, int (*pred)(void *arg), void *pred_arg, uint32_t flags) { QUIC_REACTOR *rtor; assert(qc->ch != NULL); /* * Any attempt to block auto-disables tick inhibition as otherwise we will * hang around forever. */ ossl_quic_engine_set_inhibit_tick(qc->engine, 0); rtor = ossl_quic_channel_get_reactor(qc->ch); return ossl_quic_reactor_block_until_pred(rtor, pred, pred_arg, flags, qc->mutex); } static OSSL_TIME get_time(QUIC_CONNECTION *qc) { if (qc->override_now_cb != NULL) return qc->override_now_cb(qc->override_now_cb_arg); else return ossl_time_now(); } static OSSL_TIME get_time_cb(void *arg) { QUIC_CONNECTION *qc = arg; return get_time(qc); } /* * QCTX is a utility structure which provides information we commonly wish to * unwrap upon an API call being dispatched to us, namely: * * - a pointer to the QUIC_CONNECTION (regardless of whether a QCSO or QSSO * was passed); * - a pointer to any applicable QUIC_XSO (e.g. if a QSSO was passed, or if * a QCSO with a default stream was passed); * - whether a QSSO was passed (xso == NULL must not be used to determine this * because it may be non-NULL when a QCSO is passed if that QCSO has a * default stream); * - whether we are in "I/O context", meaning that non-normal errors can * be reported via SSL_get_error() as well as via ERR. Functions such as * SSL_read(), SSL_write() and SSL_do_handshake() are "I/O context" * functions which are allowed to change the value returned by * SSL_get_error. However, other functions (including functions which call * SSL_do_handshake() implicitly) are not allowed to change the return value * of SSL_get_error. */ struct qctx_st { QUIC_CONNECTION *qc; QUIC_XSO *xso; int is_stream, in_io; }; QUIC_NEEDS_LOCK static void quic_set_last_error(QCTX *ctx, int last_error) { if (!ctx->in_io) return; if (ctx->is_stream && ctx->xso != NULL) ctx->xso->last_error = last_error; else if (!ctx->is_stream && ctx->qc != NULL) ctx->qc->last_error = last_error; } /* * Raise a 'normal' error, meaning one that can be reported via SSL_get_error() * rather than via ERR. Note that normal errors must always be raised while * holding a lock. */ QUIC_NEEDS_LOCK static int quic_raise_normal_error(QCTX *ctx, int err) { assert(ctx->in_io); quic_set_last_error(ctx, err); return 0; } /* * Raise a 'non-normal' error, meaning any error that is not reported via * SSL_get_error() and must be reported via ERR. * * qc should be provided if available. In exceptional circumstances when qc is * not known NULL may be passed. This should generally only happen when an * expect_...() function defined below fails, which generally indicates a * dispatch error or caller error. * * ctx should be NULL if the connection lock is not held. */ static int quic_raise_non_normal_error(QCTX *ctx, const char *file, int line, const char *func, int reason, const char *fmt, ...) { va_list args; if (ctx != NULL) { quic_set_last_error(ctx, SSL_ERROR_SSL); if (reason == SSL_R_PROTOCOL_IS_SHUTDOWN && ctx->qc != NULL) ossl_quic_channel_restore_err_state(ctx->qc->ch); } ERR_new(); ERR_set_debug(file, line, func); va_start(args, fmt); ERR_vset_error(ERR_LIB_SSL, reason, fmt, args); va_end(args); return 0; } #define QUIC_RAISE_NORMAL_ERROR(ctx, err) \ quic_raise_normal_error((ctx), (err)) #define QUIC_RAISE_NON_NORMAL_ERROR(ctx, reason, msg) \ quic_raise_non_normal_error((ctx), \ OPENSSL_FILE, OPENSSL_LINE, \ OPENSSL_FUNC, \ (reason), \ (msg)) /* * Given a QCSO or QSSO, initialises a QCTX, determining the contextually * applicable QUIC_CONNECTION pointer and, if applicable, QUIC_XSO pointer. * * After this returns 1, all fields of the passed QCTX are initialised. * Returns 0 on failure. This function is intended to be used to provide API * semantics and as such, it invokes QUIC_RAISE_NON_NORMAL_ERROR() on failure. */ static int expect_quic(const SSL *s, QCTX *ctx) { QUIC_CONNECTION *qc; QUIC_XSO *xso; ctx->qc = NULL; ctx->xso = NULL; ctx->is_stream = 0; if (s == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_PASSED_NULL_PARAMETER, NULL); switch (s->type) { case SSL_TYPE_QUIC_CONNECTION: qc = (QUIC_CONNECTION *)s; ctx->qc = qc; ctx->xso = qc->default_xso; ctx->is_stream = 0; ctx->in_io = 0; return 1; case SSL_TYPE_QUIC_XSO: xso = (QUIC_XSO *)s; ctx->qc = xso->conn; ctx->xso = xso; ctx->is_stream = 1; ctx->in_io = 0; return 1; default: return QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); } } /* * Like expect_quic(), but requires a QUIC_XSO be contextually available. In * other words, requires that the passed QSO be a QSSO or a QCSO with a default * stream. * * remote_init determines if we expect the default XSO to be remotely created or * not. If it is -1, do not instantiate a default XSO if one does not yet exist. * * Channel mutex is acquired and retained on success. */ QUIC_ACQUIRES_LOCK static int ossl_unused expect_quic_with_stream_lock(const SSL *s, int remote_init, int in_io, QCTX *ctx) { if (!expect_quic(s, ctx)) return 0; if (in_io) quic_lock_for_io(ctx); else quic_lock(ctx->qc); if (ctx->xso == NULL && remote_init >= 0) { if (!quic_mutation_allowed(ctx->qc, /*req_active=*/0)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto err; } /* If we haven't finished the handshake, try to advance it. */ if (quic_do_handshake(ctx) < 1) /* ossl_quic_do_handshake raised error here */ goto err; if (remote_init == 0) { if (!qc_try_create_default_xso_for_write(ctx)) goto err; } else { if (!qc_wait_for_default_xso_for_read(ctx)) goto err; } ctx->xso = ctx->qc->default_xso; } if (ctx->xso == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_NO_STREAM, NULL); goto err; } return 1; /* coverity[missing_unlock]: lock held */ err: quic_unlock(ctx->qc); return 0; } /* * Like expect_quic(), but fails if called on a QUIC_XSO. ctx->xso may still * be non-NULL if the QCSO has a default stream. */ static int ossl_unused expect_quic_conn_only(const SSL *s, QCTX *ctx) { if (!expect_quic(s, ctx)) return 0; if (ctx->is_stream) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_CONN_USE_ONLY, NULL); return 1; } /* * Ensures that the channel mutex is held for a method which touches channel * state. * * Precondition: Channel mutex is not held (unchecked) */ static void quic_lock(QUIC_CONNECTION *qc) { #if defined(OPENSSL_THREADS) ossl_crypto_mutex_lock(qc->mutex); #endif } static void quic_lock_for_io(QCTX *ctx) { quic_lock(ctx->qc); ctx->in_io = 1; /* * We are entering an I/O function so we must update the values returned by * SSL_get_error and SSL_want. Set no error. This will be overridden later * if a call to QUIC_RAISE_NORMAL_ERROR or QUIC_RAISE_NON_NORMAL_ERROR * occurs during the API call. */ quic_set_last_error(ctx, SSL_ERROR_NONE); } /* Precondition: Channel mutex is held (unchecked) */ QUIC_NEEDS_LOCK static void quic_unlock(QUIC_CONNECTION *qc) { #if defined(OPENSSL_THREADS) ossl_crypto_mutex_unlock(qc->mutex); #endif } /* * This predicate is the criterion which should determine API call rejection for * *most* mutating API calls, particularly stream-related operations for send * parts. * * A call is rejected (this function returns 0) if shutdown is in progress * (stream flushing), or we are in a TERMINATING or TERMINATED state. If * req_active=1, the connection must be active (i.e., the IDLE state is also * rejected). */ static int quic_mutation_allowed(QUIC_CONNECTION *qc, int req_active) { if (qc->shutting_down || ossl_quic_channel_is_term_any(qc->ch)) return 0; if (req_active && !ossl_quic_channel_is_active(qc->ch)) return 0; return 1; } /* * QUIC Front-End I/O API: Initialization * ====================================== * * SSL_new => ossl_quic_new * ossl_quic_init * SSL_reset => ossl_quic_reset * SSL_clear => ossl_quic_clear * ossl_quic_deinit * SSL_free => ossl_quic_free * * SSL_set_options => ossl_quic_set_options * SSL_get_options => ossl_quic_get_options * SSL_clear_options => ossl_quic_clear_options * */ /* SSL_new */ SSL *ossl_quic_new(SSL_CTX *ctx) { QUIC_CONNECTION *qc = NULL; SSL *ssl_base = NULL; SSL_CONNECTION *sc = NULL; qc = OPENSSL_zalloc(sizeof(*qc)); if (qc == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); return NULL; } #if defined(OPENSSL_THREADS) if ((qc->mutex = ossl_crypto_mutex_new()) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } #endif /* Initialise the QUIC_CONNECTION's stub header. */ ssl_base = &qc->ssl; if (!ossl_ssl_init(ssl_base, ctx, ctx->method, SSL_TYPE_QUIC_CONNECTION)) { ssl_base = NULL; QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } qc->tls = ossl_ssl_connection_new_int(ctx, TLS_method()); if (qc->tls == NULL || (sc = SSL_CONNECTION_FROM_SSL(qc->tls)) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* override the user_ssl of the inner connection */ sc->s3.flags |= TLS1_FLAGS_QUIC; /* Restrict options derived from the SSL_CTX. */ sc->options &= OSSL_QUIC_PERMITTED_OPTIONS_CONN; sc->pha_enabled = 0; #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) qc->is_thread_assisted = (ssl_base->method == OSSL_QUIC_client_thread_method()); #endif qc->as_server = 0; /* TODO(QUIC SERVER): add server support */ qc->as_server_state = qc->as_server; qc->default_stream_mode = SSL_DEFAULT_STREAM_MODE_AUTO_BIDI; qc->default_ssl_mode = qc->ssl.ctx->mode; qc->default_ssl_options = qc->ssl.ctx->options & OSSL_QUIC_PERMITTED_OPTIONS; qc->desires_blocking = 1; qc->blocking = 0; qc->incoming_stream_policy = SSL_INCOMING_STREAM_POLICY_AUTO; qc->last_error = SSL_ERROR_NONE; if (!create_channel(qc)) goto err; ossl_quic_channel_set_msg_callback(qc->ch, ctx->msg_callback, ssl_base); ossl_quic_channel_set_msg_callback_arg(qc->ch, ctx->msg_callback_arg); qc_update_reject_policy(qc); /* * We do not create the default XSO yet. The reason for this is that the * stream ID of the default XSO will depend on whether the stream is client * or server-initiated, which depends on who transmits first. Since we do * not know whether the application will be using a client-transmits-first * or server-transmits-first protocol, we defer default XSO creation until * the client calls SSL_read() or SSL_write(). If it calls SSL_read() first, * we take that as a cue that the client is expecting a server-initiated * stream, and vice versa if SSL_write() is called first. */ return ssl_base; err: if (ssl_base == NULL) { #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(qc->mutex); #endif OPENSSL_free(qc); } else { SSL_free(ssl_base); } return NULL; } /* SSL_free */ QUIC_TAKES_LOCK void ossl_quic_free(SSL *s) { QCTX ctx; int is_default; /* We should never be called on anything but a QSO. */ if (!expect_quic(s, &ctx)) return; quic_lock(ctx.qc); if (ctx.is_stream) { /* * When a QSSO is freed, the XSO is freed immediately, because the XSO * itself only contains API personality layer data. However the * underlying QUIC_STREAM is not freed immediately but is instead marked * as deleted for later collection. */ assert(ctx.qc->num_xso > 0); --ctx.qc->num_xso; /* If a stream's send part has not been finished, auto-reset it. */ if (( ctx.xso->stream->send_state == QUIC_SSTREAM_STATE_READY || ctx.xso->stream->send_state == QUIC_SSTREAM_STATE_SEND) && !ossl_quic_sstream_get_final_size(ctx.xso->stream->sstream, NULL)) ossl_quic_stream_map_reset_stream_send_part(ossl_quic_channel_get_qsm(ctx.qc->ch), ctx.xso->stream, 0); /* Do STOP_SENDING for the receive part, if applicable. */ if ( ctx.xso->stream->recv_state == QUIC_RSTREAM_STATE_RECV || ctx.xso->stream->recv_state == QUIC_RSTREAM_STATE_SIZE_KNOWN) ossl_quic_stream_map_stop_sending_recv_part(ossl_quic_channel_get_qsm(ctx.qc->ch), ctx.xso->stream, 0); /* Update stream state. */ ctx.xso->stream->deleted = 1; ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(ctx.qc->ch), ctx.xso->stream); is_default = (ctx.xso == ctx.qc->default_xso); quic_unlock(ctx.qc); /* * Unref the connection in most cases; the XSO has a ref to the QC and * not vice versa. But for a default XSO, to avoid circular references, * the QC refs the XSO but the XSO does not ref the QC. If we are the * default XSO, we only get here when the QC is being torn down anyway, * so don't call SSL_free(qc) as we are already in it. */ if (!is_default) SSL_free(&ctx.qc->ssl); /* Note: SSL_free calls OPENSSL_free(xso) for us */ return; } /* * Free the default XSO, if any. The QUIC_STREAM is not deleted at this * stage, but is freed during the channel free when the whole QSM is freed. */ if (ctx.qc->default_xso != NULL) { QUIC_XSO *xso = ctx.qc->default_xso; quic_unlock(ctx.qc); SSL_free(&xso->ssl); quic_lock(ctx.qc); ctx.qc->default_xso = NULL; } /* Ensure we have no remaining XSOs. */ assert(ctx.qc->num_xso == 0); #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) if (ctx.qc->is_thread_assisted && ctx.qc->started) { ossl_quic_thread_assist_wait_stopped(&ctx.qc->thread_assist); ossl_quic_thread_assist_cleanup(&ctx.qc->thread_assist); } #endif ossl_quic_channel_free(ctx.qc->ch); ossl_quic_port_free(ctx.qc->port); ossl_quic_engine_free(ctx.qc->engine); BIO_free_all(ctx.qc->net_rbio); BIO_free_all(ctx.qc->net_wbio); /* Note: SSL_free calls OPENSSL_free(qc) for us */ SSL_free(ctx.qc->tls); quic_unlock(ctx.qc); /* tsan doesn't like freeing locked mutexes */ #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(&ctx.qc->mutex); #endif } /* SSL method init */ int ossl_quic_init(SSL *s) { /* Same op as SSL_clear, forward the call. */ return ossl_quic_clear(s); } /* SSL method deinit */ void ossl_quic_deinit(SSL *s) { /* No-op. */ } /* SSL_clear (ssl_reset method) */ int ossl_quic_reset(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; ERR_raise(ERR_LIB_SSL, ERR_R_UNSUPPORTED); return 0; } /* ssl_clear method (unused) */ int ossl_quic_clear(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; ERR_raise(ERR_LIB_SSL, ERR_R_UNSUPPORTED); return 0; } int ossl_quic_conn_set_override_now_cb(SSL *s, OSSL_TIME (*now_cb)(void *arg), void *now_cb_arg) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); ctx.qc->override_now_cb = now_cb; ctx.qc->override_now_cb_arg = now_cb_arg; quic_unlock(ctx.qc); return 1; } void ossl_quic_conn_force_assist_thread_wake(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return; #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) if (ctx.qc->is_thread_assisted && ctx.qc->started) ossl_quic_thread_assist_notify_deadline_changed(&ctx.qc->thread_assist); #endif } QUIC_NEEDS_LOCK static void qc_touch_default_xso(QUIC_CONNECTION *qc) { qc->default_xso_created = 1; qc_update_reject_policy(qc); } /* * Changes default XSO. Allows caller to keep reference to the old default XSO * (if any). Reference to new XSO is transferred from caller. */ QUIC_NEEDS_LOCK static void qc_set_default_xso_keep_ref(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch, QUIC_XSO **old_xso) { int refs; *old_xso = NULL; if (qc->default_xso != xso) { *old_xso = qc->default_xso; /* transfer old XSO ref to caller */ qc->default_xso = xso; if (xso == NULL) { /* * Changing to not having a default XSO. XSO becomes standalone and * now has a ref to the QC. */ if (!ossl_assert(SSL_up_ref(&qc->ssl))) return; } else { /* * Changing from not having a default XSO to having one. The new XSO * will have had a reference to the QC we need to drop to avoid a * circular reference. * * Currently we never change directly from one default XSO to * another, though this function would also still be correct if this * weren't the case. */ assert(*old_xso == NULL); CRYPTO_DOWN_REF(&qc->ssl.references, &refs); assert(refs > 0); } } if (touch) qc_touch_default_xso(qc); } /* * Changes default XSO, releasing the reference to any previous default XSO. * Reference to new XSO is transferred from caller. */ QUIC_NEEDS_LOCK static void qc_set_default_xso(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch) { QUIC_XSO *old_xso = NULL; qc_set_default_xso_keep_ref(qc, xso, touch, &old_xso); if (old_xso != NULL) SSL_free(&old_xso->ssl); } QUIC_NEEDS_LOCK static void xso_update_options(QUIC_XSO *xso) { int cleanse = ((xso->ssl_options & SSL_OP_CLEANSE_PLAINTEXT) != 0); if (xso->stream->rstream != NULL) ossl_quic_rstream_set_cleanse(xso->stream->rstream, cleanse); if (xso->stream->sstream != NULL) ossl_quic_sstream_set_cleanse(xso->stream->sstream, cleanse); } /* * SSL_set_options * --------------- * * Setting options on a QCSO * - configures the handshake-layer options; * - configures the default data-plane options for new streams; * - configures the data-plane options on the default XSO, if there is one. * * Setting options on a QSSO * - configures data-plane options for that stream only. */ QUIC_TAKES_LOCK static uint64_t quic_mask_or_options(SSL *ssl, uint64_t mask_value, uint64_t or_value) { QCTX ctx; uint64_t hs_mask_value, hs_or_value, ret; if (!expect_quic(ssl, &ctx)) return 0; quic_lock(ctx.qc); if (!ctx.is_stream) { /* * If we were called on the connection, we apply any handshake option * changes. */ hs_mask_value = (mask_value & OSSL_QUIC_PERMITTED_OPTIONS_CONN); hs_or_value = (or_value & OSSL_QUIC_PERMITTED_OPTIONS_CONN); SSL_clear_options(ctx.qc->tls, hs_mask_value); SSL_set_options(ctx.qc->tls, hs_or_value); /* Update defaults for new streams. */ ctx.qc->default_ssl_options = ((ctx.qc->default_ssl_options & ~mask_value) | or_value) & OSSL_QUIC_PERMITTED_OPTIONS; } if (ctx.xso != NULL) { ctx.xso->ssl_options = ((ctx.xso->ssl_options & ~mask_value) | or_value) & OSSL_QUIC_PERMITTED_OPTIONS_STREAM; xso_update_options(ctx.xso); } ret = ctx.is_stream ? ctx.xso->ssl_options : ctx.qc->default_ssl_options; quic_unlock(ctx.qc); return ret; } uint64_t ossl_quic_set_options(SSL *ssl, uint64_t options) { return quic_mask_or_options(ssl, 0, options); } /* SSL_clear_options */ uint64_t ossl_quic_clear_options(SSL *ssl, uint64_t options) { return quic_mask_or_options(ssl, options, 0); } /* SSL_get_options */ uint64_t ossl_quic_get_options(const SSL *ssl) { return quic_mask_or_options((SSL *)ssl, 0, 0); } /* * QUIC Front-End I/O API: Network BIO Configuration * ================================================= * * Handling the different BIOs is difficult: * * - It is more or less a requirement that we use non-blocking network I/O; * we need to be able to have timeouts on recv() calls, and make best effort * (non blocking) send() and recv() calls. * * The only sensible way to do this is to configure the socket into * non-blocking mode. We could try to do select() before calling send() or * recv() to get a guarantee that the call will not block, but this will * probably run into issues with buggy OSes which generate spurious socket * readiness events. In any case, relying on this to work reliably does not * seem sane. * * Timeouts could be handled via setsockopt() socket timeout options, but * this depends on OS support and adds another syscall to every network I/O * operation. It also has obvious thread safety concerns if we want to move * to concurrent use of a single socket at some later date. * * Some OSes support a MSG_DONTWAIT flag which allows a single I/O option to * be made non-blocking. However some OSes (e.g. Windows) do not support * this, so we cannot rely on this. * * As such, we need to configure any FD in non-blocking mode. This may * confound users who pass a blocking socket to libssl. However, in practice * it would be extremely strange for a user of QUIC to pass an FD to us, * then also try and send receive traffic on the same socket(!). Thus the * impact of this should be limited, and can be documented. * * - We support both blocking and non-blocking operation in terms of the API * presented to the user. One prospect is to set the blocking mode based on * whether the socket passed to us was already in blocking mode. However, * Windows has no API for determining if a socket is in blocking mode (!), * therefore this cannot be done portably. Currently therefore we expose an * explicit API call to set this, and default to blocking mode. * * - We need to determine our initial destination UDP address. The "natural" * way for a user to do this is to set the peer variable on a BIO_dgram. * However, this has problems because BIO_dgram's peer variable is used for * both transmission and reception. This means it can be constantly being * changed to a malicious value (e.g. if some random unrelated entity on the * network starts sending traffic to us) on every read call. This is not a * direct issue because we use the 'stateless' BIO_sendmmsg and BIO_recvmmsg * calls only, which do not use this variable. However, we do need to let * the user specify the peer in a 'normal' manner. The compromise here is * that we grab the current peer value set at the time the write BIO is set * and do not read the value again. * * - We also need to support memory BIOs (e.g. BIO_dgram_pair) or custom BIOs. * Currently we do this by only supporting non-blocking mode. * */ /* * Determines what initial destination UDP address we should use, if possible. * If this fails the client must set the destination address manually, or use a * BIO which does not need a destination address. */ static int csm_analyse_init_peer_addr(BIO *net_wbio, BIO_ADDR *peer) { if (BIO_dgram_detect_peer_addr(net_wbio, peer) <= 0) return 0; return 1; } static int qc_can_support_blocking_cached(QUIC_CONNECTION *qc) { QUIC_REACTOR *rtor = ossl_quic_channel_get_reactor(qc->ch); return ossl_quic_reactor_can_poll_r(rtor) && ossl_quic_reactor_can_poll_w(rtor); } static void qc_update_can_support_blocking(QUIC_CONNECTION *qc) { ossl_quic_port_update_poll_descriptors(qc->port); /* best effort */ } static void qc_update_blocking_mode(QUIC_CONNECTION *qc) { qc->blocking = qc->desires_blocking && qc_can_support_blocking_cached(qc); } void ossl_quic_conn_set0_net_rbio(SSL *s, BIO *net_rbio) { QCTX ctx; if (!expect_quic(s, &ctx)) return; if (ctx.qc->net_rbio == net_rbio) return; if (!ossl_quic_port_set_net_rbio(ctx.qc->port, net_rbio)) return; BIO_free_all(ctx.qc->net_rbio); ctx.qc->net_rbio = net_rbio; if (net_rbio != NULL) BIO_set_nbio(net_rbio, 1); /* best effort autoconfig */ /* * Determine if the current pair of read/write BIOs now set allows blocking * mode to be supported. */ qc_update_can_support_blocking(ctx.qc); qc_update_blocking_mode(ctx.qc); } void ossl_quic_conn_set0_net_wbio(SSL *s, BIO *net_wbio) { QCTX ctx; if (!expect_quic(s, &ctx)) return; if (ctx.qc->net_wbio == net_wbio) return; if (!ossl_quic_port_set_net_wbio(ctx.qc->port, net_wbio)) return; BIO_free_all(ctx.qc->net_wbio); ctx.qc->net_wbio = net_wbio; if (net_wbio != NULL) BIO_set_nbio(net_wbio, 1); /* best effort autoconfig */ /* * Determine if the current pair of read/write BIOs now set allows blocking * mode to be supported. */ qc_update_can_support_blocking(ctx.qc); qc_update_blocking_mode(ctx.qc); } BIO *ossl_quic_conn_get_net_rbio(const SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return NULL; return ctx.qc->net_rbio; } BIO *ossl_quic_conn_get_net_wbio(const SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return NULL; return ctx.qc->net_wbio; } int ossl_quic_conn_get_blocking_mode(const SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; if (ctx.is_stream) return xso_blocking_mode(ctx.xso); return qc_blocking_mode(ctx.qc); } QUIC_TAKES_LOCK int ossl_quic_conn_set_blocking_mode(SSL *s, int blocking) { int ret = 0; QCTX ctx; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); /* Sanity check - can we support the request given the current network BIO? */ if (blocking) { /* * If called directly on a QCSO, update our information on network BIO * capabilities. */ if (!ctx.is_stream) qc_update_can_support_blocking(ctx.qc); /* Cannot enable blocking mode if we do not have pollable FDs. */ if (!qc_can_support_blocking_cached(ctx.qc)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_UNSUPPORTED, NULL); goto out; } } if (!ctx.is_stream) /* * If called directly on a QCSO, update default and connection-level * blocking modes. */ ctx.qc->desires_blocking = (blocking != 0); if (ctx.xso != NULL) { /* * If called on a QSSO or a QCSO with a default XSO, update the blocking * mode. */ ctx.xso->desires_blocking = (blocking != 0); ctx.xso->desires_blocking_set = 1; } ret = 1; out: qc_update_blocking_mode(ctx.qc); quic_unlock(ctx.qc); return ret; } int ossl_quic_conn_set_initial_peer_addr(SSL *s, const BIO_ADDR *peer_addr) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; if (ctx.qc->started) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, NULL); if (peer_addr == NULL) { BIO_ADDR_clear(&ctx.qc->init_peer_addr); return 1; } ctx.qc->init_peer_addr = *peer_addr; return 1; } /* * QUIC Front-End I/O API: Asynchronous I/O Management * =================================================== * * (BIO/)SSL_handle_events => ossl_quic_handle_events * (BIO/)SSL_get_event_timeout => ossl_quic_get_event_timeout * (BIO/)SSL_get_poll_fd => ossl_quic_get_poll_fd * */ /* Returns 1 if the connection is being used in blocking mode. */ static int qc_blocking_mode(const QUIC_CONNECTION *qc) { return qc->blocking; } static int xso_blocking_mode(const QUIC_XSO *xso) { if (xso->desires_blocking_set) return xso->desires_blocking && qc_can_support_blocking_cached(xso->conn); else /* Only ever set if we can support blocking. */ return xso->conn->blocking; } /* SSL_handle_events; performs QUIC I/O and timeout processing. */ QUIC_TAKES_LOCK int ossl_quic_handle_events(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0); quic_unlock(ctx.qc); return 1; } /* * SSL_get_event_timeout. Get the time in milliseconds until the SSL object * should next have events handled by the application by calling * SSL_handle_events(). tv is set to 0 if the object should have events handled * immediately. If no timeout is currently active, *is_infinite is set to 1 and * the value of *tv is undefined. */ QUIC_TAKES_LOCK int ossl_quic_get_event_timeout(SSL *s, struct timeval *tv, int *is_infinite) { QCTX ctx; OSSL_TIME deadline = ossl_time_infinite(); if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); deadline = ossl_quic_reactor_get_tick_deadline(ossl_quic_channel_get_reactor(ctx.qc->ch)); if (ossl_time_is_infinite(deadline)) { *is_infinite = 1; /* * Robustness against faulty applications that don't check *is_infinite; * harmless long timeout. */ tv->tv_sec = 1000000; tv->tv_usec = 0; quic_unlock(ctx.qc); return 1; } *tv = ossl_time_to_timeval(ossl_time_subtract(deadline, get_time(ctx.qc))); *is_infinite = 0; quic_unlock(ctx.qc); return 1; } /* SSL_get_rpoll_descriptor */ int ossl_quic_get_rpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; if (desc == NULL || ctx.qc->net_rbio == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return BIO_get_rpoll_descriptor(ctx.qc->net_rbio, desc); } /* SSL_get_wpoll_descriptor */ int ossl_quic_get_wpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; if (desc == NULL || ctx.qc->net_wbio == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return BIO_get_wpoll_descriptor(ctx.qc->net_wbio, desc); } /* SSL_net_read_desired */ QUIC_TAKES_LOCK int ossl_quic_get_net_read_desired(SSL *s) { QCTX ctx; int ret; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); ret = ossl_quic_reactor_net_read_desired(ossl_quic_channel_get_reactor(ctx.qc->ch)); quic_unlock(ctx.qc); return ret; } /* SSL_net_write_desired */ QUIC_TAKES_LOCK int ossl_quic_get_net_write_desired(SSL *s) { int ret; QCTX ctx; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); ret = ossl_quic_reactor_net_write_desired(ossl_quic_channel_get_reactor(ctx.qc->ch)); quic_unlock(ctx.qc); return ret; } /* * QUIC Front-End I/O API: Connection Lifecycle Operations * ======================================================= * * SSL_do_handshake => ossl_quic_do_handshake * SSL_set_connect_state => ossl_quic_set_connect_state * SSL_set_accept_state => ossl_quic_set_accept_state * SSL_shutdown => ossl_quic_shutdown * SSL_ctrl => ossl_quic_ctrl * (BIO/)SSL_connect => ossl_quic_connect * (BIO/)SSL_accept => ossl_quic_accept * */ QUIC_NEEDS_LOCK static void qc_shutdown_flush_init(QUIC_CONNECTION *qc) { QUIC_STREAM_MAP *qsm; if (qc->shutting_down) return; qsm = ossl_quic_channel_get_qsm(qc->ch); ossl_quic_stream_map_begin_shutdown_flush(qsm); qc->shutting_down = 1; } /* Returns 1 if all shutdown-flush streams have been done with. */ QUIC_NEEDS_LOCK static int qc_shutdown_flush_finished(QUIC_CONNECTION *qc) { QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(qc->ch); return qc->shutting_down && ossl_quic_stream_map_is_shutdown_flush_finished(qsm); } /* SSL_shutdown */ static int quic_shutdown_wait(void *arg) { QUIC_CONNECTION *qc = arg; return ossl_quic_channel_is_terminated(qc->ch); } /* Returns 1 if shutdown flush process has finished or is inapplicable. */ static int quic_shutdown_flush_wait(void *arg) { QUIC_CONNECTION *qc = arg; return ossl_quic_channel_is_term_any(qc->ch) || qc_shutdown_flush_finished(qc); } static int quic_shutdown_peer_wait(void *arg) { QUIC_CONNECTION *qc = arg; return ossl_quic_channel_is_term_any(qc->ch); } QUIC_TAKES_LOCK int ossl_quic_conn_shutdown(SSL *s, uint64_t flags, const SSL_SHUTDOWN_EX_ARGS *args, size_t args_len) { int ret; QCTX ctx; int stream_flush = ((flags & SSL_SHUTDOWN_FLAG_NO_STREAM_FLUSH) == 0); int no_block = ((flags & SSL_SHUTDOWN_FLAG_NO_BLOCK) != 0); int wait_peer = ((flags & SSL_SHUTDOWN_FLAG_WAIT_PEER) != 0); if (!expect_quic(s, &ctx)) return -1; if (ctx.is_stream) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_CONN_USE_ONLY, NULL); return -1; } quic_lock(ctx.qc); if (ossl_quic_channel_is_terminated(ctx.qc->ch)) { quic_unlock(ctx.qc); return 1; } /* Phase 1: Stream Flushing */ if (!wait_peer && stream_flush) { qc_shutdown_flush_init(ctx.qc); if (!qc_shutdown_flush_finished(ctx.qc)) { if (!no_block && qc_blocking_mode(ctx.qc)) { ret = block_until_pred(ctx.qc, quic_shutdown_flush_wait, ctx.qc, 0); if (ret < 1) { ret = 0; goto err; } } else { ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0); } } if (!qc_shutdown_flush_finished(ctx.qc)) { quic_unlock(ctx.qc); return 0; /* ongoing */ } } /* Phase 2: Connection Closure */ if (wait_peer && !ossl_quic_channel_is_term_any(ctx.qc->ch)) { if (!no_block && qc_blocking_mode(ctx.qc)) { ret = block_until_pred(ctx.qc, quic_shutdown_peer_wait, ctx.qc, 0); if (ret < 1) { ret = 0; goto err; } } else { ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0); } if (!ossl_quic_channel_is_term_any(ctx.qc->ch)) { ret = 0; /* peer hasn't closed yet - still not done */ goto err; } /* * We are at least terminating - go through the normal process of * waiting until we are in the TERMINATED state. */ } /* Block mutation ops regardless of if we did stream flush. */ ctx.qc->shutting_down = 1; /* * This call is a no-op if we are already terminating, so it doesn't * affect the wait_peer case. */ ossl_quic_channel_local_close(ctx.qc->ch, args != NULL ? args->quic_error_code : 0, args != NULL ? args->quic_reason : NULL); SSL_set_shutdown(ctx.qc->tls, SSL_SENT_SHUTDOWN); if (ossl_quic_channel_is_terminated(ctx.qc->ch)) { quic_unlock(ctx.qc); return 1; } /* Phase 3: Terminating Wait Time */ if (!no_block && qc_blocking_mode(ctx.qc) && (flags & SSL_SHUTDOWN_FLAG_RAPID) == 0) { ret = block_until_pred(ctx.qc, quic_shutdown_wait, ctx.qc, 0); if (ret < 1) { ret = 0; goto err; } } else { ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0); } ret = ossl_quic_channel_is_terminated(ctx.qc->ch); err: quic_unlock(ctx.qc); return ret; } /* SSL_ctrl */ long ossl_quic_ctrl(SSL *s, int cmd, long larg, void *parg) { QCTX ctx; if (!expect_quic(s, &ctx)) return 0; switch (cmd) { case SSL_CTRL_MODE: /* If called on a QCSO, update the default mode. */ if (!ctx.is_stream) ctx.qc->default_ssl_mode |= (uint32_t)larg; /* * If we were called on a QSSO or have a default stream, we also update * that. */ if (ctx.xso != NULL) { /* Cannot enable EPW while AON write in progress. */ if (ctx.xso->aon_write_in_progress) larg &= ~SSL_MODE_ENABLE_PARTIAL_WRITE; ctx.xso->ssl_mode |= (uint32_t)larg; return ctx.xso->ssl_mode; } return ctx.qc->default_ssl_mode; case SSL_CTRL_CLEAR_MODE: if (!ctx.is_stream) ctx.qc->default_ssl_mode &= ~(uint32_t)larg; if (ctx.xso != NULL) { ctx.xso->ssl_mode &= ~(uint32_t)larg; return ctx.xso->ssl_mode; } return ctx.qc->default_ssl_mode; case SSL_CTRL_SET_MSG_CALLBACK_ARG: ossl_quic_channel_set_msg_callback_arg(ctx.qc->ch, parg); /* This ctrl also needs to be passed to the internal SSL object */ return SSL_ctrl(ctx.qc->tls, cmd, larg, parg); case DTLS_CTRL_GET_TIMEOUT: /* DTLSv1_get_timeout */ { int is_infinite; if (!ossl_quic_get_event_timeout(s, parg, &is_infinite)) return 0; return !is_infinite; } case DTLS_CTRL_HANDLE_TIMEOUT: /* DTLSv1_handle_timeout */ /* For legacy compatibility with DTLS calls. */ return ossl_quic_handle_events(s) == 1 ? 1 : -1; /* Mask ctrls we shouldn't support for QUIC. */ case SSL_CTRL_GET_READ_AHEAD: case SSL_CTRL_SET_READ_AHEAD: case SSL_CTRL_SET_MAX_SEND_FRAGMENT: case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT: case SSL_CTRL_SET_MAX_PIPELINES: return 0; default: /* * Probably a TLS related ctrl. Send back to the frontend SSL_ctrl * implementation. Either SSL_ctrl will handle it itself by direct * access into handshake layer state, or failing that, it will be passed * to the handshake layer via the SSL_METHOD vtable. If the ctrl is not * supported by anything, the handshake layer's ctrl method will finally * return 0. */ return ossl_ctrl_internal(&ctx.qc->ssl, cmd, larg, parg, /*no_quic=*/1); } } /* SSL_set_connect_state */ void ossl_quic_set_connect_state(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return; /* Cannot be changed after handshake started */ if (ctx.qc->started || ctx.is_stream) return; ctx.qc->as_server_state = 0; } /* SSL_set_accept_state */ void ossl_quic_set_accept_state(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return; /* Cannot be changed after handshake started */ if (ctx.qc->started || ctx.is_stream) return; ctx.qc->as_server_state = 1; } /* SSL_do_handshake */ struct quic_handshake_wait_args { QUIC_CONNECTION *qc; }; static int tls_wants_non_io_retry(QUIC_CONNECTION *qc) { int want = SSL_want(qc->tls); if (want == SSL_X509_LOOKUP || want == SSL_CLIENT_HELLO_CB || want == SSL_RETRY_VERIFY) return 1; return 0; } static int quic_handshake_wait(void *arg) { struct quic_handshake_wait_args *args = arg; if (!quic_mutation_allowed(args->qc, /*req_active=*/1)) return -1; if (ossl_quic_channel_is_handshake_complete(args->qc->ch)) return 1; if (tls_wants_non_io_retry(args->qc)) return 1; return 0; } static int configure_channel(QUIC_CONNECTION *qc) { assert(qc->ch != NULL); if (!ossl_quic_port_set_net_rbio(qc->port, qc->net_rbio) || !ossl_quic_port_set_net_wbio(qc->port, qc->net_wbio) || !ossl_quic_channel_set_peer_addr(qc->ch, &qc->init_peer_addr)) return 0; return 1; } QUIC_NEEDS_LOCK static int create_channel(QUIC_CONNECTION *qc) { QUIC_ENGINE_ARGS engine_args = {0}; QUIC_PORT_ARGS port_args = {0}; engine_args.libctx = qc->ssl.ctx->libctx; engine_args.propq = qc->ssl.ctx->propq; engine_args.mutex = qc->mutex; engine_args.now_cb = get_time_cb; engine_args.now_cb_arg = qc; qc->engine = ossl_quic_engine_new(&engine_args); if (qc->engine == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); return 0; } port_args.channel_ctx = qc->ssl.ctx; qc->port = ossl_quic_engine_create_port(qc->engine, &port_args); if (qc->port == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); ossl_quic_engine_free(qc->engine); return 0; } qc->ch = ossl_quic_port_create_outgoing(qc->port, qc->tls); if (qc->ch == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); ossl_quic_port_free(qc->port); ossl_quic_engine_free(qc->engine); return 0; } return 1; } /* * Configures a channel with the information we have accumulated via calls made * to us from the application prior to starting a handshake attempt. */ QUIC_NEEDS_LOCK static int ensure_channel_started(QCTX *ctx) { QUIC_CONNECTION *qc = ctx->qc; if (!qc->started) { if (!configure_channel(qc)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, "failed to configure channel"); return 0; } if (!ossl_quic_channel_start(qc->ch)) { ossl_quic_channel_restore_err_state(qc->ch); QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, "failed to start channel"); return 0; } #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) if (qc->is_thread_assisted) if (!ossl_quic_thread_assist_init_start(&qc->thread_assist, qc->ch, qc->override_now_cb, qc->override_now_cb_arg)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, "failed to start assist thread"); return 0; } #endif } qc->started = 1; return 1; } QUIC_NEEDS_LOCK static int quic_do_handshake(QCTX *ctx) { int ret; QUIC_CONNECTION *qc = ctx->qc; if (ossl_quic_channel_is_handshake_complete(qc->ch)) /* Handshake already completed. */ return 1; if (!quic_mutation_allowed(qc, /*req_active=*/0)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); if (qc->as_server != qc->as_server_state) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return -1; /* Non-protocol error */ } if (qc->net_rbio == NULL || qc->net_wbio == NULL) { /* Need read and write BIOs. */ QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_BIO_NOT_SET, NULL); return -1; /* Non-protocol error */ } /* * We need to determine our addressing mode. There are basically two * ways we can use L4 addresses: * * - Addressed mode, in which our BIO_sendmmsg calls have destination * addresses attached to them which we expect the underlying network BIO * to handle; * * - Unaddressed mode, in which the BIO provided to us on the * network side neither provides us with L4 addresses nor is capable of * honouring ones we provide. We don't know where the QUIC traffic we * send ends up exactly and trust the application to know what it is * doing. * * Addressed mode is preferred because it enables support for connection * migration, multipath, etc. in the future. Addressed mode is automatically * enabled if we are using e.g. BIO_s_datagram, with or without * BIO_s_connect. * * If we are passed a BIO_s_dgram_pair (or some custom BIO) we may have to * use unaddressed mode unless that BIO supports capability flags indicating * it can provide and honour L4 addresses. * * Our strategy for determining address mode is simple: we probe the * underlying network BIOs for their capabilities. If the network BIOs * support what we need, we use addressed mode. Otherwise, we use * unaddressed mode. * * If addressed mode is chosen, we require an initial peer address to be * set. If this is not set, we fail. If unaddressed mode is used, we do not * require this, as such an address is superfluous, though it can be set if * desired. */ if (!qc->started && !qc->addressing_probe_done) { long rcaps = BIO_dgram_get_effective_caps(qc->net_rbio); long wcaps = BIO_dgram_get_effective_caps(qc->net_wbio); qc->addressed_mode_r = ((rcaps & BIO_DGRAM_CAP_PROVIDES_SRC_ADDR) != 0); qc->addressed_mode_w = ((wcaps & BIO_DGRAM_CAP_HANDLES_DST_ADDR) != 0); qc->addressing_probe_done = 1; } if (!qc->started && qc->addressed_mode_w && BIO_ADDR_family(&qc->init_peer_addr) == AF_UNSPEC) { /* * We are trying to connect and are using addressed mode, which means we * need an initial peer address; if we do not have a peer address yet, * we should try to autodetect one. * * We do this as late as possible because some BIOs (e.g. BIO_s_connect) * may not be able to provide us with a peer address until they have * finished their own processing. They may not be able to perform this * processing until an application has finished configuring that BIO * (e.g. with setter calls), which might happen after SSL_set_bio is * called. */ if (!csm_analyse_init_peer_addr(qc->net_wbio, &qc->init_peer_addr)) /* best effort */ BIO_ADDR_clear(&qc->init_peer_addr); else ossl_quic_channel_set_peer_addr(qc->ch, &qc->init_peer_addr); } if (!qc->started && qc->addressed_mode_w && BIO_ADDR_family(&qc->init_peer_addr) == AF_UNSPEC) { /* * If we still don't have a peer address in addressed mode, we can't do * anything. */ QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_REMOTE_PEER_ADDRESS_NOT_SET, NULL); return -1; /* Non-protocol error */ } /* * Start connection process. Note we may come here multiple times in * non-blocking mode, which is fine. */ if (!ensure_channel_started(ctx)) /* raises on failure */ return -1; /* Non-protocol error */ if (ossl_quic_channel_is_handshake_complete(qc->ch)) /* The handshake is now done. */ return 1; if (!qc_blocking_mode(qc)) { /* Try to advance the reactor. */ ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(qc->ch), 0); if (ossl_quic_channel_is_handshake_complete(qc->ch)) /* The handshake is now done. */ return 1; if (ossl_quic_channel_is_term_any(qc->ch)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return 0; } else if (qc->desires_blocking) { /* * As a special case when doing a handshake when blocking mode is * desired yet not available, see if the network BIOs have become * poll descriptor-enabled. This supports BIOs such as BIO_s_connect * which do late creation of socket FDs and therefore cannot expose * a poll descriptor until after a network BIO is set on the QCSO. */ assert(!qc->blocking); qc_update_can_support_blocking(qc); qc_update_blocking_mode(qc); } } /* * We are either in blocking mode or just entered it due to the code above. */ if (qc_blocking_mode(qc)) { /* In blocking mode, wait for the handshake to complete. */ struct quic_handshake_wait_args args; args.qc = qc; ret = block_until_pred(qc, quic_handshake_wait, &args, 0); if (!quic_mutation_allowed(qc, /*req_active=*/1)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return 0; /* Shutdown before completion */ } else if (ret <= 0) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); return -1; /* Non-protocol error */ } if (tls_wants_non_io_retry(qc)) { QUIC_RAISE_NORMAL_ERROR(ctx, SSL_get_error(qc->tls, 0)); return -1; } assert(ossl_quic_channel_is_handshake_complete(qc->ch)); return 1; } if (tls_wants_non_io_retry(qc)) { QUIC_RAISE_NORMAL_ERROR(ctx, SSL_get_error(qc->tls, 0)); return -1; } /* * Otherwise, indicate that the handshake isn't done yet. * We can only get here in non-blocking mode. */ QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_READ); return -1; /* Non-protocol error */ } QUIC_TAKES_LOCK int ossl_quic_do_handshake(SSL *s) { int ret; QCTX ctx; if (!expect_quic(s, &ctx)) return 0; quic_lock_for_io(&ctx); ret = quic_do_handshake(&ctx); quic_unlock(ctx.qc); return ret; } /* SSL_connect */ int ossl_quic_connect(SSL *s) { /* Ensure we are in connect state (no-op if non-idle). */ ossl_quic_set_connect_state(s); /* Begin or continue the handshake */ return ossl_quic_do_handshake(s); } /* SSL_accept */ int ossl_quic_accept(SSL *s) { /* Ensure we are in accept state (no-op if non-idle). */ ossl_quic_set_accept_state(s); /* Begin or continue the handshake */ return ossl_quic_do_handshake(s); } /* * QUIC Front-End I/O API: Stream Lifecycle Operations * =================================================== * * SSL_stream_new => ossl_quic_conn_stream_new * */ /* * Try to create the default XSO if it doesn't already exist. Returns 1 if the * default XSO was created. Returns 0 if it was not (e.g. because it already * exists). Note that this is NOT an error condition. */ QUIC_NEEDS_LOCK static int qc_try_create_default_xso_for_write(QCTX *ctx) { uint64_t flags = 0; QUIC_CONNECTION *qc = ctx->qc; if (qc->default_xso_created || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) /* * We only do this once. If the user detaches a previously created * default XSO we don't auto-create another one. */ return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_NO_STREAM, NULL); /* Create a locally-initiated stream. */ if (qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_AUTO_UNI) flags |= SSL_STREAM_FLAG_UNI; qc_set_default_xso(qc, (QUIC_XSO *)quic_conn_stream_new(ctx, flags, /*needs_lock=*/0), /*touch=*/0); if (qc->default_xso == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); qc_touch_default_xso(qc); return 1; } struct quic_wait_for_stream_args { QUIC_CONNECTION *qc; QUIC_STREAM *qs; QCTX *ctx; uint64_t expect_id; }; QUIC_NEEDS_LOCK static int quic_wait_for_stream(void *arg) { struct quic_wait_for_stream_args *args = arg; if (!quic_mutation_allowed(args->qc, /*req_active=*/1)) { /* If connection is torn down due to an error while blocking, stop. */ QUIC_RAISE_NON_NORMAL_ERROR(args->ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return -1; } args->qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(args->qc->ch), args->expect_id | QUIC_STREAM_DIR_BIDI); if (args->qs == NULL) args->qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(args->qc->ch), args->expect_id | QUIC_STREAM_DIR_UNI); if (args->qs != NULL) return 1; /* stream now exists */ return 0; /* did not get a stream, keep trying */ } QUIC_NEEDS_LOCK static int qc_wait_for_default_xso_for_read(QCTX *ctx) { /* Called on a QCSO and we don't currently have a default stream. */ uint64_t expect_id; QUIC_CONNECTION *qc = ctx->qc; QUIC_STREAM *qs; int res; struct quic_wait_for_stream_args wargs; OSSL_RTT_INFO rtt_info; /* * If default stream functionality is disabled or we already detached * one, don't make another default stream and just fail. */ if (qc->default_xso_created || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_NO_STREAM, NULL); /* * The peer may have opened a stream since we last ticked. So tick and * see if the stream with ordinal 0 (remote, bidi/uni based on stream * mode) exists yet. QUIC stream IDs must be allocated in order, so the * first stream created by a peer must have an ordinal of 0. */ expect_id = qc->as_server ? QUIC_STREAM_INITIATOR_CLIENT : QUIC_STREAM_INITIATOR_SERVER; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch), expect_id | QUIC_STREAM_DIR_BIDI); if (qs == NULL) qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch), expect_id | QUIC_STREAM_DIR_UNI); if (qs == NULL) { ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(qc->ch), 0); qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch), expect_id); } if (qs == NULL) { if (!qc_blocking_mode(qc)) /* Non-blocking mode, so just bail immediately. */ return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_READ); /* Block until we have a stream. */ wargs.qc = qc; wargs.qs = NULL; wargs.ctx = ctx; wargs.expect_id = expect_id; res = block_until_pred(qc, quic_wait_for_stream, &wargs, 0); if (res == 0) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); else if (res < 0 || wargs.qs == NULL) /* quic_wait_for_stream raised error here */ return 0; qs = wargs.qs; } /* * We now have qs != NULL. Remove it from the incoming stream queue so that * it isn't also returned by any future SSL_accept_stream calls. */ ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(qc->ch), &rtt_info); ossl_quic_stream_map_remove_from_accept_queue(ossl_quic_channel_get_qsm(qc->ch), qs, rtt_info.smoothed_rtt); /* * Now make qs the default stream, creating the necessary XSO. */ qc_set_default_xso(qc, create_xso_from_stream(qc, qs), /*touch=*/0); if (qc->default_xso == NULL) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); qc_touch_default_xso(qc); /* inhibits default XSO */ return 1; } QUIC_NEEDS_LOCK static QUIC_XSO *create_xso_from_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs) { QUIC_XSO *xso = NULL; if ((xso = OPENSSL_zalloc(sizeof(*xso))) == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_CRYPTO_LIB, NULL); goto err; } if (!ossl_ssl_init(&xso->ssl, qc->ssl.ctx, qc->ssl.method, SSL_TYPE_QUIC_XSO)) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL); goto err; } /* XSO refs QC */ if (!SSL_up_ref(&qc->ssl)) { QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_SSL_LIB, NULL); goto err; } xso->conn = qc; xso->ssl_mode = qc->default_ssl_mode; xso->ssl_options = qc->default_ssl_options & OSSL_QUIC_PERMITTED_OPTIONS_STREAM; xso->last_error = SSL_ERROR_NONE; xso->stream = qs; ++qc->num_xso; xso_update_options(xso); return xso; err: OPENSSL_free(xso); return NULL; } struct quic_new_stream_wait_args { QUIC_CONNECTION *qc; int is_uni; }; static int quic_new_stream_wait(void *arg) { struct quic_new_stream_wait_args *args = arg; QUIC_CONNECTION *qc = args->qc; if (!quic_mutation_allowed(qc, /*req_active=*/1)) return -1; if (ossl_quic_channel_is_new_local_stream_admissible(qc->ch, args->is_uni)) return 1; return 0; } /* locking depends on need_lock */ static SSL *quic_conn_stream_new(QCTX *ctx, uint64_t flags, int need_lock) { int ret; QUIC_CONNECTION *qc = ctx->qc; QUIC_XSO *xso = NULL; QUIC_STREAM *qs = NULL; int is_uni = ((flags & SSL_STREAM_FLAG_UNI) != 0); int no_blocking = ((flags & SSL_STREAM_FLAG_NO_BLOCK) != 0); int advance = ((flags & SSL_STREAM_FLAG_ADVANCE) != 0); if (need_lock) quic_lock(qc); if (!quic_mutation_allowed(qc, /*req_active=*/0)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto err; } if (!advance && !ossl_quic_channel_is_new_local_stream_admissible(qc->ch, is_uni)) { struct quic_new_stream_wait_args args; /* * Stream count flow control currently doesn't permit this stream to be * opened. */ if (no_blocking || !qc_blocking_mode(qc)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_STREAM_COUNT_LIMITED, NULL); goto err; } args.qc = qc; args.is_uni = is_uni; /* Blocking mode - wait until we can get a stream. */ ret = block_until_pred(ctx->qc, quic_new_stream_wait, &args, 0); if (!quic_mutation_allowed(qc, /*req_active=*/1)) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto err; /* Shutdown before completion */ } else if (ret <= 0) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); goto err; /* Non-protocol error */ } } qs = ossl_quic_channel_new_stream_local(qc->ch, is_uni); if (qs == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); goto err; } xso = create_xso_from_stream(qc, qs); if (xso == NULL) goto err; qc_touch_default_xso(qc); /* inhibits default XSO */ if (need_lock) quic_unlock(qc); return &xso->ssl; err: OPENSSL_free(xso); ossl_quic_stream_map_release(ossl_quic_channel_get_qsm(qc->ch), qs); if (need_lock) quic_unlock(qc); return NULL; } QUIC_TAKES_LOCK SSL *ossl_quic_conn_stream_new(SSL *s, uint64_t flags) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return NULL; return quic_conn_stream_new(&ctx, flags, /*need_lock=*/1); } /* * QUIC Front-End I/O API: Steady-State Operations * =============================================== * * Here we dispatch calls to the steady-state front-end I/O API functions; that * is, the functions used during the established phase of a QUIC connection * (e.g. SSL_read, SSL_write). * * Each function must handle both blocking and non-blocking modes. As discussed * above, all QUIC I/O is implemented using non-blocking mode internally. * * SSL_get_error => partially implemented by ossl_quic_get_error * SSL_want => ossl_quic_want * (BIO/)SSL_read => ossl_quic_read * (BIO/)SSL_write => ossl_quic_write * SSL_pending => ossl_quic_pending * SSL_stream_conclude => ossl_quic_conn_stream_conclude * SSL_key_update => ossl_quic_key_update */ /* SSL_get_error */ int ossl_quic_get_error(const SSL *s, int i) { QCTX ctx; int net_error, last_error; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); net_error = ossl_quic_channel_net_error(ctx.qc->ch); last_error = ctx.is_stream ? ctx.xso->last_error : ctx.qc->last_error; quic_unlock(ctx.qc); if (net_error) return SSL_ERROR_SYSCALL; return last_error; } /* Converts a code returned by SSL_get_error to a code returned by SSL_want. */ static int error_to_want(int error) { switch (error) { case SSL_ERROR_WANT_CONNECT: /* never used - UDP is connectionless */ case SSL_ERROR_WANT_ACCEPT: /* never used - UDP is connectionless */ case SSL_ERROR_ZERO_RETURN: default: return SSL_NOTHING; case SSL_ERROR_WANT_READ: return SSL_READING; case SSL_ERROR_WANT_WRITE: return SSL_WRITING; case SSL_ERROR_WANT_RETRY_VERIFY: return SSL_RETRY_VERIFY; case SSL_ERROR_WANT_CLIENT_HELLO_CB: return SSL_CLIENT_HELLO_CB; case SSL_ERROR_WANT_X509_LOOKUP: return SSL_X509_LOOKUP; } } /* SSL_want */ int ossl_quic_want(const SSL *s) { QCTX ctx; int w; if (!expect_quic(s, &ctx)) return SSL_NOTHING; quic_lock(ctx.qc); w = error_to_want(ctx.is_stream ? ctx.xso->last_error : ctx.qc->last_error); quic_unlock(ctx.qc); return w; } /* * SSL_write * --------- * * The set of functions below provide the implementation of the public SSL_write * function. We must handle: * * - both blocking and non-blocking operation at the application level, * depending on how we are configured; * * - SSL_MODE_ENABLE_PARTIAL_WRITE being on or off; * * - SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER. * */ QUIC_NEEDS_LOCK static void quic_post_write(QUIC_XSO *xso, int did_append, int do_tick) { /* * We have appended at least one byte to the stream. * Potentially mark stream as active, depending on FC. */ if (did_append) ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(xso->conn->ch), xso->stream); /* * Try and send. * * TODO(QUIC FUTURE): It is probably inefficient to try and do this * immediately, plus we should eventually consider Nagle's algorithm. */ if (do_tick) ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(xso->conn->ch), 0); } struct quic_write_again_args { QUIC_XSO *xso; const unsigned char *buf; size_t len; size_t total_written; int err; }; /* * Absolute maximum write buffer size, enforced to prevent a rogue peer from * deliberately inducing DoS. This has been chosen based on the optimal buffer * size for an RTT of 500ms and a bandwidth of 100 Mb/s. */ #define MAX_WRITE_BUF_SIZE (6 * 1024 * 1024) /* * Ensure spare buffer space available (up until a limit, at least). */ QUIC_NEEDS_LOCK static int sstream_ensure_spare(QUIC_SSTREAM *sstream, uint64_t spare) { size_t cur_sz = ossl_quic_sstream_get_buffer_size(sstream); size_t avail = ossl_quic_sstream_get_buffer_avail(sstream); size_t spare_ = (spare > SIZE_MAX) ? SIZE_MAX : (size_t)spare; size_t new_sz, growth; if (spare_ <= avail || cur_sz == MAX_WRITE_BUF_SIZE) return 1; growth = spare_ - avail; if (cur_sz + growth > MAX_WRITE_BUF_SIZE) new_sz = MAX_WRITE_BUF_SIZE; else new_sz = cur_sz + growth; return ossl_quic_sstream_set_buffer_size(sstream, new_sz); } /* * Append to a QUIC_STREAM's QUIC_SSTREAM, ensuring buffer space is expanded * as needed according to flow control. */ QUIC_NEEDS_LOCK static int xso_sstream_append(QUIC_XSO *xso, const unsigned char *buf, size_t len, size_t *actual_written) { QUIC_SSTREAM *sstream = xso->stream->sstream; uint64_t cur = ossl_quic_sstream_get_cur_size(sstream); uint64_t cwm = ossl_quic_txfc_get_cwm(&xso->stream->txfc); uint64_t permitted = (cwm >= cur ? cwm - cur : 0); if (len > permitted) len = (size_t)permitted; if (!sstream_ensure_spare(sstream, len)) return 0; return ossl_quic_sstream_append(sstream, buf, len, actual_written); } QUIC_NEEDS_LOCK static int quic_write_again(void *arg) { struct quic_write_again_args *args = arg; size_t actual_written = 0; if (!quic_mutation_allowed(args->xso->conn, /*req_active=*/1)) /* If connection is torn down due to an error while blocking, stop. */ return -2; if (!quic_validate_for_write(args->xso, &args->err)) /* * Stream may have become invalid for write due to connection events * while we blocked. */ return -2; args->err = ERR_R_INTERNAL_ERROR; if (!xso_sstream_append(args->xso, args->buf, args->len, &actual_written)) return -2; quic_post_write(args->xso, actual_written > 0, 0); args->buf += actual_written; args->len -= actual_written; args->total_written += actual_written; if (args->len == 0) /* Written everything, done. */ return 1; /* Not written everything yet, keep trying. */ return 0; } QUIC_NEEDS_LOCK static int quic_write_blocking(QCTX *ctx, const void *buf, size_t len, size_t *written) { int res; QUIC_XSO *xso = ctx->xso; struct quic_write_again_args args; size_t actual_written = 0; /* First make a best effort to append as much of the data as possible. */ if (!xso_sstream_append(xso, buf, len, &actual_written)) { /* Stream already finished or allocation error. */ *written = 0; return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } quic_post_write(xso, actual_written > 0, 1); if (actual_written == len) { /* Managed to append everything on the first try. */ *written = actual_written; return 1; } /* * We did not manage to append all of the data immediately, so the stream * buffer has probably filled up. This means we need to block until some of * it is freed up. */ args.xso = xso; args.buf = (const unsigned char *)buf + actual_written; args.len = len - actual_written; args.total_written = 0; args.err = ERR_R_INTERNAL_ERROR; res = block_until_pred(xso->conn, quic_write_again, &args, 0); if (res <= 0) { if (!quic_mutation_allowed(xso->conn, /*req_active=*/1)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); else return QUIC_RAISE_NON_NORMAL_ERROR(ctx, args.err, NULL); } *written = args.total_written; return 1; } /* * Functions to manage All-or-Nothing (AON) (that is, non-ENABLE_PARTIAL_WRITE) * write semantics. */ static void aon_write_begin(QUIC_XSO *xso, const unsigned char *buf, size_t buf_len, size_t already_sent) { assert(!xso->aon_write_in_progress); xso->aon_write_in_progress = 1; xso->aon_buf_base = buf; xso->aon_buf_pos = already_sent; xso->aon_buf_len = buf_len; } static void aon_write_finish(QUIC_XSO *xso) { xso->aon_write_in_progress = 0; xso->aon_buf_base = NULL; xso->aon_buf_pos = 0; xso->aon_buf_len = 0; } QUIC_NEEDS_LOCK static int quic_write_nonblocking_aon(QCTX *ctx, const void *buf, size_t len, size_t *written) { QUIC_XSO *xso = ctx->xso; const void *actual_buf; size_t actual_len, actual_written = 0; int accept_moving_buffer = ((xso->ssl_mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) != 0); if (xso->aon_write_in_progress) { /* * We are in the middle of an AON write (i.e., a previous write did not * manage to append all data to the SSTREAM and we have Enable Partial * Write (EPW) mode disabled.) */ if ((!accept_moving_buffer && xso->aon_buf_base != buf) || len != xso->aon_buf_len) /* * Pointer must not have changed if we are not in accept moving * buffer mode. Length must never change. */ return QUIC_RAISE_NON_NORMAL_ERROR(ctx, SSL_R_BAD_WRITE_RETRY, NULL); actual_buf = (unsigned char *)buf + xso->aon_buf_pos; actual_len = len - xso->aon_buf_pos; assert(actual_len > 0); } else { actual_buf = buf; actual_len = len; } /* First make a best effort to append as much of the data as possible. */ if (!xso_sstream_append(xso, actual_buf, actual_len, &actual_written)) { /* Stream already finished or allocation error. */ *written = 0; return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } quic_post_write(xso, actual_written > 0, 1); if (actual_written == actual_len) { /* We have sent everything. */ if (xso->aon_write_in_progress) { /* * We have sent everything, and we were in the middle of an AON * write. The output write length is the total length of the AON * buffer, not however many bytes we managed to write to the stream * in this call. */ *written = xso->aon_buf_len; aon_write_finish(xso); } else { *written = actual_written; } return 1; } if (xso->aon_write_in_progress) { /* * AON write is in progress but we have not written everything yet. We * may have managed to send zero bytes, or some number of bytes less * than the total remaining which need to be appended during this * AON operation. */ xso->aon_buf_pos += actual_written; assert(xso->aon_buf_pos < xso->aon_buf_len); return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_WRITE); } /* * Not in an existing AON operation but partial write is not enabled, so we * need to begin a new AON operation. However we needn't bother if we didn't * actually append anything. */ if (actual_written > 0) aon_write_begin(xso, buf, len, actual_written); /* * AON - We do not publicly admit to having appended anything until AON * completes. */ *written = 0; return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_WANT_WRITE); } QUIC_NEEDS_LOCK static int quic_write_nonblocking_epw(QCTX *ctx, const void *buf, size_t len, size_t *written) { QUIC_XSO *xso = ctx->xso; /* Simple best effort operation. */ if (!xso_sstream_append(xso, buf, len, written)) { /* Stream already finished or allocation error. */ *written = 0; return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } quic_post_write(xso, *written > 0, 1); return 1; } QUIC_NEEDS_LOCK static int quic_validate_for_write(QUIC_XSO *xso, int *err) { QUIC_STREAM_MAP *qsm; if (xso == NULL || xso->stream == NULL) { *err = ERR_R_INTERNAL_ERROR; return 0; } switch (xso->stream->send_state) { default: case QUIC_SSTREAM_STATE_NONE: *err = SSL_R_STREAM_RECV_ONLY; return 0; case QUIC_SSTREAM_STATE_READY: qsm = ossl_quic_channel_get_qsm(xso->conn->ch); if (!ossl_quic_stream_map_ensure_send_part_id(qsm, xso->stream)) { *err = ERR_R_INTERNAL_ERROR; return 0; } /* FALLTHROUGH */ case QUIC_SSTREAM_STATE_SEND: case QUIC_SSTREAM_STATE_DATA_SENT: case QUIC_SSTREAM_STATE_DATA_RECVD: if (ossl_quic_sstream_get_final_size(xso->stream->sstream, NULL)) { *err = SSL_R_STREAM_FINISHED; return 0; } return 1; case QUIC_SSTREAM_STATE_RESET_SENT: case QUIC_SSTREAM_STATE_RESET_RECVD: *err = SSL_R_STREAM_RESET; return 0; } } QUIC_TAKES_LOCK int ossl_quic_write(SSL *s, const void *buf, size_t len, size_t *written) { int ret; QCTX ctx; int partial_write, err; *written = 0; if (!expect_quic_with_stream_lock(s, /*remote_init=*/0, /*io=*/1, &ctx)) return 0; partial_write = ((ctx.xso->ssl_mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0); if (!quic_mutation_allowed(ctx.qc, /*req_active=*/0)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto out; } /* * If we haven't finished the handshake, try to advance it. * We don't accept writes until the handshake is completed. */ if (quic_do_handshake(&ctx) < 1) { ret = 0; goto out; } /* Ensure correct stream state, stream send part not concluded, etc. */ if (!quic_validate_for_write(ctx.xso, &err)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, err, NULL); goto out; } if (len == 0) { ret = 1; goto out; } if (xso_blocking_mode(ctx.xso)) ret = quic_write_blocking(&ctx, buf, len, written); else if (partial_write) ret = quic_write_nonblocking_epw(&ctx, buf, len, written); else ret = quic_write_nonblocking_aon(&ctx, buf, len, written); out: quic_unlock(ctx.qc); return ret; } /* * SSL_read * -------- */ struct quic_read_again_args { QCTX *ctx; QUIC_STREAM *stream; void *buf; size_t len; size_t *bytes_read; int peek; }; QUIC_NEEDS_LOCK static int quic_validate_for_read(QUIC_XSO *xso, int *err, int *eos) { QUIC_STREAM_MAP *qsm; *eos = 0; if (xso == NULL || xso->stream == NULL) { *err = ERR_R_INTERNAL_ERROR; return 0; } switch (xso->stream->recv_state) { default: case QUIC_RSTREAM_STATE_NONE: *err = SSL_R_STREAM_SEND_ONLY; return 0; case QUIC_RSTREAM_STATE_RECV: case QUIC_RSTREAM_STATE_SIZE_KNOWN: case QUIC_RSTREAM_STATE_DATA_RECVD: return 1; case QUIC_RSTREAM_STATE_DATA_READ: *eos = 1; return 0; case QUIC_RSTREAM_STATE_RESET_RECVD: qsm = ossl_quic_channel_get_qsm(xso->conn->ch); ossl_quic_stream_map_notify_app_read_reset_recv_part(qsm, xso->stream); /* FALLTHROUGH */ case QUIC_RSTREAM_STATE_RESET_READ: *err = SSL_R_STREAM_RESET; return 0; } } QUIC_NEEDS_LOCK static int quic_read_actual(QCTX *ctx, QUIC_STREAM *stream, void *buf, size_t buf_len, size_t *bytes_read, int peek) { int is_fin = 0, err, eos; QUIC_CONNECTION *qc = ctx->qc; if (!quic_validate_for_read(ctx->xso, &err, &eos)) { if (eos) return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_ZERO_RETURN); else return QUIC_RAISE_NON_NORMAL_ERROR(ctx, err, NULL); } if (peek) { if (!ossl_quic_rstream_peek(stream->rstream, buf, buf_len, bytes_read, &is_fin)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } else { if (!ossl_quic_rstream_read(stream->rstream, buf, buf_len, bytes_read, &is_fin)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } if (!peek) { if (*bytes_read > 0) { /* * We have read at least one byte from the stream. Inform stream-level * RXFC of the retirement of controlled bytes. Update the active stream * status (the RXFC may now want to emit a frame granting more credit to * the peer). */ OSSL_RTT_INFO rtt_info; ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(qc->ch), &rtt_info); if (!ossl_quic_rxfc_on_retire(&stream->rxfc, *bytes_read, rtt_info.smoothed_rtt)) return QUIC_RAISE_NON_NORMAL_ERROR(ctx, ERR_R_INTERNAL_ERROR, NULL); } if (is_fin && !peek) { QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(ctx->qc->ch); ossl_quic_stream_map_notify_totally_read(qsm, ctx->xso->stream); } if (*bytes_read > 0) ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(qc->ch), stream); } if (*bytes_read == 0 && is_fin) return QUIC_RAISE_NORMAL_ERROR(ctx, SSL_ERROR_ZERO_RETURN); return 1; } QUIC_NEEDS_LOCK static int quic_read_again(void *arg) { struct quic_read_again_args *args = arg; if (!quic_mutation_allowed(args->ctx->qc, /*req_active=*/1)) { /* If connection is torn down due to an error while blocking, stop. */ QUIC_RAISE_NON_NORMAL_ERROR(args->ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return -1; } if (!quic_read_actual(args->ctx, args->stream, args->buf, args->len, args->bytes_read, args->peek)) return -1; if (*args->bytes_read > 0) /* got at least one byte, the SSL_read op can finish now */ return 1; return 0; /* did not read anything, keep trying */ } QUIC_TAKES_LOCK static int quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read, int peek) { int ret, res; QCTX ctx; struct quic_read_again_args args; *bytes_read = 0; if (!expect_quic(s, &ctx)) return 0; quic_lock_for_io(&ctx); if (!quic_mutation_allowed(ctx.qc, /*req_active=*/0)) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); goto out; } /* If we haven't finished the handshake, try to advance it. */ if (quic_do_handshake(&ctx) < 1) { ret = 0; /* ossl_quic_do_handshake raised error here */ goto out; } if (ctx.xso == NULL) { /* * Called on a QCSO and we don't currently have a default stream. * * Wait until we get a stream initiated by the peer (blocking mode) or * fail if we don't have one yet (non-blocking mode). */ if (!qc_wait_for_default_xso_for_read(&ctx)) { ret = 0; /* error already raised here */ goto out; } ctx.xso = ctx.qc->default_xso; } if (!quic_read_actual(&ctx, ctx.xso->stream, buf, len, bytes_read, peek)) { ret = 0; /* quic_read_actual raised error here */ goto out; } if (*bytes_read > 0) { /* * Even though we succeeded, tick the reactor here to ensure we are * handling other aspects of the QUIC connection. */ ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0); ret = 1; } else if (xso_blocking_mode(ctx.xso)) { /* * We were not able to read anything immediately, so our stream * buffer is empty. This means we need to block until we get * at least one byte. */ args.ctx = &ctx; args.stream = ctx.xso->stream; args.buf = buf; args.len = len; args.bytes_read = bytes_read; args.peek = peek; res = block_until_pred(ctx.qc, quic_read_again, &args, 0); if (res == 0) { ret = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } else if (res < 0) { ret = 0; /* quic_read_again raised error here */ goto out; } ret = 1; } else { /* * We did not get any bytes and are not in blocking mode. * Tick to see if this delivers any more. */ ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0); /* Try the read again. */ if (!quic_read_actual(&ctx, ctx.xso->stream, buf, len, bytes_read, peek)) { ret = 0; /* quic_read_actual raised error here */ goto out; } if (*bytes_read > 0) ret = 1; /* Succeeded this time. */ else ret = QUIC_RAISE_NORMAL_ERROR(&ctx, SSL_ERROR_WANT_READ); } out: quic_unlock(ctx.qc); return ret; } int ossl_quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read) { return quic_read(s, buf, len, bytes_read, 0); } int ossl_quic_peek(SSL *s, void *buf, size_t len, size_t *bytes_read) { return quic_read(s, buf, len, bytes_read, 1); } /* * SSL_pending * ----------- */ QUIC_TAKES_LOCK static size_t ossl_quic_pending_int(const SSL *s, int check_channel) { QCTX ctx; size_t avail = 0; int fin = 0; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); if (ctx.xso == NULL) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_NO_STREAM, NULL); goto out; } if (ctx.xso->stream == NULL || !ossl_quic_stream_has_recv_buffer(ctx.xso->stream)) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } if (!ossl_quic_rstream_available(ctx.xso->stream->rstream, &avail, &fin)) avail = 0; if (avail == 0 && check_channel && ossl_quic_channel_has_pending(ctx.qc->ch)) avail = 1; out: quic_unlock(ctx.qc); return avail; } size_t ossl_quic_pending(const SSL *s) { return ossl_quic_pending_int(s, /*check_channel=*/0); } int ossl_quic_has_pending(const SSL *s) { /* Do we have app-side pending data or pending URXEs or RXEs? */ return ossl_quic_pending_int(s, /*check_channel=*/1) > 0; } /* * SSL_stream_conclude * ------------------- */ QUIC_TAKES_LOCK int ossl_quic_conn_stream_conclude(SSL *s) { QCTX ctx; QUIC_STREAM *qs; int err; if (!expect_quic_with_stream_lock(s, /*remote_init=*/0, /*io=*/0, &ctx)) return 0; qs = ctx.xso->stream; if (!quic_mutation_allowed(ctx.qc, /*req_active=*/1)) { quic_unlock(ctx.qc); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); } if (!quic_validate_for_write(ctx.xso, &err)) { quic_unlock(ctx.qc); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, err, NULL); } if (ossl_quic_sstream_get_final_size(qs->sstream, NULL)) { quic_unlock(ctx.qc); return 1; } ossl_quic_sstream_fin(qs->sstream); quic_post_write(ctx.xso, 1, 1); quic_unlock(ctx.qc); return 1; } /* * SSL_inject_net_dgram * -------------------- */ QUIC_TAKES_LOCK int SSL_inject_net_dgram(SSL *s, const unsigned char *buf, size_t buf_len, const BIO_ADDR *peer, const BIO_ADDR *local) { int ret; QCTX ctx; QUIC_DEMUX *demux; if (!expect_quic(s, &ctx)) return 0; quic_lock(ctx.qc); demux = ossl_quic_channel_get0_demux(ctx.qc->ch); ret = ossl_quic_demux_inject(demux, buf, buf_len, peer, local); quic_unlock(ctx.qc); return ret; } /* * SSL_get0_connection * ------------------- */ SSL *ossl_quic_get0_connection(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return NULL; return &ctx.qc->ssl; } /* * SSL_get_stream_type * ------------------- */ int ossl_quic_get_stream_type(SSL *s) { QCTX ctx; if (!expect_quic(s, &ctx)) return SSL_STREAM_TYPE_BIDI; if (ctx.xso == NULL) { /* * If deferred XSO creation has yet to occur, proceed according to the * default stream mode. If AUTO_BIDI or AUTO_UNI is set, we cannot know * what kind of stream will be created yet, so return BIDI on the basis * that at this time, the client still has the option of calling * SSL_read() or SSL_write() first. */ if (ctx.qc->default_xso_created || ctx.qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) return SSL_STREAM_TYPE_NONE; else return SSL_STREAM_TYPE_BIDI; } if (ossl_quic_stream_is_bidi(ctx.xso->stream)) return SSL_STREAM_TYPE_BIDI; if (ossl_quic_stream_is_server_init(ctx.xso->stream) != ctx.qc->as_server) return SSL_STREAM_TYPE_READ; else return SSL_STREAM_TYPE_WRITE; } /* * SSL_get_stream_id * ----------------- */ QUIC_TAKES_LOCK uint64_t ossl_quic_get_stream_id(SSL *s) { QCTX ctx; uint64_t id; if (!expect_quic_with_stream_lock(s, /*remote_init=*/-1, /*io=*/0, &ctx)) return UINT64_MAX; id = ctx.xso->stream->id; quic_unlock(ctx.qc); return id; } /* * SSL_is_stream_local * ------------------- */ QUIC_TAKES_LOCK int ossl_quic_is_stream_local(SSL *s) { QCTX ctx; int is_local; if (!expect_quic_with_stream_lock(s, /*remote_init=*/-1, /*io=*/0, &ctx)) return -1; is_local = ossl_quic_stream_is_local_init(ctx.xso->stream); quic_unlock(ctx.qc); return is_local; } /* * SSL_set_default_stream_mode * --------------------------- */ QUIC_TAKES_LOCK int ossl_quic_set_default_stream_mode(SSL *s, uint32_t mode) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return 0; quic_lock(ctx.qc); if (ctx.qc->default_xso_created) { quic_unlock(ctx.qc); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, "too late to change default stream mode"); } switch (mode) { case SSL_DEFAULT_STREAM_MODE_NONE: case SSL_DEFAULT_STREAM_MODE_AUTO_BIDI: case SSL_DEFAULT_STREAM_MODE_AUTO_UNI: ctx.qc->default_stream_mode = mode; break; default: quic_unlock(ctx.qc); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, "bad default stream type"); } quic_unlock(ctx.qc); return 1; } /* * SSL_detach_stream * ----------------- */ QUIC_TAKES_LOCK SSL *ossl_quic_detach_stream(SSL *s) { QCTX ctx; QUIC_XSO *xso = NULL; if (!expect_quic_conn_only(s, &ctx)) return NULL; quic_lock(ctx.qc); /* Calling this function inhibits default XSO autocreation. */ /* QC ref to any default XSO is transferred to us and to caller. */ qc_set_default_xso_keep_ref(ctx.qc, NULL, /*touch=*/1, &xso); quic_unlock(ctx.qc); return xso != NULL ? &xso->ssl : NULL; } /* * SSL_attach_stream * ----------------- */ QUIC_TAKES_LOCK int ossl_quic_attach_stream(SSL *conn, SSL *stream) { QCTX ctx; QUIC_XSO *xso; int nref; if (!expect_quic_conn_only(conn, &ctx)) return 0; if (stream == NULL || stream->type != SSL_TYPE_QUIC_XSO) return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_NULL_PARAMETER, "stream to attach must be a valid QUIC stream"); xso = (QUIC_XSO *)stream; quic_lock(ctx.qc); if (ctx.qc->default_xso != NULL) { quic_unlock(ctx.qc); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, "connection already has a default stream"); } /* * It is a caller error for the XSO being attached as a default XSO to have * more than one ref. */ if (!CRYPTO_GET_REF(&xso->ssl.references, &nref)) { quic_unlock(ctx.qc); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, "ref"); } if (nref != 1) { quic_unlock(ctx.qc); return QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, "stream being attached must have " "only 1 reference"); } /* Caller's reference to the XSO is transferred to us. */ /* Calling this function inhibits default XSO autocreation. */ qc_set_default_xso(ctx.qc, xso, /*touch=*/1); quic_unlock(ctx.qc); return 1; } /* * SSL_set_incoming_stream_policy * ------------------------------ */ QUIC_NEEDS_LOCK static int qc_get_effective_incoming_stream_policy(QUIC_CONNECTION *qc) { switch (qc->incoming_stream_policy) { case SSL_INCOMING_STREAM_POLICY_AUTO: if ((qc->default_xso == NULL && !qc->default_xso_created) || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE) return SSL_INCOMING_STREAM_POLICY_ACCEPT; else return SSL_INCOMING_STREAM_POLICY_REJECT; default: return qc->incoming_stream_policy; } } QUIC_NEEDS_LOCK static void qc_update_reject_policy(QUIC_CONNECTION *qc) { int policy = qc_get_effective_incoming_stream_policy(qc); int enable_reject = (policy == SSL_INCOMING_STREAM_POLICY_REJECT); ossl_quic_channel_set_incoming_stream_auto_reject(qc->ch, enable_reject, qc->incoming_stream_aec); } QUIC_TAKES_LOCK int ossl_quic_set_incoming_stream_policy(SSL *s, int policy, uint64_t aec) { int ret = 1; QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return 0; quic_lock(ctx.qc); switch (policy) { case SSL_INCOMING_STREAM_POLICY_AUTO: case SSL_INCOMING_STREAM_POLICY_ACCEPT: case SSL_INCOMING_STREAM_POLICY_REJECT: ctx.qc->incoming_stream_policy = policy; ctx.qc->incoming_stream_aec = aec; break; default: QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); ret = 0; break; } qc_update_reject_policy(ctx.qc); quic_unlock(ctx.qc); return ret; } /* * SSL_accept_stream * ----------------- */ struct wait_for_incoming_stream_args { QCTX *ctx; QUIC_STREAM *qs; }; QUIC_NEEDS_LOCK static int wait_for_incoming_stream(void *arg) { struct wait_for_incoming_stream_args *args = arg; QUIC_CONNECTION *qc = args->ctx->qc; QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(qc->ch); if (!quic_mutation_allowed(qc, /*req_active=*/1)) { /* If connection is torn down due to an error while blocking, stop. */ QUIC_RAISE_NON_NORMAL_ERROR(args->ctx, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL); return -1; } args->qs = ossl_quic_stream_map_peek_accept_queue(qsm); if (args->qs != NULL) return 1; /* got a stream */ return 0; /* did not get a stream, keep trying */ } QUIC_TAKES_LOCK SSL *ossl_quic_accept_stream(SSL *s, uint64_t flags) { QCTX ctx; int ret; SSL *new_s = NULL; QUIC_STREAM_MAP *qsm; QUIC_STREAM *qs; QUIC_XSO *xso; OSSL_RTT_INFO rtt_info; if (!expect_quic_conn_only(s, &ctx)) return NULL; quic_lock(ctx.qc); if (qc_get_effective_incoming_stream_policy(ctx.qc) == SSL_INCOMING_STREAM_POLICY_REJECT) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, NULL); goto out; } qsm = ossl_quic_channel_get_qsm(ctx.qc->ch); qs = ossl_quic_stream_map_peek_accept_queue(qsm); if (qs == NULL) { if (qc_blocking_mode(ctx.qc) && (flags & SSL_ACCEPT_STREAM_NO_BLOCK) == 0) { struct wait_for_incoming_stream_args args; args.ctx = &ctx; args.qs = NULL; ret = block_until_pred(ctx.qc, wait_for_incoming_stream, &args, 0); if (ret == 0) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } else if (ret < 0 || args.qs == NULL) { goto out; } qs = args.qs; } else { goto out; } } xso = create_xso_from_stream(ctx.qc, qs); if (xso == NULL) goto out; ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ctx.qc->ch), &rtt_info); ossl_quic_stream_map_remove_from_accept_queue(qsm, qs, rtt_info.smoothed_rtt); new_s = &xso->ssl; /* Calling this function inhibits default XSO autocreation. */ qc_touch_default_xso(ctx.qc); /* inhibits default XSO */ out: quic_unlock(ctx.qc); return new_s; } /* * SSL_get_accept_stream_queue_len * ------------------------------- */ QUIC_TAKES_LOCK size_t ossl_quic_get_accept_stream_queue_len(SSL *s) { QCTX ctx; size_t v; if (!expect_quic_conn_only(s, &ctx)) return 0; quic_lock(ctx.qc); v = ossl_quic_stream_map_get_accept_queue_len(ossl_quic_channel_get_qsm(ctx.qc->ch)); quic_unlock(ctx.qc); return v; } /* * SSL_stream_reset * ---------------- */ int ossl_quic_stream_reset(SSL *ssl, const SSL_STREAM_RESET_ARGS *args, size_t args_len) { QCTX ctx; QUIC_STREAM_MAP *qsm; QUIC_STREAM *qs; uint64_t error_code; int ok, err; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/0, /*io=*/0, &ctx)) return 0; qsm = ossl_quic_channel_get_qsm(ctx.qc->ch); qs = ctx.xso->stream; error_code = (args != NULL ? args->quic_error_code : 0); if (!quic_validate_for_write(ctx.xso, &err)) { ok = QUIC_RAISE_NON_NORMAL_ERROR(&ctx, err, NULL); goto err; } ok = ossl_quic_stream_map_reset_stream_send_part(qsm, qs, error_code); err: quic_unlock(ctx.qc); return ok; } /* * SSL_get_stream_read_state * ------------------------- */ static void quic_classify_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs, int is_write, int *state, uint64_t *app_error_code) { int local_init; uint64_t final_size; local_init = (ossl_quic_stream_is_server_init(qs) == qc->as_server); if (app_error_code != NULL) *app_error_code = UINT64_MAX; else app_error_code = &final_size; /* throw away value */ if (!ossl_quic_stream_is_bidi(qs) && local_init != is_write) { /* * Unidirectional stream and this direction of transmission doesn't * exist. */ *state = SSL_STREAM_STATE_WRONG_DIR; } else if (ossl_quic_channel_is_term_any(qc->ch)) { /* Connection already closed. */ *state = SSL_STREAM_STATE_CONN_CLOSED; } else if (!is_write && qs->recv_state == QUIC_RSTREAM_STATE_DATA_READ) { /* Application has read a FIN. */ *state = SSL_STREAM_STATE_FINISHED; } else if ((!is_write && qs->stop_sending) || (is_write && ossl_quic_stream_send_is_reset(qs))) { /* * Stream has been reset locally. FIN takes precedence over this for the * read case as the application need not care if the stream is reset * after a FIN has been successfully processed. */ *state = SSL_STREAM_STATE_RESET_LOCAL; *app_error_code = !is_write ? qs->stop_sending_aec : qs->reset_stream_aec; } else if ((!is_write && ossl_quic_stream_recv_is_reset(qs)) || (is_write && qs->peer_stop_sending)) { /* * Stream has been reset remotely. */ *state = SSL_STREAM_STATE_RESET_REMOTE; *app_error_code = !is_write ? qs->peer_reset_stream_aec : qs->peer_stop_sending_aec; } else if (is_write && ossl_quic_sstream_get_final_size(qs->sstream, &final_size)) { /* * Stream has been finished. Stream reset takes precedence over this for * the write case as peer may not have received all data. */ *state = SSL_STREAM_STATE_FINISHED; } else { /* Stream still healthy. */ *state = SSL_STREAM_STATE_OK; } } static int quic_get_stream_state(SSL *ssl, int is_write) { QCTX ctx; int state; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, /*io=*/0, &ctx)) return SSL_STREAM_STATE_NONE; quic_classify_stream(ctx.qc, ctx.xso->stream, is_write, &state, NULL); quic_unlock(ctx.qc); return state; } int ossl_quic_get_stream_read_state(SSL *ssl) { return quic_get_stream_state(ssl, /*is_write=*/0); } /* * SSL_get_stream_write_state * -------------------------- */ int ossl_quic_get_stream_write_state(SSL *ssl) { return quic_get_stream_state(ssl, /*is_write=*/1); } /* * SSL_get_stream_read_error_code * ------------------------------ */ static int quic_get_stream_error_code(SSL *ssl, int is_write, uint64_t *app_error_code) { QCTX ctx; int state; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, /*io=*/0, &ctx)) return -1; quic_classify_stream(ctx.qc, ctx.xso->stream, /*is_write=*/0, &state, app_error_code); quic_unlock(ctx.qc); switch (state) { case SSL_STREAM_STATE_FINISHED: return 0; case SSL_STREAM_STATE_RESET_LOCAL: case SSL_STREAM_STATE_RESET_REMOTE: return 1; default: return -1; } } int ossl_quic_get_stream_read_error_code(SSL *ssl, uint64_t *app_error_code) { return quic_get_stream_error_code(ssl, /*is_write=*/0, app_error_code); } /* * SSL_get_stream_write_error_code * ------------------------------- */ int ossl_quic_get_stream_write_error_code(SSL *ssl, uint64_t *app_error_code) { return quic_get_stream_error_code(ssl, /*is_write=*/1, app_error_code); } /* * Write buffer size mutation * -------------------------- */ int ossl_quic_set_write_buffer_size(SSL *ssl, size_t size) { int ret = 0; QCTX ctx; if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, /*io=*/0, &ctx)) return 0; if (!ossl_quic_stream_has_send(ctx.xso->stream)) { /* Called on a unidirectional receive-only stream - error. */ QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED, NULL); goto out; } if (!ossl_quic_stream_has_send_buffer(ctx.xso->stream)) { /* * If the stream has a send part but we have disposed of it because we * no longer need it, this is a no-op. */ ret = 1; goto out; } if (!ossl_quic_sstream_set_buffer_size(ctx.xso->stream->sstream, size)) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_INTERNAL_ERROR, NULL); goto out; } ret = 1; out: quic_unlock(ctx.qc); return ret; } /* * SSL_get_conn_close_info * ----------------------- */ int ossl_quic_get_conn_close_info(SSL *ssl, SSL_CONN_CLOSE_INFO *info, size_t info_len) { QCTX ctx; const QUIC_TERMINATE_CAUSE *tc; if (!expect_quic_conn_only(ssl, &ctx)) return -1; tc = ossl_quic_channel_get_terminate_cause(ctx.qc->ch); if (tc == NULL) return 0; info->error_code = tc->error_code; info->frame_type = tc->frame_type; info->reason = tc->reason; info->reason_len = tc->reason_len; info->flags = 0; if (!tc->remote) info->flags |= SSL_CONN_CLOSE_FLAG_LOCAL; if (!tc->app) info->flags |= SSL_CONN_CLOSE_FLAG_TRANSPORT; return 1; } /* * SSL_key_update * -------------- */ int ossl_quic_key_update(SSL *ssl, int update_type) { QCTX ctx; if (!expect_quic_conn_only(ssl, &ctx)) return 0; switch (update_type) { case SSL_KEY_UPDATE_NOT_REQUESTED: /* * QUIC signals peer key update implicily by triggering a local * spontaneous TXKU. Silently upgrade this to SSL_KEY_UPDATE_REQUESTED. */ case SSL_KEY_UPDATE_REQUESTED: break; default: QUIC_RAISE_NON_NORMAL_ERROR(&ctx, ERR_R_PASSED_INVALID_ARGUMENT, NULL); return 0; } quic_lock(ctx.qc); /* Attempt to perform a TXKU. */ if (!ossl_quic_channel_trigger_txku(ctx.qc->ch)) { QUIC_RAISE_NON_NORMAL_ERROR(&ctx, SSL_R_TOO_MANY_KEY_UPDATES, NULL); quic_unlock(ctx.qc); return 0; } quic_unlock(ctx.qc); return 1; } /* * SSL_get_key_update_type * ----------------------- */ int ossl_quic_get_key_update_type(const SSL *s) { /* * We always handle key updates immediately so a key update is never * pending. */ return SSL_KEY_UPDATE_NONE; } /* * QUIC Front-End I/O API: SSL_CTX Management * ========================================== */ long ossl_quic_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) { switch (cmd) { default: return ssl3_ctx_ctrl(ctx, cmd, larg, parg); } } long ossl_quic_callback_ctrl(SSL *s, int cmd, void (*fp) (void)) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return 0; switch (cmd) { case SSL_CTRL_SET_MSG_CALLBACK: ossl_quic_channel_set_msg_callback(ctx.qc->ch, (ossl_msg_cb)fp, &ctx.qc->ssl); /* This callback also needs to be set on the internal SSL object */ return ssl3_callback_ctrl(ctx.qc->tls, cmd, fp);; default: /* Probably a TLS related ctrl. Defer to our internal SSL object */ return ssl3_callback_ctrl(ctx.qc->tls, cmd, fp); } } long ossl_quic_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void)) { return ssl3_ctx_callback_ctrl(ctx, cmd, fp); } int ossl_quic_renegotiate_check(SSL *ssl, int initok) { /* We never do renegotiation. */ return 0; } const SSL_CIPHER *ossl_quic_get_cipher_by_char(const unsigned char *p) { const SSL_CIPHER *ciph = ssl3_get_cipher_by_char(p); if ((ciph->algorithm2 & SSL_QUIC) == 0) return NULL; return ciph; } /* * These functions define the TLSv1.2 (and below) ciphers that are supported by * the SSL_METHOD. Since QUIC only supports TLSv1.3 we don't support any. */ int ossl_quic_num_ciphers(void) { return 0; } const SSL_CIPHER *ossl_quic_get_cipher(unsigned int u) { return NULL; } /* * SSL_get_shutdown() * ------------------ */ int ossl_quic_get_shutdown(const SSL *s) { QCTX ctx; int shut = 0; if (!expect_quic_conn_only(s, &ctx)) return 0; if (ossl_quic_channel_is_term_any(ctx.qc->ch)) { shut |= SSL_SENT_SHUTDOWN; if (!ossl_quic_channel_is_closing(ctx.qc->ch)) shut |= SSL_RECEIVED_SHUTDOWN; } return shut; } /* * Internal Testing APIs * ===================== */ QUIC_CHANNEL *ossl_quic_conn_get_channel(SSL *s) { QCTX ctx; if (!expect_quic_conn_only(s, &ctx)) return NULL; return ctx.qc->ch; }
./openssl/ssl/quic/quic_stream_map.c
/* * 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 "internal/quic_stream_map.h" #include "internal/nelem.h" /* * QUIC Stream Map * =============== */ DEFINE_LHASH_OF_EX(QUIC_STREAM); static void shutdown_flush_done(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs); /* Circular list management. */ static void list_insert_tail(QUIC_STREAM_LIST_NODE *l, QUIC_STREAM_LIST_NODE *n) { /* Must not be in list. */ assert(n->prev == NULL && n->next == NULL && l->prev != NULL && l->next != NULL); n->prev = l->prev; n->prev->next = n; l->prev = n; n->next = l; } static void list_remove(QUIC_STREAM_LIST_NODE *l, QUIC_STREAM_LIST_NODE *n) { assert(n->prev != NULL && n->next != NULL && n->prev != n && n->next != n); n->prev->next = n->next; n->next->prev = n->prev; n->next = n->prev = NULL; } static QUIC_STREAM *list_next(QUIC_STREAM_LIST_NODE *l, QUIC_STREAM_LIST_NODE *n, size_t off) { assert(n->prev != NULL && n->next != NULL && (n == l || (n->prev != n && n->next != n)) && l->prev != NULL && l->next != NULL); n = n->next; if (n == l) n = n->next; if (n == l) return NULL; assert(n != NULL); return (QUIC_STREAM *)(((char *)n) - off); } #define active_next(l, s) list_next((l), &(s)->active_node, \ offsetof(QUIC_STREAM, active_node)) #define accept_next(l, s) list_next((l), &(s)->accept_node, \ offsetof(QUIC_STREAM, accept_node)) #define ready_for_gc_next(l, s) list_next((l), &(s)->ready_for_gc_node, \ offsetof(QUIC_STREAM, ready_for_gc_node)) #define accept_head(l) list_next((l), (l), \ offsetof(QUIC_STREAM, accept_node)) #define ready_for_gc_head(l) list_next((l), (l), \ offsetof(QUIC_STREAM, ready_for_gc_node)) static unsigned long hash_stream(const QUIC_STREAM *s) { return (unsigned long)s->id; } static int cmp_stream(const QUIC_STREAM *a, const QUIC_STREAM *b) { if (a->id < b->id) return -1; if (a->id > b->id) return 1; return 0; } 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) { qsm->map = lh_QUIC_STREAM_new(hash_stream, cmp_stream); qsm->active_list.prev = qsm->active_list.next = &qsm->active_list; qsm->accept_list.prev = qsm->accept_list.next = &qsm->accept_list; qsm->ready_for_gc_list.prev = qsm->ready_for_gc_list.next = &qsm->ready_for_gc_list; qsm->rr_stepping = 1; qsm->rr_counter = 0; qsm->rr_cur = NULL; qsm->num_accept = 0; qsm->num_shutdown_flush = 0; qsm->get_stream_limit_cb = get_stream_limit_cb; qsm->get_stream_limit_cb_arg = get_stream_limit_cb_arg; qsm->max_streams_bidi_rxfc = max_streams_bidi_rxfc; qsm->max_streams_uni_rxfc = max_streams_uni_rxfc; qsm->is_server = is_server; return 1; } static void release_each(QUIC_STREAM *stream, void *arg) { QUIC_STREAM_MAP *qsm = arg; ossl_quic_stream_map_release(qsm, stream); } void ossl_quic_stream_map_cleanup(QUIC_STREAM_MAP *qsm) { ossl_quic_stream_map_visit(qsm, release_each, qsm); lh_QUIC_STREAM_free(qsm->map); qsm->map = NULL; } void ossl_quic_stream_map_visit(QUIC_STREAM_MAP *qsm, void (*visit_cb)(QUIC_STREAM *stream, void *arg), void *visit_cb_arg) { lh_QUIC_STREAM_doall_arg(qsm->map, visit_cb, visit_cb_arg); } QUIC_STREAM *ossl_quic_stream_map_alloc(QUIC_STREAM_MAP *qsm, uint64_t stream_id, int type) { QUIC_STREAM *s; QUIC_STREAM key; key.id = stream_id; s = lh_QUIC_STREAM_retrieve(qsm->map, &key); if (s != NULL) return NULL; s = OPENSSL_zalloc(sizeof(*s)); if (s == NULL) return NULL; s->id = stream_id; s->type = type; s->as_server = qsm->is_server; s->send_state = (ossl_quic_stream_is_local_init(s) || ossl_quic_stream_is_bidi(s)) ? QUIC_SSTREAM_STATE_READY : QUIC_SSTREAM_STATE_NONE; s->recv_state = (!ossl_quic_stream_is_local_init(s) || ossl_quic_stream_is_bidi(s)) ? QUIC_RSTREAM_STATE_RECV : QUIC_RSTREAM_STATE_NONE; s->send_final_size = UINT64_MAX; lh_QUIC_STREAM_insert(qsm->map, s); return s; } void ossl_quic_stream_map_release(QUIC_STREAM_MAP *qsm, QUIC_STREAM *stream) { if (stream == NULL) return; if (stream->active_node.next != NULL) list_remove(&qsm->active_list, &stream->active_node); if (stream->accept_node.next != NULL) list_remove(&qsm->accept_list, &stream->accept_node); if (stream->ready_for_gc_node.next != NULL) list_remove(&qsm->ready_for_gc_list, &stream->ready_for_gc_node); ossl_quic_sstream_free(stream->sstream); stream->sstream = NULL; ossl_quic_rstream_free(stream->rstream); stream->rstream = NULL; lh_QUIC_STREAM_delete(qsm->map, stream); OPENSSL_free(stream); } QUIC_STREAM *ossl_quic_stream_map_get_by_id(QUIC_STREAM_MAP *qsm, uint64_t stream_id) { QUIC_STREAM key; key.id = stream_id; return lh_QUIC_STREAM_retrieve(qsm->map, &key); } static void stream_map_mark_active(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s) { if (s->active) return; list_insert_tail(&qsm->active_list, &s->active_node); if (qsm->rr_cur == NULL) qsm->rr_cur = s; s->active = 1; } static void stream_map_mark_inactive(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s) { if (!s->active) return; if (qsm->rr_cur == s) qsm->rr_cur = active_next(&qsm->active_list, s); if (qsm->rr_cur == s) qsm->rr_cur = NULL; list_remove(&qsm->active_list, &s->active_node); s->active = 0; } void ossl_quic_stream_map_set_rr_stepping(QUIC_STREAM_MAP *qsm, size_t stepping) { qsm->rr_stepping = stepping; qsm->rr_counter = 0; } static int stream_has_data_to_send(QUIC_STREAM *s) { OSSL_QUIC_FRAME_STREAM shdr; OSSL_QTX_IOVEC iov[2]; size_t num_iov; uint64_t fc_credit, fc_swm, fc_limit; switch (s->send_state) { case QUIC_SSTREAM_STATE_READY: case QUIC_SSTREAM_STATE_SEND: case QUIC_SSTREAM_STATE_DATA_SENT: /* * We can still have data to send in DATA_SENT due to retransmissions, * etc. */ break; default: return 0; /* Nothing to send. */ } /* * We cannot determine if we have data to send simply by checking if * ossl_quic_txfc_get_credit() is zero, because we may also have older * stream data we need to retransmit. The SSTREAM returns older data first, * so we do a simple comparison of the next chunk the SSTREAM wants to send * against the TXFC CWM. */ num_iov = OSSL_NELEM(iov); if (!ossl_quic_sstream_get_stream_frame(s->sstream, 0, &shdr, iov, &num_iov)) return 0; fc_credit = ossl_quic_txfc_get_credit(&s->txfc, 0); fc_swm = ossl_quic_txfc_get_swm(&s->txfc); fc_limit = fc_swm + fc_credit; return (shdr.is_fin && shdr.len == 0) || shdr.offset < fc_limit; } static ossl_unused int qsm_send_part_permits_gc(const QUIC_STREAM *qs) { switch (qs->send_state) { case QUIC_SSTREAM_STATE_NONE: case QUIC_SSTREAM_STATE_DATA_RECVD: case QUIC_SSTREAM_STATE_RESET_RECVD: return 1; default: return 0; } } static int qsm_ready_for_gc(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { int recv_stream_fully_drained = 0; /* TODO(QUIC FUTURE): Optimisation */ /* * If sstream has no FIN, we auto-reset it at marked-for-deletion time, so * we don't need to worry about that here. */ assert(!qs->deleted || !ossl_quic_stream_has_send(qs) || ossl_quic_stream_send_is_reset(qs) || ossl_quic_stream_send_get_final_size(qs, NULL)); return qs->deleted && (!ossl_quic_stream_has_recv(qs) || recv_stream_fully_drained || qs->acked_stop_sending) && (!ossl_quic_stream_has_send(qs) || qs->send_state == QUIC_SSTREAM_STATE_DATA_RECVD || qs->send_state == QUIC_SSTREAM_STATE_RESET_RECVD); } int ossl_quic_stream_map_is_local_allowed_by_stream_limit(QUIC_STREAM_MAP *qsm, uint64_t stream_ordinal, int is_uni) { uint64_t stream_limit; if (qsm->get_stream_limit_cb == NULL) return 1; stream_limit = qsm->get_stream_limit_cb(is_uni, qsm->get_stream_limit_cb_arg); return stream_ordinal < stream_limit; } void ossl_quic_stream_map_update_state(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s) { int should_be_active, allowed_by_stream_limit = 1; if (ossl_quic_stream_is_server_init(s) == qsm->is_server) { int is_uni = !ossl_quic_stream_is_bidi(s); uint64_t stream_ordinal = s->id >> 2; allowed_by_stream_limit = ossl_quic_stream_map_is_local_allowed_by_stream_limit(qsm, stream_ordinal, is_uni); } if (s->send_state == QUIC_SSTREAM_STATE_DATA_SENT && ossl_quic_sstream_is_totally_acked(s->sstream)) ossl_quic_stream_map_notify_totally_acked(qsm, s); else if (s->shutdown_flush && s->send_state == QUIC_SSTREAM_STATE_SEND && ossl_quic_sstream_is_totally_acked(s->sstream)) shutdown_flush_done(qsm, s); if (!s->ready_for_gc) { s->ready_for_gc = qsm_ready_for_gc(qsm, s); if (s->ready_for_gc) list_insert_tail(&qsm->ready_for_gc_list, &s->ready_for_gc_node); } should_be_active = allowed_by_stream_limit && !s->ready_for_gc && ((ossl_quic_stream_has_recv(s) && !ossl_quic_stream_recv_is_reset(s) && (s->recv_state == QUIC_RSTREAM_STATE_RECV && (s->want_max_stream_data || ossl_quic_rxfc_has_cwm_changed(&s->rxfc, 0)))) || s->want_stop_sending || s->want_reset_stream || (!s->peer_stop_sending && stream_has_data_to_send(s))); if (should_be_active) stream_map_mark_active(qsm, s); else stream_map_mark_inactive(qsm, s); } /* * Stream Send Part State Management * ================================= */ int ossl_quic_stream_map_ensure_send_part_id(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { switch (qs->send_state) { case QUIC_SSTREAM_STATE_NONE: /* Stream without send part - caller error. */ return 0; case QUIC_SSTREAM_STATE_READY: /* * We always allocate a stream ID upfront, so we don't need to do it * here. */ qs->send_state = QUIC_SSTREAM_STATE_SEND; return 1; default: /* Nothing to do. */ return 1; } } int ossl_quic_stream_map_notify_all_data_sent(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { switch (qs->send_state) { default: /* Wrong state - caller error. */ case QUIC_SSTREAM_STATE_NONE: /* Stream without send part - caller error. */ return 0; case QUIC_SSTREAM_STATE_SEND: if (!ossl_quic_sstream_get_final_size(qs->sstream, &qs->send_final_size)) return 0; qs->send_state = QUIC_SSTREAM_STATE_DATA_SENT; return 1; } } static void shutdown_flush_done(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { if (!qs->shutdown_flush) return; assert(qsm->num_shutdown_flush > 0); qs->shutdown_flush = 0; --qsm->num_shutdown_flush; } int ossl_quic_stream_map_notify_totally_acked(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { switch (qs->send_state) { default: /* Wrong state - caller error. */ case QUIC_SSTREAM_STATE_NONE: /* Stream without send part - caller error. */ return 0; case QUIC_SSTREAM_STATE_DATA_SENT: qs->send_state = QUIC_SSTREAM_STATE_DATA_RECVD; /* We no longer need a QUIC_SSTREAM in this state. */ ossl_quic_sstream_free(qs->sstream); qs->sstream = NULL; shutdown_flush_done(qsm, qs); return 1; } } int ossl_quic_stream_map_reset_stream_send_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs, uint64_t aec) { switch (qs->send_state) { default: case QUIC_SSTREAM_STATE_NONE: /* * RESET_STREAM pertains to sending part only, so we cannot reset a * receive-only stream. */ case QUIC_SSTREAM_STATE_DATA_RECVD: /* * RFC 9000 s. 3.3: A sender MUST NOT [...] send RESET_STREAM from a * terminal state. If the stream has already finished normally and the * peer has acknowledged this, we cannot reset it. */ return 0; case QUIC_SSTREAM_STATE_READY: if (!ossl_quic_stream_map_ensure_send_part_id(qsm, qs)) return 0; /* FALLTHROUGH */ case QUIC_SSTREAM_STATE_SEND: /* * If we already have a final size (e.g. because we are coming from * DATA_SENT), we have to be consistent with that, so don't change it. * If we don't already have a final size, determine a final size value. * This is the value which we will end up using for a RESET_STREAM frame * for flow control purposes. We could send the stream size (total * number of bytes appended to QUIC_SSTREAM by the application), but it * is in our interest to exclude any bytes we have not actually * transmitted yet, to avoid unnecessarily consuming flow control * credit. We can get this from the TXFC. */ qs->send_final_size = ossl_quic_txfc_get_swm(&qs->txfc); /* FALLTHROUGH */ case QUIC_SSTREAM_STATE_DATA_SENT: qs->reset_stream_aec = aec; qs->want_reset_stream = 1; qs->send_state = QUIC_SSTREAM_STATE_RESET_SENT; ossl_quic_sstream_free(qs->sstream); qs->sstream = NULL; shutdown_flush_done(qsm, qs); ossl_quic_stream_map_update_state(qsm, qs); return 1; case QUIC_SSTREAM_STATE_RESET_SENT: case QUIC_SSTREAM_STATE_RESET_RECVD: /* * Idempotent - no-op. In any case, do not send RESET_STREAM again - as * mentioned, we must not send it from a terminal state. */ return 1; } } int ossl_quic_stream_map_notify_reset_stream_acked(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { switch (qs->send_state) { default: /* Wrong state - caller error. */ case QUIC_SSTREAM_STATE_NONE: /* Stream without send part - caller error. */ return 0; case QUIC_SSTREAM_STATE_RESET_SENT: qs->send_state = QUIC_SSTREAM_STATE_RESET_RECVD; return 1; case QUIC_SSTREAM_STATE_RESET_RECVD: /* Already in the correct state. */ return 1; } } /* * Stream Receive Part State Management * ==================================== */ int ossl_quic_stream_map_notify_size_known_recv_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs, uint64_t final_size) { switch (qs->recv_state) { default: /* Wrong state - caller error. */ case QUIC_RSTREAM_STATE_NONE: /* Stream without receive part - caller error. */ return 0; case QUIC_RSTREAM_STATE_RECV: qs->recv_state = QUIC_RSTREAM_STATE_SIZE_KNOWN; return 1; } } int ossl_quic_stream_map_notify_totally_received(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { switch (qs->recv_state) { default: /* Wrong state - caller error. */ case QUIC_RSTREAM_STATE_NONE: /* Stream without receive part - caller error. */ return 0; case QUIC_RSTREAM_STATE_SIZE_KNOWN: qs->recv_state = QUIC_RSTREAM_STATE_DATA_RECVD; qs->want_stop_sending = 0; return 1; } } int ossl_quic_stream_map_notify_totally_read(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { switch (qs->recv_state) { default: /* Wrong state - caller error. */ case QUIC_RSTREAM_STATE_NONE: /* Stream without receive part - caller error. */ return 0; case QUIC_RSTREAM_STATE_DATA_RECVD: qs->recv_state = QUIC_RSTREAM_STATE_DATA_READ; /* QUIC_RSTREAM is no longer needed */ ossl_quic_rstream_free(qs->rstream); qs->rstream = NULL; return 1; } } 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) { uint64_t prev_final_size; switch (qs->recv_state) { default: case QUIC_RSTREAM_STATE_NONE: /* Stream without receive part - caller error. */ return 0; case QUIC_RSTREAM_STATE_RECV: case QUIC_RSTREAM_STATE_SIZE_KNOWN: case QUIC_RSTREAM_STATE_DATA_RECVD: if (ossl_quic_stream_recv_get_final_size(qs, &prev_final_size) && prev_final_size != final_size) /* Cannot change previous final size. */ return 0; qs->recv_state = QUIC_RSTREAM_STATE_RESET_RECVD; qs->peer_reset_stream_aec = app_error_code; /* RFC 9000 s. 3.3: No point sending STOP_SENDING if already reset. */ qs->want_stop_sending = 0; /* QUIC_RSTREAM is no longer needed */ ossl_quic_rstream_free(qs->rstream); qs->rstream = NULL; ossl_quic_stream_map_update_state(qsm, qs); return 1; case QUIC_RSTREAM_STATE_DATA_READ: /* * If we already retired the FIN to the application this is moot * - just ignore. */ case QUIC_RSTREAM_STATE_RESET_RECVD: case QUIC_RSTREAM_STATE_RESET_READ: /* Could be a reordered/retransmitted frame - just ignore. */ return 1; } } int ossl_quic_stream_map_notify_app_read_reset_recv_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { switch (qs->recv_state) { default: /* Wrong state - caller error. */ case QUIC_RSTREAM_STATE_NONE: /* Stream without receive part - caller error. */ return 0; case QUIC_RSTREAM_STATE_RESET_RECVD: qs->recv_state = QUIC_RSTREAM_STATE_RESET_READ; return 1; } } int ossl_quic_stream_map_stop_sending_recv_part(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs, uint64_t aec) { if (qs->stop_sending) return 0; switch (qs->recv_state) { default: case QUIC_RSTREAM_STATE_NONE: /* Send-only stream, so this makes no sense. */ case QUIC_RSTREAM_STATE_DATA_RECVD: case QUIC_RSTREAM_STATE_DATA_READ: /* * Not really any point in STOP_SENDING if we already received all data. */ case QUIC_RSTREAM_STATE_RESET_RECVD: case QUIC_RSTREAM_STATE_RESET_READ: /* * RFC 9000 s. 3.5: "STOP_SENDING SHOULD only be sent for a stream that * has not been reset by the peer." * * No point in STOP_SENDING if the peer already reset their send part. */ return 0; case QUIC_RSTREAM_STATE_RECV: case QUIC_RSTREAM_STATE_SIZE_KNOWN: /* * RFC 9000 s. 3.5: "If the stream is in the Recv or Size Known state, * the transport SHOULD signal this by sending a STOP_SENDING frame to * prompt closure of the stream in the opposite direction." * * Note that it does make sense to send STOP_SENDING for a receive part * of a stream which has a known size (because we have received a FIN) * but which still has other (previous) stream data yet to be received. */ break; } qs->stop_sending = 1; qs->stop_sending_aec = aec; return ossl_quic_stream_map_schedule_stop_sending(qsm, qs); } /* Called to mark STOP_SENDING for generation, or regeneration after loss. */ int ossl_quic_stream_map_schedule_stop_sending(QUIC_STREAM_MAP *qsm, QUIC_STREAM *qs) { if (!qs->stop_sending) return 0; /* * Ignore the call as a no-op if already scheduled, or in a state * where it makes no sense to send STOP_SENDING. */ if (qs->want_stop_sending) return 1; switch (qs->recv_state) { default: return 1; /* ignore */ case QUIC_RSTREAM_STATE_RECV: case QUIC_RSTREAM_STATE_SIZE_KNOWN: /* * RFC 9000 s. 3.5: "An endpoint is expected to send another * STOP_SENDING frame if a packet containing a previous STOP_SENDING is * lost. However, once either all stream data or a RESET_STREAM frame * has been received for the stream -- that is, the stream is in any * state other than "Recv" or "Size Known" -- sending a STOP_SENDING * frame is unnecessary." */ break; } qs->want_stop_sending = 1; ossl_quic_stream_map_update_state(qsm, qs); return 1; } QUIC_STREAM *ossl_quic_stream_map_peek_accept_queue(QUIC_STREAM_MAP *qsm) { return accept_head(&qsm->accept_list); } void ossl_quic_stream_map_push_accept_queue(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s) { list_insert_tail(&qsm->accept_list, &s->accept_node); ++qsm->num_accept; } static QUIC_RXFC *qsm_get_max_streams_rxfc(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s) { return ossl_quic_stream_is_bidi(s) ? qsm->max_streams_bidi_rxfc : qsm->max_streams_uni_rxfc; } void ossl_quic_stream_map_remove_from_accept_queue(QUIC_STREAM_MAP *qsm, QUIC_STREAM *s, OSSL_TIME rtt) { QUIC_RXFC *max_streams_rxfc; list_remove(&qsm->accept_list, &s->accept_node); --qsm->num_accept; if ((max_streams_rxfc = qsm_get_max_streams_rxfc(qsm, s)) != NULL) ossl_quic_rxfc_on_retire(max_streams_rxfc, 1, rtt); } size_t ossl_quic_stream_map_get_accept_queue_len(QUIC_STREAM_MAP *qsm) { return qsm->num_accept; } void ossl_quic_stream_map_gc(QUIC_STREAM_MAP *qsm) { QUIC_STREAM *qs, *qs_head, *qsn = NULL; for (qs = qs_head = ready_for_gc_head(&qsm->ready_for_gc_list); qs != NULL && qs != qs_head; qs = qsn) { qsn = ready_for_gc_next(&qsm->ready_for_gc_list, qs); ossl_quic_stream_map_release(qsm, qs); } } static int eligible_for_shutdown_flush(QUIC_STREAM *qs) { /* * We only care about servicing the send part of a stream (if any) during * shutdown flush. We make sure we flush a stream if it is either * non-terminated or was terminated normally such as via * SSL_stream_conclude. A stream which was terminated via a reset is not * flushed, and we will have thrown away the send buffer in that case * anyway. */ switch (qs->send_state) { case QUIC_SSTREAM_STATE_SEND: case QUIC_SSTREAM_STATE_DATA_SENT: return !ossl_quic_sstream_is_totally_acked(qs->sstream); default: return 0; } } static void begin_shutdown_flush_each(QUIC_STREAM *qs, void *arg) { QUIC_STREAM_MAP *qsm = arg; if (!eligible_for_shutdown_flush(qs) || qs->shutdown_flush) return; qs->shutdown_flush = 1; ++qsm->num_shutdown_flush; } void ossl_quic_stream_map_begin_shutdown_flush(QUIC_STREAM_MAP *qsm) { qsm->num_shutdown_flush = 0; ossl_quic_stream_map_visit(qsm, begin_shutdown_flush_each, qsm); } int ossl_quic_stream_map_is_shutdown_flush_finished(QUIC_STREAM_MAP *qsm) { return qsm->num_shutdown_flush == 0; } /* * QUIC Stream Iterator * ==================== */ void ossl_quic_stream_iter_init(QUIC_STREAM_ITER *it, QUIC_STREAM_MAP *qsm, int advance_rr) { it->qsm = qsm; it->stream = it->first_stream = qsm->rr_cur; if (advance_rr && it->stream != NULL && ++qsm->rr_counter >= qsm->rr_stepping) { qsm->rr_counter = 0; qsm->rr_cur = active_next(&qsm->active_list, qsm->rr_cur); } } void ossl_quic_stream_iter_next(QUIC_STREAM_ITER *it) { if (it->stream == NULL) return; it->stream = active_next(&it->qsm->active_list, it->stream); if (it->stream == it->first_stream) it->stream = NULL; }
./openssl/ssl/quic/uint_set.c
/* * 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 "internal/uint_set.h" #include "internal/common.h" #include <assert.h> /* * uint64_t Integer Sets * ===================== * * This data structure supports the following operations: * * Insert Range: Adds an inclusive range of integers [start, end] * to the set. Equivalent to Insert for each number * in the range. * * Remove Range: Removes an inclusive range of integers [start, end] * from the set. Not all of the range need already be in * the set, but any part of the range in the set is removed. * * Query: Is an integer in the data structure? * * The data structure can be iterated. * * For greater efficiency in tracking large numbers of contiguous integers, we * track integer ranges rather than individual integers. The data structure * manages a list of integer ranges [[start, end]...]. Internally this is * implemented as a doubly linked sorted list of range structures, which are * automatically split and merged as necessary. * * This data structure requires O(n) traversal of the list for insertion, * removal and query when we are not adding/removing ranges which are near the * beginning or end of the set of ranges. For the applications for which this * data structure is used (e.g. QUIC PN tracking for ACK generation), it is * expected that the number of integer ranges needed at any given time will * generally be small and that most operations will be close to the beginning or * end of the range. * * Invariant: The data structure is always sorted in ascending order by value. * * Invariant: No two adjacent ranges ever 'border' one another (have no * numerical gap between them) as the data structure always ensures * such ranges are merged. * * Invariant: No two ranges ever overlap. * * Invariant: No range [a, b] ever has a > b. * * Invariant: Since ranges are represented using inclusive bounds, no range * item inside the data structure can represent a span of zero * integers. */ void ossl_uint_set_init(UINT_SET *s) { ossl_list_uint_set_init(s); } void ossl_uint_set_destroy(UINT_SET *s) { UINT_SET_ITEM *x, *xnext; for (x = ossl_list_uint_set_head(s); x != NULL; x = xnext) { xnext = ossl_list_uint_set_next(x); OPENSSL_free(x); } } /* Possible merge of x, prev(x) */ static void uint_set_merge_adjacent(UINT_SET *s, UINT_SET_ITEM *x) { UINT_SET_ITEM *xprev = ossl_list_uint_set_prev(x); if (xprev == NULL) return; if (x->range.start - 1 != xprev->range.end) return; x->range.start = xprev->range.start; ossl_list_uint_set_remove(s, xprev); OPENSSL_free(xprev); } static uint64_t u64_min(uint64_t x, uint64_t y) { return x < y ? x : y; } static uint64_t u64_max(uint64_t x, uint64_t y) { return x > y ? x : y; } /* * Returns 1 if there exists an integer x which falls within both ranges a and * b. */ static int uint_range_overlaps(const UINT_RANGE *a, const UINT_RANGE *b) { return u64_min(a->end, b->end) >= u64_max(a->start, b->start); } static UINT_SET_ITEM *create_set_item(uint64_t start, uint64_t end) { UINT_SET_ITEM *x = OPENSSL_malloc(sizeof(UINT_SET_ITEM)); if (x == NULL) return NULL; ossl_list_uint_set_init_elem(x); x->range.start = start; x->range.end = end; return x; } int ossl_uint_set_insert(UINT_SET *s, const UINT_RANGE *range) { UINT_SET_ITEM *x, *xnext, *z, *zprev, *f; uint64_t start = range->start, end = range->end; if (!ossl_assert(start <= end)) return 0; if (ossl_list_uint_set_is_empty(s)) { /* Nothing in the set yet, so just add this range. */ x = create_set_item(start, end); if (x == NULL) return 0; ossl_list_uint_set_insert_head(s, x); return 1; } z = ossl_list_uint_set_tail(s); if (start > z->range.end) { /* * Range is after the latest range in the set, so append. * * Note: The case where the range is before the earliest range in the * set is handled as a degenerate case of the final case below. See * optimization note (*) below. */ if (z->range.end + 1 == start) { z->range.end = end; return 1; } x = create_set_item(start, end); if (x == NULL) return 0; ossl_list_uint_set_insert_tail(s, x); return 1; } f = ossl_list_uint_set_head(s); if (start <= f->range.start && end >= z->range.end) { /* * New range dwarfs all ranges in our set. * * Free everything except the first range in the set, which we scavenge * and reuse. */ x = ossl_list_uint_set_head(s); x->range.start = start; x->range.end = end; for (x = ossl_list_uint_set_next(x); x != NULL; x = xnext) { xnext = ossl_list_uint_set_next(x); ossl_list_uint_set_remove(s, x); } return 1; } /* * Walk backwards since we will most often be inserting at the end. As an * optimization, test the head node first and skip iterating over the * entire list if we are inserting at the start. The assumption is that * insertion at the start and end of the space will be the most common * operations. (*) */ z = end < f->range.start ? f : z; for (; z != NULL; z = zprev) { zprev = ossl_list_uint_set_prev(z); /* An existing range dwarfs our new range (optimisation). */ if (z->range.start <= start && z->range.end >= end) return 1; if (uint_range_overlaps(&z->range, range)) { /* * Our new range overlaps an existing range, or possibly several * existing ranges. */ UINT_SET_ITEM *ovend = z; ovend->range.end = u64_max(end, z->range.end); /* Get earliest overlapping range. */ while (zprev != NULL && uint_range_overlaps(&zprev->range, range)) { z = zprev; zprev = ossl_list_uint_set_prev(z); } ovend->range.start = u64_min(start, z->range.start); /* Replace sequence of nodes z..ovend with updated ovend only. */ while (z != ovend) { z = ossl_list_uint_set_next(x = z); ossl_list_uint_set_remove(s, x); OPENSSL_free(x); } break; } else if (end < z->range.start && (zprev == NULL || start > zprev->range.end)) { if (z->range.start == end + 1) { /* We can extend the following range backwards. */ z->range.start = start; /* * If this closes a gap we now need to merge * consecutive nodes. */ uint_set_merge_adjacent(s, z); } else if (zprev != NULL && zprev->range.end + 1 == start) { /* We can extend the preceding range forwards. */ zprev->range.end = end; /* * If this closes a gap we now need to merge * consecutive nodes. */ uint_set_merge_adjacent(s, z); } else { /* * The new interval is between intervals without overlapping or * touching them, so insert between, preserving sort. */ x = create_set_item(start, end); if (x == NULL) return 0; ossl_list_uint_set_insert_before(s, z, x); } break; } } return 1; } int ossl_uint_set_remove(UINT_SET *s, const UINT_RANGE *range) { UINT_SET_ITEM *z, *zprev, *y; uint64_t start = range->start, end = range->end; if (!ossl_assert(start <= end)) return 0; /* Walk backwards since we will most often be removing at the end. */ for (z = ossl_list_uint_set_tail(s); z != NULL; z = zprev) { zprev = ossl_list_uint_set_prev(z); if (start > z->range.end) /* No overlapping ranges can exist beyond this point, so stop. */ break; if (start <= z->range.start && end >= z->range.end) { /* * The range being removed dwarfs this range, so it should be * removed. */ ossl_list_uint_set_remove(s, z); OPENSSL_free(z); } else if (start <= z->range.start && end >= z->range.start) { /* * The range being removed includes start of this range, but does * not cover the entire range (as this would be caught by the case * above). Shorten the range. */ assert(end < z->range.end); z->range.start = end + 1; } else if (end >= z->range.end) { /* * The range being removed includes the end of this range, but does * not cover the entire range (as this would be caught by the case * above). Shorten the range. We can also stop iterating. */ assert(start > z->range.start); assert(start > 0); z->range.end = start - 1; break; } else if (start > z->range.start && end < z->range.end) { /* * The range being removed falls entirely in this range, so cut it * into two. Cases where a zero-length range would be created are * handled by the above cases. */ y = create_set_item(end + 1, z->range.end); ossl_list_uint_set_insert_after(s, z, y); z->range.end = start - 1; break; } else { /* Assert no partial overlap; all cases should be covered above. */ assert(!uint_range_overlaps(&z->range, range)); } } return 1; } int ossl_uint_set_query(const UINT_SET *s, uint64_t v) { UINT_SET_ITEM *x; if (ossl_list_uint_set_is_empty(s)) return 0; for (x = ossl_list_uint_set_tail(s); x != NULL; x = ossl_list_uint_set_prev(x)) if (x->range.start <= v && x->range.end >= v) return 1; else if (x->range.end < v) return 0; return 0; }
./openssl/ssl/quic/quic_port_local.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_LOCAL_H # define OSSL_QUIC_PORT_LOCAL_H # include "internal/quic_port.h" # include "internal/quic_reactor.h" # include "internal/list.h" # ifndef OPENSSL_NO_QUIC /* * QUIC Port Structure * =================== * * QUIC port internals. It is intended that only the QUIC_PORT and QUIC_CHANNEL * implementation be allowed to access this structure directly. * * Other components should not include this header. */ DECLARE_LIST_OF(ch, QUIC_CHANNEL); /* A port is always in one of the following states: */ enum { /* Initial and steady state. */ QUIC_PORT_STATE_RUNNING, /* * Terminal state indicating port is no longer functioning. There are no * transitions out of this state. May be triggered by e.g. a permanent * network BIO error. */ QUIC_PORT_STATE_FAILED }; struct quic_port_st { /* The engine which this port is a child of. */ QUIC_ENGINE *engine; /* * QUIC_ENGINE keeps the ports which belong to it on a list for bookkeeping * purposes. */ OSSL_LIST_MEMBER(port, QUIC_PORT); /* Used to create handshake layer objects inside newly created channels. */ SSL_CTX *channel_ctx; /* Network-side read and write BIOs. */ BIO *net_rbio, *net_wbio; /* RX demuxer. We register incoming DCIDs with this. */ QUIC_DEMUX *demux; /* List of all child channels. */ OSSL_LIST(ch) channel_list; /* Special TSERVER channel. To be removed in the future. */ QUIC_CHANNEL *tserver_ch; /* LCIDM used for incoming packet routing by DCID. */ QUIC_LCIDM *lcidm; /* SRTM used for incoming packet routing by SRT. */ QUIC_SRTM *srtm; /* Port-level permanent errors (causing failure state) are stored here. */ ERR_STATE *err_state; /* DCID length used for incoming short header packets. */ unsigned char rx_short_dcid_len; /* For clients, CID length used for outgoing Initial packets. */ unsigned char tx_init_dcid_len; /* Port state (QUIC_PORT_STATE_*). */ unsigned int state : 1; /* Is this port created to support multiple connections? */ unsigned int is_multi_conn : 1; /* Has this port sent any packet of any kind yet? */ unsigned int have_sent_any_pkt : 1; /* Does this port allow incoming connections? */ unsigned int is_server : 1; /* Are we on the QUIC_ENGINE linked list of ports? */ unsigned int on_engine_list : 1; }; # endif #endif
./openssl/ssl/quic/quic_fc.c
/* * 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 "internal/quic_fc.h" #include "internal/quic_error.h" #include "internal/common.h" #include "internal/safe_math.h" #include <assert.h> OSSL_SAFE_MATH_UNSIGNED(uint64_t, uint64_t) /* * TX Flow Controller (TXFC) * ========================= */ int ossl_quic_txfc_init(QUIC_TXFC *txfc, QUIC_TXFC *conn_txfc) { if (conn_txfc != NULL && conn_txfc->parent != NULL) return 0; txfc->swm = 0; txfc->cwm = 0; txfc->parent = conn_txfc; txfc->has_become_blocked = 0; return 1; } QUIC_TXFC *ossl_quic_txfc_get_parent(QUIC_TXFC *txfc) { return txfc->parent; } int ossl_quic_txfc_bump_cwm(QUIC_TXFC *txfc, uint64_t cwm) { if (cwm <= txfc->cwm) return 0; txfc->cwm = cwm; return 1; } uint64_t ossl_quic_txfc_get_credit_local(QUIC_TXFC *txfc, uint64_t consumed) { assert((txfc->swm + consumed) <= txfc->cwm); return txfc->cwm - (consumed + txfc->swm); } uint64_t ossl_quic_txfc_get_credit(QUIC_TXFC *txfc, uint64_t consumed) { uint64_t r, conn_r; r = ossl_quic_txfc_get_credit_local(txfc, 0); if (txfc->parent != NULL) { assert(txfc->parent->parent == NULL); conn_r = ossl_quic_txfc_get_credit_local(txfc->parent, consumed); if (conn_r < r) r = conn_r; } return r; } int ossl_quic_txfc_consume_credit_local(QUIC_TXFC *txfc, uint64_t num_bytes) { int ok = 1; uint64_t credit = ossl_quic_txfc_get_credit_local(txfc, 0); if (num_bytes > credit) { ok = 0; num_bytes = credit; } if (num_bytes > 0 && num_bytes == credit) txfc->has_become_blocked = 1; txfc->swm += num_bytes; return ok; } int ossl_quic_txfc_consume_credit(QUIC_TXFC *txfc, uint64_t num_bytes) { int ok = ossl_quic_txfc_consume_credit_local(txfc, num_bytes); if (txfc->parent != NULL) { assert(txfc->parent->parent == NULL); if (!ossl_quic_txfc_consume_credit_local(txfc->parent, num_bytes)) return 0; } return ok; } int ossl_quic_txfc_has_become_blocked(QUIC_TXFC *txfc, int clear) { int r = txfc->has_become_blocked; if (clear) txfc->has_become_blocked = 0; return r; } uint64_t ossl_quic_txfc_get_cwm(QUIC_TXFC *txfc) { return txfc->cwm; } uint64_t ossl_quic_txfc_get_swm(QUIC_TXFC *txfc) { return txfc->swm; } /* * RX Flow Controller (RXFC) * ========================= */ 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 *now_arg), void *now_arg) { if (conn_rxfc != NULL && conn_rxfc->parent != NULL) return 0; rxfc->swm = 0; rxfc->cwm = initial_window_size; rxfc->rwm = 0; rxfc->esrwm = 0; rxfc->hwm = 0; rxfc->cur_window_size = initial_window_size; rxfc->max_window_size = max_window_size; rxfc->parent = conn_rxfc; rxfc->error_code = 0; rxfc->has_cwm_changed = 0; rxfc->epoch_start = ossl_time_zero(); rxfc->now = now; rxfc->now_arg = now_arg; rxfc->is_fin = 0; rxfc->standalone = 0; return 1; } int ossl_quic_rxfc_init_standalone(QUIC_RXFC *rxfc, uint64_t initial_window_size, OSSL_TIME (*now)(void *arg), void *now_arg) { if (!ossl_quic_rxfc_init(rxfc, NULL, initial_window_size, initial_window_size, now, now_arg)) return 0; rxfc->standalone = 1; return 1; } QUIC_RXFC *ossl_quic_rxfc_get_parent(QUIC_RXFC *rxfc) { return rxfc->parent; } void ossl_quic_rxfc_set_max_window_size(QUIC_RXFC *rxfc, size_t max_window_size) { rxfc->max_window_size = max_window_size; } static void rxfc_start_epoch(QUIC_RXFC *rxfc) { rxfc->epoch_start = rxfc->now(rxfc->now_arg); rxfc->esrwm = rxfc->rwm; } static int on_rx_controlled_bytes(QUIC_RXFC *rxfc, uint64_t num_bytes) { int ok = 1; uint64_t credit = rxfc->cwm - rxfc->swm; if (num_bytes > credit) { ok = 0; num_bytes = credit; rxfc->error_code = QUIC_ERR_FLOW_CONTROL_ERROR; } rxfc->swm += num_bytes; return ok; } int ossl_quic_rxfc_on_rx_stream_frame(QUIC_RXFC *rxfc, uint64_t end, int is_fin) { uint64_t delta; if (!rxfc->standalone && rxfc->parent == NULL) return 0; if (rxfc->is_fin && ((is_fin && rxfc->hwm != end) || end > rxfc->hwm)) { /* Stream size cannot change after the stream is finished */ rxfc->error_code = QUIC_ERR_FINAL_SIZE_ERROR; return 1; /* not a caller error */ } if (is_fin) rxfc->is_fin = 1; if (end > rxfc->hwm) { delta = end - rxfc->hwm; rxfc->hwm = end; on_rx_controlled_bytes(rxfc, delta); /* result ignored */ if (rxfc->parent != NULL) on_rx_controlled_bytes(rxfc->parent, delta); /* result ignored */ } else if (end < rxfc->hwm && is_fin) { rxfc->error_code = QUIC_ERR_FINAL_SIZE_ERROR; return 1; /* not a caller error */ } return 1; } /* threshold = 3/4 */ #define WINDOW_THRESHOLD_NUM 3 #define WINDOW_THRESHOLD_DEN 4 static int rxfc_cwm_bump_desired(QUIC_RXFC *rxfc) { int err = 0; uint64_t window_rem = rxfc->cwm - rxfc->rwm; uint64_t threshold = safe_muldiv_uint64_t(rxfc->cur_window_size, WINDOW_THRESHOLD_NUM, WINDOW_THRESHOLD_DEN, &err); if (err) /* * Extremely large window should never occur, but if it does, just use * 1/2 as the threshold. */ threshold = rxfc->cur_window_size / 2; /* * No point emitting a new MAX_STREAM_DATA frame if the stream has a final * size. */ return !rxfc->is_fin && window_rem <= threshold; } static int rxfc_should_bump_window_size(QUIC_RXFC *rxfc, OSSL_TIME rtt) { /* * dt: time since start of epoch * b: bytes of window consumed since start of epoch * dw: proportion of window consumed since start of epoch * T_window: time it will take to use up the entire window, based on dt, dw * RTT: The current estimated RTT. * * b = rwm - esrwm * dw = b / window_size * T_window = dt / dw * T_window = dt / (b / window_size) * T_window = (dt * window_size) / b * * We bump the window size if T_window < 4 * RTT. * * We leave the division by b on the LHS to reduce the risk of overflowing * our 64-bit nanosecond representation, which will afford plenty of * precision left over after the division anyway. */ uint64_t b = rxfc->rwm - rxfc->esrwm; OSSL_TIME now, dt, t_window; if (b == 0) return 0; now = rxfc->now(rxfc->now_arg); dt = ossl_time_subtract(now, rxfc->epoch_start); t_window = ossl_time_muldiv(dt, rxfc->cur_window_size, b); return ossl_time_compare(t_window, ossl_time_multiply(rtt, 4)) < 0; } static void rxfc_adjust_window_size(QUIC_RXFC *rxfc, uint64_t min_window_size, OSSL_TIME rtt) { /* Are we sending updates too often? */ uint64_t new_window_size; new_window_size = rxfc->cur_window_size; if (rxfc_should_bump_window_size(rxfc, rtt)) new_window_size *= 2; if (new_window_size < min_window_size) new_window_size = min_window_size; if (new_window_size > rxfc->max_window_size) /* takes precedence over min size */ new_window_size = rxfc->max_window_size; rxfc->cur_window_size = new_window_size; rxfc_start_epoch(rxfc); } static void rxfc_update_cwm(QUIC_RXFC *rxfc, uint64_t min_window_size, OSSL_TIME rtt) { uint64_t new_cwm; if (!rxfc_cwm_bump_desired(rxfc)) return; rxfc_adjust_window_size(rxfc, min_window_size, rtt); new_cwm = rxfc->rwm + rxfc->cur_window_size; if (new_cwm > rxfc->cwm) { rxfc->cwm = new_cwm; rxfc->has_cwm_changed = 1; } } static int rxfc_on_retire(QUIC_RXFC *rxfc, uint64_t num_bytes, uint64_t min_window_size, OSSL_TIME rtt) { if (ossl_time_is_zero(rxfc->epoch_start)) /* This happens when we retire our first ever bytes. */ rxfc_start_epoch(rxfc); rxfc->rwm += num_bytes; rxfc_update_cwm(rxfc, min_window_size, rtt); return 1; } int ossl_quic_rxfc_on_retire(QUIC_RXFC *rxfc, uint64_t num_bytes, OSSL_TIME rtt) { if (rxfc->parent == NULL && !rxfc->standalone) return 0; if (num_bytes == 0) return 1; if (rxfc->rwm + num_bytes > rxfc->swm) /* Impossible for us to retire more bytes than we have received. */ return 0; rxfc_on_retire(rxfc, num_bytes, 0, rtt); if (!rxfc->standalone) rxfc_on_retire(rxfc->parent, num_bytes, rxfc->cur_window_size, rtt); return 1; } uint64_t ossl_quic_rxfc_get_cwm(QUIC_RXFC *rxfc) { return rxfc->cwm; } uint64_t ossl_quic_rxfc_get_swm(QUIC_RXFC *rxfc) { return rxfc->swm; } uint64_t ossl_quic_rxfc_get_rwm(QUIC_RXFC *rxfc) { return rxfc->rwm; } int ossl_quic_rxfc_has_cwm_changed(QUIC_RXFC *rxfc, int clear) { int r = rxfc->has_cwm_changed; if (clear) rxfc->has_cwm_changed = 0; return r; } int ossl_quic_rxfc_get_error(QUIC_RXFC *rxfc, int clear) { int r = rxfc->error_code; if (clear) rxfc->error_code = 0; return r; } int ossl_quic_rxfc_get_final_size(const QUIC_RXFC *rxfc, uint64_t *final_size) { if (!rxfc->is_fin) return 0; if (final_size != NULL) *final_size = rxfc->hwm; return 1; }
./openssl/ssl/quic/quic_channel_local.h
#ifndef OSSL_QUIC_CHANNEL_LOCAL_H # define OSSL_QUIC_CHANNEL_LOCAL_H # include "internal/quic_channel.h" # ifndef OPENSSL_NO_QUIC # include <openssl/lhash.h> # include "internal/list.h" # include "internal/quic_predef.h" # include "internal/quic_fc.h" # include "internal/quic_stream_map.h" /* * QUIC Channel Structure * ====================== * * QUIC channel internals. It is intended that only the QUIC_CHANNEL * implementation and the RX depacketiser be allowed to access this structure * directly. As the RX depacketiser has no state of its own and computes over a * QUIC_CHANNEL structure, it can be viewed as an extension of the QUIC_CHANNEL * implementation. While the RX depacketiser could be provided with adequate * accessors to do what it needs, this would weaken the abstraction provided by * the QUIC_CHANNEL to other components; moreover the coupling of the RX * depacketiser to QUIC_CHANNEL internals is too deep and bespoke to make this * desirable. * * Other components should not include this header. */ struct quic_channel_st { QUIC_PORT *port; /* * QUIC_PORT keeps the channels which belong to it on a list for bookkeeping * purposes. */ OSSL_LIST_MEMBER(ch, struct quic_channel_st); /* * The associated TLS 1.3 connection data. Used to provide the handshake * layer; its 'network' side is plugged into the crypto stream for each EL * (other than the 0-RTT EL). */ QUIC_TLS *qtls; SSL *tls; /* Port LCIDM we use to register LCIDs. */ QUIC_LCIDM *lcidm; /* SRTM we register SRTs with. */ QUIC_SRTM *srtm; /* * The transport parameter block we will send or have sent. * Freed after sending or when connection is freed. */ unsigned char *local_transport_params; /* Our current L4 peer address, if any. */ BIO_ADDR cur_peer_addr; /* * Subcomponents of the connection. All of these components are instantiated * and owned by us. */ OSSL_QUIC_TX_PACKETISER *txp; QUIC_TXPIM *txpim; QUIC_CFQ *cfq; /* * Connection level FC. The stream_count RXFCs is used to manage * MAX_STREAMS signalling. */ QUIC_TXFC conn_txfc; QUIC_RXFC conn_rxfc, crypto_rxfc[QUIC_PN_SPACE_NUM]; QUIC_RXFC max_streams_bidi_rxfc, max_streams_uni_rxfc; QUIC_STREAM_MAP qsm; OSSL_STATM statm; OSSL_CC_DATA *cc_data; const OSSL_CC_METHOD *cc_method; OSSL_ACKM *ackm; /* Record layers in the TX and RX directions. */ OSSL_QTX *qtx; OSSL_QRX *qrx; /* Message callback related arguments */ ossl_msg_cb msg_callback; void *msg_callback_arg; SSL *msg_callback_ssl; /* * Send and receive parts of the crypto streams. * crypto_send[QUIC_PN_SPACE_APP] is the 1-RTT crypto stream. There is no * 0-RTT crypto stream. */ QUIC_SSTREAM *crypto_send[QUIC_PN_SPACE_NUM]; QUIC_RSTREAM *crypto_recv[QUIC_PN_SPACE_NUM]; /* Internal state. */ /* * Client: The DCID used in the first Initial packet we transmit as a client. * Server: The DCID used in the first Initial packet the client transmitted. * Randomly generated and required by RFC to be at least 8 bytes. */ QUIC_CONN_ID init_dcid; /* * Client: The SCID found in the first Initial packet from the server. * Not valid for servers. * Valid if have_received_enc_pkt is set. */ QUIC_CONN_ID init_scid; /* * Client only: The SCID found in an incoming Retry packet we handled. * Not valid for servers. */ QUIC_CONN_ID retry_scid; /* * The DCID we currently use to talk to the peer and its sequence num. */ QUIC_CONN_ID cur_remote_dcid; uint64_t cur_remote_seq_num; uint64_t cur_retire_prior_to; /* Server only: The DCID we currently expect the peer to use to talk to us. */ QUIC_CONN_ID cur_local_cid; /* Transport parameter values we send to our peer. */ uint64_t tx_init_max_stream_data_bidi_local; uint64_t tx_init_max_stream_data_bidi_remote; uint64_t tx_init_max_stream_data_uni; uint64_t tx_max_ack_delay; /* ms */ /* Transport parameter values received from server. */ uint64_t rx_init_max_stream_data_bidi_local; uint64_t rx_init_max_stream_data_bidi_remote; uint64_t rx_init_max_stream_data_uni; uint64_t rx_max_ack_delay; /* ms */ unsigned char rx_ack_delay_exp; /* * Temporary staging area to store information about the incoming packet we * are currently processing. */ OSSL_QRX_PKT *qrx_pkt; /* * Current limit on number of streams we may create. Set by transport * parameters initially and then by MAX_STREAMS frames. */ uint64_t max_local_streams_bidi; uint64_t max_local_streams_uni; /* The negotiated maximum idle timeout in milliseconds. */ uint64_t max_idle_timeout; /* * Maximum payload size in bytes for datagrams sent to our peer, as * negotiated by transport parameters. */ uint64_t rx_max_udp_payload_size; /* Maximum active CID limit, as negotiated by transport parameters. */ uint64_t rx_active_conn_id_limit; /* * Used to allocate stream IDs. This is a stream ordinal, i.e., a stream ID * without the low two bits designating type and initiator. Shift and or in * the type bits to convert to a stream ID. */ uint64_t next_local_stream_ordinal_bidi; uint64_t next_local_stream_ordinal_uni; /* * Used to track which stream ordinals within a given stream type have been * used by the remote peer. This is an optimisation used to determine * which streams should be implicitly created due to usage of a higher * stream ordinal. */ uint64_t next_remote_stream_ordinal_bidi; uint64_t next_remote_stream_ordinal_uni; /* * Application error code to be used for STOP_SENDING/RESET_STREAM frames * used to autoreject incoming streams. */ uint64_t incoming_stream_auto_reject_aec; /* * Override packet count threshold at which we do a spontaneous TXKU. * Usually UINT64_MAX in which case a suitable value is chosen based on AEAD * limit advice from the QRL utility functions. This is intended for testing * use only. Usually set to UINT64_MAX. */ uint64_t txku_threshold_override; /* Diagnostic counters for testing purposes only. May roll over. */ uint16_t diag_num_rx_ack; /* Number of ACK frames received */ /* Valid if we are in the TERMINATING or TERMINATED states. */ QUIC_TERMINATE_CAUSE terminate_cause; /* * Deadline at which we move to TERMINATING state. Valid if in the * TERMINATING state. */ OSSL_TIME terminate_deadline; /* * Deadline at which connection dies due to idle timeout if no further * events occur. */ OSSL_TIME idle_deadline; /* * Deadline at which we should send an ACK-eliciting packet to ensure * idle timeout does not occur. */ OSSL_TIME ping_deadline; /* * The deadline at which the period in which it is RECOMMENDED that we not * initiate any spontaneous TXKU ends. This is zero if no such deadline * applies. */ OSSL_TIME txku_cooldown_deadline; /* * The deadline at which we take the QRX out of UPDATING and back to NORMAL. * Valid if rxku_in_progress in 1. */ OSSL_TIME rxku_update_end_deadline; /* * The first (application space) PN sent with a new key phase. Valid if the * QTX key epoch is greater than 0. Once a packet we sent with a PN p (p >= * txku_pn) is ACKed, the TXKU is considered completed and txku_in_progress * becomes 0. For sanity's sake, such a PN p should also be <= the highest * PN we have ever sent, of course. */ QUIC_PN txku_pn; /* * The (application space) PN which triggered RXKU detection. Valid if * rxku_pending_confirm. */ QUIC_PN rxku_trigger_pn; /* * State tracking. QUIC connection-level state is best represented based on * whether various things have happened yet or not, rather than as an * explicit FSM. We do have a coarse state variable which tracks the basic * state of the connection's lifecycle, but more fine-grained conditions of * the Active state are tracked via flags below. For more details, see * doc/designs/quic-design/connection-state-machine.md. We are in the Open * state if the state is QUIC_CHANNEL_STATE_ACTIVE and handshake_confirmed is * set. */ unsigned int state : 3; /* * Have we received at least one encrypted packet from the peer? * (If so, Retry and Version Negotiation messages should no longer * be received and should be ignored if they do occur.) */ unsigned int have_received_enc_pkt : 1; /* * Have we successfully processed any packet, including a Version * Negotiation packet? If so, further Version Negotiation packets should be * ignored. */ unsigned int have_processed_any_pkt : 1; /* * Have we sent literally any packet yet? If not, there is no point polling * RX. */ unsigned int have_sent_any_pkt : 1; /* * Are we currently doing proactive version negotiation? */ unsigned int doing_proactive_ver_neg : 1; /* We have received transport parameters from the peer. */ unsigned int got_remote_transport_params : 1; /* * This monotonically transitions to 1 once the TLS state machine is * 'complete', meaning that it has both sent a Finished and successfully * verified the peer's Finished (see RFC 9001 s. 4.1.1). Note that it * does not transition to 1 at both peers simultaneously. * * Handshake completion is not the same as handshake confirmation (see * below). */ unsigned int handshake_complete : 1; /* * This monotonically transitions to 1 once the handshake is confirmed. * This happens on the client when we receive a HANDSHAKE_DONE frame. * At our option, we may also take acknowledgement of any 1-RTT packet * we sent as a handshake confirmation. */ unsigned int handshake_confirmed : 1; /* * We are sending Initial packets based on a Retry. This means we definitely * should not receive another Retry, and if we do it is an error. */ unsigned int doing_retry : 1; /* * We don't store the current EL here; the TXP asks the QTX which ELs * are provisioned to determine which ELs to use. */ /* Have statm, qsm been initialised? Used to track cleanup. */ unsigned int have_statm : 1; unsigned int have_qsm : 1; /* * Preferred ELs for transmission and reception. This is not strictly needed * as it can be inferred from what keys we have provisioned, but makes * determining the current EL simpler and faster. A separate EL for * transmission and reception is not strictly necessary but makes things * easier for interoperation with the handshake layer, which likes to invoke * the yield secret callback at different times for TX and RX. */ unsigned int tx_enc_level : 3; unsigned int rx_enc_level : 3; /* If bit n is set, EL n has been discarded. */ unsigned int el_discarded : 4; /* * While in TERMINATING - CLOSING, set when we should generate a connection * close frame. */ unsigned int conn_close_queued : 1; /* Are we in server mode? Never changes after instantiation. */ unsigned int is_server : 1; /* * Set temporarily when the handshake layer has given us a new RX secret. * Used to determine if we need to check our RX queues again. */ unsigned int have_new_rx_secret : 1; /* Have we ever called QUIC_TLS yet during RX processing? */ unsigned int did_tls_tick : 1; /* Has any CRYPTO frame been processed during this tick? */ unsigned int did_crypto_frame : 1; /* * Have we sent an ack-eliciting packet since the last successful packet * reception? Used to determine when to bump idle timer (see RFC 9000 s. * 10.1). */ unsigned int have_sent_ack_eliciting_since_rx : 1; /* Should incoming streams automatically be rejected? */ unsigned int incoming_stream_auto_reject : 1; /* * 1 if a key update sequence was locally initiated, meaning we sent the * TXKU first and the resultant RXKU shouldn't result in our triggering * another TXKU. 0 if a key update sequence was initiated by the peer, * meaning we detect a RXKU first and have to generate a TXKU in response. */ unsigned int ku_locally_initiated : 1; /* * 1 if we have triggered TXKU (whether spontaneous or solicited) but are * waiting for any PN using that new KP to be ACKed. While this is set, we * are not allowed to trigger spontaneous TXKU (but solicited TXKU is * potentially still possible). */ unsigned int txku_in_progress : 1; /* * We have received an RXKU event and currently are going through * UPDATING/COOLDOWN on the QRX. COOLDOWN is currently not used. Since RXKU * cannot be detected in this state, this doesn't cause a protocol error or * anything similar if a peer tries TXKU in this state. That traffic would * simply be dropped. It's only used to track that our UPDATING timer is * active so we know when to take the QRX out of UPDATING and back to * NORMAL. */ unsigned int rxku_in_progress : 1; /* * We have received an RXKU but have yet to send an ACK for it, which means * no further RXKUs are allowed yet. Note that we cannot detect further * RXKUs anyway while the QRX remains in the UPDATING/COOLDOWN states, so * this restriction comes into play if we take more than PTO time to send * an ACK for it (not likely). */ unsigned int rxku_pending_confirm : 1; /* Temporary variable indicating rxku_pending_confirm is to become 0. */ unsigned int rxku_pending_confirm_done : 1; /* * If set, RXKU is expected (because we initiated a spontaneous TXKU). */ unsigned int rxku_expected : 1; /* Permanent net error encountered */ unsigned int net_error : 1; /* * Protocol error encountered. Note that you should refer to the state field * rather than this. This is only used so we can ignore protocol errors * after the first protocol error, but still record the first protocol error * if it happens during the TERMINATING state. */ unsigned int protocol_error : 1; /* Are we using addressed mode? */ unsigned int addressed_mode : 1; /* Are we on the QUIC_PORT linked list of channels? */ unsigned int on_port_list : 1; /* Saved error stack in case permanent error was encountered */ ERR_STATE *err_state; /* Scratch area for use by RXDP to store decoded ACK ranges. */ OSSL_QUIC_ACK_RANGE *ack_range_scratch; size_t num_ack_range_scratch; }; # endif #endif
./openssl/ssl/quic/quic_tserver.c
/* * 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 "internal/quic_tserver.h" #include "internal/quic_channel.h" #include "internal/quic_statm.h" #include "internal/quic_port.h" #include "internal/quic_engine.h" #include "internal/common.h" #include "internal/time.h" #include "quic_local.h" /* * QUIC Test Server Module * ======================= */ struct quic_tserver_st { QUIC_TSERVER_ARGS args; /* Dummy SSL object for this QUIC connection for use by msg_callback */ SSL *ssl; /* * The QUIC engine, port and channel providing the core QUIC connection * implementation. */ QUIC_ENGINE *engine; QUIC_PORT *port; QUIC_CHANNEL *ch; /* The mutex we give to the QUIC channel. */ CRYPTO_MUTEX *mutex; /* SSL_CTX for creating the underlying TLS connection */ SSL_CTX *ctx; /* SSL for the underlying TLS connection */ SSL *tls; /* The current peer L4 address. AF_UNSPEC if we do not have a peer yet. */ BIO_ADDR cur_peer_addr; /* Are we connected to a peer? */ unsigned int connected : 1; }; static int alpn_select_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { QUIC_TSERVER *srv = arg; static const unsigned char alpndeflt[] = { 8, 'o', 's', 's', 'l', 't', 'e', 's', 't' }; const unsigned char *alpn; size_t alpnlen; if (srv->args.alpn == NULL) { alpn = alpndeflt; alpnlen = sizeof(alpn); } else { alpn = srv->args.alpn; alpnlen = srv->args.alpnlen; } if (SSL_select_next_proto((unsigned char **)out, outlen, alpn, alpnlen, in, inlen) != OPENSSL_NPN_NEGOTIATED) return SSL_TLSEXT_ERR_ALERT_FATAL; return SSL_TLSEXT_ERR_OK; } QUIC_TSERVER *ossl_quic_tserver_new(const QUIC_TSERVER_ARGS *args, const char *certfile, const char *keyfile) { QUIC_TSERVER *srv = NULL; QUIC_ENGINE_ARGS engine_args = {0}; QUIC_PORT_ARGS port_args = {0}; QUIC_CONNECTION *qc = NULL; if (args->net_rbio == NULL || args->net_wbio == NULL) goto err; if ((srv = OPENSSL_zalloc(sizeof(*srv))) == NULL) goto err; srv->args = *args; #if defined(OPENSSL_THREADS) if ((srv->mutex = ossl_crypto_mutex_new()) == NULL) goto err; #endif if (args->ctx != NULL) srv->ctx = args->ctx; else srv->ctx = SSL_CTX_new_ex(srv->args.libctx, srv->args.propq, TLS_method()); if (srv->ctx == NULL) goto err; if (certfile != NULL && SSL_CTX_use_certificate_file(srv->ctx, certfile, SSL_FILETYPE_PEM) <= 0) goto err; if (keyfile != NULL && SSL_CTX_use_PrivateKey_file(srv->ctx, keyfile, SSL_FILETYPE_PEM) <= 0) goto err; SSL_CTX_set_alpn_select_cb(srv->ctx, alpn_select_cb, srv); srv->tls = SSL_new(srv->ctx); if (srv->tls == NULL) goto err; engine_args.libctx = srv->args.libctx; engine_args.propq = srv->args.propq; engine_args.mutex = srv->mutex; engine_args.now_cb = srv->args.now_cb; engine_args.now_cb_arg = srv->args.now_cb_arg; if ((srv->engine = ossl_quic_engine_new(&engine_args)) == NULL) goto err; port_args.channel_ctx = srv->ctx; port_args.is_multi_conn = 1; if ((srv->port = ossl_quic_engine_create_port(srv->engine, &port_args)) == NULL) goto err; if ((srv->ch = ossl_quic_port_create_incoming(srv->port, srv->tls)) == NULL) goto err; if (!ossl_quic_port_set_net_rbio(srv->port, srv->args.net_rbio) || !ossl_quic_port_set_net_wbio(srv->port, srv->args.net_wbio)) goto err; qc = OPENSSL_zalloc(sizeof(*qc)); if (qc == NULL) goto err; srv->ssl = (SSL *)qc; qc->ch = srv->ch; srv->ssl->type = SSL_TYPE_QUIC_CONNECTION; return srv; err: if (srv != NULL) { if (args->ctx == NULL) SSL_CTX_free(srv->ctx); SSL_free(srv->tls); ossl_quic_channel_free(srv->ch); ossl_quic_port_free(srv->port); ossl_quic_engine_free(srv->engine); #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(&srv->mutex); #endif OPENSSL_free(qc); } OPENSSL_free(srv); return NULL; } void ossl_quic_tserver_free(QUIC_TSERVER *srv) { if (srv == NULL) return; ossl_quic_channel_free(srv->ch); ossl_quic_port_free(srv->port); ossl_quic_engine_free(srv->engine); BIO_free_all(srv->args.net_rbio); BIO_free_all(srv->args.net_wbio); OPENSSL_free(srv->ssl); SSL_free(srv->tls); SSL_CTX_free(srv->ctx); #if defined(OPENSSL_THREADS) ossl_crypto_mutex_free(&srv->mutex); #endif OPENSSL_free(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) { return ossl_quic_channel_set_mutator(srv->ch, mutatecb, finishmutatecb, 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) { return ossl_statem_set_mutator(ossl_quic_channel_get0_ssl(srv->ch), mutate_handshake_cb, finish_mutate_handshake_cb, mutatearg); } int ossl_quic_tserver_tick(QUIC_TSERVER *srv) { ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(srv->ch), 0); if (ossl_quic_channel_is_active(srv->ch)) srv->connected = 1; return 1; } int ossl_quic_tserver_is_connected(QUIC_TSERVER *srv) { return ossl_quic_channel_is_active(srv->ch); } /* Returns 1 if the server is in any terminating or terminated state */ int ossl_quic_tserver_is_term_any(const QUIC_TSERVER *srv) { return ossl_quic_channel_is_term_any(srv->ch); } const QUIC_TERMINATE_CAUSE * ossl_quic_tserver_get_terminate_cause(const QUIC_TSERVER *srv) { return ossl_quic_channel_get_terminate_cause(srv->ch); } /* Returns 1 if the server is in a terminated state */ int ossl_quic_tserver_is_terminated(const QUIC_TSERVER *srv) { return ossl_quic_channel_is_terminated(srv->ch); } int ossl_quic_tserver_is_handshake_confirmed(const QUIC_TSERVER *srv) { return ossl_quic_channel_is_handshake_confirmed(srv->ch); } int ossl_quic_tserver_read(QUIC_TSERVER *srv, uint64_t stream_id, unsigned char *buf, size_t buf_len, size_t *bytes_read) { int is_fin = 0; QUIC_STREAM *qs; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch), stream_id); if (qs == NULL) { int is_client_init = ((stream_id & QUIC_STREAM_INITIATOR_MASK) == QUIC_STREAM_INITIATOR_CLIENT); /* * A client-initiated stream might spontaneously come into existence, so * allow trying to read on a client-initiated stream before it exists, * assuming the connection is still active. * Otherwise, fail. */ if (!is_client_init || !ossl_quic_channel_is_active(srv->ch)) return 0; *bytes_read = 0; return 1; } if (qs->recv_state == QUIC_RSTREAM_STATE_DATA_READ || !ossl_quic_stream_has_recv_buffer(qs)) return 0; if (!ossl_quic_rstream_read(qs->rstream, buf, buf_len, bytes_read, &is_fin)) return 0; if (*bytes_read > 0) { /* * We have read at least one byte from the stream. Inform stream-level * RXFC of the retirement of controlled bytes. Update the active stream * status (the RXFC may now want to emit a frame granting more credit to * the peer). */ OSSL_RTT_INFO rtt_info; ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(srv->ch), &rtt_info); if (!ossl_quic_rxfc_on_retire(&qs->rxfc, *bytes_read, rtt_info.smoothed_rtt)) return 0; } if (is_fin) ossl_quic_stream_map_notify_totally_read(ossl_quic_channel_get_qsm(srv->ch), qs); if (*bytes_read > 0) ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs); return 1; } int ossl_quic_tserver_has_read_ended(QUIC_TSERVER *srv, uint64_t stream_id) { QUIC_STREAM *qs; unsigned char buf[1]; size_t bytes_read = 0; int is_fin = 0; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch), stream_id); if (qs == NULL) return 0; if (qs->recv_state == QUIC_RSTREAM_STATE_DATA_READ) return 1; if (!ossl_quic_stream_has_recv_buffer(qs)) return 0; /* * If we do not have the DATA_READ, it is possible we should still return 1 * if there is a lone FIN (but no more data) remaining to be retired from * the RSTREAM, for example because ossl_quic_tserver_read() has not been * called since the FIN was received. */ if (!ossl_quic_rstream_peek(qs->rstream, buf, sizeof(buf), &bytes_read, &is_fin)) return 0; if (is_fin && bytes_read == 0) { /* If we have a FIN awaiting retirement and no data before it... */ /* Let RSTREAM know we've consumed this FIN. */ if (!ossl_quic_rstream_read(qs->rstream, buf, sizeof(buf), &bytes_read, &is_fin)) return 0; assert(is_fin && bytes_read == 0); assert(qs->recv_state == QUIC_RSTREAM_STATE_DATA_RECVD); ossl_quic_stream_map_notify_totally_read(ossl_quic_channel_get_qsm(srv->ch), qs); ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs); return 1; } return 0; } int ossl_quic_tserver_write(QUIC_TSERVER *srv, uint64_t stream_id, const unsigned char *buf, size_t buf_len, size_t *bytes_written) { QUIC_STREAM *qs; if (!ossl_quic_channel_is_active(srv->ch)) return 0; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch), stream_id); if (qs == NULL || !ossl_quic_stream_has_send_buffer(qs)) return 0; if (!ossl_quic_sstream_append(qs->sstream, buf, buf_len, bytes_written)) return 0; if (*bytes_written > 0) /* * We have appended at least one byte to the stream. Potentially mark * the stream as active, depending on FC. */ ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs); /* Try and send. */ ossl_quic_tserver_tick(srv); return 1; } int ossl_quic_tserver_conclude(QUIC_TSERVER *srv, uint64_t stream_id) { QUIC_STREAM *qs; if (!ossl_quic_channel_is_active(srv->ch)) return 0; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch), stream_id); if (qs == NULL || !ossl_quic_stream_has_send_buffer(qs)) return 0; if (!ossl_quic_sstream_get_final_size(qs->sstream, NULL)) { ossl_quic_sstream_fin(qs->sstream); ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(srv->ch), qs); } ossl_quic_tserver_tick(srv); return 1; } int ossl_quic_tserver_stream_new(QUIC_TSERVER *srv, int is_uni, uint64_t *stream_id) { QUIC_STREAM *qs; if (!ossl_quic_channel_is_active(srv->ch)) return 0; if ((qs = ossl_quic_channel_new_stream_local(srv->ch, is_uni)) == NULL) return 0; *stream_id = qs->id; return 1; } BIO *ossl_quic_tserver_get0_rbio(QUIC_TSERVER *srv) { return srv->args.net_rbio; } SSL_CTX *ossl_quic_tserver_get0_ssl_ctx(QUIC_TSERVER *srv) { return srv->ctx; } int ossl_quic_tserver_stream_has_peer_stop_sending(QUIC_TSERVER *srv, uint64_t stream_id, uint64_t *app_error_code) { QUIC_STREAM *qs; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch), stream_id); if (qs == NULL) return 0; if (qs->peer_stop_sending && app_error_code != NULL) *app_error_code = qs->peer_stop_sending_aec; return qs->peer_stop_sending; } int ossl_quic_tserver_stream_has_peer_reset_stream(QUIC_TSERVER *srv, uint64_t stream_id, uint64_t *app_error_code) { QUIC_STREAM *qs; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch), stream_id); if (qs == NULL) return 0; if (ossl_quic_stream_recv_is_reset(qs) && app_error_code != NULL) *app_error_code = qs->peer_reset_stream_aec; return ossl_quic_stream_recv_is_reset(qs); } int ossl_quic_tserver_set_new_local_cid(QUIC_TSERVER *srv, const QUIC_CONN_ID *conn_id) { /* Replace existing local connection ID in the QUIC_CHANNEL */ return ossl_quic_channel_replace_local_cid(srv->ch, conn_id); } uint64_t ossl_quic_tserver_pop_incoming_stream(QUIC_TSERVER *srv) { QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(srv->ch); QUIC_STREAM *qs = ossl_quic_stream_map_peek_accept_queue(qsm); if (qs == NULL) return UINT64_MAX; ossl_quic_stream_map_remove_from_accept_queue(qsm, qs, ossl_time_zero()); return qs->id; } int ossl_quic_tserver_is_stream_totally_acked(QUIC_TSERVER *srv, uint64_t stream_id) { QUIC_STREAM *qs; qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(srv->ch), stream_id); if (qs == NULL) return 1; return ossl_quic_sstream_is_totally_acked(qs->sstream); } int ossl_quic_tserver_get_net_read_desired(QUIC_TSERVER *srv) { return ossl_quic_reactor_net_read_desired( ossl_quic_channel_get_reactor(srv->ch)); } int ossl_quic_tserver_get_net_write_desired(QUIC_TSERVER *srv) { return ossl_quic_reactor_net_write_desired( ossl_quic_channel_get_reactor(srv->ch)); } OSSL_TIME ossl_quic_tserver_get_deadline(QUIC_TSERVER *srv) { return ossl_quic_reactor_get_tick_deadline( ossl_quic_channel_get_reactor(srv->ch)); } int ossl_quic_tserver_shutdown(QUIC_TSERVER *srv, uint64_t app_error_code) { ossl_quic_channel_local_close(srv->ch, app_error_code, NULL); /* TODO(QUIC SERVER): !SSL_SHUTDOWN_FLAG_NO_STREAM_FLUSH */ if (ossl_quic_channel_is_terminated(srv->ch)) return 1; ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(srv->ch), 0); return ossl_quic_channel_is_terminated(srv->ch); } int ossl_quic_tserver_ping(QUIC_TSERVER *srv) { if (ossl_quic_channel_is_terminated(srv->ch)) return 0; if (!ossl_quic_channel_ping(srv->ch)) return 0; ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(srv->ch), 0); return 1; } QUIC_CHANNEL *ossl_quic_tserver_get_channel(QUIC_TSERVER *srv) { return srv->ch; } 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) { ossl_quic_channel_set_msg_callback(srv->ch, f, srv->ssl); ossl_quic_channel_set_msg_callback_arg(srv->ch, arg); SSL_set_msg_callback(srv->tls, f); SSL_set_msg_callback_arg(srv->tls, arg); } int ossl_quic_tserver_new_ticket(QUIC_TSERVER *srv) { return SSL_new_session_ticket(srv->tls); } int ossl_quic_tserver_set_max_early_data(QUIC_TSERVER *srv, uint32_t max_early_data) { return SSL_set_max_early_data(srv->tls, max_early_data); } void ossl_quic_tserver_set_psk_find_session_cb(QUIC_TSERVER *srv, SSL_psk_find_session_cb_func cb) { SSL_set_psk_find_session_callback(srv->tls, cb); }
./openssl/ssl/quic/quic_trace.c
/* * 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 <openssl/bio.h> #include "../ssl_local.h" #include "internal/quic_wire_pkt.h" static const char *packet_type(int type) { switch (type) { case QUIC_PKT_TYPE_INITIAL: return "Initial"; case QUIC_PKT_TYPE_0RTT: return "0RTT"; case QUIC_PKT_TYPE_HANDSHAKE: return "Handshake"; case QUIC_PKT_TYPE_RETRY: return "Retry"; case QUIC_PKT_TYPE_1RTT: return "1RTT"; case QUIC_PKT_TYPE_VERSION_NEG: return "VersionNeg"; default: return "Unknown"; } } /* Print a non-NUL terminated string to BIO */ static void put_str(BIO *bio, char *str, size_t slen) { size_t i; for (i = 0; i < slen; i++) BIO_printf(bio, "%c", str[i]); } static void put_data(BIO *bio, const uint8_t *data, size_t datalen) { size_t i; for (i = 0; i < datalen; i++) BIO_printf(bio, "%02x", data[i]); } static void put_conn_id(BIO *bio, QUIC_CONN_ID *id) { if (id->id_len == 0) { BIO_puts(bio, "<zero length id>"); return; } BIO_puts(bio, "0x"); put_data(bio, id->id, id->id_len); } static void put_token(BIO *bio, const uint8_t *token, size_t token_len) { if (token_len == 0) BIO_puts(bio, "<zero length token>"); else put_data(bio, token, token_len); } static int frame_ack(BIO *bio, PACKET *pkt) { OSSL_QUIC_FRAME_ACK ack; OSSL_QUIC_ACK_RANGE *ack_ranges = NULL; uint64_t total_ranges = 0; uint64_t i; if (!ossl_quic_wire_peek_frame_ack_num_ranges(pkt, &total_ranges) /* In case sizeof(uint64_t) > sizeof(size_t) */ || total_ranges > SIZE_MAX / sizeof(ack_ranges[0]) || (ack_ranges = OPENSSL_zalloc(sizeof(ack_ranges[0]) * (size_t)total_ranges)) == NULL) return 0; ack.ack_ranges = ack_ranges; ack.num_ack_ranges = (size_t)total_ranges; /* Ack delay exponent is 0, so we can get the raw delay time below */ if (!ossl_quic_wire_decode_frame_ack(pkt, 0, &ack, NULL)) return 0; BIO_printf(bio, " Largest acked: %llu\n", (unsigned long long)ack.ack_ranges[0].end); BIO_printf(bio, " Ack delay (raw) %llu\n", (unsigned long long)ossl_time2ticks(ack.delay_time)); BIO_printf(bio, " Ack range count: %llu\n", (unsigned long long)total_ranges - 1); BIO_printf(bio, " First ack range: %llu\n", (unsigned long long)(ack.ack_ranges[0].end - ack.ack_ranges[0].start)); for (i = 1; i < total_ranges; i++) { BIO_printf(bio, " Gap: %llu\n", (unsigned long long)(ack.ack_ranges[i - 1].start - ack.ack_ranges[i].end - 2)); BIO_printf(bio, " Ack range len: %llu\n", (unsigned long long)(ack.ack_ranges[i].end - ack.ack_ranges[i].start)); } OPENSSL_free(ack_ranges); return 1; } static int frame_reset_stream(BIO *bio, PACKET *pkt) { OSSL_QUIC_FRAME_RESET_STREAM frame_data; if (!ossl_quic_wire_decode_frame_reset_stream(pkt, &frame_data)) return 0; BIO_printf(bio, " Stream id: %llu\n", (unsigned long long)frame_data.stream_id); BIO_printf(bio, " App Protocol Error Code: %llu\n", (unsigned long long)frame_data.app_error_code); BIO_printf(bio, " Final size: %llu\n", (unsigned long long)frame_data.final_size); return 1; } static int frame_stop_sending(BIO *bio, PACKET *pkt) { OSSL_QUIC_FRAME_STOP_SENDING frame_data; if (!ossl_quic_wire_decode_frame_stop_sending(pkt, &frame_data)) return 0; BIO_printf(bio, " Stream id: %llu\n", (unsigned long long)frame_data.stream_id); BIO_printf(bio, " App Protocol Error Code: %llu\n", (unsigned long long)frame_data.app_error_code); return 1; } static int frame_crypto(BIO *bio, PACKET *pkt) { OSSL_QUIC_FRAME_CRYPTO frame_data; if (!ossl_quic_wire_decode_frame_crypto(pkt, 1, &frame_data)) return 0; BIO_printf(bio, " Offset: %llu\n", (unsigned long long)frame_data.offset); BIO_printf(bio, " Len: %llu\n", (unsigned long long)frame_data.len); return 1; } static int frame_new_token(BIO *bio, PACKET *pkt) { const uint8_t *token; size_t token_len; if (!ossl_quic_wire_decode_frame_new_token(pkt, &token, &token_len)) return 0; BIO_puts(bio, " Token: "); put_token(bio, token, token_len); BIO_puts(bio, "\n"); return 1; } static int frame_stream(BIO *bio, PACKET *pkt, uint64_t frame_type) { OSSL_QUIC_FRAME_STREAM frame_data; BIO_puts(bio, "Stream"); switch(frame_type) { case OSSL_QUIC_FRAME_TYPE_STREAM: BIO_puts(bio, "\n"); break; case OSSL_QUIC_FRAME_TYPE_STREAM_FIN: BIO_puts(bio, " (Fin)\n"); break; case OSSL_QUIC_FRAME_TYPE_STREAM_LEN: BIO_puts(bio, " (Len)\n"); break; case OSSL_QUIC_FRAME_TYPE_STREAM_LEN_FIN: BIO_puts(bio, " (Len, Fin)\n"); break; case OSSL_QUIC_FRAME_TYPE_STREAM_OFF: BIO_puts(bio, " (Off)\n"); break; case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_FIN: BIO_puts(bio, " (Off, Fin)\n"); break; case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN: BIO_puts(bio, " (Off, Len)\n"); break; case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN_FIN: BIO_puts(bio, " (Off, Len, Fin)\n"); break; default: return 0; } if (!ossl_quic_wire_decode_frame_stream(pkt, 1, &frame_data)) return 0; BIO_printf(bio, " Stream id: %llu\n", (unsigned long long)frame_data.stream_id); BIO_printf(bio, " Offset: %llu\n", (unsigned long long)frame_data.offset); /* * It would be nice to find a way of passing the implicit length through * to the msg_callback. But this is not currently possible. */ if (frame_data.has_explicit_len) BIO_printf(bio, " Len: %llu\n", (unsigned long long)frame_data.len); else BIO_puts(bio, " Len: <implicit length>\n"); return 1; } static int frame_max_data(BIO *bio, PACKET *pkt) { uint64_t max_data = 0; if (!ossl_quic_wire_decode_frame_max_data(pkt, &max_data)) return 0; BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data); return 1; } static int frame_max_stream_data(BIO *bio, PACKET *pkt) { uint64_t stream_id = 0; uint64_t max_stream_data = 0; if (!ossl_quic_wire_decode_frame_max_stream_data(pkt, &stream_id, &max_stream_data)) return 0; BIO_printf(bio, " Max Stream Data: %llu\n", (unsigned long long)max_stream_data); return 1; } static int frame_max_streams(BIO *bio, PACKET *pkt) { uint64_t max_streams = 0; if (!ossl_quic_wire_decode_frame_max_streams(pkt, &max_streams)) return 0; BIO_printf(bio, " Max Streams: %llu\n", (unsigned long long)max_streams); return 1; } static int frame_data_blocked(BIO *bio, PACKET *pkt) { uint64_t max_data = 0; if (!ossl_quic_wire_decode_frame_data_blocked(pkt, &max_data)) return 0; BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data); return 1; } static int frame_stream_data_blocked(BIO *bio, PACKET *pkt) { uint64_t stream_id = 0; uint64_t max_data = 0; if (!ossl_quic_wire_decode_frame_stream_data_blocked(pkt, &stream_id, &max_data)) return 0; BIO_printf(bio, " Stream id: %llu\n", (unsigned long long)stream_id); BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data); return 1; } static int frame_streams_blocked(BIO *bio, PACKET *pkt) { uint64_t max_data = 0; if (!ossl_quic_wire_decode_frame_streams_blocked(pkt, &max_data)) return 0; BIO_printf(bio, " Max Data: %llu\n", (unsigned long long)max_data); return 1; } static int frame_new_conn_id(BIO *bio, PACKET *pkt) { OSSL_QUIC_FRAME_NEW_CONN_ID frame_data; if (!ossl_quic_wire_decode_frame_new_conn_id(pkt, &frame_data)) return 0; BIO_printf(bio, " Sequence Number: %llu\n", (unsigned long long)frame_data.seq_num); BIO_printf(bio, " Retire prior to: %llu\n", (unsigned long long)frame_data.retire_prior_to); BIO_puts(bio, " Connection id: "); put_conn_id(bio, &frame_data.conn_id); BIO_puts(bio, "\n Stateless Reset Token: "); put_data(bio, frame_data.stateless_reset.token, sizeof(frame_data.stateless_reset.token)); BIO_puts(bio, "\n"); return 1; } static int frame_retire_conn_id(BIO *bio, PACKET *pkt) { uint64_t seq_num; if (!ossl_quic_wire_decode_frame_retire_conn_id(pkt, &seq_num)) return 0; BIO_printf(bio, " Sequence Number: %llu\n", (unsigned long long)seq_num); return 1; } static int frame_path_challenge(BIO *bio, PACKET *pkt) { uint64_t data = 0; if (!ossl_quic_wire_decode_frame_path_challenge(pkt, &data)) return 0; BIO_printf(bio, " Data: %016llx\n", (unsigned long long)data); return 1; } static int frame_path_response(BIO *bio, PACKET *pkt) { uint64_t data = 0; if (!ossl_quic_wire_decode_frame_path_response(pkt, &data)) return 0; BIO_printf(bio, " Data: %016llx\n", (unsigned long long)data); return 1; } static int frame_conn_closed(BIO *bio, PACKET *pkt) { OSSL_QUIC_FRAME_CONN_CLOSE frame_data; if (!ossl_quic_wire_decode_frame_conn_close(pkt, &frame_data)) return 0; BIO_printf(bio, " Error Code: %llu\n", (unsigned long long)frame_data.error_code); BIO_puts(bio, " Reason: "); put_str(bio, frame_data.reason, frame_data.reason_len); BIO_puts(bio, "\n"); return 1; } static int trace_frame_data(BIO *bio, PACKET *pkt) { uint64_t frame_type; if (!ossl_quic_wire_peek_frame_header(pkt, &frame_type, NULL)) return 0; switch (frame_type) { case OSSL_QUIC_FRAME_TYPE_PING: BIO_puts(bio, "Ping\n"); if (!ossl_quic_wire_decode_frame_ping(pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_PADDING: BIO_puts(bio, "Padding\n"); ossl_quic_wire_decode_padding(pkt); break; case OSSL_QUIC_FRAME_TYPE_ACK_WITHOUT_ECN: case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN: BIO_puts(bio, "Ack "); if (frame_type == OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN) BIO_puts(bio, " (with ECN)\n"); else BIO_puts(bio, " (without ECN)\n"); if (!frame_ack(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_RESET_STREAM: BIO_puts(bio, "Reset stream\n"); if (!frame_reset_stream(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_STOP_SENDING: BIO_puts(bio, "Stop sending\n"); if (!frame_stop_sending(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_CRYPTO: BIO_puts(bio, "Crypto\n"); if (!frame_crypto(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN: BIO_puts(bio, "New token\n"); if (!frame_new_token(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_STREAM: case OSSL_QUIC_FRAME_TYPE_STREAM_FIN: case OSSL_QUIC_FRAME_TYPE_STREAM_LEN: case OSSL_QUIC_FRAME_TYPE_STREAM_LEN_FIN: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_FIN: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN: case OSSL_QUIC_FRAME_TYPE_STREAM_OFF_LEN_FIN: /* frame_stream() prints the frame type string */ if (!frame_stream(bio, pkt, frame_type)) return 0; break; case OSSL_QUIC_FRAME_TYPE_MAX_DATA: BIO_puts(bio, "Max data\n"); if (!frame_max_data(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA: BIO_puts(bio, "Max stream data\n"); if (!frame_max_stream_data(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI: case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI: BIO_puts(bio, "Max streams "); if (frame_type == OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI) BIO_puts(bio, " (Bidi)\n"); else BIO_puts(bio, " (Uni)\n"); if (!frame_max_streams(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_DATA_BLOCKED: BIO_puts(bio, "Data blocked\n"); if (!frame_data_blocked(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_STREAM_DATA_BLOCKED: BIO_puts(bio, "Stream data blocked\n"); if (!frame_stream_data_blocked(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_BIDI: case OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_UNI: BIO_puts(bio, "Streams blocked"); if (frame_type == OSSL_QUIC_FRAME_TYPE_STREAMS_BLOCKED_BIDI) BIO_puts(bio, " (Bidi)\n"); else BIO_puts(bio, " (Uni)\n"); if (!frame_streams_blocked(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID: BIO_puts(bio, "New conn id\n"); if (!frame_new_conn_id(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID: BIO_puts(bio, "Retire conn id\n"); if (!frame_retire_conn_id(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_PATH_CHALLENGE: BIO_puts(bio, "Path challenge\n"); if (!frame_path_challenge(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE: BIO_puts(bio, "Path response\n"); if (!frame_path_response(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_APP: case OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_TRANSPORT: BIO_puts(bio, "Connection close"); if (frame_type == OSSL_QUIC_FRAME_TYPE_CONN_CLOSE_APP) BIO_puts(bio, " (app)\n"); else BIO_puts(bio, " (transport)\n"); if (!frame_conn_closed(bio, pkt)) return 0; break; case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE: BIO_puts(bio, "Handshake done\n"); if (!ossl_quic_wire_decode_frame_handshake_done(pkt)) return 0; break; default: return 0; } if (PACKET_remaining(pkt) != 0) BIO_puts(bio, " <unexpected trailing frame data skipped>\n"); return 1; } int ossl_quic_trace(int write_p, int version, int content_type, const void *buf, size_t msglen, SSL *ssl, void *arg) { BIO *bio = arg; PACKET pkt; switch (content_type) { case SSL3_RT_QUIC_DATAGRAM: BIO_puts(bio, write_p ? "Sent" : "Received"); /* * Unfortunately there is no way of receiving auxiliary information * about the datagram through the msg_callback API such as the peer * address */ BIO_printf(bio, " Datagram\n Length: %zu\n", msglen); break; case SSL3_RT_QUIC_PACKET: { QUIC_PKT_HDR hdr; size_t i; if (!PACKET_buf_init(&pkt, buf, msglen)) return 0; /* Decode the packet header */ /* * TODO(QUIC SERVER): We need to query the short connection id len * here, e.g. via some API SSL_get_short_conn_id_len() */ if (ossl_quic_wire_decode_pkt_hdr(&pkt, 0, 0, 1, &hdr, NULL) != 1) return 0; BIO_puts(bio, write_p ? "Sent" : "Received"); BIO_puts(bio, " Packet\n"); BIO_printf(bio, " Packet Type: %s\n", packet_type(hdr.type)); if (hdr.type != QUIC_PKT_TYPE_1RTT) BIO_printf(bio, " Version: 0x%08lx\n", (unsigned long)hdr.version); BIO_puts(bio, " Destination Conn Id: "); put_conn_id(bio, &hdr.dst_conn_id); BIO_puts(bio, "\n"); if (hdr.type != QUIC_PKT_TYPE_1RTT) { BIO_puts(bio, " Source Conn Id: "); put_conn_id(bio, &hdr.src_conn_id); BIO_puts(bio, "\n"); } BIO_printf(bio, " Payload length: %zu\n", hdr.len); if (hdr.type == QUIC_PKT_TYPE_INITIAL) { BIO_puts(bio, " Token: "); put_token(bio, hdr.token, hdr.token_len); BIO_puts(bio, "\n"); } if (hdr.type != QUIC_PKT_TYPE_VERSION_NEG && hdr.type != QUIC_PKT_TYPE_RETRY) { BIO_puts(bio, " Packet Number: 0x"); /* Will always be at least 1 byte */ for (i = 0; i < hdr.pn_len; i++) BIO_printf(bio, "%02x", hdr.pn[i]); BIO_puts(bio, "\n"); } break; } case SSL3_RT_QUIC_FRAME_PADDING: case SSL3_RT_QUIC_FRAME_FULL: case SSL3_RT_QUIC_FRAME_HEADER: { BIO_puts(bio, write_p ? "Sent" : "Received"); BIO_puts(bio, " Frame: "); if (!PACKET_buf_init(&pkt, buf, msglen)) return 0; if (!trace_frame_data(bio, &pkt)) { BIO_puts(bio, " <error processing frame data>\n"); return 0; } } break; default: /* Unrecognised content_type. We defer to SSL_trace */ return 0; } return 1; }
./openssl/ssl/quic/quic_record_shared.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_QUIC_RECORD_SHARED_H # define OSSL_QUIC_RECORD_SHARED_H # include <openssl/ssl.h> # include "internal/quic_types.h" # include "internal/quic_wire_pkt.h" /* * QUIC Record Layer EL Management Utilities * ========================================= * * This defines a structure for managing the cryptographic state at a given * encryption level, as this functionality is shared between QRX and QTX. For * QRL use only. */ /* * States an EL can be in. The Updating and Cooldown states are used by RX only; * a TX EL in the Provisioned state is always in the Normal substate. * * Key material is available if in the Provisioned state. */ #define QRL_EL_STATE_UNPROV 0 /* Unprovisioned (initial state) */ #define QRL_EL_STATE_PROV_NORMAL 1 /* Provisioned - Normal */ #define QRL_EL_STATE_PROV_UPDATING 2 /* Provisioned - Updating */ #define QRL_EL_STATE_PROV_COOLDOWN 3 /* Provisioned - Cooldown */ #define QRL_EL_STATE_DISCARDED 4 /* Discarded (terminal state) */ typedef struct ossl_qrl_enc_level_st { /* * Cryptographic context used to apply and remove header protection from * packet headers. */ QUIC_HDR_PROTECTOR hpr; /* Hash function used for key derivation. */ EVP_MD *md; /* Context used for packet body ciphering. One for each keyslot. */ EVP_CIPHER_CTX *cctx[2]; OSSL_LIB_CTX *libctx; const char *propq; /* * Key epoch, essentially the number of times we have done a key update. * * The least significant bit of this is therefore by definition the current * Key Phase bit value. */ uint64_t key_epoch; /* Usage counter. The caller maintains this. Used by TX side only. */ uint64_t op_count; /* QRL_SUITE_* value. */ uint32_t suite_id; /* Length of authentication tag. */ uint32_t tag_len; /* Current EL state. */ unsigned char state; /* QRL_EL_STATE_* */ /* 1 if for TX, else RX. Initialised when secret provided. */ unsigned char is_tx; /* IV used to construct nonces used for AEAD packet body ciphering. */ unsigned char iv[2][EVP_MAX_IV_LENGTH]; /* * Secret for next key epoch. */ unsigned char ku[EVP_MAX_KEY_LENGTH]; } OSSL_QRL_ENC_LEVEL; typedef struct ossl_qrl_enc_level_set_st { OSSL_QRL_ENC_LEVEL el[QUIC_ENC_LEVEL_NUM]; } OSSL_QRL_ENC_LEVEL_SET; /* * Returns 1 if we have key material for a given encryption level (that is, if * we are in the PROVISIONED state), 0 if we do not yet have material (we are in * the UNPROVISIONED state) and -1 if the EL is discarded (we are in the * DISCARDED state). */ int ossl_qrl_enc_level_set_have_el(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level); /* * Returns EL in a set. If enc_level is not a valid QUIC_ENC_LEVEL_* value, * returns NULL. If require_prov is 1, returns NULL if the EL is not in * the PROVISIONED state; otherwise, the returned EL may be in any state. */ OSSL_QRL_ENC_LEVEL *ossl_qrl_enc_level_set_get(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level, int require_prov); /* Provide secret to an EL. md may be NULL. */ int ossl_qrl_enc_level_set_provide_secret(OSSL_QRL_ENC_LEVEL_SET *els, OSSL_LIB_CTX *libctx, const char *propq, uint32_t enc_level, uint32_t suite_id, EVP_MD *md, const unsigned char *secret, size_t secret_len, unsigned char init_key_phase_bit, int is_tx); /* * Returns 1 if the given keyslot index is currently valid for a given EL and EL * state. */ int ossl_qrl_enc_level_set_has_keyslot(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level, unsigned char tgt_state, size_t keyslot); /* Perform a key update. Transitions from PROV_NORMAL to PROV_UPDATING. */ int ossl_qrl_enc_level_set_key_update(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level); /* Transitions from PROV_UPDATING to PROV_COOLDOWN. */ int ossl_qrl_enc_level_set_key_update_done(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level); /* * Transitions from PROV_COOLDOWN to PROV_NORMAL. (If in PROV_UPDATING, * auto-transitions to PROV_COOLDOWN first.) */ int ossl_qrl_enc_level_set_key_cooldown_done(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level); /* * Discard an EL. No secret can be provided for the EL ever again. */ void ossl_qrl_enc_level_set_discard(OSSL_QRL_ENC_LEVEL_SET *els, uint32_t enc_level); #endif
./openssl/ssl/quic/quic_record_tx.c
/* * 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 "internal/quic_record_tx.h" #include "internal/bio_addr.h" #include "internal/common.h" #include "quic_record_shared.h" #include "internal/list.h" #include "../ssl_local.h" /* * TXE * === * Encrypted packets awaiting transmission are kept in TX Entries (TXEs), which * are queued in linked lists just like TXEs. */ typedef struct txe_st TXE; struct txe_st { OSSL_LIST_MEMBER(txe, TXE); size_t data_len, alloc_len; /* * Destination and local addresses, as applicable. Both of these are only * used if the family is not AF_UNSPEC. */ BIO_ADDR peer, local; /* * alloc_len allocated bytes (of which data_len bytes are valid) follow this * structure. */ }; DEFINE_LIST_OF(txe, TXE); typedef OSSL_LIST(txe) TXE_LIST; static ossl_inline unsigned char *txe_data(const TXE *e) { return (unsigned char *)(e + 1); } /* * QTX * === */ struct ossl_qtx_st { OSSL_LIB_CTX *libctx; const char *propq; /* Per encryption-level state. */ OSSL_QRL_ENC_LEVEL_SET el_set; /* TX BIO. */ BIO *bio; /* TX maximum datagram payload length. */ size_t mdpl; /* * List of TXEs which are not currently in use. These are moved to the * pending list (possibly via tx_cons first) as they are filled. */ TXE_LIST free; /* * List of TXEs which are filled with completed datagrams ready to be * transmitted. */ TXE_LIST pending; size_t pending_count; /* items in list */ size_t pending_bytes; /* sum(txe->data_len) in pending */ /* * TXE which is under construction for coalescing purposes, if any. * This TXE is neither on the free nor pending list. Once the datagram * is completed, it is moved to the pending list. */ TXE *cons; size_t cons_count; /* num packets */ /* * Number of packets transmitted in this key epoch. Used to enforce AEAD * confidentiality limit. */ uint64_t epoch_pkt_count; ossl_mutate_packet_cb mutatecb; ossl_finish_mutate_cb finishmutatecb; void *mutatearg; /* Message callback related arguments */ ossl_msg_cb msg_callback; void *msg_callback_arg; SSL *msg_callback_ssl; }; /* Instantiates a new QTX. */ OSSL_QTX *ossl_qtx_new(const OSSL_QTX_ARGS *args) { OSSL_QTX *qtx; if (args->mdpl < QUIC_MIN_INITIAL_DGRAM_LEN) return 0; qtx = OPENSSL_zalloc(sizeof(OSSL_QTX)); if (qtx == NULL) return 0; qtx->libctx = args->libctx; qtx->propq = args->propq; qtx->bio = args->bio; qtx->mdpl = args->mdpl; return qtx; } static void qtx_cleanup_txl(TXE_LIST *l) { TXE *e, *enext; for (e = ossl_list_txe_head(l); e != NULL; e = enext) { enext = ossl_list_txe_next(e); OPENSSL_free(e); } } /* Frees the QTX. */ void ossl_qtx_free(OSSL_QTX *qtx) { uint32_t i; if (qtx == NULL) return; /* Free TXE queue data. */ qtx_cleanup_txl(&qtx->pending); qtx_cleanup_txl(&qtx->free); OPENSSL_free(qtx->cons); /* Drop keying material and crypto resources. */ for (i = 0; i < QUIC_ENC_LEVEL_NUM; ++i) ossl_qrl_enc_level_set_discard(&qtx->el_set, i); OPENSSL_free(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) { qtx->mutatecb = mutatecb; qtx->finishmutatecb = finishmutatecb; qtx->mutatearg = mutatearg; } int ossl_qtx_provide_secret(OSSL_QTX *qtx, uint32_t enc_level, uint32_t suite_id, EVP_MD *md, const unsigned char *secret, size_t secret_len) { if (enc_level >= QUIC_ENC_LEVEL_NUM) return 0; return ossl_qrl_enc_level_set_provide_secret(&qtx->el_set, qtx->libctx, qtx->propq, enc_level, suite_id, md, secret, secret_len, 0, /*is_tx=*/1); } int ossl_qtx_discard_enc_level(OSSL_QTX *qtx, uint32_t enc_level) { if (enc_level >= QUIC_ENC_LEVEL_NUM) return 0; ossl_qrl_enc_level_set_discard(&qtx->el_set, enc_level); return 1; } int ossl_qtx_is_enc_level_provisioned(OSSL_QTX *qtx, uint32_t enc_level) { return ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1) != NULL; } /* Allocate a new TXE. */ static TXE *qtx_alloc_txe(size_t alloc_len) { TXE *txe; if (alloc_len >= SIZE_MAX - sizeof(TXE)) return NULL; txe = OPENSSL_malloc(sizeof(TXE) + alloc_len); if (txe == NULL) return NULL; ossl_list_txe_init_elem(txe); txe->alloc_len = alloc_len; txe->data_len = 0; return txe; } /* * Ensures there is at least one TXE in the free list, allocating a new entry * if necessary. The returned TXE is in the free list; it is not popped. * * alloc_len is a hint which may be used to determine the TXE size if allocation * is necessary. Returns NULL on allocation failure. */ static TXE *qtx_ensure_free_txe(OSSL_QTX *qtx, size_t alloc_len) { TXE *txe; txe = ossl_list_txe_head(&qtx->free); if (txe != NULL) return txe; txe = qtx_alloc_txe(alloc_len); if (txe == NULL) return NULL; ossl_list_txe_insert_tail(&qtx->free, txe); return txe; } /* * Resize the data buffer attached to an TXE to be n bytes in size. The address * of the TXE might change; the new address is returned, or NULL on failure, in * which case the original TXE remains valid. */ static TXE *qtx_resize_txe(OSSL_QTX *qtx, TXE_LIST *txl, TXE *txe, size_t n) { TXE *txe2, *p; /* Should never happen. */ if (txe == NULL) return NULL; if (n >= SIZE_MAX - sizeof(TXE)) return NULL; /* Remove the item from the list to avoid accessing freed memory */ p = ossl_list_txe_prev(txe); ossl_list_txe_remove(txl, txe); /* * NOTE: We do not clear old memory, although it does contain decrypted * data. */ txe2 = OPENSSL_realloc(txe, sizeof(TXE) + n); if (txe2 == NULL || txe == txe2) { if (p == NULL) ossl_list_txe_insert_head(txl, txe); else ossl_list_txe_insert_after(txl, p, txe); return txe2; } if (p == NULL) ossl_list_txe_insert_head(txl, txe2); else ossl_list_txe_insert_after(txl, p, txe2); if (qtx->cons == txe) qtx->cons = txe2; txe2->alloc_len = n; return txe2; } /* * Ensure the data buffer attached to an TXE is at least n bytes in size. * Returns NULL on failure. */ static TXE *qtx_reserve_txe(OSSL_QTX *qtx, TXE_LIST *txl, TXE *txe, size_t n) { if (txe->alloc_len >= n) return txe; return qtx_resize_txe(qtx, txl, txe, n); } /* Move a TXE from pending to free. */ static void qtx_pending_to_free(OSSL_QTX *qtx) { TXE *txe = ossl_list_txe_head(&qtx->pending); assert(txe != NULL); ossl_list_txe_remove(&qtx->pending, txe); --qtx->pending_count; qtx->pending_bytes -= txe->data_len; ossl_list_txe_insert_tail(&qtx->free, txe); } /* Add a TXE not currently in any list to the pending list. */ static void qtx_add_to_pending(OSSL_QTX *qtx, TXE *txe) { ossl_list_txe_insert_tail(&qtx->pending, txe); ++qtx->pending_count; qtx->pending_bytes += txe->data_len; } struct iovec_cur { const OSSL_QTX_IOVEC *iovec; size_t num_iovec, idx, byte_off, bytes_remaining; }; static size_t iovec_total_bytes(const OSSL_QTX_IOVEC *iovec, size_t num_iovec) { size_t i, l = 0; for (i = 0; i < num_iovec; ++i) l += iovec[i].buf_len; return l; } static void iovec_cur_init(struct iovec_cur *cur, const OSSL_QTX_IOVEC *iovec, size_t num_iovec) { cur->iovec = iovec; cur->num_iovec = num_iovec; cur->idx = 0; cur->byte_off = 0; cur->bytes_remaining = iovec_total_bytes(iovec, num_iovec); } /* * Get an extent of bytes from the iovec cursor. *buf is set to point to the * buffer and the number of bytes in length of the buffer is returned. This * value may be less than the max_buf_len argument. If no more data is * available, returns 0. */ static size_t iovec_cur_get_buffer(struct iovec_cur *cur, const unsigned char **buf, size_t max_buf_len) { size_t l; if (max_buf_len == 0) { *buf = NULL; return 0; } for (;;) { if (cur->idx >= cur->num_iovec) return 0; l = cur->iovec[cur->idx].buf_len - cur->byte_off; if (l > max_buf_len) l = max_buf_len; if (l > 0) { *buf = cur->iovec[cur->idx].buf + cur->byte_off; cur->byte_off += l; cur->bytes_remaining -= l; return l; } /* * Zero-length iovec entry or we already consumed all of it, try the * next iovec. */ ++cur->idx; cur->byte_off = 0; } } /* Determines the size of the AEAD output given the input size. */ int ossl_qtx_calculate_ciphertext_payload_len(OSSL_QTX *qtx, uint32_t enc_level, size_t plaintext_len, size_t *ciphertext_len) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1); size_t tag_len; if (el == NULL) { *ciphertext_len = 0; return 0; } /* * We currently only support ciphers with a 1:1 mapping between plaintext * and ciphertext size, save for authentication tag. */ tag_len = ossl_qrl_get_suite_cipher_tag_len(el->suite_id); *ciphertext_len = plaintext_len + tag_len; return 1; } /* Determines the size of the AEAD input given the output size. */ int ossl_qtx_calculate_plaintext_payload_len(OSSL_QTX *qtx, uint32_t enc_level, size_t ciphertext_len, size_t *plaintext_len) { OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1); size_t tag_len; if (el == NULL) { *plaintext_len = 0; return 0; } tag_len = ossl_qrl_get_suite_cipher_tag_len(el->suite_id); if (ciphertext_len <= tag_len) { *plaintext_len = 0; return 0; } *plaintext_len = ciphertext_len - tag_len; return 1; } /* Any other error (including packet being too big for MDPL). */ #define QTX_FAIL_GENERIC (-1) /* * Returned where there is insufficient room in the datagram to write the * packet. */ #define QTX_FAIL_INSUFFICIENT_LEN (-2) static int qtx_write_hdr(OSSL_QTX *qtx, const QUIC_PKT_HDR *hdr, TXE *txe, QUIC_PKT_HDR_PTRS *ptrs) { WPACKET wpkt; size_t l = 0; unsigned char *data = txe_data(txe) + txe->data_len; if (!WPACKET_init_static_len(&wpkt, data, txe->alloc_len - txe->data_len, 0)) return 0; if (!ossl_quic_wire_encode_pkt_hdr(&wpkt, hdr->dst_conn_id.id_len, hdr, ptrs) || !WPACKET_get_total_written(&wpkt, &l)) { WPACKET_finish(&wpkt); return 0; } WPACKET_finish(&wpkt); if (qtx->msg_callback != NULL) qtx->msg_callback(1, OSSL_QUIC1_VERSION, SSL3_RT_QUIC_PACKET, data, l, qtx->msg_callback_ssl, qtx->msg_callback_arg); txe->data_len += l; return 1; } static int qtx_encrypt_into_txe(OSSL_QTX *qtx, struct iovec_cur *cur, TXE *txe, uint32_t enc_level, QUIC_PN pn, const unsigned char *hdr, size_t hdr_len, QUIC_PKT_HDR_PTRS *ptrs) { int l = 0, l2 = 0, nonce_len; OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1); unsigned char nonce[EVP_MAX_IV_LENGTH]; size_t i; EVP_CIPHER_CTX *cctx = NULL; /* We should not have been called if we do not have key material. */ if (!ossl_assert(el != NULL)) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } /* * Have we already encrypted the maximum number of packets using the current * key? */ if (el->op_count >= ossl_qrl_get_suite_max_pkt(el->suite_id)) { ERR_raise(ERR_LIB_SSL, SSL_R_MAXIMUM_ENCRYPTED_PKTS_REACHED); return 0; } /* * TX key update is simpler than for RX; once we initiate a key update, we * never need the old keys, as we never deliberately send a packet with old * keys. Thus the EL always uses keyslot 0 for the TX side. */ cctx = el->cctx[0]; if (!ossl_assert(cctx != NULL)) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } /* Construct nonce (nonce=IV ^ PN). */ nonce_len = EVP_CIPHER_CTX_get_iv_length(cctx); if (!ossl_assert(nonce_len >= (int)sizeof(QUIC_PN))) { ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR); return 0; } memcpy(nonce, el->iv[0], (size_t)nonce_len); for (i = 0; i < sizeof(QUIC_PN); ++i) nonce[nonce_len - i - 1] ^= (unsigned char)(pn >> (i * 8)); /* type and key will already have been setup; feed the IV. */ if (EVP_CipherInit_ex(cctx, NULL, NULL, NULL, nonce, /*enc=*/1) != 1) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); return 0; } /* Feed AAD data. */ if (EVP_CipherUpdate(cctx, NULL, &l, hdr, hdr_len) != 1) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); return 0; } /* Encrypt plaintext directly into TXE. */ for (;;) { const unsigned char *src; size_t src_len; src_len = iovec_cur_get_buffer(cur, &src, SIZE_MAX); if (src_len == 0) break; if (EVP_CipherUpdate(cctx, txe_data(txe) + txe->data_len, &l, src, src_len) != 1) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); return 0; } #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION /* Ignore what we just encrypted and overwrite it with the plaintext */ memcpy(txe_data(txe) + txe->data_len, src, l); #endif assert(l > 0 && src_len == (size_t)l); txe->data_len += src_len; } /* Finalise and get tag. */ if (EVP_CipherFinal_ex(cctx, NULL, &l2) != 1) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); return 0; } if (EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_GET_TAG, el->tag_len, txe_data(txe) + txe->data_len) != 1) { ERR_raise(ERR_LIB_SSL, ERR_R_EVP_LIB); return 0; } txe->data_len += el->tag_len; /* Apply header protection. */ if (!ossl_quic_hdr_protector_encrypt(&el->hpr, ptrs)) return 0; ++el->op_count; return 1; } /* * Append a packet to the TXE buffer, serializing and encrypting it in the * process. */ static int qtx_write(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt, TXE *txe, uint32_t enc_level) { int ret, needs_encrypt; size_t hdr_len, pred_hdr_len, payload_len, pkt_len, space_left; size_t min_len, orig_data_len; struct iovec_cur cur; QUIC_PKT_HDR_PTRS ptrs; unsigned char *hdr_start; OSSL_QRL_ENC_LEVEL *el = NULL; QUIC_PKT_HDR *hdr; const OSSL_QTX_IOVEC *iovec; size_t num_iovec; /* * Determine if the packet needs encryption and the minimum conceivable * serialization length. */ if (!ossl_quic_pkt_type_is_encrypted(pkt->hdr->type)) { needs_encrypt = 0; min_len = QUIC_MIN_VALID_PKT_LEN; } else { needs_encrypt = 1; min_len = QUIC_MIN_VALID_PKT_LEN_CRYPTO; el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1); if (!ossl_assert(el != NULL)) /* should already have been checked */ return 0; } orig_data_len = txe->data_len; space_left = txe->alloc_len - txe->data_len; if (space_left < min_len) { /* Not even a possibility of it fitting. */ ret = QTX_FAIL_INSUFFICIENT_LEN; goto err; } /* Set some fields in the header we are responsible for. */ if (pkt->hdr->type == QUIC_PKT_TYPE_1RTT) pkt->hdr->key_phase = (unsigned char)(el->key_epoch & 1); /* If we are running tests then mutate_packet may be non NULL */ if (qtx->mutatecb != NULL) { if (!qtx->mutatecb(pkt->hdr, pkt->iovec, pkt->num_iovec, &hdr, &iovec, &num_iovec, qtx->mutatearg)) { ret = QTX_FAIL_GENERIC; goto err; } } else { hdr = pkt->hdr; iovec = pkt->iovec; num_iovec = pkt->num_iovec; } /* Walk the iovecs to determine actual input payload length. */ iovec_cur_init(&cur, iovec, num_iovec); if (cur.bytes_remaining == 0) { /* No zero-length payloads allowed. */ ret = QTX_FAIL_GENERIC; goto err; } /* Determine encrypted payload length. */ if (needs_encrypt) ossl_qtx_calculate_ciphertext_payload_len(qtx, enc_level, cur.bytes_remaining, &payload_len); else payload_len = cur.bytes_remaining; /* Determine header length. */ hdr->data = NULL; hdr->len = payload_len; pred_hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(hdr->dst_conn_id.id_len, hdr); if (pred_hdr_len == 0) { ret = QTX_FAIL_GENERIC; goto err; } /* We now definitively know our packet length. */ pkt_len = pred_hdr_len + payload_len; if (pkt_len > space_left) { ret = QTX_FAIL_INSUFFICIENT_LEN; goto err; } if (ossl_quic_pkt_type_has_pn(hdr->type)) { if (!ossl_quic_wire_encode_pkt_hdr_pn(pkt->pn, hdr->pn, hdr->pn_len)) { ret = QTX_FAIL_GENERIC; goto err; } } /* Append the header to the TXE. */ hdr_start = txe_data(txe) + txe->data_len; if (!qtx_write_hdr(qtx, hdr, txe, &ptrs)) { ret = QTX_FAIL_GENERIC; goto err; } hdr_len = (txe_data(txe) + txe->data_len) - hdr_start; assert(hdr_len == pred_hdr_len); if (!needs_encrypt) { /* Just copy the payload across. */ const unsigned char *src; size_t src_len; for (;;) { /* Buffer length has already been checked above. */ src_len = iovec_cur_get_buffer(&cur, &src, SIZE_MAX); if (src_len == 0) break; memcpy(txe_data(txe) + txe->data_len, src, src_len); txe->data_len += src_len; } } else { /* Encrypt into TXE. */ if (!qtx_encrypt_into_txe(qtx, &cur, txe, enc_level, pkt->pn, hdr_start, hdr_len, &ptrs)) { ret = QTX_FAIL_GENERIC; goto err; } assert(txe->data_len - orig_data_len == pkt_len); } if (qtx->finishmutatecb != NULL) qtx->finishmutatecb(qtx->mutatearg); return 1; err: /* * Restore original length so we don't leave a half-written packet in the * TXE. */ txe->data_len = orig_data_len; if (qtx->finishmutatecb != NULL) qtx->finishmutatecb(qtx->mutatearg); return ret; } static TXE *qtx_ensure_cons(OSSL_QTX *qtx) { TXE *txe = qtx->cons; if (txe != NULL) return txe; txe = qtx_ensure_free_txe(qtx, qtx->mdpl); if (txe == NULL) return NULL; ossl_list_txe_remove(&qtx->free, txe); qtx->cons = txe; qtx->cons_count = 0; txe->data_len = 0; return txe; } static int addr_eq(const BIO_ADDR *a, const BIO_ADDR *b) { return ((a == NULL || BIO_ADDR_family(a) == AF_UNSPEC) && (b == NULL || BIO_ADDR_family(b) == AF_UNSPEC)) || (a != NULL && b != NULL && memcmp(a, b, sizeof(*a)) == 0); } int ossl_qtx_write_pkt(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt) { int ret; int coalescing = (pkt->flags & OSSL_QTX_PKT_FLAG_COALESCE) != 0; int was_coalescing; TXE *txe; uint32_t enc_level; /* Must have EL configured, must have header. */ if (pkt->hdr == NULL) return 0; enc_level = ossl_quic_pkt_type_to_enc_level(pkt->hdr->type); /* Some packet types must be in a packet all by themselves. */ if (!ossl_quic_pkt_type_can_share_dgram(pkt->hdr->type)) ossl_qtx_finish_dgram(qtx); else if (enc_level >= QUIC_ENC_LEVEL_NUM || ossl_qrl_enc_level_set_have_el(&qtx->el_set, enc_level) != 1) { /* All other packet types are encrypted. */ return 0; } was_coalescing = (qtx->cons != NULL && qtx->cons->data_len > 0); if (was_coalescing) if (!addr_eq(&qtx->cons->peer, pkt->peer) || !addr_eq(&qtx->cons->local, pkt->local)) { /* Must stop coalescing if addresses have changed */ ossl_qtx_finish_dgram(qtx); was_coalescing = 0; } for (;;) { /* * Start a new coalescing session or continue using the existing one and * serialize/encrypt the packet. We always encrypt packets as soon as * our caller gives them to us, which relieves the caller of any need to * keep the plaintext around. */ txe = qtx_ensure_cons(qtx); if (txe == NULL) return 0; /* allocation failure */ /* * Ensure TXE has at least MDPL bytes allocated. This should only be * possible if the MDPL has increased. */ if (!qtx_reserve_txe(qtx, NULL, txe, qtx->mdpl)) return 0; if (!was_coalescing) { /* Set addresses in TXE. */ if (pkt->peer != NULL) txe->peer = *pkt->peer; else BIO_ADDR_clear(&txe->peer); if (pkt->local != NULL) txe->local = *pkt->local; else BIO_ADDR_clear(&txe->local); } ret = qtx_write(qtx, pkt, txe, enc_level); if (ret == 1) { break; } else if (ret == QTX_FAIL_INSUFFICIENT_LEN) { if (was_coalescing) { /* * We failed due to insufficient length, so end the current * datagram and try again. */ ossl_qtx_finish_dgram(qtx); was_coalescing = 0; } else { /* * We failed due to insufficient length, but we were not * coalescing/started with an empty datagram, so any future * attempt to write this packet must also fail. */ return 0; } } else { return 0; /* other error */ } } ++qtx->cons_count; /* * Some packet types cannot have another packet come after them. */ if (ossl_quic_pkt_type_must_be_last(pkt->hdr->type)) coalescing = 0; if (!coalescing) ossl_qtx_finish_dgram(qtx); return 1; } /* * Finish any incomplete datagrams for transmission which were flagged for * coalescing. If there is no current coalescing datagram, this is a no-op. */ void ossl_qtx_finish_dgram(OSSL_QTX *qtx) { TXE *txe = qtx->cons; if (txe == NULL) return; if (txe->data_len == 0) /* * If we did not put anything in the datagram, just move it back to the * free list. */ ossl_list_txe_insert_tail(&qtx->free, txe); else qtx_add_to_pending(qtx, txe); qtx->cons = NULL; qtx->cons_count = 0; } static void txe_to_msg(TXE *txe, BIO_MSG *msg) { msg->data = txe_data(txe); msg->data_len = txe->data_len; msg->flags = 0; msg->peer = BIO_ADDR_family(&txe->peer) != AF_UNSPEC ? &txe->peer : NULL; msg->local = BIO_ADDR_family(&txe->local) != AF_UNSPEC ? &txe->local : NULL; } #define MAX_MSGS_PER_SEND 32 int ossl_qtx_flush_net(OSSL_QTX *qtx) { BIO_MSG msg[MAX_MSGS_PER_SEND]; size_t wr, i, total_written = 0; TXE *txe; int res; if (ossl_list_txe_head(&qtx->pending) == NULL) return QTX_FLUSH_NET_RES_OK; /* Nothing to send. */ if (qtx->bio == NULL) return QTX_FLUSH_NET_RES_PERMANENT_FAIL; for (;;) { for (txe = ossl_list_txe_head(&qtx->pending), i = 0; txe != NULL && i < OSSL_NELEM(msg); txe = ossl_list_txe_next(txe), ++i) txe_to_msg(txe, &msg[i]); if (!i) /* Nothing to send. */ break; ERR_set_mark(); res = BIO_sendmmsg(qtx->bio, msg, sizeof(BIO_MSG), i, 0, &wr); if (res && wr == 0) { /* * Treat 0 messages sent as a transient error and just stop for now. */ ERR_clear_last_mark(); break; } else if (!res) { /* * We did not get anything, so further calls will probably not * succeed either. */ if (BIO_err_is_non_fatal(ERR_peek_last_error())) { /* Transient error, just stop for now, clearing the error. */ ERR_pop_to_mark(); break; } else { /* Non-transient error, fail and do not clear the error. */ ERR_clear_last_mark(); return QTX_FLUSH_NET_RES_PERMANENT_FAIL; } } ERR_clear_last_mark(); /* * Remove everything which was successfully sent from the pending queue. */ for (i = 0; i < wr; ++i) { if (qtx->msg_callback != NULL) qtx->msg_callback(1, OSSL_QUIC1_VERSION, SSL3_RT_QUIC_DATAGRAM, msg[i].data, msg[i].data_len, qtx->msg_callback_ssl, qtx->msg_callback_arg); qtx_pending_to_free(qtx); } total_written += wr; } return total_written > 0 ? QTX_FLUSH_NET_RES_OK : QTX_FLUSH_NET_RES_TRANSIENT_FAIL; } int ossl_qtx_pop_net(OSSL_QTX *qtx, BIO_MSG *msg) { TXE *txe = ossl_list_txe_head(&qtx->pending); if (txe == NULL) return 0; txe_to_msg(txe, msg); qtx_pending_to_free(qtx); return 1; } void ossl_qtx_set_bio(OSSL_QTX *qtx, BIO *bio) { qtx->bio = bio; } int ossl_qtx_set_mdpl(OSSL_QTX *qtx, size_t mdpl) { if (mdpl < QUIC_MIN_INITIAL_DGRAM_LEN) return 0; qtx->mdpl = mdpl; return 1; } size_t ossl_qtx_get_mdpl(OSSL_QTX *qtx) { return qtx->mdpl; } size_t ossl_qtx_get_queue_len_datagrams(OSSL_QTX *qtx) { return qtx->pending_count; } size_t ossl_qtx_get_queue_len_bytes(OSSL_QTX *qtx) { return qtx->pending_bytes; } size_t ossl_qtx_get_cur_dgram_len_bytes(OSSL_QTX *qtx) { return qtx->cons != NULL ? qtx->cons->data_len : 0; } size_t ossl_qtx_get_unflushed_pkt_count(OSSL_QTX *qtx) { return qtx->cons_count; } int ossl_qtx_trigger_key_update(OSSL_QTX *qtx) { return ossl_qrl_enc_level_set_key_update(&qtx->el_set, QUIC_ENC_LEVEL_1RTT); } uint64_t ossl_qtx_get_cur_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el; el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1); if (el == NULL) return UINT64_MAX; return el->op_count; } uint64_t ossl_qtx_get_max_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level) { OSSL_QRL_ENC_LEVEL *el; el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1); if (el == NULL) return UINT64_MAX; return ossl_qrl_get_suite_max_pkt(el->suite_id); } void ossl_qtx_set_msg_callback(OSSL_QTX *qtx, ossl_msg_cb msg_callback, SSL *msg_callback_ssl) { qtx->msg_callback = msg_callback; qtx->msg_callback_ssl = msg_callback_ssl; } void ossl_qtx_set_msg_callback_arg(OSSL_QTX *qtx, void *msg_callback_arg) { qtx->msg_callback_arg = msg_callback_arg; } uint64_t ossl_qtx_get_key_epoch(OSSL_QTX *qtx) { OSSL_QRL_ENC_LEVEL *el; el = ossl_qrl_enc_level_set_get(&qtx->el_set, QUIC_ENC_LEVEL_1RTT, 1); if (el == NULL) return 0; return el->key_epoch; }
./openssl/ssl/quic/quic_lcidm.c
/* * 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 "internal/quic_lcidm.h" #include "internal/quic_types.h" #include "internal/quic_vlint.h" #include "internal/common.h" #include <openssl/lhash.h> #include <openssl/rand.h> #include <openssl/err.h> /* * QUIC Local Connection ID Manager * ================================ */ typedef struct quic_lcidm_conn_st QUIC_LCIDM_CONN; enum { LCID_TYPE_ODCID, /* This LCID is the ODCID from the peer */ LCID_TYPE_INITIAL, /* This is our Initial SCID */ LCID_TYPE_NCID /* This LCID was issued via a NCID frame */ }; typedef struct quic_lcid_st { QUIC_CONN_ID cid; uint64_t seq_num; /* Back-pointer to the owning QUIC_LCIDM_CONN structure. */ QUIC_LCIDM_CONN *conn; /* LCID_TYPE_* */ unsigned int type : 2; } QUIC_LCID; DEFINE_LHASH_OF_EX(QUIC_LCID); DEFINE_LHASH_OF_EX(QUIC_LCIDM_CONN); struct quic_lcidm_conn_st { size_t num_active_lcid; LHASH_OF(QUIC_LCID) *lcids; void *opaque; QUIC_LCID *odcid_lcid_obj; uint64_t next_seq_num; /* Have we enrolled an ODCID? */ unsigned int done_odcid : 1; }; struct quic_lcidm_st { OSSL_LIB_CTX *libctx; LHASH_OF(QUIC_LCID) *lcids; /* (QUIC_CONN_ID) -> (QUIC_LCID *) */ LHASH_OF(QUIC_LCIDM_CONN) *conns; /* (void *opaque) -> (QUIC_LCIDM_CONN *) */ size_t lcid_len; /* Length in bytes for all LCIDs */ #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION QUIC_CONN_ID next_lcid; #endif }; static unsigned long bin_hash(const unsigned char *buf, size_t buf_len) { unsigned long hash = 0; size_t i; for (i = 0; i < buf_len; ++i) hash ^= ((unsigned long)buf[i]) << (8 * (i % sizeof(unsigned long))); return hash; } static unsigned long lcid_hash(const QUIC_LCID *lcid_obj) { return bin_hash(lcid_obj->cid.id, lcid_obj->cid.id_len); } static int lcid_comp(const QUIC_LCID *a, const QUIC_LCID *b) { return !ossl_quic_conn_id_eq(&a->cid, &b->cid); } static unsigned long lcidm_conn_hash(const QUIC_LCIDM_CONN *conn) { return (unsigned long)(uintptr_t)conn->opaque; } static int lcidm_conn_comp(const QUIC_LCIDM_CONN *a, const QUIC_LCIDM_CONN *b) { return a->opaque != b->opaque; } QUIC_LCIDM *ossl_quic_lcidm_new(OSSL_LIB_CTX *libctx, size_t lcid_len) { QUIC_LCIDM *lcidm = NULL; if (lcid_len > QUIC_MAX_CONN_ID_LEN) goto err; if ((lcidm = OPENSSL_zalloc(sizeof(*lcidm))) == NULL) goto err; if ((lcidm->lcids = lh_QUIC_LCID_new(lcid_hash, lcid_comp)) == NULL) goto err; if ((lcidm->conns = lh_QUIC_LCIDM_CONN_new(lcidm_conn_hash, lcidm_conn_comp)) == NULL) goto err; lcidm->libctx = libctx; lcidm->lcid_len = lcid_len; return lcidm; err: if (lcidm != NULL) { lh_QUIC_LCID_free(lcidm->lcids); lh_QUIC_LCIDM_CONN_free(lcidm->conns); OPENSSL_free(lcidm); } return NULL; } static void lcidm_delete_conn(QUIC_LCIDM *lcidm, QUIC_LCIDM_CONN *conn); static void lcidm_delete_conn_(QUIC_LCIDM_CONN *conn, void *arg) { lcidm_delete_conn((QUIC_LCIDM *)arg, conn); } void ossl_quic_lcidm_free(QUIC_LCIDM *lcidm) { if (lcidm == NULL) return; /* * Calling OPENSSL_lh_delete during a doall call is unsafe with our * current LHASH implementation for several reasons: * * - firstly, because deletes can cause the hashtable to be contracted, * resulting in rehashing which might cause items in later buckets to * move to earlier buckets, which might cause doall to skip an item, * resulting in a memory leak; * * - secondly, because doall in general is not safe across hashtable * size changes, as it caches hashtable size and pointer values * while operating. * * The fix for this is to disable hashtable contraction using the following * call, which guarantees that no rehashing will occur so long as we only * call delete and not insert. */ lh_QUIC_LCIDM_CONN_set_down_load(lcidm->conns, 0); lh_QUIC_LCIDM_CONN_doall_arg(lcidm->conns, lcidm_delete_conn_, lcidm); lh_QUIC_LCID_free(lcidm->lcids); lh_QUIC_LCIDM_CONN_free(lcidm->conns); OPENSSL_free(lcidm); } static QUIC_LCID *lcidm_get0_lcid(const QUIC_LCIDM *lcidm, const QUIC_CONN_ID *lcid) { QUIC_LCID key; key.cid = *lcid; if (key.cid.id_len > QUIC_MAX_CONN_ID_LEN) return NULL; return lh_QUIC_LCID_retrieve(lcidm->lcids, &key); } static QUIC_LCIDM_CONN *lcidm_get0_conn(const QUIC_LCIDM *lcidm, void *opaque) { QUIC_LCIDM_CONN key; key.opaque = opaque; return lh_QUIC_LCIDM_CONN_retrieve(lcidm->conns, &key); } static QUIC_LCIDM_CONN *lcidm_upsert_conn(const QUIC_LCIDM *lcidm, void *opaque) { QUIC_LCIDM_CONN *conn = lcidm_get0_conn(lcidm, opaque); if (conn != NULL) return conn; if ((conn = OPENSSL_zalloc(sizeof(*conn))) == NULL) goto err; if ((conn->lcids = lh_QUIC_LCID_new(lcid_hash, lcid_comp)) == NULL) goto err; conn->opaque = opaque; lh_QUIC_LCIDM_CONN_insert(lcidm->conns, conn); if (lh_QUIC_LCIDM_CONN_error(lcidm->conns)) goto err; return conn; err: if (conn != NULL) { lh_QUIC_LCID_free(conn->lcids); OPENSSL_free(conn); } return NULL; } static void lcidm_delete_conn_lcid(QUIC_LCIDM *lcidm, QUIC_LCID *lcid_obj) { lh_QUIC_LCID_delete(lcidm->lcids, lcid_obj); lh_QUIC_LCID_delete(lcid_obj->conn->lcids, lcid_obj); assert(lcid_obj->conn->num_active_lcid > 0); --lcid_obj->conn->num_active_lcid; OPENSSL_free(lcid_obj); } /* doall_arg wrapper */ static void lcidm_delete_conn_lcid_(QUIC_LCID *lcid_obj, void *arg) { lcidm_delete_conn_lcid((QUIC_LCIDM *)arg, lcid_obj); } static void lcidm_delete_conn(QUIC_LCIDM *lcidm, QUIC_LCIDM_CONN *conn) { /* See comment in ossl_quic_lcidm_free */ lh_QUIC_LCID_set_down_load(conn->lcids, 0); lh_QUIC_LCID_doall_arg(conn->lcids, lcidm_delete_conn_lcid_, lcidm); lh_QUIC_LCIDM_CONN_delete(lcidm->conns, conn); lh_QUIC_LCID_free(conn->lcids); OPENSSL_free(conn); } static QUIC_LCID *lcidm_conn_new_lcid(QUIC_LCIDM *lcidm, QUIC_LCIDM_CONN *conn, const QUIC_CONN_ID *lcid) { QUIC_LCID *lcid_obj = NULL; if (lcid->id_len > QUIC_MAX_CONN_ID_LEN) return NULL; if ((lcid_obj = OPENSSL_zalloc(sizeof(*lcid_obj))) == NULL) goto err; lcid_obj->cid = *lcid; lcid_obj->conn = conn; lh_QUIC_LCID_insert(conn->lcids, lcid_obj); if (lh_QUIC_LCID_error(conn->lcids)) goto err; lh_QUIC_LCID_insert(lcidm->lcids, lcid_obj); if (lh_QUIC_LCID_error(lcidm->lcids)) { lh_QUIC_LCID_delete(conn->lcids, lcid_obj); goto err; } ++conn->num_active_lcid; return lcid_obj; err: OPENSSL_free(lcid_obj); return NULL; } size_t ossl_quic_lcidm_get_lcid_len(const QUIC_LCIDM *lcidm) { return lcidm->lcid_len; } size_t ossl_quic_lcidm_get_num_active_lcid(const QUIC_LCIDM *lcidm, void *opaque) { QUIC_LCIDM_CONN *conn; conn = lcidm_get0_conn(lcidm, opaque); if (conn == NULL) return 0; return conn->num_active_lcid; } static int lcidm_generate_cid(QUIC_LCIDM *lcidm, QUIC_CONN_ID *cid) { #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION int i; lcidm->next_lcid.id_len = (unsigned char)lcidm->lcid_len; *cid = lcidm->next_lcid; for (i = lcidm->lcid_len - 1; i >= 0; --i) if (++lcidm->next_lcid.id[i] != 0) break; return 1; #else return ossl_quic_gen_rand_conn_id(lcidm->libctx, lcidm->lcid_len, cid); #endif } static int lcidm_generate(QUIC_LCIDM *lcidm, void *opaque, unsigned int type, QUIC_CONN_ID *lcid_out, uint64_t *seq_num) { QUIC_LCIDM_CONN *conn; QUIC_LCID key, *lcid_obj; size_t i; #define MAX_RETRIES 8 if ((conn = lcidm_upsert_conn(lcidm, opaque)) == NULL) return 0; if ((type == LCID_TYPE_INITIAL && conn->next_seq_num > 0) || conn->next_seq_num > OSSL_QUIC_VLINT_MAX) return 0; i = 0; do { if (i++ >= MAX_RETRIES) /* * Too many retries; should not happen but if it does, don't loop * endlessly. */ return 0; if (!lcidm_generate_cid(lcidm, lcid_out)) return 0; key.cid = *lcid_out; /* If a collision occurs, retry. */ } while (lh_QUIC_LCID_retrieve(lcidm->lcids, &key) != NULL); if ((lcid_obj = lcidm_conn_new_lcid(lcidm, conn, lcid_out)) == NULL) return 0; lcid_obj->seq_num = conn->next_seq_num; lcid_obj->type = type; if (seq_num != NULL) *seq_num = lcid_obj->seq_num; ++conn->next_seq_num; return 1; } int ossl_quic_lcidm_enrol_odcid(QUIC_LCIDM *lcidm, void *opaque, const QUIC_CONN_ID *initial_odcid) { QUIC_LCIDM_CONN *conn; QUIC_LCID key, *lcid_obj; if (initial_odcid == NULL || initial_odcid->id_len < QUIC_MIN_ODCID_LEN || initial_odcid->id_len > QUIC_MAX_CONN_ID_LEN) return 0; if ((conn = lcidm_upsert_conn(lcidm, opaque)) == NULL) return 0; if (conn->done_odcid) return 0; key.cid = *initial_odcid; if (lh_QUIC_LCID_retrieve(lcidm->lcids, &key) != NULL) return 0; if ((lcid_obj = lcidm_conn_new_lcid(lcidm, conn, initial_odcid)) == NULL) return 0; lcid_obj->seq_num = LCIDM_ODCID_SEQ_NUM; lcid_obj->type = LCID_TYPE_ODCID; conn->odcid_lcid_obj = lcid_obj; conn->done_odcid = 1; return 1; } int ossl_quic_lcidm_generate_initial(QUIC_LCIDM *lcidm, void *opaque, QUIC_CONN_ID *initial_lcid) { return lcidm_generate(lcidm, opaque, LCID_TYPE_INITIAL, initial_lcid, NULL); } int ossl_quic_lcidm_generate(QUIC_LCIDM *lcidm, void *opaque, OSSL_QUIC_FRAME_NEW_CONN_ID *ncid_frame) { ncid_frame->seq_num = 0; ncid_frame->retire_prior_to = 0; return lcidm_generate(lcidm, opaque, LCID_TYPE_NCID, &ncid_frame->conn_id, &ncid_frame->seq_num); } int ossl_quic_lcidm_retire_odcid(QUIC_LCIDM *lcidm, void *opaque) { QUIC_LCIDM_CONN *conn; if ((conn = lcidm_upsert_conn(lcidm, opaque)) == NULL) return 0; if (conn->odcid_lcid_obj == NULL) return 0; lcidm_delete_conn_lcid(lcidm, conn->odcid_lcid_obj); conn->odcid_lcid_obj = NULL; return 1; } struct retire_args { QUIC_LCID *earliest_seq_num_lcid_obj; uint64_t earliest_seq_num, retire_prior_to; }; static void retire_for_conn(QUIC_LCID *lcid_obj, void *arg) { struct retire_args *args = arg; /* ODCID LCID cannot be retired via this API */ if (lcid_obj->type == LCID_TYPE_ODCID || lcid_obj->seq_num >= args->retire_prior_to) return; if (lcid_obj->seq_num < args->earliest_seq_num) { args->earliest_seq_num = lcid_obj->seq_num; args->earliest_seq_num_lcid_obj = lcid_obj; } } int ossl_quic_lcidm_retire(QUIC_LCIDM *lcidm, void *opaque, uint64_t retire_prior_to, const QUIC_CONN_ID *containing_pkt_dcid, QUIC_CONN_ID *retired_lcid, uint64_t *retired_seq_num, int *did_retire) { QUIC_LCIDM_CONN key, *conn; struct retire_args args = {0}; key.opaque = opaque; if (did_retire == NULL) return 0; *did_retire = 0; if ((conn = lh_QUIC_LCIDM_CONN_retrieve(lcidm->conns, &key)) == NULL) return 1; args.retire_prior_to = retire_prior_to; args.earliest_seq_num = UINT64_MAX; lh_QUIC_LCID_doall_arg(conn->lcids, retire_for_conn, &args); if (args.earliest_seq_num_lcid_obj == NULL) return 1; if (containing_pkt_dcid != NULL && ossl_quic_conn_id_eq(&args.earliest_seq_num_lcid_obj->cid, containing_pkt_dcid)) return 0; *did_retire = 1; if (retired_lcid != NULL) *retired_lcid = args.earliest_seq_num_lcid_obj->cid; if (retired_seq_num != NULL) *retired_seq_num = args.earliest_seq_num_lcid_obj->seq_num; lcidm_delete_conn_lcid(lcidm, args.earliest_seq_num_lcid_obj); return 1; } int ossl_quic_lcidm_cull(QUIC_LCIDM *lcidm, void *opaque) { QUIC_LCIDM_CONN key, *conn; key.opaque = opaque; if ((conn = lh_QUIC_LCIDM_CONN_retrieve(lcidm->conns, &key)) == NULL) return 0; lcidm_delete_conn(lcidm, conn); return 1; } int ossl_quic_lcidm_lookup(QUIC_LCIDM *lcidm, const QUIC_CONN_ID *lcid, uint64_t *seq_num, void **opaque) { QUIC_LCID *lcid_obj; if (lcid == NULL) return 0; if ((lcid_obj = lcidm_get0_lcid(lcidm, lcid)) == NULL) return 0; if (seq_num != NULL) *seq_num = lcid_obj->seq_num; if (opaque != NULL) *opaque = lcid_obj->conn->opaque; return 1; } int ossl_quic_lcidm_debug_remove(QUIC_LCIDM *lcidm, const QUIC_CONN_ID *lcid) { QUIC_LCID key, *lcid_obj; key.cid = *lcid; if ((lcid_obj = lh_QUIC_LCID_retrieve(lcidm->lcids, &key)) == NULL) return 0; lcidm_delete_conn_lcid(lcidm, lcid_obj); return 1; } int ossl_quic_lcidm_debug_add(QUIC_LCIDM *lcidm, void *opaque, const QUIC_CONN_ID *lcid, uint64_t seq_num) { QUIC_LCIDM_CONN *conn; QUIC_LCID key, *lcid_obj; if (lcid == NULL || lcid->id_len > QUIC_MAX_CONN_ID_LEN) return 0; if ((conn = lcidm_upsert_conn(lcidm, opaque)) == NULL) return 0; key.cid = *lcid; if (lh_QUIC_LCID_retrieve(lcidm->lcids, &key) != NULL) return 0; if ((lcid_obj = lcidm_conn_new_lcid(lcidm, conn, lcid)) == NULL) return 0; lcid_obj->seq_num = seq_num; lcid_obj->type = LCID_TYPE_NCID; return 1; }
./openssl/ssl/quic/quic_reactor.c
/* * 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 "internal/quic_reactor.h" #include "internal/common.h" #include "internal/thread_arch.h" /* * Core I/O Reactor Framework * ========================== */ 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) { rtor->poll_r.type = BIO_POLL_DESCRIPTOR_TYPE_NONE; rtor->poll_w.type = BIO_POLL_DESCRIPTOR_TYPE_NONE; rtor->net_read_desired = 0; rtor->net_write_desired = 0; rtor->can_poll_r = 0; rtor->can_poll_w = 0; rtor->tick_deadline = initial_tick_deadline; rtor->tick_cb = tick_cb; rtor->tick_cb_arg = tick_cb_arg; } void ossl_quic_reactor_set_poll_r(QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *r) { if (r == NULL) rtor->poll_r.type = BIO_POLL_DESCRIPTOR_TYPE_NONE; else rtor->poll_r = *r; rtor->can_poll_r = ossl_quic_reactor_can_support_poll_descriptor(rtor, &rtor->poll_r); } void ossl_quic_reactor_set_poll_w(QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *w) { if (w == NULL) rtor->poll_w.type = BIO_POLL_DESCRIPTOR_TYPE_NONE; else rtor->poll_w = *w; rtor->can_poll_w = ossl_quic_reactor_can_support_poll_descriptor(rtor, &rtor->poll_w); } const BIO_POLL_DESCRIPTOR *ossl_quic_reactor_get_poll_r(const QUIC_REACTOR *rtor) { return &rtor->poll_r; } const BIO_POLL_DESCRIPTOR *ossl_quic_reactor_get_poll_w(const QUIC_REACTOR *rtor) { return &rtor->poll_w; } int ossl_quic_reactor_can_support_poll_descriptor(const QUIC_REACTOR *rtor, const BIO_POLL_DESCRIPTOR *d) { return d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD; } int ossl_quic_reactor_can_poll_r(const QUIC_REACTOR *rtor) { return rtor->can_poll_r; } int ossl_quic_reactor_can_poll_w(const QUIC_REACTOR *rtor) { return rtor->can_poll_w; } int ossl_quic_reactor_net_read_desired(QUIC_REACTOR *rtor) { return rtor->net_read_desired; } int ossl_quic_reactor_net_write_desired(QUIC_REACTOR *rtor) { return rtor->net_write_desired; } OSSL_TIME ossl_quic_reactor_get_tick_deadline(QUIC_REACTOR *rtor) { return rtor->tick_deadline; } int ossl_quic_reactor_tick(QUIC_REACTOR *rtor, uint32_t flags) { QUIC_TICK_RESULT res = {0}; /* * Note that the tick callback cannot fail; this is intentional. Arguably it * does not make that much sense for ticking to 'fail' (in the sense of an * explicit error indicated to the user) because ticking is by its nature * best effort. If something fatal happens with a connection we can report * it on the next actual application I/O call. */ rtor->tick_cb(&res, rtor->tick_cb_arg, flags); rtor->net_read_desired = res.net_read_desired; rtor->net_write_desired = res.net_write_desired; rtor->tick_deadline = res.tick_deadline; return 1; } /* * Blocking I/O Adaptation Layer * ============================= */ /* * Utility which can be used to poll on up to two FDs. This is designed to * support use of split FDs (e.g. with SSL_set_rfd and SSL_set_wfd where * different FDs are used for read and write). * * Generally use of poll(2) is preferred where available. Windows, however, * hasn't traditionally offered poll(2), only select(2). WSAPoll() was * introduced in Vista but has seemingly been buggy until relatively recent * versions of Windows 10. Moreover we support XP so this is not a suitable * target anyway. However, the traditional issues with select(2) turn out not to * be an issue on Windows; whereas traditional *NIX select(2) uses a bitmap of * FDs (and thus is limited in the magnitude of the FDs expressible), Windows * select(2) is very different. In Windows, socket handles are not allocated * contiguously from zero and thus this bitmap approach was infeasible. Thus in * adapting the Berkeley sockets API to Windows a different approach was taken * whereby the fd_set contains a fixed length array of socket handles and an * integer indicating how many entries are valid; thus Windows select() * ironically is actually much more like *NIX poll(2) than *NIX select(2). In * any case, this means that the relevant limit for Windows select() is the * number of FDs being polled, not the magnitude of those FDs. Since we only * poll for two FDs here, this limit does not concern us. * * Usage: rfd and wfd may be the same or different. Either or both may also be * -1. If rfd_want_read is 1, rfd is polled for readability, and if * wfd_want_write is 1, wfd is polled for writability. Note that since any * passed FD is always polled for error conditions, setting rfd_want_read=0 and * wfd_want_write=0 is not the same as passing -1 for both FDs. * * deadline is a timestamp to return at. If it is ossl_time_infinite(), the call * never times out. * * Returns 0 on error and 1 on success. Timeout expiry is considered a success * condition. We don't elaborate our return values here because the way we are * actually using this doesn't currently care. * * If mutex is non-NULL, it is assumed to be held for write and is unlocked for * the duration of the call. * * 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) */ static int poll_two_fds(int rfd, int rfd_want_read, int wfd, int wfd_want_write, OSSL_TIME deadline, CRYPTO_MUTEX *mutex) { #if defined(OPENSSL_SYS_WINDOWS) || !defined(POLLIN) fd_set rfd_set, wfd_set, efd_set; OSSL_TIME now, timeout; struct timeval tv, *ptv; int maxfd, pres; # ifndef OPENSSL_SYS_WINDOWS /* * On Windows there is no relevant limit to the magnitude of a fd value (see * above). On *NIX the fd_set uses a bitmap and we must check the limit. */ if (rfd >= FD_SETSIZE || wfd >= FD_SETSIZE) return 0; # endif FD_ZERO(&rfd_set); FD_ZERO(&wfd_set); FD_ZERO(&efd_set); if (rfd != -1 && rfd_want_read) openssl_fdset(rfd, &rfd_set); if (wfd != -1 && wfd_want_write) openssl_fdset(wfd, &wfd_set); /* Always check for error conditions. */ if (rfd != -1) openssl_fdset(rfd, &efd_set); if (wfd != -1) openssl_fdset(wfd, &efd_set); maxfd = rfd; if (wfd > maxfd) maxfd = wfd; if (!ossl_assert(rfd != -1 || wfd != -1 || !ossl_time_is_infinite(deadline))) /* Do not block forever; should not happen. */ return 0; # if defined(OPENSSL_THREADS) if (mutex != NULL) ossl_crypto_mutex_unlock(mutex); # endif do { /* * select expects a timeout, not a deadline, so do the conversion. * Update for each call to ensure the correct value is used if we repeat * due to EINTR. */ if (ossl_time_is_infinite(deadline)) { ptv = NULL; } else { now = ossl_time_now(); /* * ossl_time_subtract saturates to zero so we don't need to check if * now > deadline. */ timeout = ossl_time_subtract(deadline, now); tv = ossl_time_to_timeval(timeout); ptv = &tv; } pres = select(maxfd + 1, &rfd_set, &wfd_set, &efd_set, ptv); } while (pres == -1 && get_last_socket_error_is_eintr()); # if defined(OPENSSL_THREADS) if (mutex != NULL) ossl_crypto_mutex_lock(mutex); # endif return pres < 0 ? 0 : 1; #else int pres, timeout_ms; OSSL_TIME now, timeout; struct pollfd pfds[2] = {0}; size_t npfd = 0; if (rfd == wfd) { pfds[npfd].fd = rfd; pfds[npfd].events = (rfd_want_read ? POLLIN : 0) | (wfd_want_write ? POLLOUT : 0); if (rfd >= 0 && pfds[npfd].events != 0) ++npfd; } else { pfds[npfd].fd = rfd; pfds[npfd].events = (rfd_want_read ? POLLIN : 0); if (rfd >= 0 && pfds[npfd].events != 0) ++npfd; pfds[npfd].fd = wfd; pfds[npfd].events = (wfd_want_write ? POLLOUT : 0); if (wfd >= 0 && pfds[npfd].events != 0) ++npfd; } if (!ossl_assert(npfd != 0 || !ossl_time_is_infinite(deadline))) /* Do not block forever; should not happen. */ return 0; # if defined(OPENSSL_THREADS) if (mutex != NULL) ossl_crypto_mutex_unlock(mutex); # endif do { if (ossl_time_is_infinite(deadline)) { timeout_ms = -1; } else { now = ossl_time_now(); timeout = ossl_time_subtract(deadline, now); timeout_ms = ossl_time2ms(timeout); } pres = poll(pfds, npfd, timeout_ms); } while (pres == -1 && get_last_socket_error_is_eintr()); # if defined(OPENSSL_THREADS) if (mutex != NULL) ossl_crypto_mutex_lock(mutex); # endif return pres < 0 ? 0 : 1; #endif } static int poll_descriptor_to_fd(const BIO_POLL_DESCRIPTOR *d, int *fd) { if (d == NULL || d->type == BIO_POLL_DESCRIPTOR_TYPE_NONE) { *fd = INVALID_SOCKET; return 1; } if (d->type != BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD || d->value.fd == INVALID_SOCKET) return 0; *fd = d->value.fd; return 1; } /* * Poll up to two abstract poll descriptors. Currently we only support * poll descriptors which represent FDs. * * If mutex is non-NULL, it is assumed be a lock currently held for write and is * unlocked for the duration of any wait. * * 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) */ static int poll_two_descriptors(const BIO_POLL_DESCRIPTOR *r, int r_want_read, const BIO_POLL_DESCRIPTOR *w, int w_want_write, OSSL_TIME deadline, CRYPTO_MUTEX *mutex) { int rfd, wfd; if (!poll_descriptor_to_fd(r, &rfd) || !poll_descriptor_to_fd(w, &wfd)) return 0; return poll_two_fds(rfd, r_want_read, wfd, w_want_write, deadline, mutex); } /* * Block until a predicate function evaluates to true. * * If mutex is non-NULL, it is assumed be a lock currently held for write and is * unlocked for the duration of any wait. * * Precondition: Must hold channel write lock (unchecked) * 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) */ int ossl_quic_reactor_block_until_pred(QUIC_REACTOR *rtor, int (*pred)(void *arg), void *pred_arg, uint32_t flags, CRYPTO_MUTEX *mutex) { int res; for (;;) { if ((flags & SKIP_FIRST_TICK) != 0) flags &= ~SKIP_FIRST_TICK; else /* best effort */ ossl_quic_reactor_tick(rtor, 0); if ((res = pred(pred_arg)) != 0) return res; if (!poll_two_descriptors(ossl_quic_reactor_get_poll_r(rtor), ossl_quic_reactor_net_read_desired(rtor), ossl_quic_reactor_get_poll_w(rtor), ossl_quic_reactor_net_write_desired(rtor), ossl_quic_reactor_get_tick_deadline(rtor), mutex)) /* * We don't actually care why the call succeeded (timeout, FD * readiness), we just call reactor_tick and start trying to do I/O * things again. If poll_two_fds returns 0, this is some other * non-timeout failure and we should stop here. * * TODO(QUIC FUTURE): In the future we could avoid unnecessary * syscalls by not retrying network I/O that isn't ready based * on the result of the poll call. However this might be difficult * because it requires we do the call to poll(2) or equivalent * syscall ourselves, whereas in the general case the application * does the polling and just calls SSL_handle_events(). * Implementing this optimisation in the future will probably * therefore require API changes. */ return 0; } }
./openssl/ssl/quic/quic_sstream.c
/* * 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 "internal/quic_stream.h" #include "internal/uint_set.h" #include "internal/common.h" #include "internal/ring_buf.h" /* * ================================================================== * QUIC Send Stream */ struct quic_sstream_st { struct ring_buf ring_buf; /* * Any logical byte in the stream is in one of these states: * * - NEW: The byte has not yet been transmitted, or has been lost and is * in need of retransmission. * * - IN_FLIGHT: The byte has been transmitted but is awaiting * acknowledgement. We continue to store the data in case we return * to the NEW state. * * - ACKED: The byte has been acknowledged and we can cease storing it. * We do not necessarily cull it immediately, so there may be a delay * between reaching the ACKED state and the buffer space actually being * recycled. * * A logical byte in the stream is * * - in the NEW state if it is in new_set; * - is in the ACKED state if it is in acked_set * (and may or may not have been culled); * - is in the IN_FLIGHT state otherwise. * * Invariant: No logical byte is ever in both new_set and acked_set. */ UINT_SET new_set, acked_set; /* * The current size of the stream is ring_buf.head_offset. If * have_final_size is true, this is also the final size of the stream. */ unsigned int have_final_size : 1; unsigned int sent_final_size : 1; unsigned int acked_final_size : 1; unsigned int cleanse : 1; }; static void qss_cull(QUIC_SSTREAM *qss); QUIC_SSTREAM *ossl_quic_sstream_new(size_t init_buf_size) { QUIC_SSTREAM *qss; qss = OPENSSL_zalloc(sizeof(QUIC_SSTREAM)); if (qss == NULL) return NULL; ring_buf_init(&qss->ring_buf); if (!ring_buf_resize(&qss->ring_buf, init_buf_size, 0)) { ring_buf_destroy(&qss->ring_buf, 0); OPENSSL_free(qss); return NULL; } ossl_uint_set_init(&qss->new_set); ossl_uint_set_init(&qss->acked_set); return qss; } void ossl_quic_sstream_free(QUIC_SSTREAM *qss) { if (qss == NULL) return; ossl_uint_set_destroy(&qss->new_set); ossl_uint_set_destroy(&qss->acked_set); ring_buf_destroy(&qss->ring_buf, qss->cleanse); OPENSSL_free(qss); } 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) { size_t num_iov_ = 0, src_len = 0, total_len = 0, i; uint64_t max_len; const unsigned char *src = NULL; UINT_SET_ITEM *range = ossl_list_uint_set_head(&qss->new_set); if (*num_iov < 2) return 0; for (i = 0; i < skip && range != NULL; ++i) range = ossl_list_uint_set_next(range); if (range == NULL) { if (i < skip) /* Don't return FIN for infinitely increasing skip */ return 0; /* No new bytes to send, but we might have a FIN */ if (!qss->have_final_size || qss->sent_final_size) return 0; hdr->offset = qss->ring_buf.head_offset; hdr->len = 0; hdr->is_fin = 1; *num_iov = 0; return 1; } /* * We can only send a contiguous range of logical bytes in a single * stream frame, so limit ourselves to the range of the first set entry. * * Set entries never have 'adjacent' entries so we don't have to worry * about them here. */ max_len = range->range.end - range->range.start + 1; for (i = 0;; ++i) { if (total_len >= max_len) break; if (!ring_buf_get_buf_at(&qss->ring_buf, range->range.start + total_len, &src, &src_len)) return 0; if (src_len == 0) break; assert(i < 2); if (total_len + src_len > max_len) src_len = (size_t)(max_len - total_len); iov[num_iov_].buf = src; iov[num_iov_].buf_len = src_len; total_len += src_len; ++num_iov_; } hdr->offset = range->range.start; hdr->len = total_len; hdr->is_fin = qss->have_final_size && hdr->offset + hdr->len == qss->ring_buf.head_offset; *num_iov = num_iov_; return 1; } int ossl_quic_sstream_has_pending(QUIC_SSTREAM *qss) { OSSL_QUIC_FRAME_STREAM shdr; OSSL_QTX_IOVEC iov[2]; size_t num_iov = OSSL_NELEM(iov); return ossl_quic_sstream_get_stream_frame(qss, 0, &shdr, iov, &num_iov); } uint64_t ossl_quic_sstream_get_cur_size(QUIC_SSTREAM *qss) { return qss->ring_buf.head_offset; } int ossl_quic_sstream_mark_transmitted(QUIC_SSTREAM *qss, uint64_t start, uint64_t end) { UINT_RANGE r; r.start = start; r.end = end; if (!ossl_uint_set_remove(&qss->new_set, &r)) return 0; return 1; } int ossl_quic_sstream_mark_transmitted_fin(QUIC_SSTREAM *qss, uint64_t final_size) { /* * We do not really need final_size since we already know the size of the * stream, but this serves as a sanity check. */ if (!qss->have_final_size || final_size != qss->ring_buf.head_offset) return 0; qss->sent_final_size = 1; return 1; } int ossl_quic_sstream_mark_lost(QUIC_SSTREAM *qss, uint64_t start, uint64_t end) { UINT_RANGE r; r.start = start; r.end = end; /* * We lost a range of stream data bytes, so reinsert them into the new set, * so that they are returned once more by ossl_quic_sstream_get_stream_frame. */ if (!ossl_uint_set_insert(&qss->new_set, &r)) return 0; return 1; } int ossl_quic_sstream_mark_lost_fin(QUIC_SSTREAM *qss) { if (qss->acked_final_size) /* Does not make sense to lose a FIN after it has been ACKed */ return 0; /* FIN was lost, so we need to transmit it again. */ qss->sent_final_size = 0; return 1; } int ossl_quic_sstream_mark_acked(QUIC_SSTREAM *qss, uint64_t start, uint64_t end) { UINT_RANGE r; r.start = start; r.end = end; if (!ossl_uint_set_insert(&qss->acked_set, &r)) return 0; qss_cull(qss); return 1; } int ossl_quic_sstream_mark_acked_fin(QUIC_SSTREAM *qss) { if (!qss->have_final_size) /* Cannot ack final size before we have a final size */ return 0; qss->acked_final_size = 1; return 1; } void ossl_quic_sstream_fin(QUIC_SSTREAM *qss) { if (qss->have_final_size) return; qss->have_final_size = 1; } int ossl_quic_sstream_get_final_size(QUIC_SSTREAM *qss, uint64_t *final_size) { if (!qss->have_final_size) return 0; if (final_size != NULL) *final_size = qss->ring_buf.head_offset; return 1; } int ossl_quic_sstream_append(QUIC_SSTREAM *qss, const unsigned char *buf, size_t buf_len, size_t *consumed) { size_t l, consumed_ = 0; UINT_RANGE r; struct ring_buf old_ring_buf = qss->ring_buf; if (qss->have_final_size) { *consumed = 0; return 0; } /* * Note: It is assumed that ossl_quic_sstream_append will be called during a * call to e.g. SSL_write and this function is therefore designed to support * such semantics. In particular, the buffer pointed to by buf is only * assumed to be valid for the duration of this call, therefore we must copy * the data here. We will later copy-and-encrypt the data during packet * encryption, so this is a two-copy design. Supporting a one-copy design in * the future will require applications to use a different kind of API. * Supporting such changes in future will require corresponding enhancements * to this code. */ while (buf_len > 0) { l = ring_buf_push(&qss->ring_buf, buf, buf_len); if (l == 0) break; buf += l; buf_len -= l; consumed_ += l; } if (consumed_ > 0) { r.start = old_ring_buf.head_offset; r.end = r.start + consumed_ - 1; assert(r.end + 1 == qss->ring_buf.head_offset); if (!ossl_uint_set_insert(&qss->new_set, &r)) { qss->ring_buf = old_ring_buf; *consumed = 0; return 0; } } *consumed = consumed_; return 1; } static void qss_cull(QUIC_SSTREAM *qss) { UINT_SET_ITEM *h = ossl_list_uint_set_head(&qss->acked_set); /* * Potentially cull data from our ring buffer. This can happen once data has * been ACKed and we know we are never going to have to transmit it again. * * Since we use a ring buffer design for simplicity, we cannot cull byte n + * k (for k > 0) from the ring buffer until byte n has also been culled. * This means if parts of the stream get acknowledged out of order we might * keep around some data we technically don't need to for a while. The * impact of this is likely to be small and limited to quite a short * duration, and doesn't justify the use of a more complex design. */ /* * We only need to check the first range entry in the integer set because we * can only cull contiguous areas at the start of the ring buffer anyway. */ if (h != NULL) ring_buf_cpop_range(&qss->ring_buf, h->range.start, h->range.end, qss->cleanse); } int ossl_quic_sstream_set_buffer_size(QUIC_SSTREAM *qss, size_t num_bytes) { return ring_buf_resize(&qss->ring_buf, num_bytes, qss->cleanse); } size_t ossl_quic_sstream_get_buffer_size(QUIC_SSTREAM *qss) { return qss->ring_buf.alloc; } size_t ossl_quic_sstream_get_buffer_used(QUIC_SSTREAM *qss) { return ring_buf_used(&qss->ring_buf); } size_t ossl_quic_sstream_get_buffer_avail(QUIC_SSTREAM *qss) { return ring_buf_avail(&qss->ring_buf); } int ossl_quic_sstream_is_totally_acked(QUIC_SSTREAM *qss) { UINT_RANGE r; uint64_t cur_size; if (qss->have_final_size && !qss->acked_final_size) return 0; if (ossl_quic_sstream_get_cur_size(qss) == 0) return 1; if (ossl_list_uint_set_num(&qss->acked_set) != 1) return 0; r = ossl_list_uint_set_head(&qss->acked_set)->range; cur_size = qss->ring_buf.head_offset; /* * The invariants of UINT_SET guarantee a single list element if we have a * single contiguous range, which is what we should have if everything has * been acked. */ assert(r.end + 1 <= cur_size); return r.start == 0 && r.end + 1 == cur_size; } void ossl_quic_sstream_adjust_iov(size_t len, OSSL_QTX_IOVEC *iov, size_t num_iov) { size_t running = 0, i, iovlen; for (i = 0, running = 0; i < num_iov; ++i) { iovlen = iov[i].buf_len; if (running >= len) iov[i].buf_len = 0; else if (running + iovlen > len) iov[i].buf_len = len - running; running += iovlen; } } void ossl_quic_sstream_set_cleanse(QUIC_SSTREAM *qss, int cleanse) { qss->cleanse = cleanse; }
./openssl/ssl/quic/quic_thread_assist.c
/* * 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 <openssl/macros.h> #include "quic_local.h" #include "internal/time.h" #include "internal/thread.h" #include "internal/thread_arch.h" #include "internal/quic_thread_assist.h" #if !defined(OPENSSL_NO_QUIC_THREAD_ASSIST) /* Main loop for the QUIC assist thread. */ static unsigned int assist_thread_main(void *arg) { QUIC_THREAD_ASSIST *qta = arg; CRYPTO_MUTEX *m = ossl_quic_channel_get_mutex(qta->ch); QUIC_REACTOR *rtor; ossl_crypto_mutex_lock(m); rtor = ossl_quic_channel_get_reactor(qta->ch); for (;;) { OSSL_TIME deadline; if (qta->teardown) break; deadline = ossl_quic_reactor_get_tick_deadline(rtor); if (qta->now_cb != NULL && !ossl_time_is_zero(deadline) && !ossl_time_is_infinite(deadline)) { /* * ossl_crypto_condvar_wait_timeout needs to use real time for the * deadline */ deadline = ossl_time_add(ossl_time_subtract(deadline, qta->now_cb(qta->now_cb_arg)), ossl_time_now()); } ossl_crypto_condvar_wait_timeout(qta->cv, m, deadline); /* * We have now been woken up. This can be for one of the following * reasons: * * - We have been asked to teardown (qta->teardown is set); * - The tick deadline has passed. * - The tick deadline has changed. * * For robustness, this loop also handles spurious wakeups correctly * (which does not require any extra code). */ if (qta->teardown) break; ossl_quic_reactor_tick(rtor, QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY); } ossl_crypto_mutex_unlock(m); return 1; } int ossl_quic_thread_assist_init_start(QUIC_THREAD_ASSIST *qta, QUIC_CHANNEL *ch, OSSL_TIME (*now_cb)(void *arg), void *now_cb_arg) { CRYPTO_MUTEX *mutex = ossl_quic_channel_get_mutex(ch); if (mutex == NULL) return 0; qta->ch = ch; qta->teardown = 0; qta->joined = 0; qta->now_cb = now_cb; qta->now_cb_arg = now_cb_arg; qta->cv = ossl_crypto_condvar_new(); if (qta->cv == NULL) return 0; qta->t = ossl_crypto_thread_native_start(assist_thread_main, qta, /*joinable=*/1); if (qta->t == NULL) { ossl_crypto_condvar_free(qta->cv); return 0; } return 1; } int ossl_quic_thread_assist_stop_async(QUIC_THREAD_ASSIST *qta) { if (!qta->teardown) { qta->teardown = 1; ossl_crypto_condvar_signal(qta->cv); } return 1; } int ossl_quic_thread_assist_wait_stopped(QUIC_THREAD_ASSIST *qta) { CRYPTO_THREAD_RETVAL rv; CRYPTO_MUTEX *m = ossl_quic_channel_get_mutex(qta->ch); if (qta->joined) return 1; if (!ossl_quic_thread_assist_stop_async(qta)) return 0; ossl_crypto_mutex_unlock(m); if (!ossl_crypto_thread_native_join(qta->t, &rv)) { ossl_crypto_mutex_lock(m); return 0; } qta->joined = 1; ossl_crypto_mutex_lock(m); return 1; } int ossl_quic_thread_assist_cleanup(QUIC_THREAD_ASSIST *qta) { if (!ossl_assert(qta->joined)) return 0; ossl_crypto_condvar_free(&qta->cv); ossl_crypto_thread_native_clean(qta->t); qta->ch = NULL; qta->t = NULL; return 1; } int ossl_quic_thread_assist_notify_deadline_changed(QUIC_THREAD_ASSIST *qta) { if (qta->teardown) return 0; ossl_crypto_condvar_signal(qta->cv); return 1; } #endif
./openssl/os-dep/haiku.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 */ #include <sys/select.h> #include <sys/time.h>
./openssl/crypto/sparse_array.c
/* * Copyright 2019-2022 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 */ #include <openssl/crypto.h> #include <openssl/bn.h> #include "crypto/sparse_array.h" /* * How many bits are used to index each level in the tree structure? * This setting determines the number of pointers stored in each node of the * tree used to represent the sparse array. Having more pointers reduces the * depth of the tree but potentially wastes more memory. That is, this is a * direct space versus time tradeoff. * * The default is to use four bits which means that the are 16 * pointers in each tree node. * * The library builder is also permitted to define other sizes in the closed * interval [2, sizeof(ossl_uintmax_t) * 8]. Space use generally scales * exponentially with the block size, although the implementation only * creates enough blocks to support the largest used index. The depth is: * ceil(log_2(largest index) / 2^{block size}) * E.g. with a block size of 4, and a largest index of 1000, the depth * will be three. */ #ifndef OPENSSL_SA_BLOCK_BITS # define OPENSSL_SA_BLOCK_BITS 4 #elif OPENSSL_SA_BLOCK_BITS < 2 || OPENSSL_SA_BLOCK_BITS > (BN_BITS2 - 1) # error OPENSSL_SA_BLOCK_BITS is out of range #endif /* * From the number of bits, work out: * the number of pointers in a tree node; * a bit mask to quickly extract an index and * the maximum depth of the tree structure. */ #define SA_BLOCK_MAX (1 << OPENSSL_SA_BLOCK_BITS) #define SA_BLOCK_MASK (SA_BLOCK_MAX - 1) #define SA_BLOCK_MAX_LEVELS (((int)sizeof(ossl_uintmax_t) * 8 \ + OPENSSL_SA_BLOCK_BITS - 1) \ / OPENSSL_SA_BLOCK_BITS) struct sparse_array_st { int levels; ossl_uintmax_t top; size_t nelem; void **nodes; }; OPENSSL_SA *ossl_sa_new(void) { OPENSSL_SA *res = OPENSSL_zalloc(sizeof(*res)); return res; } static void sa_doall(const OPENSSL_SA *sa, void (*node)(void **), void (*leaf)(ossl_uintmax_t, void *, void *), void *arg) { int i[SA_BLOCK_MAX_LEVELS]; void *nodes[SA_BLOCK_MAX_LEVELS]; ossl_uintmax_t idx = 0; int l = 0; i[0] = 0; nodes[0] = sa->nodes; while (l >= 0) { const int n = i[l]; void ** const p = nodes[l]; if (n >= SA_BLOCK_MAX) { if (p != NULL && node != NULL) (*node)(p); l--; idx >>= OPENSSL_SA_BLOCK_BITS; } else { i[l] = n + 1; if (p != NULL && p[n] != NULL) { idx = (idx & ~SA_BLOCK_MASK) | n; if (l < sa->levels - 1) { i[++l] = 0; nodes[l] = p[n]; idx <<= OPENSSL_SA_BLOCK_BITS; } else if (leaf != NULL) { (*leaf)(idx, p[n], arg); } } } } } static void sa_free_node(void **p) { OPENSSL_free(p); } static void sa_free_leaf(ossl_uintmax_t n, void *p, void *arg) { OPENSSL_free(p); } void ossl_sa_free(OPENSSL_SA *sa) { if (sa != NULL) { sa_doall(sa, &sa_free_node, NULL, NULL); OPENSSL_free(sa); } } void ossl_sa_free_leaves(OPENSSL_SA *sa) { sa_doall(sa, &sa_free_node, &sa_free_leaf, NULL); OPENSSL_free(sa); } /* Wrap this in a structure to avoid compiler warnings */ struct trampoline_st { void (*func)(ossl_uintmax_t, void *); }; static void trampoline(ossl_uintmax_t n, void *l, void *arg) { ((const struct trampoline_st *)arg)->func(n, l); } void ossl_sa_doall(const OPENSSL_SA *sa, void (*leaf)(ossl_uintmax_t, void *)) { struct trampoline_st tramp; tramp.func = leaf; if (sa != NULL) sa_doall(sa, NULL, &trampoline, &tramp); } void ossl_sa_doall_arg(const OPENSSL_SA *sa, void (*leaf)(ossl_uintmax_t, void *, void *), void *arg) { if (sa != NULL) sa_doall(sa, NULL, leaf, arg); } size_t ossl_sa_num(const OPENSSL_SA *sa) { return sa == NULL ? 0 : sa->nelem; } void *ossl_sa_get(const OPENSSL_SA *sa, ossl_uintmax_t n) { int level; void **p, *r = NULL; if (sa == NULL || sa->nelem == 0) return NULL; if (n <= sa->top) { p = sa->nodes; for (level = sa->levels - 1; p != NULL && level > 0; level--) p = (void **)p[(n >> (OPENSSL_SA_BLOCK_BITS * level)) & SA_BLOCK_MASK]; r = p == NULL ? NULL : p[n & SA_BLOCK_MASK]; } return r; } static ossl_inline void **alloc_node(void) { return OPENSSL_zalloc(SA_BLOCK_MAX * sizeof(void *)); } int ossl_sa_set(OPENSSL_SA *sa, ossl_uintmax_t posn, void *val) { int i, level = 1; ossl_uintmax_t n = posn; void **p; if (sa == NULL) return 0; for (level = 1; level < SA_BLOCK_MAX_LEVELS; level++) if ((n >>= OPENSSL_SA_BLOCK_BITS) == 0) break; for (;sa->levels < level; sa->levels++) { p = alloc_node(); if (p == NULL) return 0; p[0] = sa->nodes; sa->nodes = p; } if (sa->top < posn) sa->top = posn; p = sa->nodes; for (level = sa->levels - 1; level > 0; level--) { i = (posn >> (OPENSSL_SA_BLOCK_BITS * level)) & SA_BLOCK_MASK; if (p[i] == NULL && (p[i] = alloc_node()) == NULL) return 0; p = p[i]; } p += posn & SA_BLOCK_MASK; if (val == NULL && *p != NULL) sa->nelem--; else if (val != NULL && *p == NULL) sa->nelem++; *p = val; return 1; }
./openssl/crypto/self_test_core.c
/* * 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 */ #include <openssl/self_test.h> #include <openssl/core_names.h> #include <openssl/params.h> #include "internal/cryptlib.h" #include "crypto/context.h" typedef struct self_test_cb_st { OSSL_CALLBACK *cb; void *cbarg; } SELF_TEST_CB; struct ossl_self_test_st { /* local state variables */ const char *phase; const char *type; const char *desc; OSSL_CALLBACK *cb; /* callback related variables used to pass the state back to the user */ OSSL_PARAM params[4]; void *cb_arg; }; #ifndef FIPS_MODULE void *ossl_self_test_set_callback_new(OSSL_LIB_CTX *ctx) { SELF_TEST_CB *stcb; stcb = OPENSSL_zalloc(sizeof(*stcb)); return stcb; } void ossl_self_test_set_callback_free(void *stcb) { OPENSSL_free(stcb); } static SELF_TEST_CB *get_self_test_callback(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_SELF_TEST_CB_INDEX); } void OSSL_SELF_TEST_set_callback(OSSL_LIB_CTX *libctx, OSSL_CALLBACK *cb, void *cbarg) { SELF_TEST_CB *stcb = get_self_test_callback(libctx); if (stcb != NULL) { stcb->cb = cb; stcb->cbarg = cbarg; } } void OSSL_SELF_TEST_get_callback(OSSL_LIB_CTX *libctx, OSSL_CALLBACK **cb, void **cbarg) { SELF_TEST_CB *stcb = get_self_test_callback(libctx); if (cb != NULL) *cb = (stcb != NULL ? stcb->cb : NULL); if (cbarg != NULL) *cbarg = (stcb != NULL ? stcb->cbarg : NULL); } #endif /* FIPS_MODULE */ static void self_test_setparams(OSSL_SELF_TEST *st) { size_t n = 0; if (st->cb != NULL) { st->params[n++] = OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_PHASE, (char *)st->phase, 0); st->params[n++] = OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_TYPE, (char *)st->type, 0); st->params[n++] = OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_DESC, (char *)st->desc, 0); } st->params[n++] = OSSL_PARAM_construct_end(); } OSSL_SELF_TEST *OSSL_SELF_TEST_new(OSSL_CALLBACK *cb, void *cbarg) { OSSL_SELF_TEST *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->cb = cb; ret->cb_arg = cbarg; ret->phase = ""; ret->type = ""; ret->desc = ""; self_test_setparams(ret); return ret; } void OSSL_SELF_TEST_free(OSSL_SELF_TEST *st) { OPENSSL_free(st); } /* Can be used during application testing to log that a test has started. */ void OSSL_SELF_TEST_onbegin(OSSL_SELF_TEST *st, const char *type, const char *desc) { if (st != NULL && st->cb != NULL) { st->phase = OSSL_SELF_TEST_PHASE_START; st->type = type; st->desc = desc; self_test_setparams(st); (void)st->cb(st->params, st->cb_arg); } } /* * Can be used during application testing to log that a test has either * passed or failed. */ void OSSL_SELF_TEST_onend(OSSL_SELF_TEST *st, int ret) { if (st != NULL && st->cb != NULL) { st->phase = (ret == 1 ? OSSL_SELF_TEST_PHASE_PASS : OSSL_SELF_TEST_PHASE_FAIL); self_test_setparams(st); (void)st->cb(st->params, st->cb_arg); st->phase = OSSL_SELF_TEST_PHASE_NONE; st->type = OSSL_SELF_TEST_TYPE_NONE; st->desc = OSSL_SELF_TEST_DESC_NONE; } } /* * Used for failure testing. * * Call the applications SELF_TEST_cb() if it exists. * If the application callback decides to return 0 then the first byte of 'bytes' * is modified (corrupted). This is used to modify output signatures or * ciphertext before they are verified or decrypted. */ int OSSL_SELF_TEST_oncorrupt_byte(OSSL_SELF_TEST *st, unsigned char *bytes) { if (st != NULL && st->cb != NULL) { st->phase = OSSL_SELF_TEST_PHASE_CORRUPT; self_test_setparams(st); if (!st->cb(st->params, st->cb_arg)) { bytes[0] ^= 1; return 1; } } return 0; }
./openssl/crypto/LPdir_unix.c
/* * Copyright 2004-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 */ /* * This file is dual-licensed and is also available under the following * terms: * * Copyright (c) 2004, 2018, 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 COPYRIGHT HOLDERS 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 COPYRIGHT * OWNER 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. */ #include <stddef.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include <sys/types.h> #include <dirent.h> #include <errno.h> #ifndef LPDIR_H # include "LPdir.h" #endif #ifdef __VMS # include <ctype.h> #endif /* * The POSIX macro for the maximum number of characters in a file path is * NAME_MAX. However, some operating systems use PATH_MAX instead. * Therefore, it seems natural to first check for PATH_MAX and use that, and * if it doesn't exist, use NAME_MAX. */ #if defined(PATH_MAX) # define LP_ENTRY_SIZE PATH_MAX #elif defined(NAME_MAX) # define LP_ENTRY_SIZE NAME_MAX #endif /* * Of course, there's the possibility that neither PATH_MAX nor NAME_MAX * exist. It's also possible that NAME_MAX exists but is define to a very * small value (HP-UX offers 14), so we need to check if we got a result, and * if it meets a minimum standard, and create or change it if not. */ #if !defined(LP_ENTRY_SIZE) || LP_ENTRY_SIZE<255 # undef LP_ENTRY_SIZE # define LP_ENTRY_SIZE 255 #endif struct LP_dir_context_st { DIR *dir; char entry_name[LP_ENTRY_SIZE + 1]; #ifdef __VMS int expect_file_generations; char previous_entry_name[LP_ENTRY_SIZE + 1]; #endif }; const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory) { struct dirent *direntry = NULL; if (ctx == NULL || directory == NULL) { errno = EINVAL; return 0; } errno = 0; if (*ctx == NULL) { *ctx = malloc(sizeof(**ctx)); if (*ctx == NULL) { errno = ENOMEM; return 0; } memset(*ctx, 0, sizeof(**ctx)); #ifdef __VMS { char c = directory[strlen(directory) - 1]; if (c == ']' || c == '>' || c == ':') (*ctx)->expect_file_generations = 1; } #endif (*ctx)->dir = opendir(directory); if ((*ctx)->dir == NULL) { int save_errno = errno; /* Probably not needed, but I'm paranoid */ free(*ctx); *ctx = NULL; errno = save_errno; return 0; } } #ifdef __VMS strncpy((*ctx)->previous_entry_name, (*ctx)->entry_name, sizeof((*ctx)->previous_entry_name)); again: #endif direntry = readdir((*ctx)->dir); if (direntry == NULL) { return 0; } OPENSSL_strlcpy((*ctx)->entry_name, direntry->d_name, sizeof((*ctx)->entry_name)); #ifdef __VMS if ((*ctx)->expect_file_generations) { char *p = (*ctx)->entry_name + strlen((*ctx)->entry_name); while (p > (*ctx)->entry_name && isdigit((unsigned char)p[-1])) p--; if (p > (*ctx)->entry_name && p[-1] == ';') p[-1] = '\0'; if (OPENSSL_strcasecmp((*ctx)->entry_name, (*ctx)->previous_entry_name) == 0) goto again; } #endif return (*ctx)->entry_name; } int LP_find_file_end(LP_DIR_CTX **ctx) { if (ctx != NULL && *ctx != NULL) { int ret = closedir((*ctx)->dir); free(*ctx); switch (ret) { case 0: return 1; case -1: return 0; default: break; } } errno = EINVAL; return 0; }
./openssl/crypto/LPdir_win.c
/* * Copyright 2004-2016 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 COPYRIGHT HOLDERS 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 COPYRIGHT * OWNER 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. */ #include <windows.h> #include <tchar.h> #include "internal/numbers.h" #ifndef LPDIR_H # include "LPdir.h" #endif /* * We're most likely overcautious here, but let's reserve for broken WinCE * headers and explicitly opt for UNICODE call. Keep in mind that our WinCE * builds are compiled with -DUNICODE [as well as -D_UNICODE]. */ #if defined(LP_SYS_WINCE) && !defined(FindFirstFile) # define FindFirstFile FindFirstFileW #endif #if defined(LP_SYS_WINCE) && !defined(FindNextFile) # define FindNextFile FindNextFileW #endif #ifndef NAME_MAX # define NAME_MAX 255 #endif #ifdef CP_UTF8 # define CP_DEFAULT CP_UTF8 #else # define CP_DEFAULT CP_ACP #endif struct LP_dir_context_st { WIN32_FIND_DATA ctx; HANDLE handle; char entry_name[NAME_MAX + 1]; }; const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory) { if (ctx == NULL || directory == NULL) { errno = EINVAL; return 0; } errno = 0; if (*ctx == NULL) { size_t dirlen = strlen(directory); if (dirlen == 0 || dirlen > INT_MAX - 3) { errno = ENOENT; return 0; } *ctx = malloc(sizeof(**ctx)); if (*ctx == NULL) { errno = ENOMEM; return 0; } memset(*ctx, 0, sizeof(**ctx)); if (sizeof(TCHAR) != sizeof(char)) { TCHAR *wdir = NULL; /* len_0 denotes string length *with* trailing 0 */ size_t index = 0, len_0 = dirlen + 1; #ifdef LP_MULTIBYTE_AVAILABLE int sz = 0; UINT cp; do { # ifdef CP_UTF8 if ((sz = MultiByteToWideChar((cp = CP_UTF8), 0, directory, len_0, NULL, 0)) > 0 || GetLastError() != ERROR_NO_UNICODE_TRANSLATION) break; # endif sz = MultiByteToWideChar((cp = CP_ACP), 0, directory, len_0, NULL, 0); } while (0); if (sz > 0) { /* * allocate two additional characters in case we need to * concatenate asterisk, |sz| covers trailing '\0'! */ wdir = _alloca((sz + 2) * sizeof(TCHAR)); if (!MultiByteToWideChar(cp, 0, directory, len_0, (WCHAR *)wdir, sz)) { free(*ctx); *ctx = NULL; errno = EINVAL; return 0; } } else #endif { sz = len_0; /* * allocate two additional characters in case we need to * concatenate asterisk, |sz| covers trailing '\0'! */ wdir = _alloca((sz + 2) * sizeof(TCHAR)); for (index = 0; index < len_0; index++) wdir[index] = (TCHAR)directory[index]; } sz--; /* wdir[sz] is trailing '\0' now */ if (wdir[sz - 1] != TEXT('*')) { if (wdir[sz - 1] != TEXT('/') && wdir[sz - 1] != TEXT('\\')) _tcscpy(wdir + sz, TEXT("/*")); else _tcscpy(wdir + sz, TEXT("*")); } (*ctx)->handle = FindFirstFile(wdir, &(*ctx)->ctx); } else { if (directory[dirlen - 1] != '*') { char *buf = _alloca(dirlen + 3); strcpy(buf, directory); if (buf[dirlen - 1] != '/' && buf[dirlen - 1] != '\\') strcpy(buf + dirlen, "/*"); else strcpy(buf + dirlen, "*"); directory = buf; } (*ctx)->handle = FindFirstFile((TCHAR *)directory, &(*ctx)->ctx); } if ((*ctx)->handle == INVALID_HANDLE_VALUE) { free(*ctx); *ctx = NULL; errno = EINVAL; return 0; } } else { if (FindNextFile((*ctx)->handle, &(*ctx)->ctx) == FALSE) { return 0; } } if (sizeof(TCHAR) != sizeof(char)) { TCHAR *wdir = (*ctx)->ctx.cFileName; size_t index, len_0 = 0; while (wdir[len_0] && len_0 < (sizeof((*ctx)->entry_name) - 1)) len_0++; len_0++; #ifdef LP_MULTIBYTE_AVAILABLE if (!WideCharToMultiByte(CP_DEFAULT, 0, (WCHAR *)wdir, len_0, (*ctx)->entry_name, sizeof((*ctx)->entry_name), NULL, 0)) #endif for (index = 0; index < len_0; index++) (*ctx)->entry_name[index] = (char)wdir[index]; } else strncpy((*ctx)->entry_name, (const char *)(*ctx)->ctx.cFileName, sizeof((*ctx)->entry_name) - 1); (*ctx)->entry_name[sizeof((*ctx)->entry_name) - 1] = '\0'; return (*ctx)->entry_name; } int LP_find_file_end(LP_DIR_CTX **ctx) { if (ctx != NULL && *ctx != NULL) { FindClose((*ctx)->handle); free(*ctx); *ctx = NULL; return 1; } errno = EINVAL; return 0; }
./openssl/crypto/s390x_arch.h
/* * Copyright 2017-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_S390X_ARCH_H # define OSSL_CRYPTO_S390X_ARCH_H # ifndef __ASSEMBLER__ #include "crypto/bn.h" void s390x_kimd(const unsigned char *in, size_t len, unsigned int fc, void *param); void s390x_klmd(const unsigned char *in, size_t inlen, unsigned char *out, size_t outlen, unsigned int fc, void *param); void s390x_km(const unsigned char *in, size_t len, unsigned char *out, unsigned int fc, void *param); void s390x_kmac(const unsigned char *in, size_t len, unsigned int fc, void *param); void s390x_kmo(const unsigned char *in, size_t len, unsigned char *out, unsigned int fc, void *param); void s390x_kmf(const unsigned char *in, size_t len, unsigned char *out, unsigned int fc, void *param); void s390x_kma(const unsigned char *aad, size_t alen, const unsigned char *in, size_t len, unsigned char *out, unsigned int fc, void *param); int s390x_pcc(unsigned int fc, void *param); int s390x_kdsa(unsigned int fc, void *param, const unsigned char *in, size_t len); void s390x_flip_endian32(unsigned char dst[32], const unsigned char src[32]); void s390x_flip_endian64(unsigned char dst[64], const unsigned char src[64]); int s390x_x25519_mul(unsigned char u_dst[32], const unsigned char u_src[32], const unsigned char d_src[32]); int s390x_x448_mul(unsigned char u_dst[56], const unsigned char u_src[56], const unsigned char d_src[56]); int s390x_ed25519_mul(unsigned char x_dst[32], unsigned char y_dst[32], const unsigned char x_src[32], const unsigned char y_src[32], const unsigned char d_src[32]); int s390x_ed448_mul(unsigned char x_dst[57], unsigned char y_dst[57], const unsigned char x_src[57], const unsigned char y_src[57], const unsigned char d_src[57]); /* * The field elements of OPENSSL_s390xcap_P are the 64-bit words returned by * the STFLE instruction followed by the 64-bit word pairs returned by * instructions' QUERY functions. If STFLE returns fewer data or an instruction * is not supported, the corresponding field elements are zero. */ struct OPENSSL_s390xcap_st { unsigned long long stfle[4]; unsigned long long kimd[2]; unsigned long long klmd[2]; unsigned long long km[2]; unsigned long long kmc[2]; unsigned long long kmac[2]; unsigned long long kmctr[2]; unsigned long long kmo[2]; unsigned long long kmf[2]; unsigned long long prno[2]; unsigned long long kma[2]; unsigned long long pcc[2]; unsigned long long kdsa[2]; }; #if defined(__GNUC__) && defined(__linux) __attribute__ ((visibility("hidden"))) #endif extern struct OPENSSL_s390xcap_st OPENSSL_s390xcap_P; #ifdef S390X_MOD_EXP # if defined(__GNUC__) && defined(__linux) __attribute__ ((visibility("hidden"))) # endif extern int OPENSSL_s390xcex; #endif /* Max number of 64-bit words currently returned by STFLE */ # define S390X_STFLE_MAX 3 /* convert facility bit number or function code to bit mask */ # define S390X_CAPBIT(i) (1ULL << (63 - (i) % 64)) # endif /* OPENSSL_s390xcap_P offsets [bytes] */ # define S390X_STFLE 0x00 # define S390X_KIMD 0x20 # define S390X_KLMD 0x30 # define S390X_KM 0x40 # define S390X_KMC 0x50 # define S390X_KMAC 0x60 # define S390X_KMCTR 0x70 # define S390X_KMO 0x80 # define S390X_KMF 0x90 # define S390X_PRNO 0xa0 # define S390X_KMA 0xb0 # define S390X_PCC 0xc0 # define S390X_KDSA 0xd0 /* Facility Bit Numbers */ # define S390X_MSA 17 /* message-security-assist */ # define S390X_STCKF 25 /* store-clock-fast */ # define S390X_MSA5 57 /* message-security-assist-ext. 5 */ # define S390X_MSA3 76 /* message-security-assist-ext. 3 */ # define S390X_MSA4 77 /* message-security-assist-ext. 4 */ # define S390X_VX 129 /* vector */ # define S390X_VXD 134 /* vector packed decimal */ # define S390X_VXE 135 /* vector enhancements 1 */ # define S390X_MSA8 146 /* message-security-assist-ext. 8 */ # define S390X_MSA9 155 /* message-security-assist-ext. 9 */ /* Function Codes */ /* all instructions */ # define S390X_QUERY 0 /* kimd/klmd */ # define S390X_SHA_1 1 # define S390X_SHA_256 2 # define S390X_SHA_512 3 # define S390X_SHA3_224 32 # define S390X_SHA3_256 33 # define S390X_SHA3_384 34 # define S390X_SHA3_512 35 # define S390X_KECCAK_224 32 # define S390X_KECCAK_256 33 # define S390X_KECCAK_384 34 # define S390X_KECCAK_512 35 # define S390X_SHAKE_128 36 # define S390X_SHAKE_256 37 # define S390X_GHASH 65 /* km/kmc/kmac/kmctr/kmo/kmf/kma */ # define S390X_AES_128 18 # define S390X_AES_192 19 # define S390X_AES_256 20 /* km */ # define S390X_XTS_AES_128 50 # define S390X_XTS_AES_256 52 /* prno */ # define S390X_SHA_512_DRNG 3 # define S390X_TRNG 114 /* pcc */ # define S390X_SCALAR_MULTIPLY_P256 64 # define S390X_SCALAR_MULTIPLY_P384 65 # define S390X_SCALAR_MULTIPLY_P521 66 # define S390X_SCALAR_MULTIPLY_ED25519 72 # define S390X_SCALAR_MULTIPLY_ED448 73 # define S390X_SCALAR_MULTIPLY_X25519 80 # define S390X_SCALAR_MULTIPLY_X448 81 /* kdsa */ # define S390X_ECDSA_VERIFY_P256 1 # define S390X_ECDSA_VERIFY_P384 2 # define S390X_ECDSA_VERIFY_P521 3 # define S390X_ECDSA_SIGN_P256 9 # define S390X_ECDSA_SIGN_P384 10 # define S390X_ECDSA_SIGN_P521 11 # define S390X_EDDSA_VERIFY_ED25519 32 # define S390X_EDDSA_VERIFY_ED448 36 # define S390X_EDDSA_SIGN_ED25519 40 # define S390X_EDDSA_SIGN_ED448 44 /* Register 0 Flags */ # define S390X_DECRYPT 0x80 # define S390X_KMA_LPC 0x100 # define S390X_KMA_LAAD 0x200 # define S390X_KMA_HS 0x400 # define S390X_KDSA_D 0x80 # define S390X_KLMD_PS 0x100 #endif
./openssl/crypto/cversion.c
/* * Copyright 1995-2016 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" #include "buildinf.h" unsigned long OpenSSL_version_num(void) { return OPENSSL_VERSION_NUMBER; } unsigned int OPENSSL_version_major(void) { return OPENSSL_VERSION_MAJOR; } unsigned int OPENSSL_version_minor(void) { return OPENSSL_VERSION_MINOR; } unsigned int OPENSSL_version_patch(void) { return OPENSSL_VERSION_PATCH; } const char *OPENSSL_version_pre_release(void) { return OPENSSL_VERSION_PRE_RELEASE; } const char *OPENSSL_version_build_metadata(void) { return OPENSSL_VERSION_BUILD_METADATA; } extern char ossl_cpu_info_str[]; const char *OpenSSL_version(int t) { switch (t) { case OPENSSL_VERSION: return OPENSSL_VERSION_TEXT; case OPENSSL_VERSION_STRING: return OPENSSL_VERSION_STR; case OPENSSL_FULL_VERSION_STRING: return OPENSSL_FULL_VERSION_STR; case OPENSSL_BUILT_ON: return DATE; case OPENSSL_CFLAGS: return compiler_flags; case OPENSSL_PLATFORM: return PLATFORM; case OPENSSL_DIR: #ifdef OPENSSLDIR return "OPENSSLDIR: \"" OPENSSLDIR "\""; #else return "OPENSSLDIR: N/A"; #endif case OPENSSL_ENGINES_DIR: #ifdef ENGINESDIR return "ENGINESDIR: \"" ENGINESDIR "\""; #else return "ENGINESDIR: N/A"; #endif case OPENSSL_MODULES_DIR: #ifdef MODULESDIR return "MODULESDIR: \"" MODULESDIR "\""; #else return "MODULESDIR: N/A"; #endif case OPENSSL_CPU_INFO: if (OPENSSL_info(OPENSSL_INFO_CPU_SETTINGS) != NULL) return ossl_cpu_info_str; else return "CPUINFO: N/A"; } return "not available"; }
./openssl/crypto/o_str.c
/* * Copyright 2003-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 "internal/e_os.h" #include <string.h> #include <limits.h> #include <openssl/crypto.h> #include "crypto/ctype.h" #include "internal/cryptlib.h" #include "internal/thread_once.h" #define DEFAULT_SEPARATOR ':' #define CH_ZERO '\0' char *CRYPTO_strdup(const char *str, const char* file, int line) { char *ret; if (str == NULL) return NULL; ret = CRYPTO_malloc(strlen(str) + 1, file, line); if (ret != NULL) strcpy(ret, str); return ret; } char *CRYPTO_strndup(const char *str, size_t s, const char* file, int line) { size_t maxlen; char *ret; if (str == NULL) return NULL; maxlen = OPENSSL_strnlen(str, s); ret = CRYPTO_malloc(maxlen + 1, file, line); if (ret) { memcpy(ret, str, maxlen); ret[maxlen] = CH_ZERO; } return ret; } void *CRYPTO_memdup(const void *data, size_t siz, const char* file, int line) { void *ret; if (data == NULL || siz >= INT_MAX) return NULL; ret = CRYPTO_malloc(siz, file, line); if (ret == NULL) return NULL; return memcpy(ret, data, siz); } size_t OPENSSL_strnlen(const char *str, size_t maxlen) { const char *p; for (p = str; maxlen-- != 0 && *p != CH_ZERO; ++p) ; return p - str; } size_t OPENSSL_strlcpy(char *dst, const char *src, size_t size) { size_t l = 0; for (; size > 1 && *src; size--) { *dst++ = *src++; l++; } if (size) *dst = CH_ZERO; return l + strlen(src); } size_t OPENSSL_strlcat(char *dst, const char *src, size_t size) { size_t l = 0; for (; size > 0 && *dst; size--, dst++) l++; return l + OPENSSL_strlcpy(dst, src, size); } int OPENSSL_hexchar2int(unsigned char c) { #ifdef CHARSET_EBCDIC c = os_toebcdic[c]; #endif switch (c) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 0x0A; case 'b': case 'B': return 0x0B; case 'c': case 'C': return 0x0C; case 'd': case 'D': return 0x0D; case 'e': case 'E': return 0x0E; case 'f': case 'F': return 0x0F; } return -1; } static int hexstr2buf_sep(unsigned char *buf, size_t buf_n, size_t *buflen, const char *str, const char sep) { unsigned char *q; unsigned char ch, cl; int chi, cli; const unsigned char *p; size_t cnt; for (p = (const unsigned char *)str, q = buf, cnt = 0; *p; ) { ch = *p++; /* A separator of CH_ZERO means there is no separator */ if (ch == sep && sep != CH_ZERO) continue; cl = *p++; if (!cl) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ODD_NUMBER_OF_DIGITS); return 0; } cli = OPENSSL_hexchar2int(cl); chi = OPENSSL_hexchar2int(ch); if (cli < 0 || chi < 0) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ILLEGAL_HEX_DIGIT); return 0; } cnt++; if (q != NULL) { if (cnt > buf_n) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER); return 0; } *q++ = (unsigned char)((chi << 4) | cli); } } if (buflen != NULL) *buflen = cnt; return 1; } /* * Given a string of hex digits convert to a buffer */ int OPENSSL_hexstr2buf_ex(unsigned char *buf, size_t buf_n, size_t *buflen, const char *str, const char sep) { return hexstr2buf_sep(buf, buf_n, buflen, str, sep); } unsigned char *ossl_hexstr2buf_sep(const char *str, long *buflen, const char sep) { unsigned char *buf; size_t buf_n, tmp_buflen; buf_n = strlen(str); if (buf_n <= 1) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_HEX_STRING_TOO_SHORT); return NULL; } buf_n /= 2; if ((buf = OPENSSL_malloc(buf_n)) == NULL) return NULL; if (buflen != NULL) *buflen = 0; tmp_buflen = 0; if (hexstr2buf_sep(buf, buf_n, &tmp_buflen, str, sep)) { if (buflen != NULL) *buflen = (long)tmp_buflen; return buf; } OPENSSL_free(buf); return NULL; } unsigned char *OPENSSL_hexstr2buf(const char *str, long *buflen) { return ossl_hexstr2buf_sep(str, buflen, DEFAULT_SEPARATOR); } static int buf2hexstr_sep(char *str, size_t str_n, size_t *strlength, const unsigned char *buf, size_t buflen, const char sep) { static const char hexdig[] = "0123456789ABCDEF"; const unsigned char *p; char *q; size_t i; int has_sep = (sep != CH_ZERO); size_t len = has_sep ? buflen * 3 : 1 + buflen * 2; if (strlength != NULL) *strlength = len; if (str == NULL) return 1; if (str_n < (unsigned long)len) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER); return 0; } q = str; for (i = 0, p = buf; i < buflen; i++, p++) { *q++ = hexdig[(*p >> 4) & 0xf]; *q++ = hexdig[*p & 0xf]; if (has_sep) *q++ = sep; } if (has_sep) --q; *q = CH_ZERO; #ifdef CHARSET_EBCDIC ebcdic2ascii(str, str, q - str - 1); #endif return 1; } int OPENSSL_buf2hexstr_ex(char *str, size_t str_n, size_t *strlength, const unsigned char *buf, size_t buflen, const char sep) { return buf2hexstr_sep(str, str_n, strlength, buf, buflen, sep); } char *ossl_buf2hexstr_sep(const unsigned char *buf, long buflen, char sep) { char *tmp; size_t tmp_n; if (buflen == 0) return OPENSSL_zalloc(1); tmp_n = (sep != CH_ZERO) ? buflen * 3 : 1 + buflen * 2; if ((tmp = OPENSSL_malloc(tmp_n)) == NULL) return NULL; if (buf2hexstr_sep(tmp, tmp_n, NULL, buf, buflen, sep)) return tmp; OPENSSL_free(tmp); return NULL; } /* * Given a buffer of length 'buflen' return a OPENSSL_malloc'ed string with * its hex representation @@@ (Contents of buffer are always kept in ASCII, * also on EBCDIC machines) */ char *OPENSSL_buf2hexstr(const unsigned char *buf, long buflen) { return ossl_buf2hexstr_sep(buf, buflen, DEFAULT_SEPARATOR); } int openssl_strerror_r(int errnum, char *buf, size_t buflen) { #if defined(_MSC_VER) && _MSC_VER>=1400 && !defined(_WIN32_WCE) return !strerror_s(buf, buflen, errnum); #elif defined(_GNU_SOURCE) char *err; /* * GNU strerror_r may not actually set buf. * It can return a pointer to some (immutable) static string in which case * buf is left unused. */ err = strerror_r(errnum, buf, buflen); if (err == NULL || buflen == 0) return 0; /* * If err is statically allocated, err != buf and we need to copy the data. * If err points somewhere inside buf, OPENSSL_strlcpy can handle this, * since src and dest are not annotated with __restrict and the function * reads src byte for byte and writes to dest. * If err == buf we do not have to copy anything. */ if (err != buf) OPENSSL_strlcpy(buf, err, buflen); return 1; #elif (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || \ (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600) /* * We can use "real" strerror_r. The OpenSSL version differs in that it * gives 1 on success and 0 on failure for consistency with other OpenSSL * functions. Real strerror_r does it the other way around */ return !strerror_r(errnum, buf, buflen); #else char *err; /* Fall back to non-thread safe strerror()...its all we can do */ if (buflen < 2) return 0; err = strerror(errnum); /* Can this ever happen? */ if (err == NULL) return 0; OPENSSL_strlcpy(buf, err, buflen); return 1; #endif } int OPENSSL_strcasecmp(const char *s1, const char *s2) { int t; while ((t = ossl_tolower(*s1) - ossl_tolower(*s2++)) == 0) if (*s1++ == '\0') return 0; return t; } int OPENSSL_strncasecmp(const char *s1, const char *s2, size_t n) { int t; size_t i; for (i = 0; i < n; i++) if ((t = ossl_tolower(*s1) - ossl_tolower(*s2++)) != 0) return t; else if (*s1++ == '\0') return 0; return 0; }
./openssl/crypto/trace.c
/* * 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 */ #include <stdio.h> #include <string.h> #include "internal/thread_once.h" #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/trace.h> #include "internal/bio.h" #include "internal/nelem.h" #include "internal/refcount.h" #include "crypto/cryptlib.h" #include "crypto/ctype.h" #ifndef OPENSSL_NO_TRACE static CRYPTO_RWLOCK *trace_lock = NULL; static const BIO *current_channel = NULL; /*- * INTERNAL TRACE CHANNEL IMPLEMENTATION * * For our own flexibility, all trace categories are associated with a * BIO sink object, also called the trace channel. Instead of a BIO object, * the application can also provide a callback function, in which case an * internal trace channel is attached, which simply calls the registered * callback function. */ static int trace_write(BIO *b, const char *buf, size_t num, size_t *written); static int trace_puts(BIO *b, const char *str); static long trace_ctrl(BIO *channel, int cmd, long argl, void *argp); static int trace_free(BIO *b); static const BIO_METHOD trace_method = { BIO_TYPE_SOURCE_SINK, "trace", trace_write, NULL, /* old write */ NULL, /* read_ex */ NULL, /* read */ trace_puts, NULL, /* gets */ trace_ctrl, /* ctrl */ NULL, /* create */ trace_free, /* free */ NULL, /* callback_ctrl */ }; struct trace_data_st { OSSL_trace_cb callback; int category; void *data; }; static int trace_write(BIO *channel, const char *buf, size_t num, size_t *written) { struct trace_data_st *ctx = BIO_get_data(channel); size_t cnt = ctx->callback(buf, num, ctx->category, OSSL_TRACE_CTRL_WRITE, ctx->data); *written = cnt; return cnt != 0; } static int trace_puts(BIO *channel, const char *str) { size_t written; if (trace_write(channel, str, strlen(str), &written)) return (int)written; return EOF; } static long trace_ctrl(BIO *channel, int cmd, long argl, void *argp) { struct trace_data_st *ctx = BIO_get_data(channel); switch (cmd) { case OSSL_TRACE_CTRL_BEGIN: case OSSL_TRACE_CTRL_END: /* We know that the callback is likely to return 0 here */ ctx->callback("", 0, ctx->category, cmd, ctx->data); return 1; default: break; } return -2; /* Unsupported */ } static int trace_free(BIO *channel) { if (channel == NULL) return 0; OPENSSL_free(BIO_get_data(channel)); return 1; } #endif /*- * TRACE */ /* Helper struct and macro to get name string to number mapping */ struct trace_category_st { const char * const name; const int num; }; #define TRACE_CATEGORY_(name) { #name, OSSL_TRACE_CATEGORY_##name } static const struct trace_category_st trace_categories[OSSL_TRACE_CATEGORY_NUM] = { TRACE_CATEGORY_(ALL), TRACE_CATEGORY_(TRACE), TRACE_CATEGORY_(INIT), TRACE_CATEGORY_(TLS), TRACE_CATEGORY_(TLS_CIPHER), TRACE_CATEGORY_(CONF), TRACE_CATEGORY_(ENGINE_TABLE), TRACE_CATEGORY_(ENGINE_REF_COUNT), TRACE_CATEGORY_(PKCS5V2), TRACE_CATEGORY_(PKCS12_KEYGEN), TRACE_CATEGORY_(PKCS12_DECRYPT), TRACE_CATEGORY_(X509V3_POLICY), TRACE_CATEGORY_(BN_CTX), TRACE_CATEGORY_(CMP), TRACE_CATEGORY_(STORE), TRACE_CATEGORY_(DECODER), TRACE_CATEGORY_(ENCODER), TRACE_CATEGORY_(REF_COUNT), TRACE_CATEGORY_(HTTP), }; /* KEEP THIS LIST IN SYNC with #define OSSL_TRACE_CATEGORY_... in trace.h */ const char *OSSL_trace_get_category_name(int num) { if (num < 0 || (size_t)num >= OSSL_NELEM(trace_categories)) return NULL; /* * Partial check that OSSL_TRACE_CATEGORY_... macros * are synced with trace_categories array */ if (!ossl_assert(trace_categories[num].name != NULL) || !ossl_assert(trace_categories[num].num == num)) return NULL; return trace_categories[num].name; } int OSSL_trace_get_category_num(const char *name) { size_t i; if (name == NULL) return -1; for (i = 0; i < OSSL_NELEM(trace_categories); i++) if (OPENSSL_strcasecmp(name, trace_categories[i].name) == 0) return trace_categories[i].num; return -1; /* not found */ } #ifndef OPENSSL_NO_TRACE /* We use one trace channel for each trace category */ static struct { enum { SIMPLE_CHANNEL, CALLBACK_CHANNEL } type; BIO *bio; char *prefix; char *suffix; } trace_channels[OSSL_TRACE_CATEGORY_NUM] = { { 0, NULL, NULL, NULL }, }; #endif #ifndef OPENSSL_NO_TRACE enum { CHANNEL, PREFIX, SUFFIX }; static int trace_attach_cb(int category, int type, const void *data) { switch (type) { case CHANNEL: OSSL_TRACE2(TRACE, "Attach channel %p to category '%s'\n", data, trace_categories[category].name); break; case PREFIX: OSSL_TRACE2(TRACE, "Attach prefix \"%s\" to category '%s'\n", (const char *)data, trace_categories[category].name); break; case SUFFIX: OSSL_TRACE2(TRACE, "Attach suffix \"%s\" to category '%s'\n", (const char *)data, trace_categories[category].name); break; default: /* No clue */ break; } return 1; } static int trace_detach_cb(int category, int type, const void *data) { switch (type) { case CHANNEL: OSSL_TRACE2(TRACE, "Detach channel %p from category '%s'\n", data, trace_categories[category].name); break; case PREFIX: OSSL_TRACE2(TRACE, "Detach prefix \"%s\" from category '%s'\n", (const char *)data, trace_categories[category].name); break; case SUFFIX: OSSL_TRACE2(TRACE, "Detach suffix \"%s\" from category '%s'\n", (const char *)data, trace_categories[category].name); break; default: /* No clue */ break; } return 1; } static int do_ossl_trace_init(void); static CRYPTO_ONCE trace_inited = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_trace_init) { return do_ossl_trace_init(); } static int set_trace_data(int category, int type, BIO **channel, const char **prefix, const char **suffix, int (*attach_cb)(int, int, const void *), int (*detach_cb)(int, int, const void *)) { BIO *curr_channel = NULL; char *curr_prefix = NULL; char *curr_suffix = NULL; /* Ensure do_ossl_trace_init() is called once */ if (!RUN_ONCE(&trace_inited, ossl_trace_init)) return 0; curr_channel = trace_channels[category].bio; curr_prefix = trace_channels[category].prefix; curr_suffix = trace_channels[category].suffix; /* Make sure to run the detach callback first on all data */ if (prefix != NULL && curr_prefix != NULL) { detach_cb(category, PREFIX, curr_prefix); } if (suffix != NULL && curr_suffix != NULL) { detach_cb(category, SUFFIX, curr_suffix); } if (channel != NULL && curr_channel != NULL) { detach_cb(category, CHANNEL, curr_channel); } /* After detach callbacks are done, clear data where appropriate */ if (prefix != NULL && curr_prefix != NULL) { OPENSSL_free(curr_prefix); trace_channels[category].prefix = NULL; } if (suffix != NULL && curr_suffix != NULL) { OPENSSL_free(curr_suffix); trace_channels[category].suffix = NULL; } if (channel != NULL && curr_channel != NULL) { BIO_free(curr_channel); trace_channels[category].type = 0; trace_channels[category].bio = NULL; } /* Before running callbacks are done, set new data where appropriate */ if (prefix != NULL && *prefix != NULL) { if ((curr_prefix = OPENSSL_strdup(*prefix)) == NULL) return 0; trace_channels[category].prefix = curr_prefix; } if (suffix != NULL && *suffix != NULL) { if ((curr_suffix = OPENSSL_strdup(*suffix)) == NULL) return 0; trace_channels[category].suffix = curr_suffix; } if (channel != NULL && *channel != NULL) { trace_channels[category].type = type; trace_channels[category].bio = *channel; /* * This must not be done before setting prefix/suffix, * as those may fail, and then the caller is mislead to free *channel. */ } /* Finally, run the attach callback on the new data */ if (channel != NULL && *channel != NULL) { attach_cb(category, CHANNEL, *channel); } if (prefix != NULL && *prefix != NULL) { attach_cb(category, PREFIX, *prefix); } if (suffix != NULL && *suffix != NULL) { attach_cb(category, SUFFIX, *suffix); } return 1; } static int do_ossl_trace_init(void) { trace_lock = CRYPTO_THREAD_lock_new(); return trace_lock != NULL; } #endif void ossl_trace_cleanup(void) { #ifndef OPENSSL_NO_TRACE int category; BIO *channel = NULL; const char *prefix = NULL; const char *suffix = NULL; for (category = 0; category < OSSL_TRACE_CATEGORY_NUM; category++) { /* We force the TRACE category to be treated last */ if (category == OSSL_TRACE_CATEGORY_TRACE) continue; set_trace_data(category, 0, &channel, &prefix, &suffix, trace_attach_cb, trace_detach_cb); } set_trace_data(OSSL_TRACE_CATEGORY_TRACE, 0, &channel, &prefix, &suffix, trace_attach_cb, trace_detach_cb); CRYPTO_THREAD_lock_free(trace_lock); #endif } int OSSL_trace_set_channel(int category, BIO *channel) { #ifndef OPENSSL_NO_TRACE if (category >= 0 && category < OSSL_TRACE_CATEGORY_NUM) return set_trace_data(category, SIMPLE_CHANNEL, &channel, NULL, NULL, trace_attach_cb, trace_detach_cb); #endif return 0; } #ifndef OPENSSL_NO_TRACE static int trace_attach_w_callback_cb(int category, int type, const void *data) { switch (type) { case CHANNEL: OSSL_TRACE2(TRACE, "Attach channel %p to category '%s' (with callback)\n", data, trace_categories[category].name); break; case PREFIX: OSSL_TRACE2(TRACE, "Attach prefix \"%s\" to category '%s'\n", (const char *)data, trace_categories[category].name); break; case SUFFIX: OSSL_TRACE2(TRACE, "Attach suffix \"%s\" to category '%s'\n", (const char *)data, trace_categories[category].name); break; default: /* No clue */ break; } return 1; } #endif int OSSL_trace_set_callback(int category, OSSL_trace_cb callback, void *data) { #ifndef OPENSSL_NO_TRACE BIO *channel = NULL; struct trace_data_st *trace_data = NULL; if (category < 0 || category >= OSSL_TRACE_CATEGORY_NUM) return 0; if (callback != NULL) { if ((channel = BIO_new(&trace_method)) == NULL || (trace_data = OPENSSL_zalloc(sizeof(struct trace_data_st))) == NULL) goto err; trace_data->callback = callback; trace_data->category = category; trace_data->data = data; BIO_set_data(channel, trace_data); } if (!set_trace_data(category, CALLBACK_CHANNEL, &channel, NULL, NULL, trace_attach_w_callback_cb, trace_detach_cb)) goto err; return 1; err: BIO_free(channel); OPENSSL_free(trace_data); #endif return 0; } int OSSL_trace_set_prefix(int category, const char *prefix) { #ifndef OPENSSL_NO_TRACE if (category >= 0 && category < OSSL_TRACE_CATEGORY_NUM) return set_trace_data(category, 0, NULL, &prefix, NULL, trace_attach_cb, trace_detach_cb); #endif return 0; } int OSSL_trace_set_suffix(int category, const char *suffix) { #ifndef OPENSSL_NO_TRACE if (category >= 0 && category < OSSL_TRACE_CATEGORY_NUM) return set_trace_data(category, 0, NULL, NULL, &suffix, trace_attach_cb, trace_detach_cb); #endif return 0; } #ifndef OPENSSL_NO_TRACE static int ossl_trace_get_category(int category) { if (category < 0 || category >= OSSL_TRACE_CATEGORY_NUM) return -1; if (trace_channels[category].bio != NULL) return category; return OSSL_TRACE_CATEGORY_ALL; } #endif int OSSL_trace_enabled(int category) { int ret = 0; #ifndef OPENSSL_NO_TRACE category = ossl_trace_get_category(category); if (category >= 0) ret = trace_channels[category].bio != NULL; #endif return ret; } BIO *OSSL_trace_begin(int category) { BIO *channel = NULL; #ifndef OPENSSL_NO_TRACE char *prefix = NULL; category = ossl_trace_get_category(category); if (category < 0) return NULL; channel = trace_channels[category].bio; prefix = trace_channels[category].prefix; if (channel != NULL) { if (!CRYPTO_THREAD_write_lock(trace_lock)) return NULL; current_channel = channel; switch (trace_channels[category].type) { case SIMPLE_CHANNEL: if (prefix != NULL) { (void)BIO_puts(channel, prefix); (void)BIO_puts(channel, "\n"); } break; case CALLBACK_CHANNEL: (void)BIO_ctrl(channel, OSSL_TRACE_CTRL_BEGIN, prefix == NULL ? 0 : strlen(prefix), prefix); break; } } #endif return channel; } void OSSL_trace_end(int category, BIO *channel) { #ifndef OPENSSL_NO_TRACE char *suffix = NULL; category = ossl_trace_get_category(category); if (category < 0) return; suffix = trace_channels[category].suffix; if (channel != NULL && ossl_assert(channel == current_channel)) { (void)BIO_flush(channel); switch (trace_channels[category].type) { case SIMPLE_CHANNEL: if (suffix != NULL) { (void)BIO_puts(channel, suffix); (void)BIO_puts(channel, "\n"); } break; case CALLBACK_CHANNEL: (void)BIO_ctrl(channel, OSSL_TRACE_CTRL_END, suffix == NULL ? 0 : strlen(suffix), suffix); break; } current_channel = NULL; CRYPTO_THREAD_unlock(trace_lock); } #endif } int OSSL_trace_string(BIO *out, int text, int full, const unsigned char *data, size_t size) { unsigned char buf[OSSL_TRACE_STRING_MAX + 1]; int len, i; if (!full && size > OSSL_TRACE_STRING_MAX) { BIO_printf(out, "[len %zu limited to %d]: ", size, OSSL_TRACE_STRING_MAX); len = OSSL_TRACE_STRING_MAX; } else { len = (int)size; } if (!text) { /* mask control characters while preserving newlines */ for (i = 0; i < len; i++, data++) buf[i] = (char)*data != '\n' && ossl_iscntrl((int)*data) ? ' ' : *data; if (len == 0 || data[-1] != '\n') buf[len++] = '\n'; data = buf; } return BIO_printf(out, "%.*s", len, data); }
./openssl/crypto/mem_sec.c
/* * Copyright 2015-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright 2004-2014, Akamai Technologies. 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 in two halves. The first half implements the public API * to be used by external consumers, and to be used by OpenSSL to store * data in a "secure arena." The second half implements the secure arena. * For details on that implementation, see below (look for uppercase * "SECURE HEAP IMPLEMENTATION"). */ #include "internal/e_os.h" #include <openssl/crypto.h> #include <openssl/err.h> #include <string.h> #ifndef OPENSSL_NO_SECURE_MEMORY # if defined(_WIN32) # include <windows.h> # if defined(WINAPI_FAMILY_PARTITION) # if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM) /* * While VirtualLock is available under the app partition (e.g. UWP), * the headers do not define the API. Define it ourselves instead. */ WINBASEAPI BOOL WINAPI VirtualLock( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize ); # endif # endif # endif # include <stdlib.h> # include <assert.h> # if defined(OPENSSL_SYS_UNIX) # include <unistd.h> # endif # include <sys/types.h> # if defined(OPENSSL_SYS_UNIX) # include <sys/mman.h> # if defined(__FreeBSD__) # define MADV_DONTDUMP MADV_NOCORE # endif # if !defined(MAP_CONCEAL) # define MAP_CONCEAL 0 # endif # endif # if defined(OPENSSL_SYS_LINUX) # include <sys/syscall.h> # if defined(SYS_mlock2) # include <linux/mman.h> # include <errno.h> # endif # include <sys/param.h> # endif # include <sys/stat.h> # include <fcntl.h> #endif #ifndef HAVE_MADVISE # if defined(MADV_DONTDUMP) # define HAVE_MADVISE 1 # else # define HAVE_MADVISE 0 # endif #endif #if HAVE_MADVISE # undef NO_MADVISE #else # define NO_MADVISE #endif #define CLEAR(p, s) OPENSSL_cleanse(p, s) #ifndef PAGE_SIZE # define PAGE_SIZE 4096 #endif #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS) # define MAP_ANON MAP_ANONYMOUS #endif #ifndef OPENSSL_NO_SECURE_MEMORY static size_t secure_mem_used; static int secure_mem_initialized; static CRYPTO_RWLOCK *sec_malloc_lock = NULL; /* * These are the functions that must be implemented by a secure heap (sh). */ static int sh_init(size_t size, size_t minsize); static void *sh_malloc(size_t size); static void sh_free(void *ptr); static void sh_done(void); static size_t sh_actual_size(char *ptr); static int sh_allocated(const char *ptr); #endif int CRYPTO_secure_malloc_init(size_t size, size_t minsize) { #ifndef OPENSSL_NO_SECURE_MEMORY int ret = 0; if (!secure_mem_initialized) { sec_malloc_lock = CRYPTO_THREAD_lock_new(); if (sec_malloc_lock == NULL) return 0; if ((ret = sh_init(size, minsize)) != 0) { secure_mem_initialized = 1; } else { CRYPTO_THREAD_lock_free(sec_malloc_lock); sec_malloc_lock = NULL; } } return ret; #else return 0; #endif /* OPENSSL_NO_SECURE_MEMORY */ } int CRYPTO_secure_malloc_done(void) { #ifndef OPENSSL_NO_SECURE_MEMORY if (secure_mem_used == 0) { sh_done(); secure_mem_initialized = 0; CRYPTO_THREAD_lock_free(sec_malloc_lock); sec_malloc_lock = NULL; return 1; } #endif /* OPENSSL_NO_SECURE_MEMORY */ return 0; } int CRYPTO_secure_malloc_initialized(void) { #ifndef OPENSSL_NO_SECURE_MEMORY return secure_mem_initialized; #else return 0; #endif /* OPENSSL_NO_SECURE_MEMORY */ } void *CRYPTO_secure_malloc(size_t num, const char *file, int line) { #ifndef OPENSSL_NO_SECURE_MEMORY void *ret = NULL; size_t actual_size; int reason = CRYPTO_R_SECURE_MALLOC_FAILURE; if (!secure_mem_initialized) { return CRYPTO_malloc(num, file, line); } if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) { reason = ERR_R_CRYPTO_LIB; goto err; } ret = sh_malloc(num); actual_size = ret ? sh_actual_size(ret) : 0; secure_mem_used += actual_size; CRYPTO_THREAD_unlock(sec_malloc_lock); err: if (ret == NULL && (file != NULL || line != 0)) { ERR_new(); ERR_set_debug(file, line, NULL); ERR_set_error(ERR_LIB_CRYPTO, reason, NULL); } return ret; #else return CRYPTO_malloc(num, file, line); #endif /* OPENSSL_NO_SECURE_MEMORY */ } void *CRYPTO_secure_zalloc(size_t num, const char *file, int line) { #ifndef OPENSSL_NO_SECURE_MEMORY if (secure_mem_initialized) /* CRYPTO_secure_malloc() zeroes allocations when it is implemented */ return CRYPTO_secure_malloc(num, file, line); #endif return CRYPTO_zalloc(num, file, line); } void CRYPTO_secure_free(void *ptr, const char *file, int line) { #ifndef OPENSSL_NO_SECURE_MEMORY size_t actual_size; if (ptr == NULL) return; if (!CRYPTO_secure_allocated(ptr)) { CRYPTO_free(ptr, file, line); return; } if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) return; actual_size = sh_actual_size(ptr); CLEAR(ptr, actual_size); secure_mem_used -= actual_size; sh_free(ptr); CRYPTO_THREAD_unlock(sec_malloc_lock); #else CRYPTO_free(ptr, file, line); #endif /* OPENSSL_NO_SECURE_MEMORY */ } void CRYPTO_secure_clear_free(void *ptr, size_t num, const char *file, int line) { #ifndef OPENSSL_NO_SECURE_MEMORY size_t actual_size; if (ptr == NULL) return; if (!CRYPTO_secure_allocated(ptr)) { OPENSSL_cleanse(ptr, num); CRYPTO_free(ptr, file, line); return; } if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) return; actual_size = sh_actual_size(ptr); CLEAR(ptr, actual_size); secure_mem_used -= actual_size; sh_free(ptr); CRYPTO_THREAD_unlock(sec_malloc_lock); #else if (ptr == NULL) return; OPENSSL_cleanse(ptr, num); CRYPTO_free(ptr, file, line); #endif /* OPENSSL_NO_SECURE_MEMORY */ } int CRYPTO_secure_allocated(const void *ptr) { #ifndef OPENSSL_NO_SECURE_MEMORY if (!secure_mem_initialized) return 0; /* * Only read accesses to the arena take place in sh_allocated() and this * is only changed by the sh_init() and sh_done() calls which are not * locked. Hence, it is safe to make this check without a lock too. */ return sh_allocated(ptr); #else return 0; #endif /* OPENSSL_NO_SECURE_MEMORY */ } size_t CRYPTO_secure_used(void) { size_t ret = 0; #ifndef OPENSSL_NO_SECURE_MEMORY if (!CRYPTO_THREAD_read_lock(sec_malloc_lock)) return 0; ret = secure_mem_used; CRYPTO_THREAD_unlock(sec_malloc_lock); #endif /* OPENSSL_NO_SECURE_MEMORY */ return ret; } size_t CRYPTO_secure_actual_size(void *ptr) { #ifndef OPENSSL_NO_SECURE_MEMORY size_t actual_size; if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) return 0; actual_size = sh_actual_size(ptr); CRYPTO_THREAD_unlock(sec_malloc_lock); return actual_size; #else return 0; #endif } /* * SECURE HEAP IMPLEMENTATION */ #ifndef OPENSSL_NO_SECURE_MEMORY /* * The implementation provided here uses a fixed-sized mmap() heap, * which is locked into memory, not written to core files, and protected * on either side by an unmapped page, which will catch pointer overruns * (or underruns) and an attempt to read data out of the secure heap. * Free'd memory is zero'd or otherwise cleansed. * * This is a pretty standard buddy allocator. We keep areas in a multiple * of "sh.minsize" units. The freelist and bitmaps are kept separately, * so all (and only) data is kept in the mmap'd heap. * * This code assumes eight-bit bytes. The numbers 3 and 7 are all over the * place. */ #define ONE ((size_t)1) # define TESTBIT(t, b) (t[(b) >> 3] & (ONE << ((b) & 7))) # define SETBIT(t, b) (t[(b) >> 3] |= (ONE << ((b) & 7))) # define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7)))) #define WITHIN_ARENA(p) \ ((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size]) #define WITHIN_FREELIST(p) \ ((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size]) typedef struct sh_list_st { struct sh_list_st *next; struct sh_list_st **p_next; } SH_LIST; typedef struct sh_st { char* map_result; size_t map_size; char *arena; size_t arena_size; char **freelist; ossl_ssize_t freelist_size; size_t minsize; unsigned char *bittable; unsigned char *bitmalloc; size_t bittable_size; /* size in bits */ } SH; static SH sh; static size_t sh_getlist(char *ptr) { ossl_ssize_t list = sh.freelist_size - 1; size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize; for (; bit; bit >>= 1, list--) { if (TESTBIT(sh.bittable, bit)) break; OPENSSL_assert((bit & 1) == 0); } return list; } static int sh_testbit(char *ptr, int list, unsigned char *table) { size_t bit; OPENSSL_assert(list >= 0 && list < sh.freelist_size); OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0); bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list)); OPENSSL_assert(bit > 0 && bit < sh.bittable_size); return TESTBIT(table, bit); } static void sh_clearbit(char *ptr, int list, unsigned char *table) { size_t bit; OPENSSL_assert(list >= 0 && list < sh.freelist_size); OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0); bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list)); OPENSSL_assert(bit > 0 && bit < sh.bittable_size); OPENSSL_assert(TESTBIT(table, bit)); CLEARBIT(table, bit); } static void sh_setbit(char *ptr, int list, unsigned char *table) { size_t bit; OPENSSL_assert(list >= 0 && list < sh.freelist_size); OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0); bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list)); OPENSSL_assert(bit > 0 && bit < sh.bittable_size); OPENSSL_assert(!TESTBIT(table, bit)); SETBIT(table, bit); } static void sh_add_to_list(char **list, char *ptr) { SH_LIST *temp; OPENSSL_assert(WITHIN_FREELIST(list)); OPENSSL_assert(WITHIN_ARENA(ptr)); temp = (SH_LIST *)ptr; temp->next = *(SH_LIST **)list; OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next)); temp->p_next = (SH_LIST **)list; if (temp->next != NULL) { OPENSSL_assert((char **)temp->next->p_next == list); temp->next->p_next = &(temp->next); } *list = ptr; } static void sh_remove_from_list(char *ptr) { SH_LIST *temp, *temp2; temp = (SH_LIST *)ptr; if (temp->next != NULL) temp->next->p_next = temp->p_next; *temp->p_next = temp->next; if (temp->next == NULL) return; temp2 = temp->next; OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next)); } static int sh_init(size_t size, size_t minsize) { int ret; size_t i; size_t pgsize; size_t aligned; #if defined(_WIN32) DWORD flOldProtect; SYSTEM_INFO systemInfo; #endif memset(&sh, 0, sizeof(sh)); /* make sure size is a powers of 2 */ OPENSSL_assert(size > 0); OPENSSL_assert((size & (size - 1)) == 0); if (size == 0 || (size & (size - 1)) != 0) goto err; if (minsize <= sizeof(SH_LIST)) { OPENSSL_assert(sizeof(SH_LIST) <= 65536); /* * Compute the minimum possible allocation size. * This must be a power of 2 and at least as large as the SH_LIST * structure. */ minsize = sizeof(SH_LIST) - 1; minsize |= minsize >> 1; minsize |= minsize >> 2; if (sizeof(SH_LIST) > 16) minsize |= minsize >> 4; if (sizeof(SH_LIST) > 256) minsize |= minsize >> 8; minsize++; } else { /* make sure minsize is a powers of 2 */ OPENSSL_assert((minsize & (minsize - 1)) == 0); if ((minsize & (minsize - 1)) != 0) goto err; } sh.arena_size = size; sh.minsize = minsize; sh.bittable_size = (sh.arena_size / sh.minsize) * 2; /* Prevent allocations of size 0 later on */ if (sh.bittable_size >> 3 == 0) goto err; sh.freelist_size = -1; for (i = sh.bittable_size; i; i >>= 1) sh.freelist_size++; sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *)); OPENSSL_assert(sh.freelist != NULL); if (sh.freelist == NULL) goto err; sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3); OPENSSL_assert(sh.bittable != NULL); if (sh.bittable == NULL) goto err; sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3); OPENSSL_assert(sh.bitmalloc != NULL); if (sh.bitmalloc == NULL) goto err; /* Allocate space for heap, and two extra pages as guards */ #if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE) { # if defined(_SC_PAGE_SIZE) long tmppgsize = sysconf(_SC_PAGE_SIZE); # else long tmppgsize = sysconf(_SC_PAGESIZE); # endif if (tmppgsize < 1) pgsize = PAGE_SIZE; else pgsize = (size_t)tmppgsize; } #elif defined(_WIN32) GetSystemInfo(&systemInfo); pgsize = (size_t)systemInfo.dwPageSize; #else pgsize = PAGE_SIZE; #endif sh.map_size = pgsize + sh.arena_size + pgsize; #if !defined(_WIN32) # ifdef MAP_ANON sh.map_result = mmap(NULL, sh.map_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|MAP_CONCEAL, -1, 0); # else { int fd; sh.map_result = MAP_FAILED; if ((fd = open("/dev/zero", O_RDWR)) >= 0) { sh.map_result = mmap(NULL, sh.map_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); close(fd); } } # endif if (sh.map_result == MAP_FAILED) goto err; #else sh.map_result = VirtualAlloc(NULL, sh.map_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (sh.map_result == NULL) goto err; #endif sh.arena = (char *)(sh.map_result + pgsize); sh_setbit(sh.arena, 0, sh.bittable); sh_add_to_list(&sh.freelist[0], sh.arena); /* Now try to add guard pages and lock into memory. */ ret = 1; #if !defined(_WIN32) /* Starting guard is already aligned from mmap. */ if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0) ret = 2; #else if (VirtualProtect(sh.map_result, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE) ret = 2; #endif /* Ending guard page - need to round up to page boundary */ aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1); #if !defined(_WIN32) if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0) ret = 2; #else if (VirtualProtect(sh.map_result + aligned, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE) ret = 2; #endif #if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2) if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) { if (errno == ENOSYS) { if (mlock(sh.arena, sh.arena_size) < 0) ret = 2; } else { ret = 2; } } #elif defined(_WIN32) if (VirtualLock(sh.arena, sh.arena_size) == FALSE) ret = 2; #else if (mlock(sh.arena, sh.arena_size) < 0) ret = 2; #endif #ifndef NO_MADVISE if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0) ret = 2; #endif return ret; err: sh_done(); return 0; } static void sh_done(void) { OPENSSL_free(sh.freelist); OPENSSL_free(sh.bittable); OPENSSL_free(sh.bitmalloc); #if !defined(_WIN32) if (sh.map_result != MAP_FAILED && sh.map_size) munmap(sh.map_result, sh.map_size); #else if (sh.map_result != NULL && sh.map_size) VirtualFree(sh.map_result, 0, MEM_RELEASE); #endif memset(&sh, 0, sizeof(sh)); } static int sh_allocated(const char *ptr) { return WITHIN_ARENA(ptr) ? 1 : 0; } static char *sh_find_my_buddy(char *ptr, int list) { size_t bit; char *chunk = NULL; bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list); bit ^= 1; if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit)) chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list)); return chunk; } static void *sh_malloc(size_t size) { ossl_ssize_t list, slist; size_t i; char *chunk; if (size > sh.arena_size) return NULL; list = sh.freelist_size - 1; for (i = sh.minsize; i < size; i <<= 1) list--; if (list < 0) return NULL; /* try to find a larger entry to split */ for (slist = list; slist >= 0; slist--) if (sh.freelist[slist] != NULL) break; if (slist < 0) return NULL; /* split larger entry */ while (slist != list) { char *temp = sh.freelist[slist]; /* remove from bigger list */ OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc)); sh_clearbit(temp, slist, sh.bittable); sh_remove_from_list(temp); OPENSSL_assert(temp != sh.freelist[slist]); /* done with bigger list */ slist++; /* add to smaller list */ OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc)); sh_setbit(temp, slist, sh.bittable); sh_add_to_list(&sh.freelist[slist], temp); OPENSSL_assert(sh.freelist[slist] == temp); /* split in 2 */ temp += sh.arena_size >> slist; OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc)); sh_setbit(temp, slist, sh.bittable); sh_add_to_list(&sh.freelist[slist], temp); OPENSSL_assert(sh.freelist[slist] == temp); OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist)); } /* peel off memory to hand back */ chunk = sh.freelist[list]; OPENSSL_assert(sh_testbit(chunk, list, sh.bittable)); sh_setbit(chunk, list, sh.bitmalloc); sh_remove_from_list(chunk); OPENSSL_assert(WITHIN_ARENA(chunk)); /* zero the free list header as a precaution against information leakage */ memset(chunk, 0, sizeof(SH_LIST)); return chunk; } static void sh_free(void *ptr) { size_t list; void *buddy; if (ptr == NULL) return; OPENSSL_assert(WITHIN_ARENA(ptr)); if (!WITHIN_ARENA(ptr)) return; list = sh_getlist(ptr); OPENSSL_assert(sh_testbit(ptr, list, sh.bittable)); sh_clearbit(ptr, list, sh.bitmalloc); sh_add_to_list(&sh.freelist[list], ptr); /* Try to coalesce two adjacent free areas. */ while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) { OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list)); OPENSSL_assert(ptr != NULL); OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc)); sh_clearbit(ptr, list, sh.bittable); sh_remove_from_list(ptr); OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc)); sh_clearbit(buddy, list, sh.bittable); sh_remove_from_list(buddy); list--; /* Zero the higher addressed block's free list pointers */ memset(ptr > buddy ? ptr : buddy, 0, sizeof(SH_LIST)); if (ptr > buddy) ptr = buddy; OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc)); sh_setbit(ptr, list, sh.bittable); sh_add_to_list(&sh.freelist[list], ptr); OPENSSL_assert(sh.freelist[list] == ptr); } } static size_t sh_actual_size(char *ptr) { int list; OPENSSL_assert(WITHIN_ARENA(ptr)); if (!WITHIN_ARENA(ptr)) return 0; list = sh_getlist(ptr); OPENSSL_assert(sh_testbit(ptr, list, sh.bittable)); return sh.arena_size / (ONE << list); } #endif /* OPENSSL_NO_SECURE_MEMORY */
./openssl/crypto/threads_pthread.c
/* * 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 */ /* We need to use the OPENSSL_fork_*() deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/crypto.h> #include "internal/cryptlib.h" #if defined(__sun) # include <atomic.h> #endif #if defined(__apple_build_version__) && __apple_build_version__ < 6000000 /* * OS/X 10.7 and 10.8 had a weird version of clang which has __ATOMIC_ACQUIRE and * __ATOMIC_ACQ_REL but which expects only one parameter for __atomic_is_lock_free() * rather than two which has signature __atomic_is_lock_free(sizeof(_Atomic(T))). * All of this makes impossible to use __atomic_is_lock_free here. * * See: https://github.com/llvm/llvm-project/commit/a4c2602b714e6c6edb98164550a5ae829b2de760 */ #define BROKEN_CLANG_ATOMICS #endif #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && !defined(OPENSSL_SYS_WINDOWS) # if defined(OPENSSL_SYS_UNIX) # include <sys/types.h> # include <unistd.h> #endif # include <assert.h> # ifdef PTHREAD_RWLOCK_INITIALIZER # define USE_RWLOCK # endif CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void) { # ifdef USE_RWLOCK CRYPTO_RWLOCK *lock; if ((lock = CRYPTO_zalloc(sizeof(pthread_rwlock_t), NULL, 0)) == NULL) /* Don't set error, to avoid recursion blowup. */ return NULL; if (pthread_rwlock_init(lock, NULL) != 0) { OPENSSL_free(lock); return NULL; } # else pthread_mutexattr_t attr; CRYPTO_RWLOCK *lock; if ((lock = CRYPTO_zalloc(sizeof(pthread_mutex_t), NULL, 0)) == NULL) /* Don't set error, to avoid recursion blowup. */ return NULL; /* * We don't use recursive mutexes, but try to catch errors if we do. */ pthread_mutexattr_init(&attr); # if !defined (__TANDEM) && !defined (_SPT_MODEL_) # if !defined(NDEBUG) && !defined(OPENSSL_NO_MUTEX_ERRORCHECK) pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); # endif # else /* The SPT Thread Library does not define MUTEX attributes. */ # endif if (pthread_mutex_init(lock, &attr) != 0) { pthread_mutexattr_destroy(&attr); OPENSSL_free(lock); return NULL; } pthread_mutexattr_destroy(&attr); # endif return lock; } __owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK if (pthread_rwlock_rdlock(lock) != 0) return 0; # else if (pthread_mutex_lock(lock) != 0) { assert(errno != EDEADLK && errno != EBUSY); return 0; } # endif return 1; } __owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK if (pthread_rwlock_wrlock(lock) != 0) return 0; # else if (pthread_mutex_lock(lock) != 0) { assert(errno != EDEADLK && errno != EBUSY); return 0; } # endif return 1; } int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK if (pthread_rwlock_unlock(lock) != 0) return 0; # else if (pthread_mutex_unlock(lock) != 0) { assert(errno != EPERM); return 0; } # endif return 1; } void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock) { if (lock == NULL) return; # ifdef USE_RWLOCK pthread_rwlock_destroy(lock); # else pthread_mutex_destroy(lock); # endif OPENSSL_free(lock); return; } int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void)) { if (pthread_once(once, init) != 0) return 0; return 1; } int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *)) { if (pthread_key_create(key, cleanup) != 0) return 0; return 1; } void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key) { return pthread_getspecific(*key); } int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val) { if (pthread_setspecific(*key, val) != 0) return 0; return 1; } int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key) { if (pthread_key_delete(*key) != 0) return 0; return 1; } CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void) { return pthread_self(); } int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b) { return pthread_equal(a, b); } int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*val), val)) { *ret = __atomic_add_fetch(val, amount, __ATOMIC_ACQ_REL); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (ret != NULL) { *ret = atomic_add_int_nv((volatile unsigned int *)val, amount); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_write_lock(lock)) return 0; *val += amount; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*val), val)) { *ret = __atomic_or_fetch(val, op, __ATOMIC_ACQ_REL); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (ret != NULL) { *ret = atomic_or_64_nv(val, op); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_write_lock(lock)) return 0; *val |= op; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*val), val)) { __atomic_load(val, ret, __ATOMIC_ACQUIRE); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (ret != NULL) { *ret = atomic_or_64_nv(val, 0); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_read_lock(lock)) return 0; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock) { # if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) && !defined(BROKEN_CLANG_ATOMICS) if (__atomic_is_lock_free(sizeof(*val), val)) { __atomic_load(val, ret, __ATOMIC_ACQUIRE); return 1; } # elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11)) /* This will work for all future Solaris versions. */ if (ret != NULL) { *ret = (int *)atomic_or_uint_nv((unsigned int *)val, 0); return 1; } # endif if (lock == NULL || !CRYPTO_THREAD_read_lock(lock)) return 0; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; } # ifndef FIPS_MODULE int openssl_init_fork_handlers(void) { return 1; } # endif /* FIPS_MODULE */ int openssl_get_fork_id(void) { return getpid(); } #endif
./openssl/crypto/punycode.c
/* * 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 */ #include <stddef.h> #include <stdio.h> #include <openssl/e_os2.h> #include "crypto/punycode.h" #include "internal/common.h" /* for HAS_PREFIX */ #include "internal/packet.h" /* for WPACKET */ static const unsigned int base = 36; static const unsigned int tmin = 1; static const unsigned int tmax = 26; static const unsigned int skew = 38; static const unsigned int damp = 700; static const unsigned int initial_bias = 72; static const unsigned int initial_n = 0x80; static const unsigned int maxint = 0xFFFFFFFF; static const char delimiter = '-'; #define LABEL_BUF_SIZE 512 /*- * Pseudocode: * * function adapt(delta,numpoints,firsttime): * if firsttime then let delta = delta div damp * else let delta = delta div 2 * let delta = delta + (delta div numpoints) * let k = 0 * while delta > ((base - tmin) * tmax) div 2 do begin * let delta = delta div (base - tmin) * let k = k + base * end * return k + (((base - tmin + 1) * delta) div (delta + skew)) */ static int adapt(unsigned int delta, unsigned int numpoints, unsigned int firsttime) { unsigned int k = 0; delta = (firsttime) ? delta / damp : delta / 2; delta = delta + delta / numpoints; while (delta > ((base - tmin) * tmax) / 2) { delta = delta / (base - tmin); k = k + base; } return k + (((base - tmin + 1) * delta) / (delta + skew)); } static ossl_inline int is_basic(unsigned int a) { return (a < 0x80) ? 1 : 0; } /*- * code points digit-values * ------------ ---------------------- * 41..5A (A-Z) = 0 to 25, respectively * 61..7A (a-z) = 0 to 25, respectively * 30..39 (0-9) = 26 to 35, respectively */ static ossl_inline int digit_decoded(const unsigned char a) { if (a >= 0x41 && a <= 0x5A) return a - 0x41; if (a >= 0x61 && a <= 0x7A) return a - 0x61; if (a >= 0x30 && a <= 0x39) return a - 0x30 + 26; return -1; } /*- * Pseudocode: * * function ossl_punycode_decode * let n = initial_n * let i = 0 * let bias = initial_bias * let output = an empty string indexed from 0 * consume all code points before the last delimiter (if there is one) * and copy them to output, fail on any non-basic code point * if more than zero code points were consumed then consume one more * (which will be the last delimiter) * while the input is not exhausted do begin * let oldi = i * let w = 1 * for k = base to infinity in steps of base do begin * consume a code point, or fail if there was none to consume * let digit = the code point's digit-value, fail if it has none * let i = i + digit * w, fail on overflow * let t = tmin if k <= bias {+ tmin}, or * tmax if k >= bias + tmax, or k - bias otherwise * if digit < t then break * let w = w * (base - t), fail on overflow * end * let bias = adapt(i - oldi, length(output) + 1, test oldi is 0?) * let n = n + i div (length(output) + 1), fail on overflow * let i = i mod (length(output) + 1) * {if n is a basic code point then fail} * insert n into output at position i * increment i * end */ int ossl_punycode_decode(const char *pEncoded, const size_t enc_len, unsigned int *pDecoded, unsigned int *pout_length) { unsigned int n = initial_n; unsigned int i = 0; unsigned int bias = initial_bias; size_t processed_in = 0, written_out = 0; unsigned int max_out = *pout_length; unsigned int basic_count = 0; unsigned int loop; for (loop = 0; loop < enc_len; loop++) { if (pEncoded[loop] == delimiter) basic_count = loop; } if (basic_count > 0) { if (basic_count > max_out) return 0; for (loop = 0; loop < basic_count; loop++) { if (is_basic(pEncoded[loop]) == 0) return 0; pDecoded[loop] = pEncoded[loop]; written_out++; } processed_in = basic_count + 1; } for (loop = processed_in; loop < enc_len;) { unsigned int oldi = i; unsigned int w = 1; unsigned int k, t; int digit; for (k = base;; k += base) { if (loop >= enc_len) return 0; digit = digit_decoded(pEncoded[loop]); loop++; if (digit < 0) return 0; if ((unsigned int)digit > (maxint - i) / w) return 0; i = i + digit * w; t = (k <= bias) ? tmin : (k >= bias + tmax) ? tmax : k - bias; if ((unsigned int)digit < t) break; if (w > maxint / (base - t)) return 0; w = w * (base - t); } bias = adapt(i - oldi, written_out + 1, (oldi == 0)); if (i / (written_out + 1) > maxint - n) return 0; n = n + i / (written_out + 1); i %= (written_out + 1); if (written_out >= max_out) return 0; memmove(pDecoded + i + 1, pDecoded + i, (written_out - i) * sizeof(*pDecoded)); pDecoded[i] = n; i++; written_out++; } *pout_length = written_out; return 1; } /* * Encode a code point using UTF-8 * return number of bytes on success, 0 on failure * (also produces U+FFFD, which uses 3 bytes on failure) */ static int codepoint2utf8(unsigned char *out, unsigned long utf) { if (utf <= 0x7F) { /* Plain ASCII */ out[0] = (unsigned char)utf; out[1] = 0; return 1; } else if (utf <= 0x07FF) { /* 2-byte unicode */ out[0] = (unsigned char)(((utf >> 6) & 0x1F) | 0xC0); out[1] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80); out[2] = 0; return 2; } else if (utf <= 0xFFFF) { /* 3-byte unicode */ out[0] = (unsigned char)(((utf >> 12) & 0x0F) | 0xE0); out[1] = (unsigned char)(((utf >> 6) & 0x3F) | 0x80); out[2] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80); out[3] = 0; return 3; } else if (utf <= 0x10FFFF) { /* 4-byte unicode */ out[0] = (unsigned char)(((utf >> 18) & 0x07) | 0xF0); out[1] = (unsigned char)(((utf >> 12) & 0x3F) | 0x80); out[2] = (unsigned char)(((utf >> 6) & 0x3F) | 0x80); out[3] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80); out[4] = 0; return 4; } else { /* error - use replacement character */ out[0] = (unsigned char)0xEF; out[1] = (unsigned char)0xBF; out[2] = (unsigned char)0xBD; out[3] = 0; return 0; } } /*- * Return values: * 1 - ok * 0 - ok but buf was too short * -1 - bad string passed or other error */ int ossl_a2ulabel(const char *in, char *out, size_t outlen) { /*- * Domain name has some parts consisting of ASCII chars joined with dot. * If a part is shorter than 5 chars, it becomes U-label as is. * If it does not start with xn--, it becomes U-label as is. * Otherwise we try to decode it. */ const char *inptr = in; int result = 1; unsigned int i; unsigned int buf[LABEL_BUF_SIZE]; /* It's a hostname */ WPACKET pkt; /* Internal API, so should not fail */ if (!ossl_assert(out != NULL)) return -1; if (!WPACKET_init_static_len(&pkt, (unsigned char *)out, outlen, 0)) return -1; while (1) { char *tmpptr = strchr(inptr, '.'); size_t delta = tmpptr != NULL ? (size_t)(tmpptr - inptr) : strlen(inptr); if (!HAS_PREFIX(inptr, "xn--")) { if (!WPACKET_memcpy(&pkt, inptr, delta)) result = 0; } else { unsigned int bufsize = LABEL_BUF_SIZE; if (ossl_punycode_decode(inptr + 4, delta - 4, buf, &bufsize) <= 0) { result = -1; goto end; } for (i = 0; i < bufsize; i++) { unsigned char seed[6]; size_t utfsize = codepoint2utf8(seed, buf[i]); if (utfsize == 0) { result = -1; goto end; } if (!WPACKET_memcpy(&pkt, seed, utfsize)) result = 0; } } if (tmpptr == NULL) break; if (!WPACKET_put_bytes_u8(&pkt, '.')) result = 0; inptr = tmpptr + 1; } if (!WPACKET_put_bytes_u8(&pkt, '\0')) result = 0; end: WPACKET_cleanup(&pkt); return result; }
./openssl/crypto/params.c
/* * Copyright 2019-2023 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 */ #include <string.h> #include <openssl/params.h> #include <openssl/err.h> #include "internal/thread_once.h" #include "internal/numbers.h" #include "internal/endian.h" #include "internal/params.h" #include "internal/packet.h" /* Shortcuts for raising errors that are widely used */ #define err_unsigned_negative \ ERR_raise(ERR_LIB_CRYPTO, \ CRYPTO_R_PARAM_UNSIGNED_INTEGER_NEGATIVE_VALUE_UNSUPPORTED) #define err_out_of_range \ ERR_raise(ERR_LIB_CRYPTO, \ CRYPTO_R_PARAM_VALUE_TOO_LARGE_FOR_DESTINATION) #define err_inexact \ ERR_raise(ERR_LIB_CRYPTO, \ CRYPTO_R_PARAM_CANNOT_BE_REPRESENTED_EXACTLY) #define err_not_integer \ ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_PARAM_NOT_INTEGER_TYPE) #define err_too_small \ ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER) #define err_bad_type \ ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_PARAM_OF_INCOMPATIBLE_TYPE) #define err_null_argument \ ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER) #define err_unsupported_real \ ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_PARAM_UNSUPPORTED_FLOATING_POINT_FORMAT) #ifndef OPENSSL_SYS_UEFI /* * Return the number of bits in the mantissa of a double. This is used to * shift a larger integral value to determine if it will exactly fit into a * double. */ static unsigned int real_shift(void) { return sizeof(double) == 4 ? 24 : 53; } #endif OSSL_PARAM *OSSL_PARAM_locate(OSSL_PARAM *p, const char *key) { if (p != NULL && key != NULL) for (; p->key != NULL; p++) if (strcmp(key, p->key) == 0) return p; return NULL; } const OSSL_PARAM *OSSL_PARAM_locate_const(const OSSL_PARAM *p, const char *key) { return OSSL_PARAM_locate((OSSL_PARAM *)p, key); } static OSSL_PARAM ossl_param_construct(const char *key, unsigned int data_type, void *data, size_t data_size) { OSSL_PARAM res; res.key = key; res.data_type = data_type; res.data = data; res.data_size = data_size; res.return_size = OSSL_PARAM_UNMODIFIED; return res; } int OSSL_PARAM_modified(const OSSL_PARAM *p) { return p != NULL && p->return_size != OSSL_PARAM_UNMODIFIED; } void OSSL_PARAM_set_all_unmodified(OSSL_PARAM *p) { if (p != NULL) while (p->key != NULL) p++->return_size = OSSL_PARAM_UNMODIFIED; } /* Return non-zero if the signed number is negative */ static int is_negative(const void *number, size_t s) { const unsigned char *n = number; DECLARE_IS_ENDIAN; return 0x80 & (IS_BIG_ENDIAN ? n[0] : n[s - 1]); } /* Check that all the bytes specified match the expected sign byte */ static int check_sign_bytes(const unsigned char *p, size_t n, unsigned char s) { size_t i; for (i = 0; i < n; i++) if (p[i] != s) return 0; return 1; } /* * Copy an integer to another integer. * Handle different length integers and signed and unsigned integers. * Both integers are in native byte ordering. */ static int copy_integer(unsigned char *dest, size_t dest_len, const unsigned char *src, size_t src_len, unsigned char pad, int signed_int) { size_t n; DECLARE_IS_ENDIAN; if (IS_BIG_ENDIAN) { if (src_len < dest_len) { n = dest_len - src_len; memset(dest, pad, n); memcpy(dest + n, src, src_len); } else { n = src_len - dest_len; if (!check_sign_bytes(src, n, pad) /* * Shortening a signed value must retain the correct sign. * Avoiding this kind of thing: -253 = 0xff03 -> 0x03 = 3 */ || (signed_int && ((pad ^ src[n]) & 0x80) != 0)) { err_out_of_range; return 0; } memcpy(dest, src + n, dest_len); } } else /* IS_LITTLE_ENDIAN */ { if (src_len < dest_len) { n = dest_len - src_len; memset(dest + src_len, pad, n); memcpy(dest, src, src_len); } else { n = src_len - dest_len; if (!check_sign_bytes(src + dest_len, n, pad) /* * Shortening a signed value must retain the correct sign. * Avoiding this kind of thing: 130 = 0x0082 -> 0x82 = -126 */ || (signed_int && ((pad ^ src[dest_len - 1]) & 0x80) != 0)) { err_out_of_range; return 0; } memcpy(dest, src, dest_len); } } return 1; } /* Copy a signed number to a signed number of possibly different length */ static int signed_from_signed(void *dest, size_t dest_len, const void *src, size_t src_len) { return copy_integer(dest, dest_len, src, src_len, is_negative(src, src_len) ? 0xff : 0, 1); } /* Copy an unsigned number to a signed number of possibly different length */ static int signed_from_unsigned(void *dest, size_t dest_len, const void *src, size_t src_len) { return copy_integer(dest, dest_len, src, src_len, 0, 1); } /* Copy a signed number to an unsigned number of possibly different length */ static int unsigned_from_signed(void *dest, size_t dest_len, const void *src, size_t src_len) { if (is_negative(src, src_len)) { err_unsigned_negative; return 0; } return copy_integer(dest, dest_len, src, src_len, 0, 0); } /* Copy an unsigned number to an unsigned number of possibly different length */ static int unsigned_from_unsigned(void *dest, size_t dest_len, const void *src, size_t src_len) { return copy_integer(dest, dest_len, src, src_len, 0, 0); } /* General purpose get integer parameter call that handles odd sizes */ static int general_get_int(const OSSL_PARAM *p, void *val, size_t val_size) { if (p->data == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_INTEGER) return signed_from_signed(val, val_size, p->data, p->data_size); if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) return signed_from_unsigned(val, val_size, p->data, p->data_size); err_not_integer; return 0; } /* General purpose set integer parameter call that handles odd sizes */ static int general_set_int(OSSL_PARAM *p, void *val, size_t val_size) { int r = 0; p->return_size = val_size; /* Expected size */ if (p->data == NULL) return 1; if (p->data_type == OSSL_PARAM_INTEGER) r = signed_from_signed(p->data, p->data_size, val, val_size); else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) r = unsigned_from_signed(p->data, p->data_size, val, val_size); else err_not_integer; p->return_size = r ? p->data_size : val_size; return r; } /* General purpose get unsigned integer parameter call that handles odd sizes */ static int general_get_uint(const OSSL_PARAM *p, void *val, size_t val_size) { if (p->data == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_INTEGER) return unsigned_from_signed(val, val_size, p->data, p->data_size); if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) return unsigned_from_unsigned(val, val_size, p->data, p->data_size); err_not_integer; return 0; } /* General purpose set unsigned integer parameter call that handles odd sizes */ static int general_set_uint(OSSL_PARAM *p, void *val, size_t val_size) { int r = 0; p->return_size = val_size; /* Expected size */ if (p->data == NULL) return 1; if (p->data_type == OSSL_PARAM_INTEGER) r = signed_from_unsigned(p->data, p->data_size, val, val_size); else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) r = unsigned_from_unsigned(p->data, p->data_size, val, val_size); else err_not_integer; p->return_size = r ? p->data_size : val_size; return r; } int OSSL_PARAM_get_int(const OSSL_PARAM *p, int *val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(int)) { case sizeof(int32_t): return OSSL_PARAM_get_int32(p, (int32_t *)val); case sizeof(int64_t): return OSSL_PARAM_get_int64(p, (int64_t *)val); } #endif return general_get_int(p, val, sizeof(*val)); } int OSSL_PARAM_set_int(OSSL_PARAM *p, int val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(int)) { case sizeof(int32_t): return OSSL_PARAM_set_int32(p, (int32_t)val); case sizeof(int64_t): return OSSL_PARAM_set_int64(p, (int64_t)val); } #endif return general_set_int(p, &val, sizeof(val)); } OSSL_PARAM OSSL_PARAM_construct_int(const char *key, int *buf) { return ossl_param_construct(key, OSSL_PARAM_INTEGER, buf, sizeof(int)); } int OSSL_PARAM_get_uint(const OSSL_PARAM *p, unsigned int *val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(unsigned int)) { case sizeof(uint32_t): return OSSL_PARAM_get_uint32(p, (uint32_t *)val); case sizeof(uint64_t): return OSSL_PARAM_get_uint64(p, (uint64_t *)val); } #endif return general_get_uint(p, val, sizeof(*val)); } int OSSL_PARAM_set_uint(OSSL_PARAM *p, unsigned int val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(unsigned int)) { case sizeof(uint32_t): return OSSL_PARAM_set_uint32(p, (uint32_t)val); case sizeof(uint64_t): return OSSL_PARAM_set_uint64(p, (uint64_t)val); } #endif return general_set_uint(p, &val, sizeof(val)); } OSSL_PARAM OSSL_PARAM_construct_uint(const char *key, unsigned int *buf) { return ossl_param_construct(key, OSSL_PARAM_UNSIGNED_INTEGER, buf, sizeof(unsigned int)); } int OSSL_PARAM_get_long(const OSSL_PARAM *p, long int *val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(long int)) { case sizeof(int32_t): return OSSL_PARAM_get_int32(p, (int32_t *)val); case sizeof(int64_t): return OSSL_PARAM_get_int64(p, (int64_t *)val); } #endif return general_get_int(p, val, sizeof(*val)); } int OSSL_PARAM_set_long(OSSL_PARAM *p, long int val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(long int)) { case sizeof(int32_t): return OSSL_PARAM_set_int32(p, (int32_t)val); case sizeof(int64_t): return OSSL_PARAM_set_int64(p, (int64_t)val); } #endif return general_set_int(p, &val, sizeof(val)); } OSSL_PARAM OSSL_PARAM_construct_long(const char *key, long int *buf) { return ossl_param_construct(key, OSSL_PARAM_INTEGER, buf, sizeof(long int)); } int OSSL_PARAM_get_ulong(const OSSL_PARAM *p, unsigned long int *val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(unsigned long int)) { case sizeof(uint32_t): return OSSL_PARAM_get_uint32(p, (uint32_t *)val); case sizeof(uint64_t): return OSSL_PARAM_get_uint64(p, (uint64_t *)val); } #endif return general_get_uint(p, val, sizeof(*val)); } int OSSL_PARAM_set_ulong(OSSL_PARAM *p, unsigned long int val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(unsigned long int)) { case sizeof(uint32_t): return OSSL_PARAM_set_uint32(p, (uint32_t)val); case sizeof(uint64_t): return OSSL_PARAM_set_uint64(p, (uint64_t)val); } #endif return general_set_uint(p, &val, sizeof(val)); } OSSL_PARAM OSSL_PARAM_construct_ulong(const char *key, unsigned long int *buf) { return ossl_param_construct(key, OSSL_PARAM_UNSIGNED_INTEGER, buf, sizeof(unsigned long int)); } int OSSL_PARAM_get_int32(const OSSL_PARAM *p, int32_t *val) { if (val == NULL || p == NULL) { err_null_argument; return 0; } if (p->data == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT int64_t i64; switch (p->data_size) { case sizeof(int32_t): *val = *(const int32_t *)p->data; return 1; case sizeof(int64_t): i64 = *(const int64_t *)p->data; if (i64 >= INT32_MIN && i64 <= INT32_MAX) { *val = (int32_t)i64; return 1; } err_out_of_range; return 0; } #endif return general_get_int(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT uint32_t u32; uint64_t u64; switch (p->data_size) { case sizeof(uint32_t): u32 = *(const uint32_t *)p->data; if (u32 <= INT32_MAX) { *val = (int32_t)u32; return 1; } err_out_of_range; return 0; case sizeof(uint64_t): u64 = *(const uint64_t *)p->data; if (u64 <= INT32_MAX) { *val = (int32_t)u64; return 1; } err_out_of_range; return 0; } #endif return general_get_int(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI double d; switch (p->data_size) { case sizeof(double): d = *(const double *)p->data; if (d >= INT32_MIN && d <= INT32_MAX && d == (int32_t)d) { *val = (int32_t)d; return 1; } err_out_of_range; return 0; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } int OSSL_PARAM_set_int32(OSSL_PARAM *p, int32_t val) { uint32_t u32; unsigned int shift; if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(int32_t); /* Minimum expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(int32_t): *(int32_t *)p->data = val; return 1; case sizeof(int64_t): p->return_size = sizeof(int64_t); *(int64_t *)p->data = (int64_t)val; return 1; } #endif return general_set_int(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER && val >= 0) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(uint32_t); /* Minimum expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(uint32_t): *(uint32_t *)p->data = (uint32_t)val; return 1; case sizeof(uint64_t): p->return_size = sizeof(uint64_t); *(uint64_t *)p->data = (uint64_t)val; return 1; } #endif return general_set_int(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI p->return_size = sizeof(double); if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(double): shift = real_shift(); if (shift < 8 * sizeof(val) - 1) { u32 = val < 0 ? -val : val; if ((u32 >> shift) != 0) { err_inexact; return 0; } } *(double *)p->data = (double)val; return 1; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } OSSL_PARAM OSSL_PARAM_construct_int32(const char *key, int32_t *buf) { return ossl_param_construct(key, OSSL_PARAM_INTEGER, buf, sizeof(int32_t)); } int OSSL_PARAM_get_uint32(const OSSL_PARAM *p, uint32_t *val) { if (val == NULL || p == NULL) { err_null_argument; return 0; } if (p->data == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT uint64_t u64; switch (p->data_size) { case sizeof(uint32_t): *val = *(const uint32_t *)p->data; return 1; case sizeof(uint64_t): u64 = *(const uint64_t *)p->data; if (u64 <= UINT32_MAX) { *val = (uint32_t)u64; return 1; } err_out_of_range; return 0; } #endif return general_get_uint(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT int32_t i32; int64_t i64; switch (p->data_size) { case sizeof(int32_t): i32 = *(const int32_t *)p->data; if (i32 >= 0) { *val = i32; return 1; } err_unsigned_negative; return 0; case sizeof(int64_t): i64 = *(const int64_t *)p->data; if (i64 >= 0 && i64 <= UINT32_MAX) { *val = (uint32_t)i64; return 1; } if (i64 < 0) err_unsigned_negative; else err_out_of_range; return 0; } #endif return general_get_uint(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI double d; switch (p->data_size) { case sizeof(double): d = *(const double *)p->data; if (d >= 0 && d <= UINT32_MAX && d == (uint32_t)d) { *val = (uint32_t)d; return 1; } err_inexact; return 0; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } int OSSL_PARAM_set_uint32(OSSL_PARAM *p, uint32_t val) { unsigned int shift; if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(uint32_t); /* Minimum expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(uint32_t): *(uint32_t *)p->data = val; return 1; case sizeof(uint64_t): p->return_size = sizeof(uint64_t); *(uint64_t *)p->data = val; return 1; } #endif return general_set_uint(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(int32_t); /* Minimum expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(int32_t): if (val <= INT32_MAX) { *(int32_t *)p->data = (int32_t)val; return 1; } err_out_of_range; return 0; case sizeof(int64_t): p->return_size = sizeof(int64_t); *(int64_t *)p->data = (int64_t)val; return 1; } #endif return general_set_uint(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI p->return_size = sizeof(double); if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(double): shift = real_shift(); if (shift < 8 * sizeof(val) && (val >> shift) != 0) { err_inexact; return 0; } *(double *)p->data = (double)val; return 1; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } OSSL_PARAM OSSL_PARAM_construct_uint32(const char *key, uint32_t *buf) { return ossl_param_construct(key, OSSL_PARAM_UNSIGNED_INTEGER, buf, sizeof(uint32_t)); } int OSSL_PARAM_get_int64(const OSSL_PARAM *p, int64_t *val) { if (val == NULL || p == NULL) { err_null_argument; return 0; } if (p->data == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (p->data_size) { case sizeof(int32_t): *val = *(const int32_t *)p->data; return 1; case sizeof(int64_t): *val = *(const int64_t *)p->data; return 1; } #endif return general_get_int(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT uint64_t u64; switch (p->data_size) { case sizeof(uint32_t): *val = *(const uint32_t *)p->data; return 1; case sizeof(uint64_t): u64 = *(const uint64_t *)p->data; if (u64 <= INT64_MAX) { *val = (int64_t)u64; return 1; } err_out_of_range; return 0; } #endif return general_get_int(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI double d; switch (p->data_size) { case sizeof(double): d = *(const double *)p->data; if (d >= INT64_MIN /* * By subtracting 65535 (2^16-1) we cancel the low order * 15 bits of INT64_MAX to avoid using imprecise floating * point values. */ && d < (double)(INT64_MAX - 65535) + 65536.0 && d == (int64_t)d) { *val = (int64_t)d; return 1; } err_inexact; return 0; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } int OSSL_PARAM_set_int64(OSSL_PARAM *p, int64_t val) { if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(int64_t); /* Expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(int32_t): if (val >= INT32_MIN && val <= INT32_MAX) { p->return_size = sizeof(int32_t); *(int32_t *)p->data = (int32_t)val; return 1; } err_out_of_range; return 0; case sizeof(int64_t): *(int64_t *)p->data = val; return 1; } #endif return general_set_int(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER && val >= 0) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(uint64_t); /* Expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(uint32_t): if (val <= UINT32_MAX) { p->return_size = sizeof(uint32_t); *(uint32_t *)p->data = (uint32_t)val; return 1; } err_out_of_range; return 0; case sizeof(uint64_t): *(uint64_t *)p->data = (uint64_t)val; return 1; } #endif return general_set_int(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI uint64_t u64; p->return_size = sizeof(double); if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(double): u64 = val < 0 ? -val : val; if ((u64 >> real_shift()) == 0) { *(double *)p->data = (double)val; return 1; } err_inexact; return 0; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } OSSL_PARAM OSSL_PARAM_construct_int64(const char *key, int64_t *buf) { return ossl_param_construct(key, OSSL_PARAM_INTEGER, buf, sizeof(int64_t)); } int OSSL_PARAM_get_uint64(const OSSL_PARAM *p, uint64_t *val) { if (val == NULL || p == NULL) { err_null_argument; return 0; } if (p->data == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (p->data_size) { case sizeof(uint32_t): *val = *(const uint32_t *)p->data; return 1; case sizeof(uint64_t): *val = *(const uint64_t *)p->data; return 1; } #endif return general_get_uint(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT int32_t i32; int64_t i64; switch (p->data_size) { case sizeof(int32_t): i32 = *(const int32_t *)p->data; if (i32 >= 0) { *val = (uint64_t)i32; return 1; } err_unsigned_negative; return 0; case sizeof(int64_t): i64 = *(const int64_t *)p->data; if (i64 >= 0) { *val = (uint64_t)i64; return 1; } err_unsigned_negative; return 0; } #endif return general_get_uint(p, val, sizeof(*val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI double d; switch (p->data_size) { case sizeof(double): d = *(const double *)p->data; if (d >= 0 /* * By subtracting 65535 (2^16-1) we cancel the low order * 15 bits of UINT64_MAX to avoid using imprecise floating * point values. */ && d < (double)(UINT64_MAX - 65535) + 65536.0 && d == (uint64_t)d) { *val = (uint64_t)d; return 1; } err_inexact; return 0; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } int OSSL_PARAM_set_uint64(OSSL_PARAM *p, uint64_t val) { if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(uint64_t); /* Expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(uint32_t): if (val <= UINT32_MAX) { p->return_size = sizeof(uint32_t); *(uint32_t *)p->data = (uint32_t)val; return 1; } err_out_of_range; return 0; case sizeof(uint64_t): *(uint64_t *)p->data = val; return 1; } #endif return general_set_uint(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_INTEGER) { #ifndef OPENSSL_SMALL_FOOTPRINT p->return_size = sizeof(int64_t); /* Expected size */ if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(int32_t): if (val <= INT32_MAX) { p->return_size = sizeof(int32_t); *(int32_t *)p->data = (int32_t)val; return 1; } err_out_of_range; return 0; case sizeof(int64_t): if (val <= INT64_MAX) { *(int64_t *)p->data = (int64_t)val; return 1; } err_out_of_range; return 0; } #endif return general_set_uint(p, &val, sizeof(val)); } else if (p->data_type == OSSL_PARAM_REAL) { #ifndef OPENSSL_SYS_UEFI p->return_size = sizeof(double); switch (p->data_size) { case sizeof(double): if ((val >> real_shift()) == 0) { *(double *)p->data = (double)val; return 1; } err_inexact; return 0; } err_unsupported_real; return 0; #endif } err_bad_type; return 0; } OSSL_PARAM OSSL_PARAM_construct_uint64(const char *key, uint64_t *buf) { return ossl_param_construct(key, OSSL_PARAM_UNSIGNED_INTEGER, buf, sizeof(uint64_t)); } int OSSL_PARAM_get_size_t(const OSSL_PARAM *p, size_t *val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(size_t)) { case sizeof(uint32_t): return OSSL_PARAM_get_uint32(p, (uint32_t *)val); case sizeof(uint64_t): return OSSL_PARAM_get_uint64(p, (uint64_t *)val); } #endif return general_get_uint(p, val, sizeof(*val)); } int OSSL_PARAM_set_size_t(OSSL_PARAM *p, size_t val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(size_t)) { case sizeof(uint32_t): return OSSL_PARAM_set_uint32(p, (uint32_t)val); case sizeof(uint64_t): return OSSL_PARAM_set_uint64(p, (uint64_t)val); } #endif return general_set_uint(p, &val, sizeof(val)); } OSSL_PARAM OSSL_PARAM_construct_size_t(const char *key, size_t *buf) { return ossl_param_construct(key, OSSL_PARAM_UNSIGNED_INTEGER, buf, sizeof(size_t)); } int OSSL_PARAM_get_time_t(const OSSL_PARAM *p, time_t *val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(time_t)) { case sizeof(int32_t): return OSSL_PARAM_get_int32(p, (int32_t *)val); case sizeof(int64_t): return OSSL_PARAM_get_int64(p, (int64_t *)val); } #endif return general_get_int(p, val, sizeof(*val)); } int OSSL_PARAM_set_time_t(OSSL_PARAM *p, time_t val) { #ifndef OPENSSL_SMALL_FOOTPRINT switch (sizeof(time_t)) { case sizeof(int32_t): return OSSL_PARAM_set_int32(p, (int32_t)val); case sizeof(int64_t): return OSSL_PARAM_set_int64(p, (int64_t)val); } #endif return general_set_int(p, &val, sizeof(val)); } OSSL_PARAM OSSL_PARAM_construct_time_t(const char *key, time_t *buf) { return ossl_param_construct(key, OSSL_PARAM_INTEGER, buf, sizeof(time_t)); } int OSSL_PARAM_get_BN(const OSSL_PARAM *p, BIGNUM **val) { BIGNUM *b = NULL; if (val == NULL || p == NULL || p->data == NULL) { err_null_argument; return 0; } switch (p->data_type) { case OSSL_PARAM_UNSIGNED_INTEGER: b = BN_native2bn(p->data, (int)p->data_size, *val); break; case OSSL_PARAM_INTEGER: b = BN_signed_native2bn(p->data, (int)p->data_size, *val); break; default: err_bad_type; break; } if (b == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_BN_LIB); return 0; } *val = b; return 1; } int OSSL_PARAM_set_BN(OSSL_PARAM *p, const BIGNUM *val) { size_t bytes; if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (val == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER && BN_is_negative(val)) { err_bad_type; return 0; } bytes = (size_t)BN_num_bytes(val); /* We add 1 byte for signed numbers, to make space for a sign extension */ if (p->data_type == OSSL_PARAM_INTEGER) bytes++; /* We make sure that at least one byte is used, so zero is properly set */ if (bytes == 0) bytes++; p->return_size = bytes; if (p->data == NULL) return 1; if (p->data_size >= bytes) { p->return_size = p->data_size; switch (p->data_type) { case OSSL_PARAM_UNSIGNED_INTEGER: if (BN_bn2nativepad(val, p->data, p->data_size) >= 0) return 1; ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_INTEGER_OVERFLOW); break; case OSSL_PARAM_INTEGER: if (BN_signed_bn2native(val, p->data, p->data_size) >= 0) return 1; ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_INTEGER_OVERFLOW); break; default: err_bad_type; break; } return 0; } err_too_small; return 0; } OSSL_PARAM OSSL_PARAM_construct_BN(const char *key, unsigned char *buf, size_t bsize) { return ossl_param_construct(key, OSSL_PARAM_UNSIGNED_INTEGER, buf, bsize); } #ifndef OPENSSL_SYS_UEFI int OSSL_PARAM_get_double(const OSSL_PARAM *p, double *val) { int64_t i64; uint64_t u64; if (val == NULL || p == NULL || p->data == NULL) { err_null_argument; return 0; } if (p->data_type == OSSL_PARAM_REAL) { switch (p->data_size) { case sizeof(double): *val = *(const double *)p->data; return 1; } err_unsupported_real; return 0; } else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { switch (p->data_size) { case sizeof(uint32_t): *val = *(const uint32_t *)p->data; return 1; case sizeof(uint64_t): u64 = *(const uint64_t *)p->data; if ((u64 >> real_shift()) == 0) { *val = (double)u64; return 1; } err_inexact; return 0; } } else if (p->data_type == OSSL_PARAM_INTEGER) { switch (p->data_size) { case sizeof(int32_t): *val = *(const int32_t *)p->data; return 1; case sizeof(int64_t): i64 = *(const int64_t *)p->data; u64 = i64 < 0 ? -i64 : i64; if ((u64 >> real_shift()) == 0) { *val = 0.0 + i64; return 1; } err_inexact; return 0; } } err_bad_type; return 0; } int OSSL_PARAM_set_double(OSSL_PARAM *p, double val) { if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (p->data_type == OSSL_PARAM_REAL) { p->return_size = sizeof(double); if (p->data == NULL) return 1; switch (p->data_size) { case sizeof(double): *(double *)p->data = val; return 1; } err_unsupported_real; return 0; } else if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER) { p->return_size = sizeof(double); if (p->data == NULL) return 1; if (val != (uint64_t)val) { err_inexact; return 0; } switch (p->data_size) { case sizeof(uint32_t): if (val >= 0 && val <= UINT32_MAX) { p->return_size = sizeof(uint32_t); *(uint32_t *)p->data = (uint32_t)val; return 1; } err_out_of_range; return 0; case sizeof(uint64_t): if (val >= 0 /* * By subtracting 65535 (2^16-1) we cancel the low order * 15 bits of UINT64_MAX to avoid using imprecise floating * point values. */ && val < (double)(UINT64_MAX - 65535) + 65536.0) { p->return_size = sizeof(uint64_t); *(uint64_t *)p->data = (uint64_t)val; return 1; } err_out_of_range; return 0; } } else if (p->data_type == OSSL_PARAM_INTEGER) { p->return_size = sizeof(double); if (p->data == NULL) return 1; if (val != (int64_t)val) { err_inexact; return 0; } switch (p->data_size) { case sizeof(int32_t): if (val >= INT32_MIN && val <= INT32_MAX) { p->return_size = sizeof(int32_t); *(int32_t *)p->data = (int32_t)val; return 1; } err_out_of_range; return 0; case sizeof(int64_t): if (val >= INT64_MIN /* * By subtracting 65535 (2^16-1) we cancel the low order * 15 bits of INT64_MAX to avoid using imprecise floating * point values. */ && val < (double)(INT64_MAX - 65535) + 65536.0) { p->return_size = sizeof(int64_t); *(int64_t *)p->data = (int64_t)val; return 1; } err_out_of_range; return 0; } } err_bad_type; return 0; } OSSL_PARAM OSSL_PARAM_construct_double(const char *key, double *buf) { return ossl_param_construct(key, OSSL_PARAM_REAL, buf, sizeof(double)); } #endif static int get_string_internal(const OSSL_PARAM *p, void **val, size_t *max_len, size_t *used_len, unsigned int type) { size_t sz, alloc_sz; if ((val == NULL && used_len == NULL) || p == NULL) { err_null_argument; return 0; } if (p->data_type != type) { err_bad_type; return 0; } sz = p->data_size; /* * If the input size is 0, or the input string needs NUL byte * termination, allocate an extra byte. */ alloc_sz = sz + (type == OSSL_PARAM_UTF8_STRING || sz == 0); if (used_len != NULL) *used_len = sz; if (p->data == NULL) { err_null_argument; return 0; } if (val == NULL) return 1; if (*val == NULL) { char *const q = OPENSSL_malloc(alloc_sz); if (q == NULL) return 0; *val = q; *max_len = alloc_sz; } if (*max_len < sz) { err_too_small; return 0; } memcpy(*val, p->data, sz); return 1; } int OSSL_PARAM_get_utf8_string(const OSSL_PARAM *p, char **val, size_t max_len) { int ret = get_string_internal(p, (void **)val, &max_len, NULL, OSSL_PARAM_UTF8_STRING); /* * We try to ensure that the copied string is terminated with a * NUL byte. That should be easy, just place a NUL byte at * |((char*)*val)[p->data_size]|. * Unfortunately, we have seen cases where |p->data_size| doesn't * correctly reflect the length of the string, and just happens * to be out of bounds according to |max_len|, so in that case, we * make the extra step of trying to find the true length of the * string that |p->data| points at, and use that as an index to * place the NUL byte in |*val|. */ size_t data_length = p->data_size; if (ret == 0) return 0; if (data_length >= max_len) data_length = OPENSSL_strnlen(p->data, data_length); if (data_length >= max_len) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_NO_SPACE_FOR_TERMINATING_NULL); return 0; /* No space for a terminating NUL byte */ } (*val)[data_length] = '\0'; return ret; } int OSSL_PARAM_get_octet_string(const OSSL_PARAM *p, void **val, size_t max_len, size_t *used_len) { return get_string_internal(p, val, &max_len, used_len, OSSL_PARAM_OCTET_STRING); } static int set_string_internal(OSSL_PARAM *p, const void *val, size_t len, unsigned int type) { p->return_size = len; if (p->data == NULL) return 1; if (p->data_type != type) { err_bad_type; return 0; } if (p->data_size < len) { err_too_small; return 0; } memcpy(p->data, val, len); /* If possible within the size of p->data, add a NUL terminator byte */ if (type == OSSL_PARAM_UTF8_STRING && p->data_size > len) ((char *)p->data)[len] = '\0'; return 1; } int OSSL_PARAM_set_utf8_string(OSSL_PARAM *p, const char *val) { if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (val == NULL) { err_null_argument; return 0; } return set_string_internal(p, val, strlen(val), OSSL_PARAM_UTF8_STRING); } int OSSL_PARAM_set_octet_string(OSSL_PARAM *p, const void *val, size_t len) { if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; if (val == NULL) { err_null_argument; return 0; } return set_string_internal(p, val, len, OSSL_PARAM_OCTET_STRING); } OSSL_PARAM OSSL_PARAM_construct_utf8_string(const char *key, char *buf, size_t bsize) { if (buf != NULL && bsize == 0) bsize = strlen(buf); return ossl_param_construct(key, OSSL_PARAM_UTF8_STRING, buf, bsize); } OSSL_PARAM OSSL_PARAM_construct_octet_string(const char *key, void *buf, size_t bsize) { return ossl_param_construct(key, OSSL_PARAM_OCTET_STRING, buf, bsize); } static int get_ptr_internal(const OSSL_PARAM *p, const void **val, size_t *used_len, unsigned int type) { if (val == NULL || p == NULL) { err_null_argument; return 0; } if (p->data_type != type) { err_bad_type; return 0; } if (used_len != NULL) *used_len = p->data_size; *val = *(const void **)p->data; return 1; } int OSSL_PARAM_get_utf8_ptr(const OSSL_PARAM *p, const char **val) { return get_ptr_internal(p, (const void **)val, NULL, OSSL_PARAM_UTF8_PTR); } int OSSL_PARAM_get_octet_ptr(const OSSL_PARAM *p, const void **val, size_t *used_len) { return get_ptr_internal(p, val, used_len, OSSL_PARAM_OCTET_PTR); } static int set_ptr_internal(OSSL_PARAM *p, const void *val, unsigned int type, size_t len) { p->return_size = len; if (p->data_type != type) { err_bad_type; return 0; } if (p->data != NULL) *(const void **)p->data = val; return 1; } int OSSL_PARAM_set_utf8_ptr(OSSL_PARAM *p, const char *val) { if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; return set_ptr_internal(p, val, OSSL_PARAM_UTF8_PTR, val == NULL ? 0 : strlen(val)); } int OSSL_PARAM_set_octet_ptr(OSSL_PARAM *p, const void *val, size_t used_len) { if (p == NULL) { err_null_argument; return 0; } p->return_size = 0; return set_ptr_internal(p, val, OSSL_PARAM_OCTET_PTR, used_len); } OSSL_PARAM OSSL_PARAM_construct_utf8_ptr(const char *key, char **buf, size_t bsize) { return ossl_param_construct(key, OSSL_PARAM_UTF8_PTR, buf, bsize); } OSSL_PARAM OSSL_PARAM_construct_octet_ptr(const char *key, void **buf, size_t bsize) { return ossl_param_construct(key, OSSL_PARAM_OCTET_PTR, buf, bsize); } /* * 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) { const OSSL_PARAM *p = OSSL_PARAM_locate_const(params, name); void *buf = NULL; size_t len = 0; if (p == NULL) return -1; if (p->data != NULL && p->data_size > 0 && !OSSL_PARAM_get_octet_string(p, &buf, 0, &len)) return 0; OPENSSL_clear_free(*out, *out_len); *out = buf; *out_len = len; return 1; } static int setbuf_fromparams(const OSSL_PARAM *p, const char *name, unsigned char *out, size_t *outlen) { int ret = 0; WPACKET pkt; if (out == NULL) { if (!WPACKET_init_null(&pkt, 0)) return 0; } else { if (!WPACKET_init_static_len(&pkt, out, *outlen, 0)) return 0; } for (; p != NULL; p = OSSL_PARAM_locate_const(p + 1, name)) { if (p->data_type != OSSL_PARAM_OCTET_STRING) goto err; if (p->data != NULL && p->data_size != 0 && !WPACKET_memcpy(&pkt, p->data, p->data_size)) goto err; } if (!WPACKET_get_total_written(&pkt, outlen) || !WPACKET_finish(&pkt)) goto err; ret = 1; err: WPACKET_cleanup(&pkt); return ret; } int ossl_param_get1_concat_octet_string(const OSSL_PARAM *params, const char *name, unsigned char **out, size_t *out_len, size_t maxsize) { const OSSL_PARAM *p = OSSL_PARAM_locate_const(params, name); unsigned char *res; size_t sz = 0; if (p == NULL) return -1; /* Calculate the total size */ if (!setbuf_fromparams(p, name, NULL, &sz)) return 0; /* Check that it's not oversized */ if (maxsize > 0 && sz > maxsize) return 0; /* Special case zero length */ if (sz == 0) { if ((res = OPENSSL_zalloc(1)) == NULL) return 0; goto fin; } /* Allocate the buffer */ res = OPENSSL_malloc(sz); if (res == NULL) return 0; /* Concat one or more OSSL_KDF_PARAM_INFO fields */ if (!setbuf_fromparams(p, name, res, &sz)) { OPENSSL_clear_free(res, sz); return 0; } fin: OPENSSL_clear_free(*out, *out_len); *out = res; *out_len = sz; return 1; } OSSL_PARAM OSSL_PARAM_construct_end(void) { OSSL_PARAM end = OSSL_PARAM_END; return end; } static int get_string_ptr_internal(const OSSL_PARAM *p, const void **val, size_t *used_len, unsigned int type) { if (val == NULL || p == NULL) { err_null_argument; return 0; } if (p->data_type != type) { err_bad_type; return 0; } if (used_len != NULL) *used_len = p->data_size; *val = p->data; return 1; } int OSSL_PARAM_get_utf8_string_ptr(const OSSL_PARAM *p, const char **val) { int rv; ERR_set_mark(); rv = OSSL_PARAM_get_utf8_ptr(p, val); ERR_pop_to_mark(); return rv || get_string_ptr_internal(p, (const void **)val, NULL, OSSL_PARAM_UTF8_STRING); } int OSSL_PARAM_get_octet_string_ptr(const OSSL_PARAM *p, const void **val, size_t *used_len) { int rv; ERR_set_mark(); rv = OSSL_PARAM_get_octet_ptr(p, val, used_len); ERR_pop_to_mark(); return rv || get_string_ptr_internal(p, val, used_len, OSSL_PARAM_OCTET_STRING); }
./openssl/crypto/threads_none.c
/* * 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 */ #include <openssl/crypto.h> #include "internal/cryptlib.h" #if !defined(OPENSSL_THREADS) || defined(CRYPTO_TDEBUG) # if defined(OPENSSL_SYS_UNIX) # include <sys/types.h> # include <unistd.h> # endif CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void) { CRYPTO_RWLOCK *lock; if ((lock = CRYPTO_zalloc(sizeof(unsigned int), NULL, 0)) == NULL) /* Don't set error, to avoid recursion blowup. */ return NULL; *(unsigned int *)lock = 1; return lock; } __owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock) { if (!ossl_assert(*(unsigned int *)lock == 1)) return 0; return 1; } __owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock) { if (!ossl_assert(*(unsigned int *)lock == 1)) return 0; return 1; } int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock) { if (!ossl_assert(*(unsigned int *)lock == 1)) return 0; return 1; } void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock) { if (lock == NULL) return; *(unsigned int *)lock = 0; OPENSSL_free(lock); return; } int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void)) { if (*once != 0) return 1; init(); *once = 1; return 1; } #define OPENSSL_CRYPTO_THREAD_LOCAL_KEY_MAX 256 static void *thread_local_storage[OPENSSL_CRYPTO_THREAD_LOCAL_KEY_MAX]; int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *)) { static unsigned int thread_local_key = 0; if (thread_local_key >= OPENSSL_CRYPTO_THREAD_LOCAL_KEY_MAX) return 0; *key = thread_local_key++; thread_local_storage[*key] = NULL; return 1; } void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key) { if (*key >= OPENSSL_CRYPTO_THREAD_LOCAL_KEY_MAX) return NULL; return thread_local_storage[*key]; } int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val) { if (*key >= OPENSSL_CRYPTO_THREAD_LOCAL_KEY_MAX) return 0; thread_local_storage[*key] = val; return 1; } int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key) { *key = OPENSSL_CRYPTO_THREAD_LOCAL_KEY_MAX + 1; return 1; } CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void) { return 0; } int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b) { return (a == b); } int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock) { *val += amount; *ret = *val; return 1; } int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret, CRYPTO_RWLOCK *lock) { *val |= op; *ret = *val; return 1; } int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock) { *ret = *val; return 1; } int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock) { *ret = *val; return 1; } int openssl_init_fork_handlers(void) { return 0; } int openssl_get_fork_id(void) { # if defined(OPENSSL_SYS_UNIX) return getpid(); # else return 0; # endif } #endif
./openssl/crypto/ex_data.c
/* * 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 */ #include <stdlib.h> #include "crypto/cryptlib.h" #include "internal/thread_once.h" int ossl_do_ex_data_init(OSSL_LIB_CTX *ctx) { OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx); if (global == NULL) return 0; global->ex_data_lock = CRYPTO_THREAD_lock_new(); return global->ex_data_lock != NULL; } /* * Return the EX_CALLBACKS from the |ex_data| array that corresponds to * a given class. On success, *holds the lock.* * The |global| parameter is assumed to be non null (checked by the caller). * If |read| is 1 then a read lock is obtained. Otherwise it is a write lock. */ static EX_CALLBACKS *get_and_lock(OSSL_EX_DATA_GLOBAL *global, int class_index, int read) { EX_CALLBACKS *ip; if (class_index < 0 || class_index >= CRYPTO_EX_INDEX__COUNT) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } if (global->ex_data_lock == NULL) { /* * If we get here, someone (who?) cleaned up the lock, so just * treat it as an error. */ return NULL; } if (read) { if (!CRYPTO_THREAD_read_lock(global->ex_data_lock)) return NULL; } else { if (!CRYPTO_THREAD_write_lock(global->ex_data_lock)) return NULL; } ip = &global->ex_data[class_index]; return ip; } static void cleanup_cb(EX_CALLBACK *funcs) { OPENSSL_free(funcs); } /* * Release all "ex_data" state to prevent memory leaks. This can't be made * thread-safe without overhauling a lot of stuff, and shouldn't really be * called under potential race-conditions anyway (it's for program shutdown * after all). */ void ossl_crypto_cleanup_all_ex_data_int(OSSL_LIB_CTX *ctx) { int i; OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx); if (global == NULL) return; for (i = 0; i < CRYPTO_EX_INDEX__COUNT; ++i) { EX_CALLBACKS *ip = &global->ex_data[i]; sk_EX_CALLBACK_pop_free(ip->meth, cleanup_cb); ip->meth = NULL; } CRYPTO_THREAD_lock_free(global->ex_data_lock); global->ex_data_lock = NULL; } /* * Unregister a new index by replacing the callbacks with no-ops. * Any in-use instances are leaked. */ static void dummy_new(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { } static void dummy_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp) { } static int dummy_dup(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, void **from_d, int idx, long argl, void *argp) { return 1; } int ossl_crypto_free_ex_index_ex(OSSL_LIB_CTX *ctx, int class_index, int idx) { EX_CALLBACKS *ip; EX_CALLBACK *a; int toret = 0; OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx); if (global == NULL) return 0; ip = get_and_lock(global, class_index, 0); if (ip == NULL) return 0; if (idx < 0 || idx >= sk_EX_CALLBACK_num(ip->meth)) goto err; a = sk_EX_CALLBACK_value(ip->meth, idx); if (a == NULL) goto err; a->new_func = dummy_new; a->dup_func = dummy_dup; a->free_func = dummy_free; toret = 1; err: CRYPTO_THREAD_unlock(global->ex_data_lock); return toret; } int CRYPTO_free_ex_index(int class_index, int idx) { return ossl_crypto_free_ex_index_ex(NULL, class_index, idx); } /* * Register a new index. */ 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 toret = -1; EX_CALLBACK *a; EX_CALLBACKS *ip; OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx); if (global == NULL) return -1; ip = get_and_lock(global, class_index, 0); if (ip == NULL) return -1; if (ip->meth == NULL) { ip->meth = sk_EX_CALLBACK_new_null(); /* We push an initial value on the stack because the SSL * "app_data" routines use ex_data index zero. See RT 3710. */ if (ip->meth == NULL || !sk_EX_CALLBACK_push(ip->meth, NULL)) { sk_EX_CALLBACK_free(ip->meth); ip->meth = NULL; ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); goto err; } } a = (EX_CALLBACK *)OPENSSL_malloc(sizeof(*a)); if (a == NULL) goto err; a->argl = argl; a->argp = argp; a->new_func = new_func; a->dup_func = dup_func; a->free_func = free_func; a->priority = priority; if (!sk_EX_CALLBACK_push(ip->meth, NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); OPENSSL_free(a); goto err; } toret = sk_EX_CALLBACK_num(ip->meth) - 1; (void)sk_EX_CALLBACK_set(ip->meth, toret, a); err: CRYPTO_THREAD_unlock(global->ex_data_lock); return toret; } int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp, CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) { return ossl_crypto_get_ex_new_index_ex(NULL, class_index, argl, argp, new_func, dup_func, free_func, 0); } /* * Initialise a new CRYPTO_EX_DATA for use in a particular class - including * calling new() callbacks for each index in the class used by this variable * Thread-safe by copying a class's array of "EX_CALLBACK" entries * in the lock, then using them outside the lock. Note this only applies * to the global "ex_data" state (ie. class definitions), not 'ad' itself. */ int ossl_crypto_new_ex_data_ex(OSSL_LIB_CTX *ctx, int class_index, void *obj, CRYPTO_EX_DATA *ad) { int mx, i; void *ptr; EX_CALLBACK **storage = NULL; EX_CALLBACK *stack[10]; EX_CALLBACKS *ip; OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx); if (global == NULL) return 0; ip = get_and_lock(global, class_index, 1); if (ip == NULL) return 0; ad->ctx = ctx; ad->sk = NULL; mx = sk_EX_CALLBACK_num(ip->meth); if (mx > 0) { if (mx < (int)OSSL_NELEM(stack)) storage = stack; else storage = OPENSSL_malloc(sizeof(*storage) * mx); if (storage != NULL) for (i = 0; i < mx; i++) storage[i] = sk_EX_CALLBACK_value(ip->meth, i); } CRYPTO_THREAD_unlock(global->ex_data_lock); if (mx > 0 && storage == NULL) return 0; for (i = 0; i < mx; i++) { if (storage[i] != NULL && storage[i]->new_func != NULL) { ptr = CRYPTO_get_ex_data(ad, i); storage[i]->new_func(obj, ptr, ad, i, storage[i]->argl, storage[i]->argp); } } if (storage != stack) OPENSSL_free(storage); return 1; } int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad) { return ossl_crypto_new_ex_data_ex(NULL, class_index, obj, ad); } /* * Duplicate a CRYPTO_EX_DATA variable - including calling dup() callbacks * for each index in the class used by this variable */ int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from) { int mx, j, i; void *ptr; EX_CALLBACK *stack[10]; EX_CALLBACK **storage = NULL; EX_CALLBACKS *ip; int toret = 0; OSSL_EX_DATA_GLOBAL *global; to->ctx = from->ctx; if (from->sk == NULL) /* Nothing to copy over */ return 1; global = ossl_lib_ctx_get_ex_data_global(from->ctx); if (global == NULL) return 0; ip = get_and_lock(global, class_index, 1); if (ip == NULL) return 0; mx = sk_EX_CALLBACK_num(ip->meth); j = sk_void_num(from->sk); if (j < mx) mx = j; if (mx > 0) { if (mx < (int)OSSL_NELEM(stack)) storage = stack; else storage = OPENSSL_malloc(sizeof(*storage) * mx); if (storage != NULL) for (i = 0; i < mx; i++) storage[i] = sk_EX_CALLBACK_value(ip->meth, i); } CRYPTO_THREAD_unlock(global->ex_data_lock); if (mx == 0) return 1; if (storage == NULL) return 0; /* * Make sure the ex_data stack is at least |mx| elements long to avoid * issues in the for loop that follows; so go get the |mx|'th element * (if it does not exist CRYPTO_get_ex_data() returns NULL), and assign * to itself. This is normally a no-op; but ensures the stack is the * proper size */ if (!CRYPTO_set_ex_data(to, mx - 1, CRYPTO_get_ex_data(to, mx - 1))) goto err; for (i = 0; i < mx; i++) { ptr = CRYPTO_get_ex_data(from, i); if (storage[i] != NULL && storage[i]->dup_func != NULL) if (!storage[i]->dup_func(to, from, &ptr, i, storage[i]->argl, storage[i]->argp)) goto err; CRYPTO_set_ex_data(to, i, ptr); } toret = 1; err: if (storage != stack) OPENSSL_free(storage); return toret; } struct ex_callback_entry { const EX_CALLBACK *excb; int index; }; static int ex_callback_compare(const void *a, const void *b) { const struct ex_callback_entry *ap = (const struct ex_callback_entry *)a; const struct ex_callback_entry *bp = (const struct ex_callback_entry *)b; if (ap->excb == bp->excb) return 0; if (ap->excb == NULL) return 1; if (bp->excb == NULL) return -1; if (ap->excb->priority == bp->excb->priority) return 0; return ap->excb->priority > bp->excb->priority ? -1 : 1; } /* * Cleanup a CRYPTO_EX_DATA variable - including calling free() callbacks for * each index in the class used by this variable */ void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad) { int mx, i; EX_CALLBACKS *ip; void *ptr; const EX_CALLBACK *f; struct ex_callback_entry stack[10]; struct ex_callback_entry *storage = NULL; OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ad->ctx); if (global == NULL) goto err; ip = get_and_lock(global, class_index, 1); if (ip == NULL) goto err; mx = sk_EX_CALLBACK_num(ip->meth); if (mx > 0) { if (mx < (int)OSSL_NELEM(stack)) storage = stack; else storage = OPENSSL_malloc(sizeof(*storage) * mx); if (storage != NULL) for (i = 0; i < mx; i++) { storage[i].excb = sk_EX_CALLBACK_value(ip->meth, i); storage[i].index = i; } } CRYPTO_THREAD_unlock(global->ex_data_lock); if (storage != NULL) { /* Sort according to priority. High priority first */ qsort(storage, mx, sizeof(*storage), ex_callback_compare); for (i = 0; i < mx; i++) { f = storage[i].excb; if (f != NULL && f->free_func != NULL) { ptr = CRYPTO_get_ex_data(ad, storage[i].index); f->free_func(obj, ptr, ad, storage[i].index, f->argl, f->argp); } } } if (storage != stack) OPENSSL_free(storage); err: sk_void_free(ad->sk); ad->sk = NULL; ad->ctx = NULL; } /* * Allocate a given CRYPTO_EX_DATA item using the class specific allocation * function */ int CRYPTO_alloc_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad, int idx) { void *curval; curval = CRYPTO_get_ex_data(ad, idx); /* Already there, no need to allocate */ if (curval != NULL) return 1; return ossl_crypto_alloc_ex_data_intern(class_index, obj, ad, idx); } int ossl_crypto_alloc_ex_data_intern(int class_index, void *obj, CRYPTO_EX_DATA *ad, int idx) { EX_CALLBACK *f; EX_CALLBACKS *ip; OSSL_EX_DATA_GLOBAL *global; global = ossl_lib_ctx_get_ex_data_global(ad->ctx); if (global == NULL) return 0; ip = get_and_lock(global, class_index, 1); if (ip == NULL) return 0; f = sk_EX_CALLBACK_value(ip->meth, idx); CRYPTO_THREAD_unlock(global->ex_data_lock); /* * This should end up calling CRYPTO_set_ex_data(), which allocates * everything necessary to support placing the new data in the right spot. */ if (f->new_func == NULL) return 0; f->new_func(obj, NULL, ad, idx, f->argl, f->argp); return 1; } /* * For a given CRYPTO_EX_DATA variable, set the value corresponding to a * particular index in the class used by this variable */ int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val) { int i; if (ad->sk == NULL) { if ((ad->sk = sk_void_new_null()) == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); return 0; } } for (i = sk_void_num(ad->sk); i <= idx; ++i) { if (!sk_void_push(ad->sk, NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); return 0; } } if (sk_void_set(ad->sk, idx, val) != val) { /* Probably the index is out of bounds */ ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } return 1; } /* * For a given CRYPTO_EX_DATA_ variable, get the value corresponding to a * particular index in the class used by this variable */ void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx) { if (ad->sk == NULL || idx >= sk_void_num(ad->sk)) return NULL; return sk_void_value(ad->sk, idx); } OSSL_LIB_CTX *ossl_crypto_ex_data_get_ossl_lib_ctx(const CRYPTO_EX_DATA *ad) { return ad->ctx; }
./openssl/crypto/LPdir_win32.c
/* * Copyright 2004-2016 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 COPYRIGHT HOLDERS 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 COPYRIGHT * OWNER 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. */ #define LP_SYS_WIN32 #define LP_MULTIBYTE_AVAILABLE #include "LPdir_win.c"
./openssl/crypto/arm_arch.h
/* * Copyright 2011-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_ARM_ARCH_H # define OSSL_CRYPTO_ARM_ARCH_H # if !defined(__ARM_ARCH__) # if defined(__CC_ARM) # define __ARM_ARCH__ __TARGET_ARCH_ARM # if defined(__BIG_ENDIAN) # define __ARMEB__ # else # define __ARMEL__ # endif # elif defined(__GNUC__) # if defined(__aarch64__) # define __ARM_ARCH__ 8 /* * Why doesn't gcc define __ARM_ARCH__? Instead it defines * bunch of below macros. See all_architectures[] table in * gcc/config/arm/arm.c. On a side note it defines * __ARMEL__/__ARMEB__ for little-/big-endian. */ # elif defined(__ARM_ARCH) # define __ARM_ARCH__ __ARM_ARCH # elif defined(__ARM_ARCH_8A__) # define __ARM_ARCH__ 8 # elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \ defined(__ARM_ARCH_7R__)|| defined(__ARM_ARCH_7M__) || \ defined(__ARM_ARCH_7EM__) # define __ARM_ARCH__ 7 # elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \ defined(__ARM_ARCH_6K__)|| defined(__ARM_ARCH_6M__) || \ defined(__ARM_ARCH_6Z__)|| defined(__ARM_ARCH_6ZK__) || \ defined(__ARM_ARCH_6T2__) # define __ARM_ARCH__ 6 # elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) || \ defined(__ARM_ARCH_5E__)|| defined(__ARM_ARCH_5TE__) || \ defined(__ARM_ARCH_5TEJ__) # define __ARM_ARCH__ 5 # elif defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) # define __ARM_ARCH__ 4 # else # error "unsupported ARM architecture" # endif # elif defined(__ARM_ARCH) # define __ARM_ARCH__ __ARM_ARCH # endif # endif # if !defined(__ARM_MAX_ARCH__) # define __ARM_MAX_ARCH__ __ARM_ARCH__ # endif # if __ARM_MAX_ARCH__<__ARM_ARCH__ # error "__ARM_MAX_ARCH__ can't be less than __ARM_ARCH__" # elif __ARM_MAX_ARCH__!=__ARM_ARCH__ # if __ARM_ARCH__<7 && __ARM_MAX_ARCH__>=7 && defined(__ARMEB__) # error "can't build universal big-endian binary" # endif # endif # ifndef __ASSEMBLER__ extern unsigned int OPENSSL_armcap_P; extern unsigned int OPENSSL_arm_midr; extern unsigned int OPENSSL_armv8_rsa_neonized; # endif # define ARMV7_NEON (1<<0) # define ARMV7_TICK (1<<1) # define ARMV8_AES (1<<2) # define ARMV8_SHA1 (1<<3) # define ARMV8_SHA256 (1<<4) # define ARMV8_PMULL (1<<5) # define ARMV8_SHA512 (1<<6) # define ARMV8_CPUID (1<<7) # define ARMV8_RNG (1<<8) # define ARMV8_SM3 (1<<9) # define ARMV8_SM4 (1<<10) # define ARMV8_SHA3 (1<<11) # define ARMV8_UNROLL8_EOR3 (1<<12) # define ARMV8_SVE (1<<13) # define ARMV8_SVE2 (1<<14) # define ARMV8_HAVE_SHA3_AND_WORTH_USING (1<<15) # define ARMV8_UNROLL12_EOR3 (1<<16) /* * MIDR_EL1 system register * * 63___ _ ___32_31___ _ ___24_23_____20_19_____16_15__ _ __4_3_______0 * | | | | | | | * |RES0 | Implementer | Variant | Arch | PartNum |Revision| * |____ _ _____|_____ _ _____|_________|_______ _|____ _ ___|________| * */ # define ARM_CPU_IMP_ARM 0x41 # define HISI_CPU_IMP 0x48 # define ARM_CPU_IMP_APPLE 0x61 # define ARM_CPU_PART_CORTEX_A72 0xD08 # define ARM_CPU_PART_N1 0xD0C # define ARM_CPU_PART_V1 0xD40 # define ARM_CPU_PART_N2 0xD49 # define HISI_CPU_PART_KP920 0xD01 # define ARM_CPU_PART_V2 0xD4F # define APPLE_CPU_PART_M1_ICESTORM 0x022 # define APPLE_CPU_PART_M1_FIRESTORM 0x023 # define APPLE_CPU_PART_M1_ICESTORM_PRO 0x024 # define APPLE_CPU_PART_M1_FIRESTORM_PRO 0x025 # define APPLE_CPU_PART_M1_ICESTORM_MAX 0x028 # define APPLE_CPU_PART_M1_FIRESTORM_MAX 0x029 # define APPLE_CPU_PART_M2_BLIZZARD 0x032 # define APPLE_CPU_PART_M2_AVALANCHE 0x033 # define APPLE_CPU_PART_M2_BLIZZARD_PRO 0x034 # define APPLE_CPU_PART_M2_AVALANCHE_PRO 0x035 # define APPLE_CPU_PART_M2_BLIZZARD_MAX 0x038 # define APPLE_CPU_PART_M2_AVALANCHE_MAX 0x039 # define MIDR_PARTNUM_SHIFT 4 # define MIDR_PARTNUM_MASK (0xfffU << MIDR_PARTNUM_SHIFT) # define MIDR_PARTNUM(midr) \ (((midr) & MIDR_PARTNUM_MASK) >> MIDR_PARTNUM_SHIFT) # define MIDR_IMPLEMENTER_SHIFT 24 # define MIDR_IMPLEMENTER_MASK (0xffU << MIDR_IMPLEMENTER_SHIFT) # define MIDR_IMPLEMENTER(midr) \ (((midr) & MIDR_IMPLEMENTER_MASK) >> MIDR_IMPLEMENTER_SHIFT) # define MIDR_ARCHITECTURE_SHIFT 16 # define MIDR_ARCHITECTURE_MASK (0xfU << MIDR_ARCHITECTURE_SHIFT) # define MIDR_ARCHITECTURE(midr) \ (((midr) & MIDR_ARCHITECTURE_MASK) >> MIDR_ARCHITECTURE_SHIFT) # define MIDR_CPU_MODEL_MASK \ (MIDR_IMPLEMENTER_MASK | \ MIDR_PARTNUM_MASK | \ MIDR_ARCHITECTURE_MASK) # define MIDR_CPU_MODEL(imp, partnum) \ (((imp) << MIDR_IMPLEMENTER_SHIFT) | \ (0xfU << MIDR_ARCHITECTURE_SHIFT) | \ ((partnum) << MIDR_PARTNUM_SHIFT)) # define MIDR_IS_CPU_MODEL(midr, imp, partnum) \ (((midr) & MIDR_CPU_MODEL_MASK) == MIDR_CPU_MODEL(imp, partnum)) #if defined(__ASSEMBLER__) /* * Support macros for * - Armv8.3-A Pointer Authentication and * - Armv8.5-A Branch Target Identification * features which require emitting a .note.gnu.property section with the * appropriate architecture-dependent feature bits set. * Read more: "ELF for the Arm® 64-bit Architecture" */ # if defined(__ARM_FEATURE_BTI_DEFAULT) && __ARM_FEATURE_BTI_DEFAULT == 1 # define GNU_PROPERTY_AARCH64_BTI (1 << 0) /* Has Branch Target Identification */ # define AARCH64_VALID_CALL_TARGET hint #34 /* BTI 'c' */ # else # define GNU_PROPERTY_AARCH64_BTI 0 /* No Branch Target Identification */ # define AARCH64_VALID_CALL_TARGET # endif # if defined(__ARM_FEATURE_PAC_DEFAULT) && \ (__ARM_FEATURE_PAC_DEFAULT & 1) == 1 /* Signed with A-key */ # define GNU_PROPERTY_AARCH64_POINTER_AUTH \ (1 << 1) /* Has Pointer Authentication */ # define AARCH64_SIGN_LINK_REGISTER hint #25 /* PACIASP */ # define AARCH64_VALIDATE_LINK_REGISTER hint #29 /* AUTIASP */ # elif defined(__ARM_FEATURE_PAC_DEFAULT) && \ (__ARM_FEATURE_PAC_DEFAULT & 2) == 2 /* Signed with B-key */ # define GNU_PROPERTY_AARCH64_POINTER_AUTH \ (1 << 1) /* Has Pointer Authentication */ # define AARCH64_SIGN_LINK_REGISTER hint #27 /* PACIBSP */ # define AARCH64_VALIDATE_LINK_REGISTER hint #31 /* AUTIBSP */ # else # define GNU_PROPERTY_AARCH64_POINTER_AUTH 0 /* No Pointer Authentication */ # if GNU_PROPERTY_AARCH64_BTI != 0 # define AARCH64_SIGN_LINK_REGISTER AARCH64_VALID_CALL_TARGET # else # define AARCH64_SIGN_LINK_REGISTER # endif # define AARCH64_VALIDATE_LINK_REGISTER # endif # if GNU_PROPERTY_AARCH64_POINTER_AUTH != 0 || GNU_PROPERTY_AARCH64_BTI != 0 .pushsection .note.gnu.property, "a"; .balign 8; .long 4; .long 0x10; .long 0x5; .asciz "GNU"; .long 0xc0000000; /* GNU_PROPERTY_AARCH64_FEATURE_1_AND */ .long 4; .long (GNU_PROPERTY_AARCH64_POINTER_AUTH | GNU_PROPERTY_AARCH64_BTI); .long 0; .popsection; # endif # endif /* defined __ASSEMBLER__ */ # define IS_CPU_SUPPORT_UNROLL8_EOR3() \ (OPENSSL_armcap_P & ARMV8_UNROLL8_EOR3) #endif
./openssl/crypto/asn1_dsa.c
/* * 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 */ /* * A simple ASN.1 DER encoder/decoder for DSA-Sig-Value and ECDSA-Sig-Value. * * DSA-Sig-Value ::= SEQUENCE { * r INTEGER, * s INTEGER * } * * ECDSA-Sig-Value ::= SEQUENCE { * r INTEGER, * s INTEGER * } */ #include <openssl/crypto.h> #include <openssl/bn.h> #include "crypto/asn1_dsa.h" #include "internal/packet.h" #define ID_SEQUENCE 0x30 #define ID_INTEGER 0x02 /* * Outputs the encoding of the length octets for a DER value with a content * length of cont_len bytes to pkt. The maximum supported content length is * 65535 (0xffff) bytes. * * Returns 1 on success or 0 on error. */ int ossl_encode_der_length(WPACKET *pkt, size_t cont_len) { if (cont_len > 0xffff) return 0; /* Too large for supported length encodings */ if (cont_len > 0xff) { if (!WPACKET_put_bytes_u8(pkt, 0x82) || !WPACKET_put_bytes_u16(pkt, cont_len)) return 0; } else { if (cont_len > 0x7f && !WPACKET_put_bytes_u8(pkt, 0x81)) return 0; if (!WPACKET_put_bytes_u8(pkt, cont_len)) return 0; } return 1; } /* * Outputs the DER encoding of a positive ASN.1 INTEGER to pkt. * * Results in an error if n is negative or too large. * * Returns 1 on success or 0 on error. */ int ossl_encode_der_integer(WPACKET *pkt, const BIGNUM *n) { unsigned char *bnbytes; size_t cont_len; if (BN_is_negative(n)) return 0; /* * Calculate the ASN.1 INTEGER DER content length for n. * This is the number of whole bytes required to represent n (i.e. rounded * down), plus one. * If n is zero then the content is a single zero byte (length = 1). * If the number of bits of n is a multiple of 8 then an extra zero padding * byte is included to ensure that the value is still treated as positive * in the INTEGER two's complement representation. */ cont_len = BN_num_bits(n) / 8 + 1; if (!WPACKET_start_sub_packet(pkt) || !WPACKET_put_bytes_u8(pkt, ID_INTEGER) || !ossl_encode_der_length(pkt, cont_len) || !WPACKET_allocate_bytes(pkt, cont_len, &bnbytes) || !WPACKET_close(pkt)) return 0; if (bnbytes != NULL && BN_bn2binpad(n, bnbytes, (int)cont_len) != (int)cont_len) return 0; return 1; } /* * Outputs the DER encoding of a DSA-Sig-Value or ECDSA-Sig-Value to pkt. pkt * may be initialised with a NULL buffer which enables pkt to be used to * calculate how many bytes would be needed. * * Returns 1 on success or 0 on error. */ int ossl_encode_der_dsa_sig(WPACKET *pkt, const BIGNUM *r, const BIGNUM *s) { WPACKET tmppkt, *dummypkt; size_t cont_len; int isnull = WPACKET_is_null_buf(pkt); if (!WPACKET_start_sub_packet(pkt)) return 0; if (!isnull) { if (!WPACKET_init_null(&tmppkt, 0)) return 0; dummypkt = &tmppkt; } else { /* If the input packet has a NULL buffer, we don't need a dummy packet */ dummypkt = pkt; } /* Calculate the content length */ if (!ossl_encode_der_integer(dummypkt, r) || !ossl_encode_der_integer(dummypkt, s) || !WPACKET_get_length(dummypkt, &cont_len) || (!isnull && !WPACKET_finish(dummypkt))) { if (!isnull) WPACKET_cleanup(dummypkt); return 0; } /* Add the tag and length bytes */ if (!WPACKET_put_bytes_u8(pkt, ID_SEQUENCE) || !ossl_encode_der_length(pkt, cont_len) /* * Really encode the integers. We already wrote to the main pkt * if it had a NULL buffer, so don't do it again */ || (!isnull && !ossl_encode_der_integer(pkt, r)) || (!isnull && !ossl_encode_der_integer(pkt, s)) || !WPACKET_close(pkt)) return 0; return 1; } /* * Decodes the DER length octets in pkt and initialises subpkt with the * following bytes of that length. * * Returns 1 on success or 0 on failure. */ int ossl_decode_der_length(PACKET *pkt, PACKET *subpkt) { unsigned int byte; if (!PACKET_get_1(pkt, &byte)) return 0; if (byte < 0x80) return PACKET_get_sub_packet(pkt, subpkt, (size_t)byte); if (byte == 0x81) return PACKET_get_length_prefixed_1(pkt, subpkt); if (byte == 0x82) return PACKET_get_length_prefixed_2(pkt, subpkt); /* Too large, invalid, or not DER. */ return 0; } /* * Decodes a single ASN.1 INTEGER value from pkt, which must be DER encoded, * and updates n with the decoded value. * * The BIGNUM, n, must have already been allocated by calling BN_new(). * pkt must not be NULL. * * An attempt to consume more than len bytes results in an error. * Returns 1 on success or 0 on error. * * If the PACKET is supposed to only contain a single INTEGER value with no * trailing garbage then it is up to the caller to verify that all bytes * were consumed. */ int ossl_decode_der_integer(PACKET *pkt, BIGNUM *n) { PACKET contpkt, tmppkt; unsigned int tag, tmp; /* Check we have an integer and get the content bytes */ if (!PACKET_get_1(pkt, &tag) || tag != ID_INTEGER || !ossl_decode_der_length(pkt, &contpkt)) return 0; /* Peek ahead at the first bytes to check for proper encoding */ tmppkt = contpkt; /* The INTEGER must be positive */ if (!PACKET_get_1(&tmppkt, &tmp) || (tmp & 0x80) != 0) return 0; /* If there a zero padding byte the next byte must have the msb set */ if (PACKET_remaining(&tmppkt) > 0 && tmp == 0) { if (!PACKET_get_1(&tmppkt, &tmp) || (tmp & 0x80) == 0) return 0; } if (BN_bin2bn(PACKET_data(&contpkt), (int)PACKET_remaining(&contpkt), n) == NULL) return 0; return 1; } /* * Decodes a single DSA-Sig-Value or ECDSA-Sig-Value from *ppin, which must be * DER encoded, updates r and s with the decoded values, and increments *ppin * past the data that was consumed. * * The BIGNUMs, r and s, must have already been allocated by calls to BN_new(). * ppin and *ppin must not be NULL. * * An attempt to consume more than len bytes results in an error. * Returns the number of bytes of input consumed or 0 if an error occurs. * * If the buffer is supposed to only contain a single [EC]DSA-Sig-Value with no * trailing garbage then it is up to the caller to verify that all bytes * were consumed. */ size_t ossl_decode_der_dsa_sig(BIGNUM *r, BIGNUM *s, const unsigned char **ppin, size_t len) { size_t consumed; PACKET pkt, contpkt; unsigned int tag; if (!PACKET_buf_init(&pkt, *ppin, len) || !PACKET_get_1(&pkt, &tag) || tag != ID_SEQUENCE || !ossl_decode_der_length(&pkt, &contpkt) || !ossl_decode_der_integer(&contpkt, r) || !ossl_decode_der_integer(&contpkt, s) || PACKET_remaining(&contpkt) != 0) return 0; consumed = PACKET_data(&pkt) - *ppin; *ppin += consumed; return consumed; }
./openssl/crypto/threads_lib.c
/* * Copyright 2020 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/crypto.h> #ifdef OPENSSL_SYS_UNIX # ifndef OPENSSL_NO_DEPRECATED_3_0 void OPENSSL_fork_prepare(void) { } void OPENSSL_fork_parent(void) { } void OPENSSL_fork_child(void) { } # endif #endif
./openssl/crypto/packet.c
/* * 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 */ #include "internal/cryptlib.h" #include "internal/packet.h" #if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE # include "internal/packet_quic.h" #endif #include <openssl/err.h> #define DEFAULT_BUF_SIZE 256 int WPACKET_allocate_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes) { if (!WPACKET_reserve_bytes(pkt, len, allocbytes)) return 0; pkt->written += len; pkt->curr += len; return 1; } int WPACKET_sub_allocate_bytes__(WPACKET *pkt, size_t len, unsigned char **allocbytes, size_t lenbytes) { if (!WPACKET_start_sub_packet_len__(pkt, lenbytes) || !WPACKET_allocate_bytes(pkt, len, allocbytes) || !WPACKET_close(pkt)) return 0; return 1; } #define GETBUF(p) (((p)->staticbuf != NULL) \ ? (p)->staticbuf \ : ((p)->buf != NULL \ ? (unsigned char *)(p)->buf->data \ : NULL)) int WPACKET_reserve_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes) { /* Internal API, so should not fail */ if (!ossl_assert(pkt->subs != NULL && len != 0)) return 0; if (pkt->maxsize - pkt->written < len) return 0; if (pkt->buf != NULL && (pkt->buf->length - pkt->written < len)) { size_t newlen; size_t reflen; reflen = (len > pkt->buf->length) ? len : pkt->buf->length; if (reflen > SIZE_MAX / 2) { newlen = SIZE_MAX; } else { newlen = reflen * 2; if (newlen < DEFAULT_BUF_SIZE) newlen = DEFAULT_BUF_SIZE; } if (BUF_MEM_grow(pkt->buf, newlen) == 0) return 0; } if (allocbytes != NULL) { *allocbytes = WPACKET_get_curr(pkt); if (pkt->endfirst && *allocbytes != NULL) *allocbytes -= len; } return 1; } int WPACKET_sub_reserve_bytes__(WPACKET *pkt, size_t len, unsigned char **allocbytes, size_t lenbytes) { if (pkt->endfirst && lenbytes > 0) return 0; if (!WPACKET_reserve_bytes(pkt, lenbytes + len, allocbytes)) return 0; if (*allocbytes != NULL) *allocbytes += lenbytes; return 1; } static size_t maxmaxsize(size_t lenbytes) { if (lenbytes >= sizeof(size_t) || lenbytes == 0) return SIZE_MAX; return ((size_t)1 << (lenbytes * 8)) - 1 + lenbytes; } static int wpacket_intern_init_len(WPACKET *pkt, size_t lenbytes) { unsigned char *lenchars; pkt->curr = 0; pkt->written = 0; if ((pkt->subs = OPENSSL_zalloc(sizeof(*pkt->subs))) == NULL) return 0; if (lenbytes == 0) return 1; pkt->subs->pwritten = lenbytes; pkt->subs->lenbytes = lenbytes; if (!WPACKET_allocate_bytes(pkt, lenbytes, &lenchars)) { OPENSSL_free(pkt->subs); pkt->subs = NULL; return 0; } pkt->subs->packet_len = 0; return 1; } int WPACKET_init_static_len(WPACKET *pkt, unsigned char *buf, size_t len, size_t lenbytes) { size_t max = maxmaxsize(lenbytes); /* Internal API, so should not fail */ if (!ossl_assert(buf != NULL && len > 0)) return 0; pkt->staticbuf = buf; pkt->buf = NULL; pkt->maxsize = (max < len) ? max : len; pkt->endfirst = 0; return wpacket_intern_init_len(pkt, lenbytes); } int WPACKET_init_der(WPACKET *pkt, unsigned char *buf, size_t len) { /* Internal API, so should not fail */ if (!ossl_assert(buf != NULL && len > 0)) return 0; pkt->staticbuf = buf; pkt->buf = NULL; pkt->maxsize = len; pkt->endfirst = 1; return wpacket_intern_init_len(pkt, 0); } int WPACKET_init_len(WPACKET *pkt, BUF_MEM *buf, size_t lenbytes) { /* Internal API, so should not fail */ if (!ossl_assert(buf != NULL)) return 0; pkt->staticbuf = NULL; pkt->buf = buf; pkt->maxsize = maxmaxsize(lenbytes); pkt->endfirst = 0; return wpacket_intern_init_len(pkt, lenbytes); } int WPACKET_init(WPACKET *pkt, BUF_MEM *buf) { return WPACKET_init_len(pkt, buf, 0); } int WPACKET_init_null(WPACKET *pkt, size_t lenbytes) { pkt->staticbuf = NULL; pkt->buf = NULL; pkt->maxsize = maxmaxsize(lenbytes); pkt->endfirst = 0; return wpacket_intern_init_len(pkt, 0); } int WPACKET_init_null_der(WPACKET *pkt) { pkt->staticbuf = NULL; pkt->buf = NULL; pkt->maxsize = SIZE_MAX; pkt->endfirst = 1; return wpacket_intern_init_len(pkt, 0); } int WPACKET_set_flags(WPACKET *pkt, unsigned int flags) { /* Internal API, so should not fail */ if (!ossl_assert(pkt->subs != NULL)) return 0; pkt->subs->flags = flags; return 1; } /* Store the |value| of length |len| at location |data| */ static int put_value(unsigned char *data, uint64_t value, size_t len) { if (data == NULL) return 1; for (data += len - 1; len > 0; len--) { *data = (unsigned char)(value & 0xff); data--; value >>= 8; } /* Check whether we could fit the value in the assigned number of bytes */ if (value > 0) return 0; return 1; } #if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE static int put_quic_value(unsigned char *data, size_t value, size_t len) { if (data == NULL) return 1; /* Value too large for field. */ if (ossl_quic_vlint_encode_len(value) > len) return 0; ossl_quic_vlint_encode_n(data, value, len); return 1; } #endif /* * Internal helper function used by WPACKET_close(), WPACKET_finish() and * WPACKET_fill_lengths() to close a sub-packet and write out its length if * necessary. If |doclose| is 0 then it goes through the motions of closing * (i.e. it fills in all the lengths), but doesn't actually close anything. */ static int wpacket_intern_close(WPACKET *pkt, WPACKET_SUB *sub, int doclose) { size_t packlen = pkt->written - sub->pwritten; if (packlen == 0 && (sub->flags & WPACKET_FLAGS_NON_ZERO_LENGTH) != 0) return 0; if (packlen == 0 && sub->flags & WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH) { /* We can't handle this case. Return an error */ if (!doclose) return 0; /* Deallocate any bytes allocated for the length of the WPACKET */ if ((pkt->curr - sub->lenbytes) == sub->packet_len) { pkt->written -= sub->lenbytes; pkt->curr -= sub->lenbytes; } /* Don't write out the packet length */ sub->packet_len = 0; sub->lenbytes = 0; } /* Write out the WPACKET length if needed */ if (sub->lenbytes > 0) { unsigned char *buf = GETBUF(pkt); if (buf != NULL) { #if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE if ((sub->flags & WPACKET_FLAGS_QUIC_VLINT) == 0) { if (!put_value(&buf[sub->packet_len], packlen, sub->lenbytes)) return 0; } else { if (!put_quic_value(&buf[sub->packet_len], packlen, sub->lenbytes)) return 0; } #else if (!put_value(&buf[sub->packet_len], packlen, sub->lenbytes)) return 0; #endif } } else if (pkt->endfirst && sub->parent != NULL && (packlen != 0 || (sub->flags & WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH) == 0)) { size_t tmplen = packlen; size_t numlenbytes = 1; while ((tmplen = tmplen >> 8) > 0) numlenbytes++; if (!WPACKET_put_bytes__(pkt, packlen, numlenbytes)) return 0; if (packlen > 0x7f) { numlenbytes |= 0x80; if (!WPACKET_put_bytes_u8(pkt, numlenbytes)) return 0; } } if (doclose) { pkt->subs = sub->parent; OPENSSL_free(sub); } return 1; } int WPACKET_fill_lengths(WPACKET *pkt) { WPACKET_SUB *sub; if (!ossl_assert(pkt->subs != NULL)) return 0; for (sub = pkt->subs; sub != NULL; sub = sub->parent) { if (!wpacket_intern_close(pkt, sub, 0)) return 0; } return 1; } int WPACKET_close(WPACKET *pkt) { /* * Internal API, so should not fail - but we do negative testing of this * so no assert (otherwise the tests fail) */ if (pkt->subs == NULL || pkt->subs->parent == NULL) return 0; return wpacket_intern_close(pkt, pkt->subs, 1); } int WPACKET_finish(WPACKET *pkt) { int ret; /* * Internal API, so should not fail - but we do negative testing of this * so no assert (otherwise the tests fail) */ if (pkt->subs == NULL || pkt->subs->parent != NULL) return 0; ret = wpacket_intern_close(pkt, pkt->subs, 1); if (ret) { OPENSSL_free(pkt->subs); pkt->subs = NULL; } return ret; } int WPACKET_start_sub_packet_len__(WPACKET *pkt, size_t lenbytes) { WPACKET_SUB *sub; unsigned char *lenchars; /* Internal API, so should not fail */ if (!ossl_assert(pkt->subs != NULL)) return 0; /* We don't support lenbytes greater than 0 when doing endfirst writing */ if (lenbytes > 0 && pkt->endfirst) return 0; if ((sub = OPENSSL_zalloc(sizeof(*sub))) == NULL) return 0; sub->parent = pkt->subs; pkt->subs = sub; sub->pwritten = pkt->written + lenbytes; sub->lenbytes = lenbytes; if (lenbytes == 0) { sub->packet_len = 0; return 1; } sub->packet_len = pkt->written; if (!WPACKET_allocate_bytes(pkt, lenbytes, &lenchars)) return 0; return 1; } int WPACKET_start_sub_packet(WPACKET *pkt) { return WPACKET_start_sub_packet_len__(pkt, 0); } int WPACKET_put_bytes__(WPACKET *pkt, uint64_t val, size_t size) { unsigned char *data; /* Internal API, so should not fail */ if (!ossl_assert(size <= sizeof(uint64_t)) || !WPACKET_allocate_bytes(pkt, size, &data) || !put_value(data, val, size)) return 0; return 1; } int WPACKET_set_max_size(WPACKET *pkt, size_t maxsize) { WPACKET_SUB *sub; size_t lenbytes; /* Internal API, so should not fail */ if (!ossl_assert(pkt->subs != NULL)) return 0; /* Find the WPACKET_SUB for the top level */ for (sub = pkt->subs; sub->parent != NULL; sub = sub->parent) continue; lenbytes = sub->lenbytes; if (lenbytes == 0) lenbytes = sizeof(pkt->maxsize); if (maxmaxsize(lenbytes) < maxsize || maxsize < pkt->written) return 0; pkt->maxsize = maxsize; return 1; } int WPACKET_memset(WPACKET *pkt, int ch, size_t len) { unsigned char *dest; if (len == 0) return 1; if (!WPACKET_allocate_bytes(pkt, len, &dest)) return 0; if (dest != NULL) memset(dest, ch, len); return 1; } int WPACKET_memcpy(WPACKET *pkt, const void *src, size_t len) { unsigned char *dest; if (len == 0) return 1; if (!WPACKET_allocate_bytes(pkt, len, &dest)) return 0; if (dest != NULL) memcpy(dest, src, len); return 1; } int WPACKET_sub_memcpy__(WPACKET *pkt, const void *src, size_t len, size_t lenbytes) { if (!WPACKET_start_sub_packet_len__(pkt, lenbytes) || !WPACKET_memcpy(pkt, src, len) || !WPACKET_close(pkt)) return 0; return 1; } int WPACKET_get_total_written(WPACKET *pkt, size_t *written) { /* Internal API, so should not fail */ if (!ossl_assert(written != NULL)) return 0; *written = pkt->written; return 1; } int WPACKET_get_length(WPACKET *pkt, size_t *len) { /* Internal API, so should not fail */ if (!ossl_assert(pkt->subs != NULL && len != NULL)) return 0; *len = pkt->written - pkt->subs->pwritten; return 1; } unsigned char *WPACKET_get_curr(WPACKET *pkt) { unsigned char *buf = GETBUF(pkt); if (buf == NULL) return NULL; if (pkt->endfirst) return buf + pkt->maxsize - pkt->curr; return buf + pkt->curr; } int WPACKET_is_null_buf(WPACKET *pkt) { return pkt->buf == NULL && pkt->staticbuf == NULL; } void WPACKET_cleanup(WPACKET *pkt) { WPACKET_SUB *sub, *parent; for (sub = pkt->subs; sub != NULL; sub = parent) { parent = sub->parent; OPENSSL_free(sub); } pkt->subs = NULL; } #if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE int WPACKET_start_quic_sub_packet_bound(WPACKET *pkt, size_t max_len) { size_t enclen = ossl_quic_vlint_encode_len(max_len); if (enclen == 0) return 0; if (WPACKET_start_sub_packet_len__(pkt, enclen) == 0) return 0; pkt->subs->flags |= WPACKET_FLAGS_QUIC_VLINT; return 1; } int WPACKET_start_quic_sub_packet(WPACKET *pkt) { /* * Assume no (sub)packet will exceed 4GiB, thus the 8-byte encoding need not * be used. */ return WPACKET_start_quic_sub_packet_bound(pkt, OSSL_QUIC_VLINT_4B_MIN); } int WPACKET_quic_sub_allocate_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes) { if (!WPACKET_start_quic_sub_packet_bound(pkt, len) || !WPACKET_allocate_bytes(pkt, len, allocbytes) || !WPACKET_close(pkt)) return 0; return 1; } /* * Write a QUIC variable-length integer to the packet. */ int WPACKET_quic_write_vlint(WPACKET *pkt, uint64_t v) { unsigned char *b = NULL; size_t enclen = ossl_quic_vlint_encode_len(v); if (enclen == 0) return 0; if (WPACKET_allocate_bytes(pkt, enclen, &b) == 0) return 0; ossl_quic_vlint_encode(b, v); return 1; } #endif
./openssl/crypto/der_writer.c
/* * Copyright 2020 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 <stdlib.h> #include <string.h> #include "internal/cryptlib.h" #include "internal/der.h" #include "crypto/bn.h" static int int_start_context(WPACKET *pkt, int tag) { if (tag < 0) return 1; if (!ossl_assert(tag <= 30)) return 0; return WPACKET_start_sub_packet(pkt); } static int int_end_context(WPACKET *pkt, int tag) { /* * If someone set the flag WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH on this * sub-packet and this sub-packet has nothing written to it, the DER length * will not be written, and the total written size will be unchanged before * and after WPACKET_close(). We use size1 and size2 to determine if * anything was written, and only write our tag if it has. * */ size_t size1, size2; if (tag < 0) return 1; if (!ossl_assert(tag <= 30)) return 0; /* Context specific are normally (?) constructed */ tag |= DER_F_CONSTRUCTED | DER_C_CONTEXT; return WPACKET_get_total_written(pkt, &size1) && WPACKET_close(pkt) && WPACKET_get_total_written(pkt, &size2) && (size1 == size2 || WPACKET_put_bytes_u8(pkt, tag)); } int ossl_DER_w_precompiled(WPACKET *pkt, int tag, const unsigned char *precompiled, size_t precompiled_n) { return int_start_context(pkt, tag) && WPACKET_memcpy(pkt, precompiled, precompiled_n) && int_end_context(pkt, tag); } int ossl_DER_w_boolean(WPACKET *pkt, int tag, int b) { return int_start_context(pkt, tag) && WPACKET_start_sub_packet(pkt) && (!b || WPACKET_put_bytes_u8(pkt, 0xFF)) && !WPACKET_close(pkt) && !WPACKET_put_bytes_u8(pkt, DER_P_BOOLEAN) && int_end_context(pkt, tag); } int ossl_DER_w_octet_string(WPACKET *pkt, int tag, const unsigned char *data, size_t data_n) { return int_start_context(pkt, tag) && WPACKET_start_sub_packet(pkt) && WPACKET_memcpy(pkt, data, data_n) && WPACKET_close(pkt) && WPACKET_put_bytes_u8(pkt, DER_P_OCTET_STRING) && int_end_context(pkt, tag); } int ossl_DER_w_octet_string_uint32(WPACKET *pkt, int tag, uint32_t value) { unsigned char tmp[4] = { 0, 0, 0, 0 }; unsigned char *pbuf = tmp + (sizeof(tmp) - 1); while (value > 0) { *pbuf-- = (value & 0xFF); value >>= 8; } return ossl_DER_w_octet_string(pkt, tag, tmp, sizeof(tmp)); } static int int_der_w_integer(WPACKET *pkt, int tag, int (*put_bytes)(WPACKET *pkt, const void *v, unsigned int *top_byte), const void *v) { unsigned int top_byte = 0; return int_start_context(pkt, tag) && WPACKET_start_sub_packet(pkt) && put_bytes(pkt, v, &top_byte) && ((top_byte & 0x80) == 0 || WPACKET_put_bytes_u8(pkt, 0)) && WPACKET_close(pkt) && WPACKET_put_bytes_u8(pkt, DER_P_INTEGER) && int_end_context(pkt, tag); } static int int_put_bytes_uint32(WPACKET *pkt, const void *v, unsigned int *top_byte) { const uint32_t *value = v; uint32_t tmp = *value; size_t n = 0; while (tmp != 0) { n++; *top_byte = (tmp & 0xFF); tmp >>= 8; } if (n == 0) n = 1; return WPACKET_put_bytes__(pkt, *value, n); } /* For integers, we only support unsigned values for now */ int ossl_DER_w_uint32(WPACKET *pkt, int tag, uint32_t v) { return int_der_w_integer(pkt, tag, int_put_bytes_uint32, &v); } static int int_put_bytes_bn(WPACKET *pkt, const void *v, unsigned int *top_byte) { unsigned char *p = NULL; size_t n = BN_num_bytes(v); /* The BIGNUM limbs are in LE order */ *top_byte = ((bn_get_words(v) [(n - 1) / BN_BYTES]) >> (8 * ((n - 1) % BN_BYTES))) & 0xFF; if (!WPACKET_allocate_bytes(pkt, n, &p)) return 0; if (p != NULL) BN_bn2bin(v, p); return 1; } int ossl_DER_w_bn(WPACKET *pkt, int tag, const BIGNUM *v) { if (v == NULL || BN_is_negative(v)) return 0; if (BN_is_zero(v)) return ossl_DER_w_uint32(pkt, tag, 0); return int_der_w_integer(pkt, tag, int_put_bytes_bn, v); } int ossl_DER_w_null(WPACKET *pkt, int tag) { return int_start_context(pkt, tag) && WPACKET_start_sub_packet(pkt) && WPACKET_close(pkt) && WPACKET_put_bytes_u8(pkt, DER_P_NULL) && int_end_context(pkt, tag); } /* Constructed things need a start and an end */ int ossl_DER_w_begin_sequence(WPACKET *pkt, int tag) { return int_start_context(pkt, tag) && WPACKET_start_sub_packet(pkt); } int ossl_DER_w_end_sequence(WPACKET *pkt, int tag) { /* * If someone set the flag WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH on this * sub-packet and this sub-packet has nothing written to it, the DER length * will not be written, and the total written size will be unchanged before * and after WPACKET_close(). We use size1 and size2 to determine if * anything was written, and only write our tag if it has. * * Because we know that int_end_context() needs to do the same check, * we reproduce this flag if the written length was unchanged, or we will * have an erroneous context tag. */ size_t size1, size2; return WPACKET_get_total_written(pkt, &size1) && WPACKET_close(pkt) && WPACKET_get_total_written(pkt, &size2) && (size1 == size2 ? WPACKET_set_flags(pkt, WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH) : WPACKET_put_bytes_u8(pkt, DER_F_CONSTRUCTED | DER_P_SEQUENCE)) && int_end_context(pkt, tag); }
./openssl/crypto/passphrase.c
/* * 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 */ #include <openssl/err.h> #include <openssl/ui.h> #include <openssl/core_names.h> #include "internal/cryptlib.h" #include "internal/passphrase.h" void ossl_pw_clear_passphrase_data(struct ossl_passphrase_data_st *data) { if (data != NULL) { if (data->type == is_expl_passphrase) OPENSSL_clear_free(data->_.expl_passphrase.passphrase_copy, data->_.expl_passphrase.passphrase_len); ossl_pw_clear_passphrase_cache(data); memset(data, 0, sizeof(*data)); } } void ossl_pw_clear_passphrase_cache(struct ossl_passphrase_data_st *data) { OPENSSL_clear_free(data->cached_passphrase, data->cached_passphrase_len); data->cached_passphrase = NULL; } int ossl_pw_set_passphrase(struct ossl_passphrase_data_st *data, const unsigned char *passphrase, size_t passphrase_len) { if (!ossl_assert(data != NULL && passphrase != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } ossl_pw_clear_passphrase_data(data); data->type = is_expl_passphrase; data->_.expl_passphrase.passphrase_copy = passphrase_len != 0 ? OPENSSL_memdup(passphrase, passphrase_len) : OPENSSL_malloc(1); if (data->_.expl_passphrase.passphrase_copy == NULL) return 0; data->_.expl_passphrase.passphrase_len = passphrase_len; return 1; } int ossl_pw_set_pem_password_cb(struct ossl_passphrase_data_st *data, pem_password_cb *cb, void *cbarg) { if (!ossl_assert(data != NULL && cb != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } ossl_pw_clear_passphrase_data(data); data->type = is_pem_password; data->_.pem_password.password_cb = cb; data->_.pem_password.password_cbarg = cbarg; return 1; } int ossl_pw_set_ossl_passphrase_cb(struct ossl_passphrase_data_st *data, OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg) { if (!ossl_assert(data != NULL && cb != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } ossl_pw_clear_passphrase_data(data); data->type = is_ossl_passphrase; data->_.ossl_passphrase.passphrase_cb = cb; data->_.ossl_passphrase.passphrase_cbarg = cbarg; return 1; } int ossl_pw_set_ui_method(struct ossl_passphrase_data_st *data, const UI_METHOD *ui_method, void *ui_data) { if (!ossl_assert(data != NULL && ui_method != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } ossl_pw_clear_passphrase_data(data); data->type = is_ui_method; data->_.ui_method.ui_method = ui_method; data->_.ui_method.ui_method_data = ui_data; return 1; } int ossl_pw_enable_passphrase_caching(struct ossl_passphrase_data_st *data) { data->flag_cache_passphrase = 1; return 1; } int ossl_pw_disable_passphrase_caching(struct ossl_passphrase_data_st *data) { data->flag_cache_passphrase = 0; return 1; } /*- * UI_METHOD processor. It differs from UI_UTIL_read_pw() like this: * * 1. It constructs a prompt on its own, based on |prompt_info|. * 2. It allocates a buffer for password and verification on its own * to compensate for NUL terminator in UI password strings. * 3. It raises errors. * 4. It reports back the length of the prompted pass phrase. */ static int do_ui_passphrase(char *pass, size_t pass_size, size_t *pass_len, const char *prompt_info, int verify, const UI_METHOD *ui_method, void *ui_data) { char *prompt = NULL, *ipass = NULL, *vpass = NULL; int prompt_idx = -1, verify_idx = -1, res; UI *ui = NULL; int ret = 0; if (!ossl_assert(pass != NULL && pass_size != 0 && pass_len != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((ui = UI_new()) == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB); return 0; } if (ui_method != NULL) { UI_set_method(ui, ui_method); if (ui_data != NULL) UI_add_user_data(ui, ui_data); } /* Get an application constructed prompt */ prompt = UI_construct_prompt(ui, "pass phrase", prompt_info); if (prompt == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB); goto end; } /* Get a buffer for verification prompt */ ipass = OPENSSL_zalloc(pass_size + 1); if (ipass == NULL) goto end; prompt_idx = UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD, ipass, 0, pass_size) - 1; if (prompt_idx < 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB); goto end; } if (verify) { /* Get a buffer for verification prompt */ vpass = OPENSSL_zalloc(pass_size + 1); if (vpass == NULL) goto end; verify_idx = UI_add_verify_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD, vpass, 0, pass_size, ipass) - 1; if (verify_idx < 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB); goto end; } } switch (UI_process(ui)) { case -2: ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERRUPTED_OR_CANCELLED); break; case -1: ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB); break; default: res = UI_get_result_length(ui, prompt_idx); if (res < 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB); break; } *pass_len = (size_t)res; memcpy(pass, ipass, *pass_len); ret = 1; break; } end: OPENSSL_clear_free(vpass, pass_size + 1); OPENSSL_clear_free(ipass, pass_size + 1); OPENSSL_free(prompt); UI_free(ui); return ret; } /* Central pw prompting dispatcher */ 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) { const char *source = NULL; size_t source_len = 0; const char *prompt_info = NULL; const UI_METHOD *ui_method = NULL; UI_METHOD *allocated_ui_method = NULL; void *ui_data = NULL; const OSSL_PARAM *p = NULL; int ret; /* Handle explicit and cached passphrases */ if (data->type == is_expl_passphrase) { source = data->_.expl_passphrase.passphrase_copy; source_len = data->_.expl_passphrase.passphrase_len; } else if (data->flag_cache_passphrase && data->cached_passphrase != NULL) { source = data->cached_passphrase; source_len = data->cached_passphrase_len; } if (source != NULL) { if (source_len > pass_size) source_len = pass_size; memcpy(pass, source, source_len); *pass_len = source_len; return 1; } /* Handle the is_ossl_passphrase case... that's pretty direct */ if (data->type == is_ossl_passphrase) { OSSL_PASSPHRASE_CALLBACK *cb = data->_.ossl_passphrase.passphrase_cb; void *cbarg = data->_.ossl_passphrase.passphrase_cbarg; ret = cb(pass, pass_size, pass_len, params, cbarg); goto do_cache; } /* Handle the is_pem_password and is_ui_method cases */ if ((p = OSSL_PARAM_locate_const(params, OSSL_PASSPHRASE_PARAM_INFO)) != NULL) { if (p->data_type != OSSL_PARAM_UTF8_STRING) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT, "Prompt info data type incorrect"); return 0; } prompt_info = p->data; } if (data->type == is_pem_password) { /* We use a UI wrapper for PEM */ pem_password_cb *cb = data->_.pem_password.password_cb; ui_method = allocated_ui_method = UI_UTIL_wrap_read_pem_callback(cb, verify); ui_data = data->_.pem_password.password_cbarg; if (ui_method == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB); return 0; } } else if (data->type == is_ui_method) { ui_method = data->_.ui_method.ui_method; ui_data = data->_.ui_method.ui_method_data; } if (ui_method == NULL) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT, "No password method specified"); return 0; } ret = do_ui_passphrase(pass, pass_size, pass_len, prompt_info, verify, ui_method, ui_data); UI_destroy_method(allocated_ui_method); do_cache: if (ret && data->flag_cache_passphrase) { if (data->cached_passphrase == NULL || *pass_len > data->cached_passphrase_len) { void *new_cache = OPENSSL_clear_realloc(data->cached_passphrase, data->cached_passphrase_len, *pass_len + 1); if (new_cache == NULL) { OPENSSL_cleanse(pass, *pass_len); return 0; } data->cached_passphrase = new_cache; } memcpy(data->cached_passphrase, pass, *pass_len); data->cached_passphrase[*pass_len] = '\0'; data->cached_passphrase_len = *pass_len; } return ret; } static int ossl_pw_get_password(char *buf, int size, int rwflag, void *userdata, const char *info) { size_t password_len = 0; OSSL_PARAM params[] = { OSSL_PARAM_utf8_string(OSSL_PASSPHRASE_PARAM_INFO, NULL, 0), OSSL_PARAM_END }; params[0].data = (void *)info; if (ossl_pw_get_passphrase(buf, (size_t)size, &password_len, params, rwflag, userdata)) return (int)password_len; return -1; } int ossl_pw_pem_password(char *buf, int size, int rwflag, void *userdata) { return ossl_pw_get_password(buf, size, rwflag, userdata, "PEM"); } int ossl_pw_pvk_password(char *buf, int size, int rwflag, void *userdata) { return ossl_pw_get_password(buf, size, rwflag, userdata, "PVK"); } int ossl_pw_passphrase_callback_enc(char *pass, size_t pass_size, size_t *pass_len, const OSSL_PARAM params[], void *arg) { return ossl_pw_get_passphrase(pass, pass_size, pass_len, params, 1, arg); } int ossl_pw_passphrase_callback_dec(char *pass, size_t pass_size, size_t *pass_len, const OSSL_PARAM params[], void *arg) { return ossl_pw_get_passphrase(pass, pass_size, pass_len, params, 0, arg); }
./openssl/crypto/mem_clr.c
/* * Copyright 2002-2016 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 <string.h> #include <openssl/crypto.h> /* * Pointer to memset is volatile so that compiler must de-reference * the pointer and can't assume that it points to any function in * particular (such as memset, which it then might further "optimize") */ typedef void *(*memset_t)(void *, int, size_t); static volatile memset_t memset_func = memset; void OPENSSL_cleanse(void *ptr, size_t len) { memset_func(ptr, 0, len); }
./openssl/crypto/threads_win.c
/* * 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 */ #if defined(_WIN32) # include <windows.h> # if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 # define USE_RWLOCK # endif #endif /* * VC++ 2008 or earlier x86 compilers do not have an inline implementation * of InterlockedOr64 for 32bit and will fail to run on Windows XP 32bit. * https://docs.microsoft.com/en-us/cpp/intrinsics/interlockedor-intrinsic-functions#requirements * To work around this problem, we implement a manual locking mechanism for * only VC++ 2008 or earlier x86 compilers. */ #if (defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER <= 1600) # define NO_INTERLOCKEDOR64 #endif #include <openssl/crypto.h> #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && defined(OPENSSL_SYS_WINDOWS) # ifdef USE_RWLOCK typedef struct { SRWLOCK lock; int exclusive; } CRYPTO_win_rwlock; # endif CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void) { CRYPTO_RWLOCK *lock; # ifdef USE_RWLOCK CRYPTO_win_rwlock *rwlock; if ((lock = CRYPTO_zalloc(sizeof(CRYPTO_win_rwlock), NULL, 0)) == NULL) /* Don't set error, to avoid recursion blowup. */ return NULL; rwlock = lock; InitializeSRWLock(&rwlock->lock); # else if ((lock = CRYPTO_zalloc(sizeof(CRITICAL_SECTION), NULL, 0)) == NULL) /* Don't set error, to avoid recursion blowup. */ return NULL; # if !defined(_WIN32_WCE) /* 0x400 is the spin count value suggested in the documentation */ if (!InitializeCriticalSectionAndSpinCount(lock, 0x400)) { OPENSSL_free(lock); return NULL; } # else InitializeCriticalSection(lock); # endif # endif return lock; } __owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK CRYPTO_win_rwlock *rwlock = lock; AcquireSRWLockShared(&rwlock->lock); # else EnterCriticalSection(lock); # endif return 1; } __owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK CRYPTO_win_rwlock *rwlock = lock; AcquireSRWLockExclusive(&rwlock->lock); rwlock->exclusive = 1; # else EnterCriticalSection(lock); # endif return 1; } int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock) { # ifdef USE_RWLOCK CRYPTO_win_rwlock *rwlock = lock; if (rwlock->exclusive) { rwlock->exclusive = 0; ReleaseSRWLockExclusive(&rwlock->lock); } else { ReleaseSRWLockShared(&rwlock->lock); } # else LeaveCriticalSection(lock); # endif return 1; } void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock) { if (lock == NULL) return; # ifndef USE_RWLOCK DeleteCriticalSection(lock); # endif OPENSSL_free(lock); return; } # define ONCE_UNINITED 0 # define ONCE_ININIT 1 # define ONCE_DONE 2 /* * We don't use InitOnceExecuteOnce because that isn't available in WinXP which * we still have to support. */ int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void)) { LONG volatile *lock = (LONG *)once; LONG result; if (*lock == ONCE_DONE) return 1; do { result = InterlockedCompareExchange(lock, ONCE_ININIT, ONCE_UNINITED); if (result == ONCE_UNINITED) { init(); *lock = ONCE_DONE; return 1; } } while (result == ONCE_ININIT); return (*lock == ONCE_DONE); } int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *)) { *key = TlsAlloc(); if (*key == TLS_OUT_OF_INDEXES) return 0; return 1; } void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key) { DWORD last_error; void *ret; /* * TlsGetValue clears the last error even on success, so that callers may * distinguish it successfully returning NULL or failing. It is documented * to never fail if the argument is a valid index from TlsAlloc, so we do * not need to handle this. * * However, this error-mangling behavior interferes with the caller's use of * GetLastError. In particular SSL_get_error queries the error queue to * determine whether the caller should look at the OS's errors. To avoid * destroying state, save and restore the Windows error. * * https://msdn.microsoft.com/en-us/library/windows/desktop/ms686812(v=vs.85).aspx */ last_error = GetLastError(); ret = TlsGetValue(*key); SetLastError(last_error); return ret; } int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val) { if (TlsSetValue(*key, val) == 0) return 0; return 1; } int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key) { if (TlsFree(*key) == 0) return 0; return 1; } CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void) { return GetCurrentThreadId(); } int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b) { return (a == b); } int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock) { *ret = (int)InterlockedExchangeAdd((long volatile *)val, (long)amount) + amount; return 1; } int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret, CRYPTO_RWLOCK *lock) { #if (defined(NO_INTERLOCKEDOR64)) if (lock == NULL || !CRYPTO_THREAD_write_lock(lock)) return 0; *val |= op; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; #else *ret = (uint64_t)InterlockedOr64((LONG64 volatile *)val, (LONG64)op) | op; return 1; #endif } int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock) { #if (defined(NO_INTERLOCKEDOR64)) if (lock == NULL || !CRYPTO_THREAD_read_lock(lock)) return 0; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; #else *ret = (uint64_t)InterlockedOr64((LONG64 volatile *)val, 0); return 1; #endif } int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock) { #if (defined(NO_INTERLOCKEDOR64)) if (lock == NULL || !CRYPTO_THREAD_read_lock(lock)) return 0; *ret = *val; if (!CRYPTO_THREAD_unlock(lock)) return 0; return 1; #else /* On Windows, LONG is always the same size as int. */ *ret = (int)InterlockedOr((LONG volatile *)val, 0); return 1; #endif } int openssl_init_fork_handlers(void) { return 0; } int openssl_get_fork_id(void) { return 0; } #endif
./openssl/crypto/ebcdic.c
/* * Copyright 2000-2016 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/e_os2.h> #ifndef CHARSET_EBCDIC NON_EMPTY_TRANSLATION_UNIT #else # include <openssl/ebcdic.h> # ifdef CHARSET_EBCDIC_TEST /* * Here we're looking to test the EBCDIC code on an ASCII system so we don't do * any translation in these tables at all. */ /* The ebcdic-to-ascii table: */ const unsigned char os_toascii[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The ascii-to-ebcdic table: */ const unsigned char os_toebcdic[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; # elif defined(_OSD_POSIX) /* * "BS2000 OSD" is a POSIX subsystem on a main frame. It is made by Siemens * AG, Germany, for their BS2000 mainframe machines. Within the POSIX * subsystem, the same character set was chosen as in "native BS2000", namely * EBCDIC. (EDF04) * * The name "ASCII" in these routines is misleading: actually, conversion is * not between EBCDIC and ASCII, but EBCDIC(EDF04) and ISO-8859.1; that means * that (western european) national characters are preserved. * * This table is identical to the one used by rsh/rcp/ftp and other POSIX * tools. */ /* Here's the bijective ebcdic-to-ascii table: */ const unsigned char os_toascii[256] = { /* * 00 */ 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f, 0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */ /* * 10 */ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97, 0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */ /* * 20 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /* ................ */ /* * 30 */ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /* ................ */ /* * 40 */ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, 0xe7, 0xf1, 0x60, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* .........`.<(+| */ /* * 50 */ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x9f, /* &.........!$*);. */ /* * 60 */ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, 0xc7, 0xd1, 0x5e, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /*-/........^,%_>?*/ /* * 70 */ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, 0xcc, 0xa8, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /* ..........:#@'=" */ /* * 80 */ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /* .abcdefghi...... */ /* * 90 */ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /* .jklmnopqr...... */ /* * a0 */ 0xb5, 0xaf, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, /* ..stuvwxyz...... */ /* * b0 */ 0xa2, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, 0xbd, 0xbe, 0xac, 0x5b, 0x5c, 0x5d, 0xb4, 0xd7, /* ...........[\].. */ /* * c0 */ 0xf9, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /* .ABCDEFGHI...... */ /* * d0 */ 0xa6, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xdb, 0xfa, 0xff, /* .JKLMNOPQR...... */ /* * e0 */ 0xd9, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /* ..STUVWXYZ...... */ /* * f0 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xb3, 0x7b, 0xdc, 0x7d, 0xda, 0x7e /* 0123456789.{.}.~ */ }; /* The ascii-to-ebcdic table: */ const unsigned char os_toebcdic[256] = { /* * 00 */ 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, 0x16, 0x05, 0x15, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */ /* * 10 */ 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */ /* * 20 */ 0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d, 0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, /* !"#$%&'()*+,-./ */ /* * 30 */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, /* 0123456789:;<=>? */ /* * 40 */ 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, /* @ABCDEFGHIJKLMNO */ /* * 50 */ 0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xbb, 0xbc, 0xbd, 0x6a, 0x6d, /* PQRSTUVWXYZ[\]^_ */ /* * 60 */ 0x4a, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, /* `abcdefghijklmno */ /* * 70 */ 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xfb, 0x4f, 0xfd, 0xff, 0x07, /* pqrstuvwxyz{|}~. */ /* * 80 */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x04, 0x06, 0x08, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x14, /* ................ */ /* * 90 */ 0x30, 0x31, 0x25, 0x33, 0x34, 0x35, 0x36, 0x17, 0x38, 0x39, 0x3a, 0x3b, 0x1a, 0x1b, 0x3e, 0x5f, /* ................ */ /* * a0 */ 0x41, 0xaa, 0xb0, 0xb1, 0x9f, 0xb2, 0xd0, 0xb5, 0x79, 0xb4, 0x9a, 0x8a, 0xba, 0xca, 0xaf, 0xa1, /* ................ */ /* * b0 */ 0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3, 0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, /* ................ */ /* * c0 */ 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, /* ................ */ /* * d0 */ 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, 0x80, 0xe0, 0xfe, 0xdd, 0xfc, 0xad, 0xae, 0x59, /* ................ */ /* * e0 */ 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48, 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, /* ................ */ /* * f0 */ 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, 0x70, 0xc0, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf /* ................ */ }; # else /*_OSD_POSIX*/ /* * This code does basic character mapping for IBM's TPF and OS/390 operating * systems. It is a modified version of the BS2000 table. * * Bijective EBCDIC (character set IBM-1047) to US-ASCII table: This table is * bijective - there are no ambiguous or duplicate characters. */ const unsigned char os_toascii[256] = { 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f, /* 00-0f: */ 0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97, /* 10-1f: */ 0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b, /* 20-2f: */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /* ................ */ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, /* 30-3f: */ 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /* ................ */ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, /* 40-4f: */ 0xe7, 0xf1, 0xa2, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* ...........<(+| */ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, /* 50-5f: */ 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x5e, /* &.........!$*);^ */ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, /* 60-6f: */ 0xc7, 0xd1, 0xa6, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /* -/.........,%_>? */ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, /* 70-7f: */ 0xcc, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /* .........`:#@'=" */ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 80-8f: */ 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /* .abcdefghi...... */ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, /* 90-9f: */ 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /* .jklmnopqr...... */ 0xb5, 0x7e, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, /* a0-af: */ 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0x5b, 0xde, 0xae, /* .~stuvwxyz...[.. */ 0xac, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, /* b0-bf: */ 0xbd, 0xbe, 0xdd, 0xa8, 0xaf, 0x5d, 0xb4, 0xd7, /* .............].. */ 0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* c0-cf: */ 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /* {ABCDEFGHI...... */ 0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, /* d0-df: */ 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xf9, 0xfa, 0xff, /* }JKLMNOPQR...... */ 0x5c, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, /* e0-ef: */ 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /* \.STUVWXYZ...... */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* f0-ff: */ 0x38, 0x39, 0xb3, 0xdb, 0xdc, 0xd9, 0xda, 0x9f /* 0123456789...... */ }; /* * The US-ASCII to EBCDIC (character set IBM-1047) table: This table is * bijective (no ambiguous or duplicate characters) */ const unsigned char os_toebcdic[256] = { 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, /* 00-0f: */ 0x16, 0x05, 0x15, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */ 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, /* 10-1f: */ 0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */ 0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d, /* 20-2f: */ 0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, /* !"#$%&'()*+,-./ */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 30-3f: */ 0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, /* 0123456789:;<=>? */ 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 40-4f: */ 0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, /* @ABCDEFGHIJKLMNO */ 0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, /* 50-5f: */ 0xe7, 0xe8, 0xe9, 0xad, 0xe0, 0xbd, 0x5f, 0x6d, /* PQRSTUVWXYZ[\]^_ */ 0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 60-6f: */ 0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, /* `abcdefghijklmno */ 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, /* 70-7f: */ 0xa7, 0xa8, 0xa9, 0xc0, 0x4f, 0xd0, 0xa1, 0x07, /* pqrstuvwxyz{|}~. */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x04, 0x06, 0x08, /* 80-8f: */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x14, /* ................ */ 0x30, 0x31, 0x25, 0x33, 0x34, 0x35, 0x36, 0x17, /* 90-9f: */ 0x38, 0x39, 0x3a, 0x3b, 0x1a, 0x1b, 0x3e, 0xff, /* ................ */ 0x41, 0xaa, 0x4a, 0xb1, 0x9f, 0xb2, 0x6a, 0xb5, /* a0-af: */ 0xbb, 0xb4, 0x9a, 0x8a, 0xb0, 0xca, 0xaf, 0xbc, /* ................ */ 0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3, /* b0-bf: */ 0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, /* ................ */ 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, /* c0-cf: */ 0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, /* ................ */ 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, /* d0-df: */ 0x80, 0xfd, 0xfe, 0xfb, 0xfc, 0xba, 0xae, 0x59, /* ................ */ 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48, /* e0-ef: */ 0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, /* ................ */ 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, /* f0-ff: */ 0x70, 0xdd, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf /* ................ */ }; # endif/*_OSD_POSIX*/ /* * Translate a memory block from EBCDIC (host charset) to ASCII (net charset) * dest and srce may be identical, or separate memory blocks, but should not * overlap. These functions intentionally have an interface compatible to * memcpy(3). */ void *ebcdic2ascii(void *dest, const void *srce, size_t count) { unsigned char *udest = dest; const unsigned char *usrce = srce; while (count-- != 0) { *udest++ = os_toascii[*usrce++]; } return dest; } void *ascii2ebcdic(void *dest, const void *srce, size_t count) { unsigned char *udest = dest; const unsigned char *usrce = srce; while (count-- != 0) { *udest++ = os_toebcdic[*usrce++]; } return dest; } #endif
./openssl/crypto/context.c
/* * 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 */ #include "crypto/cryptlib.h" #include <openssl/conf.h> #include "internal/thread_once.h" #include "internal/property.h" #include "internal/core.h" #include "internal/bio.h" #include "internal/provider.h" #include "crypto/decoder.h" #include "crypto/context.h" struct ossl_lib_ctx_st { CRYPTO_RWLOCK *lock, *rand_crngt_lock; OSSL_EX_DATA_GLOBAL global; void *property_string_data; void *evp_method_store; void *provider_store; void *namemap; void *property_defns; void *global_properties; void *drbg; void *drbg_nonce; #ifndef FIPS_MODULE void *provider_conf; void *bio_core; void *child_provider; OSSL_METHOD_STORE *decoder_store; void *decoder_cache; OSSL_METHOD_STORE *encoder_store; OSSL_METHOD_STORE *store_loader_store; void *self_test_cb; #endif #if defined(OPENSSL_THREADS) void *threads; #endif void *rand_crngt; #ifdef FIPS_MODULE void *thread_event_handler; void *fips_prov; #endif unsigned int ischild:1; }; int ossl_lib_ctx_write_lock(OSSL_LIB_CTX *ctx) { return CRYPTO_THREAD_write_lock(ossl_lib_ctx_get_concrete(ctx)->lock); } int ossl_lib_ctx_read_lock(OSSL_LIB_CTX *ctx) { return CRYPTO_THREAD_read_lock(ossl_lib_ctx_get_concrete(ctx)->lock); } int ossl_lib_ctx_unlock(OSSL_LIB_CTX *ctx) { return CRYPTO_THREAD_unlock(ossl_lib_ctx_get_concrete(ctx)->lock); } int ossl_lib_ctx_is_child(OSSL_LIB_CTX *ctx) { ctx = ossl_lib_ctx_get_concrete(ctx); if (ctx == NULL) return 0; return ctx->ischild; } static void context_deinit_objs(OSSL_LIB_CTX *ctx); static int context_init(OSSL_LIB_CTX *ctx) { int exdata_done = 0; ctx->lock = CRYPTO_THREAD_lock_new(); if (ctx->lock == NULL) return 0; ctx->rand_crngt_lock = CRYPTO_THREAD_lock_new(); if (ctx->rand_crngt_lock == NULL) goto err; /* Initialize ex_data. */ if (!ossl_do_ex_data_init(ctx)) goto err; exdata_done = 1; /* P2. We want evp_method_store to be cleaned up before the provider store */ ctx->evp_method_store = ossl_method_store_new(ctx); if (ctx->evp_method_store == NULL) goto err; #ifndef FIPS_MODULE /* P2. Must be freed before the provider store is freed */ ctx->provider_conf = ossl_prov_conf_ctx_new(ctx); if (ctx->provider_conf == NULL) goto err; #endif /* P2. */ ctx->drbg = ossl_rand_ctx_new(ctx); if (ctx->drbg == NULL) goto err; #ifndef FIPS_MODULE /* * P2. We want decoder_store/decoder_cache to be cleaned up before the * provider store */ ctx->decoder_store = ossl_method_store_new(ctx); if (ctx->decoder_store == NULL) goto err; ctx->decoder_cache = ossl_decoder_cache_new(ctx); if (ctx->decoder_cache == NULL) goto err; /* P2. We want encoder_store to be cleaned up before the provider store */ ctx->encoder_store = ossl_method_store_new(ctx); if (ctx->encoder_store == NULL) goto err; /* P2. We want loader_store to be cleaned up before the provider store */ ctx->store_loader_store = ossl_method_store_new(ctx); if (ctx->store_loader_store == NULL) goto err; #endif /* P1. Needs to be freed before the child provider data is freed */ ctx->provider_store = ossl_provider_store_new(ctx); if (ctx->provider_store == NULL) goto err; /* Default priority. */ ctx->property_string_data = ossl_property_string_data_new(ctx); if (ctx->property_string_data == NULL) goto err; ctx->namemap = ossl_stored_namemap_new(ctx); if (ctx->namemap == NULL) goto err; ctx->property_defns = ossl_property_defns_new(ctx); if (ctx->property_defns == NULL) goto err; ctx->global_properties = ossl_ctx_global_properties_new(ctx); if (ctx->global_properties == NULL) goto err; #ifndef FIPS_MODULE ctx->bio_core = ossl_bio_core_globals_new(ctx); if (ctx->bio_core == NULL) goto err; #endif ctx->drbg_nonce = ossl_prov_drbg_nonce_ctx_new(ctx); if (ctx->drbg_nonce == NULL) goto err; #ifndef FIPS_MODULE ctx->self_test_cb = ossl_self_test_set_callback_new(ctx); if (ctx->self_test_cb == NULL) goto err; #endif #ifdef FIPS_MODULE ctx->thread_event_handler = ossl_thread_event_ctx_new(ctx); if (ctx->thread_event_handler == NULL) goto err; ctx->fips_prov = ossl_fips_prov_ossl_ctx_new(ctx); if (ctx->fips_prov == NULL) goto err; #endif #ifndef OPENSSL_NO_THREAD_POOL ctx->threads = ossl_threads_ctx_new(ctx); if (ctx->threads == NULL) goto err; #endif /* Low priority. */ #ifndef FIPS_MODULE ctx->child_provider = ossl_child_prov_ctx_new(ctx); if (ctx->child_provider == NULL) goto err; #endif /* Everything depends on properties, so we also pre-initialise that */ if (!ossl_property_parse_init(ctx)) goto err; return 1; err: context_deinit_objs(ctx); if (exdata_done) ossl_crypto_cleanup_all_ex_data_int(ctx); CRYPTO_THREAD_lock_free(ctx->rand_crngt_lock); CRYPTO_THREAD_lock_free(ctx->lock); memset(ctx, '\0', sizeof(*ctx)); return 0; } static void context_deinit_objs(OSSL_LIB_CTX *ctx) { /* P2. We want evp_method_store to be cleaned up before the provider store */ if (ctx->evp_method_store != NULL) { ossl_method_store_free(ctx->evp_method_store); ctx->evp_method_store = NULL; } /* P2. */ if (ctx->drbg != NULL) { ossl_rand_ctx_free(ctx->drbg); ctx->drbg = NULL; } #ifndef FIPS_MODULE /* P2. */ if (ctx->provider_conf != NULL) { ossl_prov_conf_ctx_free(ctx->provider_conf); ctx->provider_conf = NULL; } /* * P2. We want decoder_store/decoder_cache to be cleaned up before the * provider store */ if (ctx->decoder_store != NULL) { ossl_method_store_free(ctx->decoder_store); ctx->decoder_store = NULL; } if (ctx->decoder_cache != NULL) { ossl_decoder_cache_free(ctx->decoder_cache); ctx->decoder_cache = NULL; } /* P2. We want encoder_store to be cleaned up before the provider store */ if (ctx->encoder_store != NULL) { ossl_method_store_free(ctx->encoder_store); ctx->encoder_store = NULL; } /* P2. We want loader_store to be cleaned up before the provider store */ if (ctx->store_loader_store != NULL) { ossl_method_store_free(ctx->store_loader_store); ctx->store_loader_store = NULL; } #endif /* P1. Needs to be freed before the child provider data is freed */ if (ctx->provider_store != NULL) { ossl_provider_store_free(ctx->provider_store); ctx->provider_store = NULL; } /* Default priority. */ if (ctx->property_string_data != NULL) { ossl_property_string_data_free(ctx->property_string_data); ctx->property_string_data = NULL; } if (ctx->namemap != NULL) { ossl_stored_namemap_free(ctx->namemap); ctx->namemap = NULL; } if (ctx->property_defns != NULL) { ossl_property_defns_free(ctx->property_defns); ctx->property_defns = NULL; } if (ctx->global_properties != NULL) { ossl_ctx_global_properties_free(ctx->global_properties); ctx->global_properties = NULL; } #ifndef FIPS_MODULE if (ctx->bio_core != NULL) { ossl_bio_core_globals_free(ctx->bio_core); ctx->bio_core = NULL; } #endif if (ctx->drbg_nonce != NULL) { ossl_prov_drbg_nonce_ctx_free(ctx->drbg_nonce); ctx->drbg_nonce = NULL; } #ifndef FIPS_MODULE if (ctx->self_test_cb != NULL) { ossl_self_test_set_callback_free(ctx->self_test_cb); ctx->self_test_cb = NULL; } #endif if (ctx->rand_crngt != NULL) { ossl_rand_crng_ctx_free(ctx->rand_crngt); ctx->rand_crngt = NULL; } #ifdef FIPS_MODULE if (ctx->thread_event_handler != NULL) { ossl_thread_event_ctx_free(ctx->thread_event_handler); ctx->thread_event_handler = NULL; } if (ctx->fips_prov != NULL) { ossl_fips_prov_ossl_ctx_free(ctx->fips_prov); ctx->fips_prov = NULL; } #endif #ifndef OPENSSL_NO_THREAD_POOL if (ctx->threads != NULL) { ossl_threads_ctx_free(ctx->threads); ctx->threads = NULL; } #endif /* Low priority. */ #ifndef FIPS_MODULE if (ctx->child_provider != NULL) { ossl_child_prov_ctx_free(ctx->child_provider); ctx->child_provider = NULL; } #endif } static int context_deinit(OSSL_LIB_CTX *ctx) { if (ctx == NULL) return 1; ossl_ctx_thread_stop(ctx); context_deinit_objs(ctx); ossl_crypto_cleanup_all_ex_data_int(ctx); CRYPTO_THREAD_lock_free(ctx->rand_crngt_lock); CRYPTO_THREAD_lock_free(ctx->lock); ctx->rand_crngt_lock = NULL; ctx->lock = NULL; return 1; } #ifndef FIPS_MODULE /* The default default context */ static OSSL_LIB_CTX default_context_int; static CRYPTO_ONCE default_context_init = CRYPTO_ONCE_STATIC_INIT; static CRYPTO_THREAD_LOCAL default_context_thread_local; static int default_context_inited = 0; DEFINE_RUN_ONCE_STATIC(default_context_do_init) { if (!CRYPTO_THREAD_init_local(&default_context_thread_local, NULL)) goto err; if (!context_init(&default_context_int)) goto deinit_thread; default_context_inited = 1; return 1; deinit_thread: CRYPTO_THREAD_cleanup_local(&default_context_thread_local); err: return 0; } void ossl_lib_ctx_default_deinit(void) { if (!default_context_inited) return; context_deinit(&default_context_int); CRYPTO_THREAD_cleanup_local(&default_context_thread_local); default_context_inited = 0; } static OSSL_LIB_CTX *get_thread_default_context(void) { if (!RUN_ONCE(&default_context_init, default_context_do_init)) return NULL; return CRYPTO_THREAD_get_local(&default_context_thread_local); } static OSSL_LIB_CTX *get_default_context(void) { OSSL_LIB_CTX *current_defctx = get_thread_default_context(); if (current_defctx == NULL) current_defctx = &default_context_int; return current_defctx; } static int set_default_context(OSSL_LIB_CTX *defctx) { if (defctx == &default_context_int) defctx = NULL; return CRYPTO_THREAD_set_local(&default_context_thread_local, defctx); } #endif OSSL_LIB_CTX *OSSL_LIB_CTX_new(void) { OSSL_LIB_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx != NULL && !context_init(ctx)) { OPENSSL_free(ctx); ctx = NULL; } return ctx; } #ifndef FIPS_MODULE OSSL_LIB_CTX *OSSL_LIB_CTX_new_from_dispatch(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in) { OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new(); if (ctx == NULL) return NULL; if (!ossl_bio_init_core(ctx, in)) { OSSL_LIB_CTX_free(ctx); return NULL; } return ctx; } OSSL_LIB_CTX *OSSL_LIB_CTX_new_child(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in) { OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new_from_dispatch(handle, in); if (ctx == NULL) return NULL; if (!ossl_provider_init_as_child(ctx, handle, in)) { OSSL_LIB_CTX_free(ctx); return NULL; } ctx->ischild = 1; return ctx; } int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file) { return CONF_modules_load_file_ex(ctx, config_file, NULL, 0) > 0; } #endif void OSSL_LIB_CTX_free(OSSL_LIB_CTX *ctx) { if (ossl_lib_ctx_is_default(ctx)) return; #ifndef FIPS_MODULE if (ctx->ischild) ossl_provider_deinit_child(ctx); #endif context_deinit(ctx); OPENSSL_free(ctx); } #ifndef FIPS_MODULE OSSL_LIB_CTX *OSSL_LIB_CTX_get0_global_default(void) { if (!RUN_ONCE(&default_context_init, default_context_do_init)) return NULL; return &default_context_int; } OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *libctx) { OSSL_LIB_CTX *current_defctx; if ((current_defctx = get_default_context()) != NULL) { if (libctx != NULL) set_default_context(libctx); return current_defctx; } return NULL; } void ossl_release_default_drbg_ctx(void) { /* early release of the DRBG in global default libctx */ if (default_context_int.drbg != NULL) { ossl_rand_ctx_free(default_context_int.drbg); default_context_int.drbg = NULL; } } #endif OSSL_LIB_CTX *ossl_lib_ctx_get_concrete(OSSL_LIB_CTX *ctx) { #ifndef FIPS_MODULE if (ctx == NULL) return get_default_context(); #endif return ctx; } int ossl_lib_ctx_is_default(OSSL_LIB_CTX *ctx) { #ifndef FIPS_MODULE if (ctx == NULL || ctx == get_default_context()) return 1; #endif return 0; } int ossl_lib_ctx_is_global_default(OSSL_LIB_CTX *ctx) { #ifndef FIPS_MODULE if (ossl_lib_ctx_get_concrete(ctx) == &default_context_int) return 1; #endif return 0; } void *ossl_lib_ctx_get_data(OSSL_LIB_CTX *ctx, int index) { void *p; ctx = ossl_lib_ctx_get_concrete(ctx); if (ctx == NULL) return NULL; switch (index) { case OSSL_LIB_CTX_PROPERTY_STRING_INDEX: return ctx->property_string_data; case OSSL_LIB_CTX_EVP_METHOD_STORE_INDEX: return ctx->evp_method_store; case OSSL_LIB_CTX_PROVIDER_STORE_INDEX: return ctx->provider_store; case OSSL_LIB_CTX_NAMEMAP_INDEX: return ctx->namemap; case OSSL_LIB_CTX_PROPERTY_DEFN_INDEX: return ctx->property_defns; case OSSL_LIB_CTX_GLOBAL_PROPERTIES: return ctx->global_properties; case OSSL_LIB_CTX_DRBG_INDEX: return ctx->drbg; case OSSL_LIB_CTX_DRBG_NONCE_INDEX: return ctx->drbg_nonce; #ifndef FIPS_MODULE case OSSL_LIB_CTX_PROVIDER_CONF_INDEX: return ctx->provider_conf; case OSSL_LIB_CTX_BIO_CORE_INDEX: return ctx->bio_core; case OSSL_LIB_CTX_CHILD_PROVIDER_INDEX: return ctx->child_provider; case OSSL_LIB_CTX_DECODER_STORE_INDEX: return ctx->decoder_store; case OSSL_LIB_CTX_DECODER_CACHE_INDEX: return ctx->decoder_cache; case OSSL_LIB_CTX_ENCODER_STORE_INDEX: return ctx->encoder_store; case OSSL_LIB_CTX_STORE_LOADER_STORE_INDEX: return ctx->store_loader_store; case OSSL_LIB_CTX_SELF_TEST_CB_INDEX: return ctx->self_test_cb; #endif #ifndef OPENSSL_NO_THREAD_POOL case OSSL_LIB_CTX_THREAD_INDEX: return ctx->threads; #endif case OSSL_LIB_CTX_RAND_CRNGT_INDEX: { /* * rand_crngt must be lazily initialized because it calls into * libctx, so must not be called from context_init, else a deadlock * will occur. * * We use a separate lock because code called by the instantiation * of rand_crngt is liable to try and take the libctx lock. */ if (CRYPTO_THREAD_read_lock(ctx->rand_crngt_lock) != 1) return NULL; if (ctx->rand_crngt == NULL) { CRYPTO_THREAD_unlock(ctx->rand_crngt_lock); if (CRYPTO_THREAD_write_lock(ctx->rand_crngt_lock) != 1) return NULL; if (ctx->rand_crngt == NULL) ctx->rand_crngt = ossl_rand_crng_ctx_new(ctx); } p = ctx->rand_crngt; CRYPTO_THREAD_unlock(ctx->rand_crngt_lock); return p; } #ifdef FIPS_MODULE case OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX: return ctx->thread_event_handler; case OSSL_LIB_CTX_FIPS_PROV_INDEX: return ctx->fips_prov; #endif default: return NULL; } } OSSL_EX_DATA_GLOBAL *ossl_lib_ctx_get_ex_data_global(OSSL_LIB_CTX *ctx) { ctx = ossl_lib_ctx_get_concrete(ctx); if (ctx == NULL) return NULL; return &ctx->global; } const char *ossl_lib_ctx_get_descriptor(OSSL_LIB_CTX *libctx) { #ifdef FIPS_MODULE return "FIPS internal library context"; #else if (ossl_lib_ctx_is_global_default(libctx)) return "Global default library context"; if (ossl_lib_ctx_is_default(libctx)) return "Thread-local default library context"; return "Non-default library context"; #endif }
./openssl/crypto/bsearch.c
/* * Copyright 2019 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 "internal/cryptlib.h" const void *ossl_bsearch(const void *key, const void *base, int num, int size, int (*cmp) (const void *, const void *), int flags) { const char *base_ = base; int l, h, i = 0, c = 0; const char *p = NULL; if (num == 0) return NULL; l = 0; h = num; while (l < h) { i = (l + h) / 2; p = &(base_[i * size]); c = (*cmp) (key, p); if (c < 0) h = i; else if (c > 0) l = i + 1; else break; } if (c != 0 && !(flags & OSSL_BSEARCH_VALUE_ON_NOMATCH)) p = NULL; else if (c == 0 && (flags & OSSL_BSEARCH_FIRST_VALUE_ON_MATCH)) { while (i > 0 && (*cmp) (key, &(base_[(i - 1) * size])) == 0) i--; p = &(base_[i * size]); } return p; }
./openssl/crypto/provider.c
/* * 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 */ #include <string.h> #include <openssl/err.h> #include <openssl/cryptoerr.h> #include <openssl/provider.h> #include <openssl/core_names.h> #include "internal/provider.h" #include "provider_local.h" OSSL_PROVIDER *OSSL_PROVIDER_try_load_ex(OSSL_LIB_CTX *libctx, const char *name, OSSL_PARAM *params, int retain_fallbacks) { OSSL_PROVIDER *prov = NULL, *actual; int isnew = 0; /* Find it or create it */ if ((prov = ossl_provider_find(libctx, name, 0)) == NULL) { if ((prov = ossl_provider_new(libctx, name, NULL, params, 0)) == NULL) return NULL; isnew = 1; } if (!ossl_provider_activate(prov, 1, 0)) { ossl_provider_free(prov); return NULL; } actual = prov; if (isnew && !ossl_provider_add_to_store(prov, &actual, retain_fallbacks)) { ossl_provider_deactivate(prov, 1); ossl_provider_free(prov); return NULL; } if (actual != prov) { if (!ossl_provider_activate(actual, 1, 0)) { ossl_provider_free(actual); return NULL; } } return actual; } OSSL_PROVIDER *OSSL_PROVIDER_try_load(OSSL_LIB_CTX *libctx, const char *name, int retain_fallbacks) { return OSSL_PROVIDER_try_load_ex(libctx, name, NULL, retain_fallbacks); } OSSL_PROVIDER *OSSL_PROVIDER_load_ex(OSSL_LIB_CTX *libctx, const char *name, OSSL_PARAM *params) { /* Any attempt to load a provider disables auto-loading of defaults */ if (ossl_provider_disable_fallback_loading(libctx)) return OSSL_PROVIDER_try_load_ex(libctx, name, params, 0); return NULL; } OSSL_PROVIDER *OSSL_PROVIDER_load(OSSL_LIB_CTX *libctx, const char *name) { return OSSL_PROVIDER_load_ex(libctx, name, NULL); } int OSSL_PROVIDER_unload(OSSL_PROVIDER *prov) { if (!ossl_provider_deactivate(prov, 1)) return 0; ossl_provider_free(prov); return 1; } const OSSL_PARAM *OSSL_PROVIDER_gettable_params(const OSSL_PROVIDER *prov) { return ossl_provider_gettable_params(prov); } int OSSL_PROVIDER_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[]) { return ossl_provider_get_params(prov, params); } const OSSL_ALGORITHM *OSSL_PROVIDER_query_operation(const OSSL_PROVIDER *prov, int operation_id, int *no_cache) { return ossl_provider_query_operation(prov, operation_id, no_cache); } void OSSL_PROVIDER_unquery_operation(const OSSL_PROVIDER *prov, int operation_id, const OSSL_ALGORITHM *algs) { ossl_provider_unquery_operation(prov, operation_id, algs); } void *OSSL_PROVIDER_get0_provider_ctx(const OSSL_PROVIDER *prov) { return ossl_provider_prov_ctx(prov); } const OSSL_DISPATCH *OSSL_PROVIDER_get0_dispatch(const OSSL_PROVIDER *prov) { return ossl_provider_get0_dispatch(prov); } int OSSL_PROVIDER_self_test(const OSSL_PROVIDER *prov) { return ossl_provider_self_test(prov); } int OSSL_PROVIDER_get_capabilities(const OSSL_PROVIDER *prov, const char *capability, OSSL_CALLBACK *cb, void *arg) { return ossl_provider_get_capabilities(prov, capability, cb, arg); } int OSSL_PROVIDER_add_builtin(OSSL_LIB_CTX *libctx, const char *name, OSSL_provider_init_fn *init_fn) { OSSL_PROVIDER_INFO entry; if (name == NULL || init_fn == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } memset(&entry, 0, sizeof(entry)); entry.name = OPENSSL_strdup(name); if (entry.name == NULL) return 0; entry.init = init_fn; if (!ossl_provider_info_add_to_store(libctx, &entry)) { ossl_provider_info_clear(&entry); return 0; } return 1; } const char *OSSL_PROVIDER_get0_name(const OSSL_PROVIDER *prov) { return ossl_provider_name(prov); } int OSSL_PROVIDER_do_all(OSSL_LIB_CTX *ctx, int (*cb)(OSSL_PROVIDER *provider, void *cbdata), void *cbdata) { return ossl_provider_doall_activated(ctx, cb, cbdata); }
./openssl/crypto/dllmain.c
/* * 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 */ #include "internal/e_os.h" #include "crypto/cryptlib.h" #if defined(_WIN32) || defined(__CYGWIN__) # ifdef __CYGWIN__ /* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */ # include <windows.h> /* * this has side-effect of _WIN32 getting defined, which otherwise is * mutually exclusive with __CYGWIN__... */ # endif /* * All we really need to do is remove the 'error' state when a thread * detaches */ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved); BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: OPENSSL_cpuid_setup(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: OPENSSL_thread_stop(); break; case DLL_PROCESS_DETACH: break; } return TRUE; } #endif
./openssl/crypto/LPdir_wince.c
/* * Copyright 2004-2016 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 COPYRIGHT HOLDERS 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 COPYRIGHT * OWNER 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. */ #define LP_SYS_WINCE /* * We might want to define LP_MULTIBYTE_AVAILABLE here. It's currently under * investigation what the exact conditions would be */ #include "LPdir_win.c"
./openssl/crypto/o_dir.c
/* * Copyright 2004-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/e_os.h" #include <errno.h> /* * The routines really come from the Levitte Programming, so to make life * simple, let's just use the raw files and hack the symbols to fit our * namespace. */ #define LP_DIR_CTX OPENSSL_DIR_CTX #define LP_dir_context_st OPENSSL_dir_context_st #define LP_find_file OPENSSL_DIR_read #define LP_find_file_end OPENSSL_DIR_end #include "internal/o_dir.h" #define LPDIR_H #if defined OPENSSL_SYS_UNIX || defined DJGPP \ || (defined __VMS_VER && __VMS_VER >= 70000000) # include "LPdir_unix.c" #elif defined OPENSSL_SYS_VMS # include "LPdir_vms.c" #elif defined OPENSSL_SYS_WIN32 # include "LPdir_win32.c" #elif defined OPENSSL_SYS_WINCE # include "LPdir_wince.c" #else # include "LPdir_nyi.c" #endif
./openssl/crypto/sparcv9cap.c
/* * Copyright 2005-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 <stdio.h> #include <stdlib.h> #include <string.h> #include <setjmp.h> #include <signal.h> #include <sys/time.h> #include <unistd.h> #include <openssl/bn.h> #include "internal/cryptlib.h" #include "crypto/sparc_arch.h" #if defined(__GNUC__) && defined(__linux) __attribute__ ((visibility("hidden"))) #endif unsigned int OPENSSL_sparcv9cap_P[2] = { SPARCV9_TICK_PRIVILEGED, 0 }; unsigned long _sparcv9_rdtick(void); void _sparcv9_vis1_probe(void); unsigned long _sparcv9_vis1_instrument(void); void _sparcv9_vis2_probe(void); void _sparcv9_fmadd_probe(void); unsigned long _sparcv9_rdcfr(void); void _sparcv9_vis3_probe(void); void _sparcv9_fjaesx_probe(void); unsigned long _sparcv9_random(void); size_t _sparcv9_vis1_instrument_bus(unsigned int *, size_t); size_t _sparcv9_vis1_instrument_bus2(unsigned int *, size_t, size_t); uint32_t OPENSSL_rdtsc(void) { if (OPENSSL_sparcv9cap_P[0] & SPARCV9_TICK_PRIVILEGED) #if defined(__sun) && defined(__SVR4) return gethrtime(); #else return 0; #endif else return _sparcv9_rdtick(); } size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt) { if ((OPENSSL_sparcv9cap_P[0] & (SPARCV9_TICK_PRIVILEGED | SPARCV9_BLK)) == SPARCV9_BLK) return _sparcv9_vis1_instrument_bus(out, cnt); else return 0; } size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max) { if ((OPENSSL_sparcv9cap_P[0] & (SPARCV9_TICK_PRIVILEGED | SPARCV9_BLK)) == SPARCV9_BLK) return _sparcv9_vis1_instrument_bus2(out, cnt, max); else return 0; } static sigjmp_buf common_jmp; static void common_handler(int sig) { siglongjmp(common_jmp, sig); } #if defined(__sun) && defined(__SVR4) # if defined(__GNUC__) && __GNUC__>=2 extern unsigned int getisax(unsigned int vec[], unsigned int sz) __attribute__ ((weak)); # elif defined(__SUNPRO_C) #pragma weak getisax extern unsigned int getisax(unsigned int vec[], unsigned int sz); # else static unsigned int (*getisax) (unsigned int vec[], unsigned int sz) = NULL; # endif #endif void OPENSSL_cpuid_setup(void) { char *e; struct sigaction common_act, ill_oact, bus_oact; sigset_t all_masked, oset; static int trigger = 0; if (trigger) return; trigger = 1; if ((e = getenv("OPENSSL_sparcv9cap"))) { OPENSSL_sparcv9cap_P[0] = strtoul(e, NULL, 0); if ((e = strchr(e, ':'))) OPENSSL_sparcv9cap_P[1] = strtoul(e + 1, NULL, 0); return; } #if defined(__sun) && defined(__SVR4) if (getisax != NULL) { unsigned int vec[2] = { 0, 0 }; if (getisax (vec,2)) { if (vec[0]&0x00020) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS1; if (vec[0]&0x00040) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS2; if (vec[0]&0x00080) OPENSSL_sparcv9cap_P[0] |= SPARCV9_BLK; if (vec[0]&0x00100) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FMADD; if (vec[0]&0x00400) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS3; if (vec[0]&0x01000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJHPCACE; if (vec[0]&0x02000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJDESX; if (vec[0]&0x08000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_IMA; if (vec[0]&0x10000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJAESX; if (vec[1]&0x00008) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS4; /* reconstruct %cfr copy */ OPENSSL_sparcv9cap_P[1] = (vec[0]>>17)&0x3ff; OPENSSL_sparcv9cap_P[1] |= (OPENSSL_sparcv9cap_P[1]&CFR_MONTMUL)<<1; if (vec[0]&0x20000000) OPENSSL_sparcv9cap_P[1] |= CFR_CRC32C; if (vec[1]&0x00000020) OPENSSL_sparcv9cap_P[1] |= CFR_XMPMUL; if (vec[1]&0x00000040) OPENSSL_sparcv9cap_P[1] |= CFR_XMONTMUL|CFR_XMONTSQR; /* Some heuristics */ /* all known VIS2-capable CPUs have unprivileged tick counter */ if (OPENSSL_sparcv9cap_P[0]&SPARCV9_VIS2) OPENSSL_sparcv9cap_P[0] &= ~SPARCV9_TICK_PRIVILEGED; OPENSSL_sparcv9cap_P[0] |= SPARCV9_PREFER_FPU; /* detect UltraSPARC-Tx, see sparccpud.S for details... */ if ((OPENSSL_sparcv9cap_P[0]&SPARCV9_VIS1) && _sparcv9_vis1_instrument() >= 12) OPENSSL_sparcv9cap_P[0] &= ~(SPARCV9_VIS1 | SPARCV9_PREFER_FPU); } if (sizeof(size_t) == 8) OPENSSL_sparcv9cap_P[0] |= SPARCV9_64BIT_STACK; return; } #endif /* Initial value, fits UltraSPARC-I&II... */ OPENSSL_sparcv9cap_P[0] = SPARCV9_PREFER_FPU | SPARCV9_TICK_PRIVILEGED; sigfillset(&all_masked); sigdelset(&all_masked, SIGILL); sigdelset(&all_masked, SIGTRAP); # ifdef SIGEMT sigdelset(&all_masked, SIGEMT); # endif sigdelset(&all_masked, SIGFPE); sigdelset(&all_masked, SIGBUS); sigdelset(&all_masked, SIGSEGV); sigprocmask(SIG_SETMASK, &all_masked, &oset); memset(&common_act, 0, sizeof(common_act)); common_act.sa_handler = common_handler; common_act.sa_mask = all_masked; sigaction(SIGILL, &common_act, &ill_oact); sigaction(SIGBUS, &common_act, &bus_oact); /* T1 fails 16-bit ldda [on * Linux] */ if (sigsetjmp(common_jmp, 1) == 0) { _sparcv9_rdtick(); OPENSSL_sparcv9cap_P[0] &= ~SPARCV9_TICK_PRIVILEGED; } if (sigsetjmp(common_jmp, 1) == 0) { _sparcv9_vis1_probe(); OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS1 | SPARCV9_BLK; /* detect UltraSPARC-Tx, see sparccpud.S for details... */ if (_sparcv9_vis1_instrument() >= 12) OPENSSL_sparcv9cap_P[0] &= ~(SPARCV9_VIS1 | SPARCV9_PREFER_FPU); else { _sparcv9_vis2_probe(); OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS2; } } if (sigsetjmp(common_jmp, 1) == 0) { _sparcv9_fmadd_probe(); OPENSSL_sparcv9cap_P[0] |= SPARCV9_FMADD; } /* * VIS3 flag is tested independently from VIS1, unlike VIS2 that is, * because VIS3 defines even integer instructions. */ if (sigsetjmp(common_jmp, 1) == 0) { _sparcv9_vis3_probe(); OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS3; } if (sigsetjmp(common_jmp, 1) == 0) { _sparcv9_fjaesx_probe(); OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJAESX; } /* * In wait for better solution _sparcv9_rdcfr is masked by * VIS3 flag, because it goes to uninterruptible endless * loop on UltraSPARC II running Solaris. Things might be * different on Linux... */ if ((OPENSSL_sparcv9cap_P[0] & SPARCV9_VIS3) && sigsetjmp(common_jmp, 1) == 0) { OPENSSL_sparcv9cap_P[1] = (unsigned int)_sparcv9_rdcfr(); } sigaction(SIGBUS, &bus_oact, NULL); sigaction(SIGILL, &ill_oact, NULL); sigprocmask(SIG_SETMASK, &oset, NULL); if (sizeof(size_t) == 8) OPENSSL_sparcv9cap_P[0] |= SPARCV9_64BIT_STACK; # ifdef __linux else { int ret = syscall(340); if (ret >= 0 && ret & 1) OPENSSL_sparcv9cap_P[0] |= SPARCV9_64BIT_STACK; } # endif }
./openssl/crypto/initthread.c
/* * 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 */ #include <openssl/crypto.h> #include <openssl/core_dispatch.h> #include "crypto/cryptlib.h" #include "prov/providercommon.h" #include "internal/thread_once.h" #include "crypto/context.h" #ifdef FIPS_MODULE #include "prov/provider_ctx.h" /* * Thread aware code may want to be told about thread stop events. We register * to hear about those thread stop events when we see a new thread has started. * We call the ossl_init_thread_start function to do that. In the FIPS provider * we have our own copy of ossl_init_thread_start, which cascades notifications * about threads stopping from libcrypto to all the code in the FIPS provider * that needs to know about it. * * The FIPS provider tells libcrypto about which threads it is interested in * by calling "c_thread_start" which is a function pointer created during * provider initialisation (i.e. OSSL_provider_init). */ extern OSSL_FUNC_core_thread_start_fn *c_thread_start; #endif typedef struct thread_event_handler_st THREAD_EVENT_HANDLER; struct thread_event_handler_st { #ifndef FIPS_MODULE const void *index; #endif void *arg; OSSL_thread_stop_handler_fn handfn; THREAD_EVENT_HANDLER *next; }; #ifndef FIPS_MODULE DEFINE_SPECIAL_STACK_OF(THREAD_EVENT_HANDLER_PTR, THREAD_EVENT_HANDLER *) typedef struct global_tevent_register_st GLOBAL_TEVENT_REGISTER; struct global_tevent_register_st { STACK_OF(THREAD_EVENT_HANDLER_PTR) *skhands; CRYPTO_RWLOCK *lock; }; static GLOBAL_TEVENT_REGISTER *glob_tevent_reg = NULL; static CRYPTO_ONCE tevent_register_runonce = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(create_global_tevent_register) { glob_tevent_reg = OPENSSL_zalloc(sizeof(*glob_tevent_reg)); if (glob_tevent_reg == NULL) return 0; glob_tevent_reg->skhands = sk_THREAD_EVENT_HANDLER_PTR_new_null(); glob_tevent_reg->lock = CRYPTO_THREAD_lock_new(); if (glob_tevent_reg->skhands == NULL || glob_tevent_reg->lock == NULL) { sk_THREAD_EVENT_HANDLER_PTR_free(glob_tevent_reg->skhands); CRYPTO_THREAD_lock_free(glob_tevent_reg->lock); OPENSSL_free(glob_tevent_reg); glob_tevent_reg = NULL; return 0; } return 1; } static GLOBAL_TEVENT_REGISTER *get_global_tevent_register(void) { if (!RUN_ONCE(&tevent_register_runonce, create_global_tevent_register)) return NULL; return glob_tevent_reg; } #endif #ifndef FIPS_MODULE static int init_thread_push_handlers(THREAD_EVENT_HANDLER **hands); static void init_thread_remove_handlers(THREAD_EVENT_HANDLER **handsin); static void init_thread_destructor(void *hands); static int init_thread_deregister(void *arg, int all); #endif static void init_thread_stop(void *arg, THREAD_EVENT_HANDLER **hands); static THREAD_EVENT_HANDLER ** init_get_thread_local(CRYPTO_THREAD_LOCAL *local, int alloc, int keep) { THREAD_EVENT_HANDLER **hands = CRYPTO_THREAD_get_local(local); if (alloc) { if (hands == NULL) { if ((hands = OPENSSL_zalloc(sizeof(*hands))) == NULL) return NULL; if (!CRYPTO_THREAD_set_local(local, hands)) { OPENSSL_free(hands); return NULL; } #ifndef FIPS_MODULE if (!init_thread_push_handlers(hands)) { CRYPTO_THREAD_set_local(local, NULL); OPENSSL_free(hands); return NULL; } #endif } } else if (!keep) { CRYPTO_THREAD_set_local(local, NULL); } return hands; } #ifndef FIPS_MODULE /* * Since per-thread-specific-data destructors are not universally * available, i.e. not on Windows, only below CRYPTO_THREAD_LOCAL key * is assumed to have destructor associated. And then an effort is made * to call this single destructor on non-pthread platform[s]. * * Initial value is "impossible". It is used as guard value to shortcut * destructor for threads terminating before libcrypto is initialized or * after it's de-initialized. Access to the key doesn't have to be * serialized for the said threads, because they didn't use libcrypto * and it doesn't matter if they pick "impossible" or dereference real * key value and pull NULL past initialization in the first thread that * intends to use libcrypto. */ static union { long sane; CRYPTO_THREAD_LOCAL value; } destructor_key = { -1 }; /* * The thread event handler list is a thread specific linked list * of callback functions which are invoked in list order by the * current thread in case of certain events. (Currently, there is * only one type of event, the 'thread stop' event.) * * We also keep a global reference to that linked list, so that we * can deregister handlers if necessary before all the threads are * stopped. */ static int init_thread_push_handlers(THREAD_EVENT_HANDLER **hands) { int ret; GLOBAL_TEVENT_REGISTER *gtr; gtr = get_global_tevent_register(); if (gtr == NULL) return 0; if (!CRYPTO_THREAD_write_lock(gtr->lock)) return 0; ret = (sk_THREAD_EVENT_HANDLER_PTR_push(gtr->skhands, hands) != 0); CRYPTO_THREAD_unlock(gtr->lock); return ret; } static void init_thread_remove_handlers(THREAD_EVENT_HANDLER **handsin) { GLOBAL_TEVENT_REGISTER *gtr; int i; gtr = get_global_tevent_register(); if (gtr == NULL) return; if (!CRYPTO_THREAD_write_lock(gtr->lock)) return; for (i = 0; i < sk_THREAD_EVENT_HANDLER_PTR_num(gtr->skhands); i++) { THREAD_EVENT_HANDLER **hands = sk_THREAD_EVENT_HANDLER_PTR_value(gtr->skhands, i); if (hands == handsin) { sk_THREAD_EVENT_HANDLER_PTR_delete(gtr->skhands, i); CRYPTO_THREAD_unlock(gtr->lock); return; } } CRYPTO_THREAD_unlock(gtr->lock); return; } static void init_thread_destructor(void *hands) { init_thread_stop(NULL, (THREAD_EVENT_HANDLER **)hands); init_thread_remove_handlers(hands); OPENSSL_free(hands); } int ossl_init_thread(void) { if (!CRYPTO_THREAD_init_local(&destructor_key.value, init_thread_destructor)) return 0; return 1; } void ossl_cleanup_thread(void) { init_thread_deregister(NULL, 1); CRYPTO_THREAD_cleanup_local(&destructor_key.value); destructor_key.sane = -1; } void OPENSSL_thread_stop_ex(OSSL_LIB_CTX *ctx) { ctx = ossl_lib_ctx_get_concrete(ctx); /* * It would be nice if we could figure out a way to do this on all threads * that have used the OSSL_LIB_CTX when the context is freed. This is * currently not possible due to the use of thread local variables. */ ossl_ctx_thread_stop(ctx); } void OPENSSL_thread_stop(void) { if (destructor_key.sane != -1) { THREAD_EVENT_HANDLER **hands = init_get_thread_local(&destructor_key.value, 0, 0); init_thread_stop(NULL, hands); init_thread_remove_handlers(hands); OPENSSL_free(hands); } } void ossl_ctx_thread_stop(OSSL_LIB_CTX *ctx) { if (destructor_key.sane != -1) { THREAD_EVENT_HANDLER **hands = init_get_thread_local(&destructor_key.value, 0, 1); init_thread_stop(ctx, hands); } } #else static void ossl_arg_thread_stop(void *arg); /* Register the current thread so that we are informed if it gets stopped */ int ossl_thread_register_fips(OSSL_LIB_CTX *libctx) { return c_thread_start(FIPS_get_core_handle(libctx), ossl_arg_thread_stop, libctx); } void *ossl_thread_event_ctx_new(OSSL_LIB_CTX *libctx) { THREAD_EVENT_HANDLER **hands = NULL; CRYPTO_THREAD_LOCAL *tlocal = OPENSSL_zalloc(sizeof(*tlocal)); if (tlocal == NULL) return NULL; if (!CRYPTO_THREAD_init_local(tlocal, NULL)) { goto err; } hands = OPENSSL_zalloc(sizeof(*hands)); if (hands == NULL) goto err; if (!CRYPTO_THREAD_set_local(tlocal, hands)) goto err; /* * We should ideally call ossl_thread_register_fips() here. This function * is called during the startup of the FIPS provider and we need to ensure * that the main thread is registered to receive thread callbacks in order * to free |hands| that we allocated above. However we are too early in * the FIPS provider initialisation that FIPS_get_core_handle() doesn't work * yet. So we defer this to the main provider OSSL_provider_init_int() * function. */ return tlocal; err: OPENSSL_free(hands); OPENSSL_free(tlocal); return NULL; } void ossl_thread_event_ctx_free(void *tlocal) { OPENSSL_free(tlocal); } static void ossl_arg_thread_stop(void *arg) { ossl_ctx_thread_stop((OSSL_LIB_CTX *)arg); } void ossl_ctx_thread_stop(OSSL_LIB_CTX *ctx) { THREAD_EVENT_HANDLER **hands; CRYPTO_THREAD_LOCAL *local = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX); if (local == NULL) return; hands = init_get_thread_local(local, 0, 0); init_thread_stop(ctx, hands); OPENSSL_free(hands); } #endif /* FIPS_MODULE */ static void init_thread_stop(void *arg, THREAD_EVENT_HANDLER **hands) { THREAD_EVENT_HANDLER *curr, *prev = NULL, *tmp; #ifndef FIPS_MODULE GLOBAL_TEVENT_REGISTER *gtr; #endif /* Can't do much about this */ if (hands == NULL) return; #ifndef FIPS_MODULE gtr = get_global_tevent_register(); if (gtr == NULL) return; if (!CRYPTO_THREAD_write_lock(gtr->lock)) return; #endif curr = *hands; while (curr != NULL) { if (arg != NULL && curr->arg != arg) { prev = curr; curr = curr->next; continue; } curr->handfn(curr->arg); if (prev == NULL) *hands = curr->next; else prev->next = curr->next; tmp = curr; curr = curr->next; OPENSSL_free(tmp); } #ifndef FIPS_MODULE CRYPTO_THREAD_unlock(gtr->lock); #endif } int ossl_init_thread_start(const void *index, void *arg, OSSL_thread_stop_handler_fn handfn) { THREAD_EVENT_HANDLER **hands; THREAD_EVENT_HANDLER *hand; #ifdef FIPS_MODULE OSSL_LIB_CTX *ctx = arg; /* * In FIPS mode the list of THREAD_EVENT_HANDLERs is unique per combination * of OSSL_LIB_CTX and thread. This is because in FIPS mode each * OSSL_LIB_CTX gets informed about thread stop events individually. */ CRYPTO_THREAD_LOCAL *local = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX); #else /* * Outside of FIPS mode the list of THREAD_EVENT_HANDLERs is unique per * thread, but may hold multiple OSSL_LIB_CTXs. We only get told about * thread stop events globally, so we have to ensure all affected * OSSL_LIB_CTXs are informed. */ CRYPTO_THREAD_LOCAL *local = &destructor_key.value; #endif hands = init_get_thread_local(local, 1, 0); if (hands == NULL) return 0; #ifdef FIPS_MODULE if (*hands == NULL) { /* * We've not yet registered any handlers for this thread. We need to get * libcrypto to tell us about later thread stop events. c_thread_start * is a callback to libcrypto defined in fipsprov.c */ if (!ossl_thread_register_fips(ctx)) return 0; } #endif hand = OPENSSL_malloc(sizeof(*hand)); if (hand == NULL) return 0; hand->handfn = handfn; hand->arg = arg; #ifndef FIPS_MODULE hand->index = index; #endif hand->next = *hands; *hands = hand; return 1; } #ifndef FIPS_MODULE static int init_thread_deregister(void *index, int all) { GLOBAL_TEVENT_REGISTER *gtr; int i; gtr = get_global_tevent_register(); if (gtr == NULL) return 0; if (!all) { if (!CRYPTO_THREAD_write_lock(gtr->lock)) return 0; } else { glob_tevent_reg = NULL; } for (i = 0; i < sk_THREAD_EVENT_HANDLER_PTR_num(gtr->skhands); i++) { THREAD_EVENT_HANDLER **hands = sk_THREAD_EVENT_HANDLER_PTR_value(gtr->skhands, i); THREAD_EVENT_HANDLER *curr = NULL, *prev = NULL, *tmp; if (hands == NULL) { if (!all) CRYPTO_THREAD_unlock(gtr->lock); return 0; } curr = *hands; while (curr != NULL) { if (all || curr->index == index) { if (prev != NULL) prev->next = curr->next; else *hands = curr->next; tmp = curr; curr = curr->next; OPENSSL_free(tmp); continue; } prev = curr; curr = curr->next; } if (all) OPENSSL_free(hands); } if (all) { CRYPTO_THREAD_lock_free(gtr->lock); sk_THREAD_EVENT_HANDLER_PTR_free(gtr->skhands); OPENSSL_free(gtr); } else { CRYPTO_THREAD_unlock(gtr->lock); } return 1; } int ossl_init_thread_deregister(void *index) { return init_thread_deregister(index, 0); } #endif
./openssl/crypto/params_dup.c
/* * 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 */ #include <string.h> #include <openssl/params.h> #include <openssl/param_build.h> #include "internal/param_build_set.h" #define OSSL_PARAM_ALLOCATED_END 127 #define OSSL_PARAM_MERGE_LIST_MAX 128 #define OSSL_PARAM_BUF_PUBLIC 0 #define OSSL_PARAM_BUF_SECURE 1 #define OSSL_PARAM_BUF_MAX (OSSL_PARAM_BUF_SECURE + 1) typedef struct { OSSL_PARAM_ALIGNED_BLOCK *alloc; /* The allocated buffer */ OSSL_PARAM_ALIGNED_BLOCK *cur; /* Current position in the allocated buf */ size_t blocks; /* Number of aligned blocks */ size_t alloc_sz; /* The size of the allocated buffer (in bytes) */ } OSSL_PARAM_BUF; size_t ossl_param_bytes_to_blocks(size_t bytes) { return (bytes + OSSL_PARAM_ALIGN_SIZE - 1) / OSSL_PARAM_ALIGN_SIZE; } static int ossl_param_buf_alloc(OSSL_PARAM_BUF *out, size_t extra_blocks, int is_secure) { size_t sz = OSSL_PARAM_ALIGN_SIZE * (extra_blocks + out->blocks); out->alloc = is_secure ? OPENSSL_secure_zalloc(sz) : OPENSSL_zalloc(sz); if (out->alloc == NULL) return 0; out->alloc_sz = sz; out->cur = out->alloc + extra_blocks; return 1; } void ossl_param_set_secure_block(OSSL_PARAM *last, void *secure_buffer, size_t secure_buffer_sz) { last->key = NULL; last->data_size = secure_buffer_sz; last->data = secure_buffer; last->data_type = OSSL_PARAM_ALLOCATED_END; } static OSSL_PARAM *ossl_param_dup(const OSSL_PARAM *src, OSSL_PARAM *dst, OSSL_PARAM_BUF buf[OSSL_PARAM_BUF_MAX], int *param_count) { const OSSL_PARAM *in; int has_dst = (dst != NULL); int is_secure; size_t param_sz, blks; for (in = src; in->key != NULL; in++) { is_secure = CRYPTO_secure_allocated(in->data); if (has_dst) { *dst = *in; dst->data = buf[is_secure].cur; } if (in->data_type == OSSL_PARAM_OCTET_PTR || in->data_type == OSSL_PARAM_UTF8_PTR) { param_sz = sizeof(in->data); if (has_dst) *((const void **)dst->data) = *(const void **)in->data; } else { param_sz = in->data_size; if (has_dst) memcpy(dst->data, in->data, param_sz); } if (in->data_type == OSSL_PARAM_UTF8_STRING) param_sz++; /* NULL terminator */ blks = ossl_param_bytes_to_blocks(param_sz); if (has_dst) { dst++; buf[is_secure].cur += blks; } else { buf[is_secure].blocks += blks; } if (param_count != NULL) ++*param_count; } return dst; } OSSL_PARAM *OSSL_PARAM_dup(const OSSL_PARAM *src) { size_t param_blocks; OSSL_PARAM_BUF buf[OSSL_PARAM_BUF_MAX]; OSSL_PARAM *last, *dst; int param_count = 1; /* Include terminator in the count */ if (src == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } memset(buf, 0, sizeof(buf)); /* First Pass: get the param_count and block sizes required */ (void)ossl_param_dup(src, NULL, buf, &param_count); param_blocks = ossl_param_bytes_to_blocks(param_count * sizeof(*src)); /* * The allocated buffer consists of an array of OSSL_PARAM followed by * aligned data bytes that the array elements will point to. */ if (!ossl_param_buf_alloc(&buf[OSSL_PARAM_BUF_PUBLIC], param_blocks, 0)) return NULL; /* Allocate a secure memory buffer if required */ if (buf[OSSL_PARAM_BUF_SECURE].blocks > 0 && !ossl_param_buf_alloc(&buf[OSSL_PARAM_BUF_SECURE], 0, 1)) { OPENSSL_free(buf[OSSL_PARAM_BUF_PUBLIC].alloc); return NULL; } dst = (OSSL_PARAM *)buf[OSSL_PARAM_BUF_PUBLIC].alloc; last = ossl_param_dup(src, dst, buf, NULL); /* Store the allocated secure memory buffer in the last param block */ ossl_param_set_secure_block(last, buf[OSSL_PARAM_BUF_SECURE].alloc, buf[OSSL_PARAM_BUF_SECURE].alloc_sz); return dst; } static int compare_params(const void *left, const void *right) { const OSSL_PARAM *l = *(const OSSL_PARAM **)left; const OSSL_PARAM *r = *(const OSSL_PARAM **)right; return OPENSSL_strcasecmp(l->key, r->key); } OSSL_PARAM *OSSL_PARAM_merge(const OSSL_PARAM *p1, const OSSL_PARAM *p2) { const OSSL_PARAM *list1[OSSL_PARAM_MERGE_LIST_MAX + 1]; const OSSL_PARAM *list2[OSSL_PARAM_MERGE_LIST_MAX + 1]; const OSSL_PARAM *p = NULL; const OSSL_PARAM **p1cur, **p2cur; OSSL_PARAM *params, *dst; size_t list1_sz = 0, list2_sz = 0; int diff; if (p1 == NULL && p2 == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } /* Copy p1 to list1 */ if (p1 != NULL) { for (p = p1; p->key != NULL && list1_sz < OSSL_PARAM_MERGE_LIST_MAX; p++) list1[list1_sz++] = p; } list1[list1_sz] = NULL; /* copy p2 to a list2 */ if (p2 != NULL) { for (p = p2; p->key != NULL && list2_sz < OSSL_PARAM_MERGE_LIST_MAX; p++) list2[list2_sz++] = p; } list2[list2_sz] = NULL; if (list1_sz == 0 && list2_sz == 0) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_NO_PARAMS_TO_MERGE); return NULL; } /* Sort the 2 lists */ qsort(list1, list1_sz, sizeof(OSSL_PARAM *), compare_params); qsort(list2, list2_sz, sizeof(OSSL_PARAM *), compare_params); /* Allocate enough space to store the merged parameters */ params = OPENSSL_zalloc((list1_sz + list2_sz + 1) * sizeof(*p1)); if (params == NULL) return NULL; dst = params; p1cur = list1; p2cur = list2; while (1) { /* If list1 is finished just tack list2 onto the end */ if (*p1cur == NULL) { do { *dst++ = **p2cur; p2cur++; } while (*p2cur != NULL); break; } /* If list2 is finished just tack list1 onto the end */ if (*p2cur == NULL) { do { *dst++ = **p1cur; p1cur++; } while (*p1cur != NULL); break; } /* consume the list element with the smaller key */ diff = OPENSSL_strcasecmp((*p1cur)->key, (*p2cur)->key); if (diff == 0) { /* If the keys are the same then throw away the list1 element */ *dst++ = **p2cur; p2cur++; p1cur++; } else if (diff > 0) { *dst++ = **p2cur; p2cur++; } else { *dst++ = **p1cur; p1cur++; } } return params; } void OSSL_PARAM_free(OSSL_PARAM *params) { if (params != NULL) { OSSL_PARAM *p; for (p = params; p->key != NULL; p++) ; if (p->data_type == OSSL_PARAM_ALLOCATED_END) OPENSSL_secure_clear_free(p->data, p->data_size); OPENSSL_free(params); } }
./openssl/crypto/mem.c
/* * 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 */ #include "internal/e_os.h" #include "internal/cryptlib.h" #include "crypto/cryptlib.h" #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <openssl/crypto.h> /* * the following pointers may be changed as long as 'allow_customize' is set */ static int allow_customize = 1; static CRYPTO_malloc_fn malloc_impl = CRYPTO_malloc; static CRYPTO_realloc_fn realloc_impl = CRYPTO_realloc; static CRYPTO_free_fn free_impl = CRYPTO_free; #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE) # include "internal/tsan_assist.h" # ifdef TSAN_REQUIRES_LOCKING # define INCREMENT(x) /* empty */ # define LOAD(x) 0 # else /* TSAN_REQUIRES_LOCKING */ static TSAN_QUALIFIER int malloc_count; static TSAN_QUALIFIER int realloc_count; static TSAN_QUALIFIER int free_count; # define INCREMENT(x) tsan_counter(&(x)) # define LOAD(x) tsan_load(&x) # endif /* TSAN_REQUIRES_LOCKING */ static char *md_failstring; static long md_count; static int md_fail_percent = 0; static int md_tracefd = -1; static void parseit(void); static int shouldfail(void); # define FAILTEST() if (shouldfail()) return NULL #else # define INCREMENT(x) /* empty */ # define FAILTEST() /* empty */ #endif int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn, CRYPTO_realloc_fn realloc_fn, CRYPTO_free_fn free_fn) { if (!allow_customize) return 0; if (malloc_fn != NULL) malloc_impl = malloc_fn; if (realloc_fn != NULL) realloc_impl = realloc_fn; if (free_fn != NULL) free_impl = free_fn; return 1; } void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn, CRYPTO_realloc_fn *realloc_fn, CRYPTO_free_fn *free_fn) { if (malloc_fn != NULL) *malloc_fn = malloc_impl; if (realloc_fn != NULL) *realloc_fn = realloc_impl; if (free_fn != NULL) *free_fn = free_impl; } #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE) void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount) { if (mcount != NULL) *mcount = LOAD(malloc_count); if (rcount != NULL) *rcount = LOAD(realloc_count); if (fcount != NULL) *fcount = LOAD(free_count); } /* * Parse a "malloc failure spec" string. This likes like a set of fields * separated by semicolons. Each field has a count and an optional failure * percentage. For example: * 100@0;100@25;0@0 * or 100;100@25;0 * This means 100 mallocs succeed, then next 100 fail 25% of the time, and * all remaining (count is zero) succeed. * The failure percentge can have 2 digits after the comma. For example: * 0@0.01 * This means 0.01% of all allocations will fail. */ static void parseit(void) { char *semi = strchr(md_failstring, ';'); char *atsign; if (semi != NULL) *semi++ = '\0'; /* Get the count (atol will stop at the @ if there), and percentage */ md_count = atol(md_failstring); atsign = strchr(md_failstring, '@'); md_fail_percent = atsign == NULL ? 0 : (int)(atof(atsign + 1) * 100 + 0.5); if (semi != NULL) md_failstring = semi; } /* * Windows doesn't have random() and srandom(), but it has rand() and srand(). * Some rand() implementations aren't good, but we're not * dealing with secure randomness here. */ # ifdef _WIN32 # define random() rand() # define srandom(seed) srand(seed) # endif /* * See if the current malloc should fail. */ static int shouldfail(void) { int roll = (int)(random() % 10000); int shoulditfail = roll < md_fail_percent; # ifndef _WIN32 /* suppressed on Windows as POSIX-like file descriptors are non-inheritable */ int len; char buff[80]; if (md_tracefd > 0) { BIO_snprintf(buff, sizeof(buff), "%c C%ld %%%d R%d\n", shoulditfail ? '-' : '+', md_count, md_fail_percent, roll); len = strlen(buff); if (write(md_tracefd, buff, len) != len) perror("shouldfail write failed"); } # endif if (md_count) { /* If we used up this one, go to the next. */ if (--md_count == 0) parseit(); } return shoulditfail; } void ossl_malloc_setup_failures(void) { const char *cp = getenv("OPENSSL_MALLOC_FAILURES"); if (cp != NULL && (md_failstring = strdup(cp)) != NULL) parseit(); if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL) md_tracefd = atoi(cp); if ((cp = getenv("OPENSSL_MALLOC_SEED")) != NULL) srandom(atoi(cp)); } #endif void *CRYPTO_malloc(size_t num, const char *file, int line) { void *ptr; INCREMENT(malloc_count); if (malloc_impl != CRYPTO_malloc) { ptr = malloc_impl(num, file, line); if (ptr != NULL || num == 0) return ptr; goto err; } if (num == 0) return NULL; FAILTEST(); if (allow_customize) { /* * Disallow customization after the first allocation. We only set this * if necessary to avoid a store to the same cache line on every * allocation. */ allow_customize = 0; } ptr = malloc(num); if (ptr != NULL) return ptr; err: /* * ossl_err_get_state_int() in err.c uses CRYPTO_zalloc(num, NULL, 0) for * ERR_STATE allocation. Prevent mem alloc error loop while reporting error. */ if (file != NULL || line != 0) { ERR_new(); ERR_set_debug(file, line, NULL); ERR_set_error(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE, NULL); } return NULL; } void *CRYPTO_zalloc(size_t num, const char *file, int line) { void *ret; ret = CRYPTO_malloc(num, file, line); if (ret != NULL) memset(ret, 0, num); return ret; } void *CRYPTO_realloc(void *str, size_t num, const char *file, int line) { INCREMENT(realloc_count); if (realloc_impl != CRYPTO_realloc) return realloc_impl(str, num, file, line); if (str == NULL) return CRYPTO_malloc(num, file, line); if (num == 0) { CRYPTO_free(str, file, line); return NULL; } FAILTEST(); return realloc(str, num); } void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num, const char *file, int line) { void *ret = NULL; if (str == NULL) return CRYPTO_malloc(num, file, line); if (num == 0) { CRYPTO_clear_free(str, old_len, file, line); return NULL; } /* Can't shrink the buffer since memcpy below copies |old_len| bytes. */ if (num < old_len) { OPENSSL_cleanse((char*)str + num, old_len - num); return str; } ret = CRYPTO_malloc(num, file, line); if (ret != NULL) { memcpy(ret, str, old_len); CRYPTO_clear_free(str, old_len, file, line); } return ret; } void CRYPTO_free(void *str, const char *file, int line) { INCREMENT(free_count); if (free_impl != CRYPTO_free) { free_impl(str, file, line); return; } free(str); } void CRYPTO_clear_free(void *str, size_t num, const char *file, int line) { if (str == NULL) return; if (num) OPENSSL_cleanse(str, num); CRYPTO_free(str, file, line); } #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) # ifndef OPENSSL_NO_DEPRECATED_3_0 int CRYPTO_mem_ctrl(int mode) { (void)mode; return -1; } int CRYPTO_set_mem_debug(int flag) { (void)flag; return -1; } int CRYPTO_mem_debug_push(const char *info, const char *file, int line) { (void)info; (void)file; (void)line; return 0; } int CRYPTO_mem_debug_pop(void) { return 0; } void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag, const char *file, int line) { (void)addr; (void)num; (void)flag; (void)file; (void)line; } void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag, const char *file, int line) { (void)addr1; (void)addr2; (void)num; (void)flag; (void)file; (void)line; } void CRYPTO_mem_debug_free(void *addr, int flag, const char *file, int line) { (void)addr; (void)flag; (void)file; (void)line; } int CRYPTO_mem_leaks(BIO *b) { (void)b; return -1; } # ifndef OPENSSL_NO_STDIO int CRYPTO_mem_leaks_fp(FILE *fp) { (void)fp; return -1; } # endif int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u), void *u) { (void)cb; (void)u; return -1; } # endif #endif
./openssl/crypto/provider_predefined.c
/* * 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 <openssl/core.h> #include "provider_local.h" OSSL_provider_init_fn ossl_default_provider_init; OSSL_provider_init_fn ossl_base_provider_init; OSSL_provider_init_fn ossl_null_provider_init; OSSL_provider_init_fn ossl_fips_intern_provider_init; #ifdef STATIC_LEGACY OSSL_provider_init_fn ossl_legacy_provider_init; #endif const OSSL_PROVIDER_INFO ossl_predefined_providers[] = { #ifdef FIPS_MODULE { "fips", NULL, ossl_fips_intern_provider_init, NULL, 1 }, #else { "default", NULL, ossl_default_provider_init, NULL, 1 }, # ifdef STATIC_LEGACY { "legacy", NULL, ossl_legacy_provider_init, NULL, 0 }, # endif { "base", NULL, ossl_base_provider_init, NULL, 0 }, { "null", NULL, ossl_null_provider_init, NULL, 0 }, #endif { NULL, NULL, NULL, NULL, 0 } };
./openssl/crypto/mips_arch.h
/* * Copyright 2011-2016 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_MIPS_ARCH_H # define OSSL_CRYPTO_MIPS_ARCH_H # if (defined(__mips_smartmips) || defined(_MIPS_ARCH_MIPS32R3) || \ defined(_MIPS_ARCH_MIPS32R5) || defined(_MIPS_ARCH_MIPS32R6)) \ && !defined(_MIPS_ARCH_MIPS32R2) # define _MIPS_ARCH_MIPS32R2 # endif # if (defined(_MIPS_ARCH_MIPS64R3) || defined(_MIPS_ARCH_MIPS64R5) || \ defined(_MIPS_ARCH_MIPS64R6)) \ && !defined(_MIPS_ARCH_MIPS64R2) # define _MIPS_ARCH_MIPS64R2 # endif # if defined(_MIPS_ARCH_MIPS64R6) # define dmultu(rs,rt) # define mflo(rd,rs,rt) dmulu rd,rs,rt # define mfhi(rd,rs,rt) dmuhu rd,rs,rt # elif defined(_MIPS_ARCH_MIPS32R6) # define multu(rs,rt) # define mflo(rd,rs,rt) mulu rd,rs,rt # define mfhi(rd,rs,rt) muhu rd,rs,rt # else # define dmultu(rs,rt) dmultu rs,rt # define multu(rs,rt) multu rs,rt # define mflo(rd,rs,rt) mflo rd # define mfhi(rd,rs,rt) mfhi rd # endif #endif
./openssl/crypto/riscvcap.c
/* * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdint.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #define OPENSSL_RISCVCAP_IMPL #include "crypto/riscv_arch.h" extern size_t riscv_vlen_asm(void); static void parse_env(const char *envstr); static void strtoupper(char *str); static size_t vlen = 0; uint32_t OPENSSL_rdtsc(void) { return 0; } size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt) { return 0; } size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max) { return 0; } static void strtoupper(char *str) { for (char *x = str; *x; ++x) *x = toupper(*x); } /* parse_env() parses a RISC-V architecture string. An example of such a string * is "rv64gc_zba_zbb_zbc_zbs". Currently, the rv64gc part is ignored * and we simply search for "_[extension]" in the arch string to see if we * should enable a given extension. */ #define BUFLEN 256 static void parse_env(const char *envstr) { char envstrupper[BUFLEN]; char buf[BUFLEN]; /* Convert env str to all uppercase */ OPENSSL_strlcpy(envstrupper, envstr, sizeof(envstrupper)); strtoupper(envstrupper); for (size_t i = 0; i < kRISCVNumCaps; ++i) { /* Prefix capability with underscore in preparation for search */ BIO_snprintf(buf, BUFLEN, "_%s", RISCV_capabilities[i].name); if (strstr(envstrupper, buf) != NULL) { /* Match, set relevant bit in OPENSSL_riscvcap_P[] */ OPENSSL_riscvcap_P[RISCV_capabilities[i].index] |= (1 << RISCV_capabilities[i].bit_offset); } } } size_t riscv_vlen(void) { return vlen; } # if defined(__GNUC__) && __GNUC__>=2 __attribute__ ((constructor)) # endif void OPENSSL_cpuid_setup(void) { char *e; static int trigger = 0; if (trigger != 0) return; trigger = 1; if ((e = getenv("OPENSSL_riscvcap"))) { parse_env(e); } if (RISCV_HAS_V()) { vlen = riscv_vlen_asm(); } }
./openssl/crypto/ppccap.c
/* * Copyright 2009-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <setjmp.h> #include <signal.h> #include <unistd.h> #if defined(__linux) || defined(_AIX) # include <sys/utsname.h> #endif #if defined(_AIX53) /* defined even on post-5.3 */ # include <sys/systemcfg.h> # if !defined(__power_set) # define __power_set(a) (_system_configuration.implementation & (a)) # endif #endif #if defined(__APPLE__) && defined(__MACH__) # include <sys/types.h> # include <sys/sysctl.h> #endif #include <openssl/crypto.h> #include "internal/cryptlib.h" #include "crypto/ppc_arch.h" unsigned int OPENSSL_ppccap_P = 0; static sigset_t all_masked; static sigjmp_buf ill_jmp; static void ill_handler(int sig) { siglongjmp(ill_jmp, sig); } void OPENSSL_fpu_probe(void); void OPENSSL_ppc64_probe(void); void OPENSSL_altivec_probe(void); void OPENSSL_crypto207_probe(void); void OPENSSL_madd300_probe(void); void OPENSSL_brd31_probe(void); long OPENSSL_rdtsc_mftb(void); long OPENSSL_rdtsc_mfspr268(void); uint32_t OPENSSL_rdtsc(void) { if (OPENSSL_ppccap_P & PPC_MFTB) return OPENSSL_rdtsc_mftb(); else if (OPENSSL_ppccap_P & PPC_MFSPR268) return OPENSSL_rdtsc_mfspr268(); else return 0; } size_t OPENSSL_instrument_bus_mftb(unsigned int *, size_t); size_t OPENSSL_instrument_bus_mfspr268(unsigned int *, size_t); size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt) { if (OPENSSL_ppccap_P & PPC_MFTB) return OPENSSL_instrument_bus_mftb(out, cnt); else if (OPENSSL_ppccap_P & PPC_MFSPR268) return OPENSSL_instrument_bus_mfspr268(out, cnt); else return 0; } size_t OPENSSL_instrument_bus2_mftb(unsigned int *, size_t, size_t); size_t OPENSSL_instrument_bus2_mfspr268(unsigned int *, size_t, size_t); size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max) { if (OPENSSL_ppccap_P & PPC_MFTB) return OPENSSL_instrument_bus2_mftb(out, cnt, max); else if (OPENSSL_ppccap_P & PPC_MFSPR268) return OPENSSL_instrument_bus2_mfspr268(out, cnt, max); else return 0; } #if defined(__GLIBC__) && defined(__GLIBC_PREREQ) # if __GLIBC_PREREQ(2, 16) # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # elif defined(__ANDROID_API__) /* see https://developer.android.google.cn/ndk/guides/cpu-features */ # if __ANDROID_API__ >= 18 # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif # endif #endif #if defined(__FreeBSD__) # include <sys/param.h> # if __FreeBSD_version >= 1200000 # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL static unsigned long getauxval(unsigned long key) { unsigned long val = 0ul; if (elf_aux_info((int)key, &val, sizeof(val)) != 0) return 0ul; return val; } # endif #endif /* I wish <sys/auxv.h> was universally available */ #ifndef AT_HWCAP # define AT_HWCAP 16 /* AT_HWCAP */ #endif #define HWCAP_PPC64 (1U << 30) #define HWCAP_ALTIVEC (1U << 28) #define HWCAP_FPU (1U << 27) #define HWCAP_POWER6_EXT (1U << 9) #define HWCAP_VSX (1U << 7) #ifndef AT_HWCAP2 # define AT_HWCAP2 26 /* AT_HWCAP2 */ #endif #define HWCAP_VEC_CRYPTO (1U << 25) #define HWCAP_ARCH_3_00 (1U << 23) #define HWCAP_ARCH_3_1 (1U << 18) # if defined(__GNUC__) && __GNUC__>=2 __attribute__ ((constructor)) # endif void OPENSSL_cpuid_setup(void) { char *e; struct sigaction ill_oact, ill_act; sigset_t oset; static int trigger = 0; if (trigger) return; trigger = 1; if ((e = getenv("OPENSSL_ppccap"))) { OPENSSL_ppccap_P = strtoul(e, NULL, 0); return; } OPENSSL_ppccap_P = 0; #if defined(_AIX) OPENSSL_ppccap_P |= PPC_FPU; if (sizeof(size_t) == 4) { struct utsname uts; # if defined(_SC_AIX_KERNEL_BITMODE) if (sysconf(_SC_AIX_KERNEL_BITMODE) != 64) return; # endif if (uname(&uts) != 0 || atoi(uts.version) < 6) return; } # if defined(__power_set) /* * Value used in __power_set is a single-bit 1<<n one denoting * specific processor class. Incidentally 0xffffffff<<n can be * used to denote specific processor and its successors. */ if (sizeof(size_t) == 4) { /* In 32-bit case PPC_FPU64 is always fastest [if option] */ if (__power_set(0xffffffffU<<13)) /* POWER5 and later */ OPENSSL_ppccap_P |= PPC_FPU64; } else { /* In 64-bit case PPC_FPU64 is fastest only on POWER6 */ if (__power_set(0x1U<<14)) /* POWER6 */ OPENSSL_ppccap_P |= PPC_FPU64; } if (__power_set(0xffffffffU<<14)) /* POWER6 and later */ OPENSSL_ppccap_P |= PPC_ALTIVEC; if (__power_set(0xffffffffU<<16)) /* POWER8 and later */ OPENSSL_ppccap_P |= PPC_CRYPTO207; if (__power_set(0xffffffffU<<17)) /* POWER9 and later */ OPENSSL_ppccap_P |= PPC_MADD300; if (__power_set(0xffffffffU<<18)) /* POWER10 and later */ OPENSSL_ppccap_P |= PPC_BRD31; return; # endif #endif #if defined(__APPLE__) && defined(__MACH__) OPENSSL_ppccap_P |= PPC_FPU; { int val; size_t len = sizeof(val); if (sysctlbyname("hw.optional.64bitops", &val, &len, NULL, 0) == 0) { if (val) OPENSSL_ppccap_P |= PPC_FPU64; } len = sizeof(val); if (sysctlbyname("hw.optional.altivec", &val, &len, NULL, 0) == 0) { if (val) OPENSSL_ppccap_P |= PPC_ALTIVEC; } return; } #endif #ifdef OSSL_IMPLEMENT_GETAUXVAL { unsigned long hwcap = getauxval(AT_HWCAP); unsigned long hwcap2 = getauxval(AT_HWCAP2); if (hwcap & HWCAP_FPU) { OPENSSL_ppccap_P |= PPC_FPU; if (sizeof(size_t) == 4) { /* In 32-bit case PPC_FPU64 is always fastest [if option] */ if (hwcap & HWCAP_PPC64) OPENSSL_ppccap_P |= PPC_FPU64; } else { /* In 64-bit case PPC_FPU64 is fastest only on POWER6 */ if (hwcap & HWCAP_POWER6_EXT) OPENSSL_ppccap_P |= PPC_FPU64; } } if (hwcap & HWCAP_ALTIVEC) { OPENSSL_ppccap_P |= PPC_ALTIVEC; if ((hwcap & HWCAP_VSX) && (hwcap2 & HWCAP_VEC_CRYPTO)) OPENSSL_ppccap_P |= PPC_CRYPTO207; } if (hwcap2 & HWCAP_ARCH_3_00) { OPENSSL_ppccap_P |= PPC_MADD300; } if (hwcap2 & HWCAP_ARCH_3_1) { OPENSSL_ppccap_P |= PPC_BRD31; } } #endif sigfillset(&all_masked); sigdelset(&all_masked, SIGILL); sigdelset(&all_masked, SIGTRAP); #ifdef SIGEMT sigdelset(&all_masked, SIGEMT); #endif sigdelset(&all_masked, SIGFPE); sigdelset(&all_masked, SIGBUS); sigdelset(&all_masked, SIGSEGV); memset(&ill_act, 0, sizeof(ill_act)); ill_act.sa_handler = ill_handler; ill_act.sa_mask = all_masked; sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset); sigaction(SIGILL, &ill_act, &ill_oact); #ifndef OSSL_IMPLEMENT_GETAUXVAL if (sigsetjmp(ill_jmp, 1) == 0) { OPENSSL_fpu_probe(); OPENSSL_ppccap_P |= PPC_FPU; if (sizeof(size_t) == 4) { # ifdef __linux struct utsname uts; if (uname(&uts) == 0 && strcmp(uts.machine, "ppc64") == 0) # endif if (sigsetjmp(ill_jmp, 1) == 0) { OPENSSL_ppc64_probe(); OPENSSL_ppccap_P |= PPC_FPU64; } } else { /* * Wanted code detecting POWER6 CPU and setting PPC_FPU64 */ } } if (sigsetjmp(ill_jmp, 1) == 0) { OPENSSL_altivec_probe(); OPENSSL_ppccap_P |= PPC_ALTIVEC; if (sigsetjmp(ill_jmp, 1) == 0) { OPENSSL_crypto207_probe(); OPENSSL_ppccap_P |= PPC_CRYPTO207; } } if (sigsetjmp(ill_jmp, 1) == 0) { OPENSSL_madd300_probe(); OPENSSL_ppccap_P |= PPC_MADD300; } #endif if (sigsetjmp(ill_jmp, 1) == 0) { OPENSSL_rdtsc_mftb(); OPENSSL_ppccap_P |= PPC_MFTB; } else if (sigsetjmp(ill_jmp, 1) == 0) { OPENSSL_rdtsc_mfspr268(); OPENSSL_ppccap_P |= PPC_MFSPR268; } sigaction(SIGILL, &ill_oact, NULL); sigprocmask(SIG_SETMASK, &oset, NULL); }
./openssl/crypto/param_build_set.c
/* * 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 */ /* * Key Management utility functions to share functionality between the export() * and get_params() methods. * export() uses OSSL_PARAM_BLD, and get_params() used the OSSL_PARAM[] to * fill in parameter data for the same key and data fields. */ #include <openssl/core_names.h> #include "internal/param_build_set.h" DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM) int ossl_param_build_set_int(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, int num) { if (bld != NULL) return OSSL_PARAM_BLD_push_int(bld, key, num); p = OSSL_PARAM_locate(p, key); if (p != NULL) return OSSL_PARAM_set_int(p, num); return 1; } int ossl_param_build_set_long(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, long num) { if (bld != NULL) return OSSL_PARAM_BLD_push_long(bld, key, num); p = OSSL_PARAM_locate(p, key); if (p != NULL) return OSSL_PARAM_set_long(p, num); return 1; } int ossl_param_build_set_utf8_string(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const char *buf) { if (bld != NULL) return OSSL_PARAM_BLD_push_utf8_string(bld, key, buf, 0); p = OSSL_PARAM_locate(p, key); if (p != NULL) return OSSL_PARAM_set_utf8_string(p, buf); return 1; } 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) { if (bld != NULL) return OSSL_PARAM_BLD_push_octet_string(bld, key, data, data_len); p = OSSL_PARAM_locate(p, key); if (p != NULL) return OSSL_PARAM_set_octet_string(p, data, data_len); return 1; } int ossl_param_build_set_bn_pad(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const BIGNUM *bn, size_t sz) { if (bld != NULL) return OSSL_PARAM_BLD_push_BN_pad(bld, key, bn, sz); p = OSSL_PARAM_locate(p, key); if (p != NULL) { if (sz > p->data_size) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER); return 0; } p->data_size = sz; return OSSL_PARAM_set_BN(p, bn); } return 1; } int ossl_param_build_set_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *p, const char *key, const BIGNUM *bn) { if (bld != NULL) return OSSL_PARAM_BLD_push_BN(bld, key, bn); p = OSSL_PARAM_locate(p, key); if (p != NULL) return OSSL_PARAM_set_BN(p, bn) > 0; return 1; } int ossl_param_build_set_multi_key_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *params, const char *names[], STACK_OF(BIGNUM_const) *stk) { int i, sz = sk_BIGNUM_const_num(stk); OSSL_PARAM *p; const BIGNUM *bn; if (bld != NULL) { for (i = 0; i < sz && names[i] != NULL; ++i) { bn = sk_BIGNUM_const_value(stk, i); if (bn != NULL && !OSSL_PARAM_BLD_push_BN(bld, names[i], bn)) return 0; } return 1; } for (i = 0; i < sz && names[i] != NULL; ++i) { bn = sk_BIGNUM_const_value(stk, i); p = OSSL_PARAM_locate(params, names[i]); if (p != NULL && bn != NULL) { if (!OSSL_PARAM_set_BN(p, bn)) return 0; } } return 1; }
./openssl/crypto/init.c
/* * 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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "internal/e_os.h" #include "crypto/cryptlib.h" #include <openssl/err.h> #include "crypto/rand.h" #include "internal/bio.h" #include <openssl/evp.h> #include "crypto/evp.h" #include "internal/conf.h" #include "crypto/async.h" #include "crypto/engine.h" #include "internal/comp.h" #include "internal/err.h" #include "crypto/err.h" #include "crypto/objects.h" #include <stdlib.h> #include <assert.h> #include "internal/thread_once.h" #include "crypto/dso_conf.h" #include "internal/dso.h" #include "crypto/store.h" #include <openssl/cmp_util.h> /* for OSSL_CMP_log_close() */ #include <openssl/trace.h> #include "crypto/ctype.h" static int stopped = 0; static uint64_t optsdone = 0; typedef struct ossl_init_stop_st OPENSSL_INIT_STOP; struct ossl_init_stop_st { void (*handler)(void); OPENSSL_INIT_STOP *next; }; static OPENSSL_INIT_STOP *stop_handlers = NULL; /* Guards access to the optsdone variable on platforms without atomics */ static CRYPTO_RWLOCK *optsdone_lock = NULL; /* Guards simultaneous INIT_LOAD_CONFIG calls with non-NULL settings */ static CRYPTO_RWLOCK *init_lock = NULL; static CRYPTO_THREAD_LOCAL in_init_config_local; static CRYPTO_ONCE base = CRYPTO_ONCE_STATIC_INIT; static int base_inited = 0; DEFINE_RUN_ONCE_STATIC(ossl_init_base) { /* no need to init trace */ OSSL_TRACE(INIT, "ossl_init_base: setting up stop handlers\n"); #ifndef OPENSSL_NO_CRYPTO_MDEBUG ossl_malloc_setup_failures(); #endif if ((optsdone_lock = CRYPTO_THREAD_lock_new()) == NULL || (init_lock = CRYPTO_THREAD_lock_new()) == NULL) goto err; OPENSSL_cpuid_setup(); if (!ossl_init_thread()) goto err; if (!CRYPTO_THREAD_init_local(&in_init_config_local, NULL)) goto err; base_inited = 1; return 1; err: OSSL_TRACE(INIT, "ossl_init_base failed!\n"); CRYPTO_THREAD_lock_free(optsdone_lock); optsdone_lock = NULL; CRYPTO_THREAD_lock_free(init_lock); init_lock = NULL; return 0; } static CRYPTO_ONCE register_atexit = CRYPTO_ONCE_STATIC_INIT; #if !defined(OPENSSL_SYS_UEFI) && defined(_WIN32) static int win32atexit(void) { OPENSSL_cleanup(); return 0; } #endif DEFINE_RUN_ONCE_STATIC(ossl_init_register_atexit) { #ifdef OPENSSL_INIT_DEBUG fprintf(stderr, "OPENSSL_INIT: ossl_init_register_atexit()\n"); #endif #ifndef OPENSSL_SYS_UEFI # if defined(_WIN32) && !defined(__BORLANDC__) /* We use _onexit() in preference because it gets called on DLL unload */ if (_onexit(win32atexit) == NULL) return 0; # else if (atexit(OPENSSL_cleanup) != 0) return 0; # endif #endif return 1; } DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_register_atexit, ossl_init_register_atexit) { #ifdef OPENSSL_INIT_DEBUG fprintf(stderr, "OPENSSL_INIT: ossl_init_no_register_atexit ok!\n"); #endif /* Do nothing in this case */ return 1; } static CRYPTO_ONCE load_crypto_nodelete = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_nodelete) { OSSL_TRACE(INIT, "ossl_init_load_crypto_nodelete()\n"); #if !defined(OPENSSL_USE_NODELETE) \ && !defined(OPENSSL_NO_PINSHARED) # if defined(DSO_WIN32) && !defined(_WIN32_WCE) { HMODULE handle = NULL; BOOL ret; /* We don't use the DSO route for WIN32 because there is a better way */ ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, (void *)&base_inited, &handle); OSSL_TRACE1(INIT, "ossl_init_load_crypto_nodelete: " "obtained DSO reference? %s\n", (ret == TRUE ? "No!" : "Yes.")); return (ret == TRUE) ? 1 : 0; } # elif !defined(DSO_NONE) /* * Deliberately leak a reference to ourselves. This will force the library * to remain loaded until the atexit() handler is run at process exit. */ { DSO *dso; void *err; if (!err_shelve_state(&err)) return 0; dso = DSO_dsobyaddr(&base_inited, DSO_FLAG_NO_UNLOAD_ON_FREE); /* * In case of No!, it is uncertain our exit()-handlers can still be * called. After dlclose() the whole library might have been unloaded * already. */ OSSL_TRACE1(INIT, "obtained DSO reference? %s\n", (dso == NULL ? "No!" : "Yes.")); DSO_free(dso); err_unshelve_state(err); } # endif #endif return 1; } static CRYPTO_ONCE load_crypto_strings = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_strings) { int ret = 1; /* * OPENSSL_NO_AUTOERRINIT is provided here to prevent at compile time * pulling in all the error strings during static linking */ #if !defined(OPENSSL_NO_ERR) && !defined(OPENSSL_NO_AUTOERRINIT) void *err; if (!err_shelve_state(&err)) return 0; OSSL_TRACE(INIT, "ossl_err_load_crypto_strings()\n"); ret = ossl_err_load_crypto_strings(); err_unshelve_state(err); #endif return ret; } DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_load_crypto_strings, ossl_init_load_crypto_strings) { /* Do nothing in this case */ return 1; } static CRYPTO_ONCE add_all_ciphers = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_ciphers) { /* * OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time * pulling in all the ciphers during static linking */ #ifndef OPENSSL_NO_AUTOALGINIT OSSL_TRACE(INIT, "openssl_add_all_ciphers_int()\n"); openssl_add_all_ciphers_int(); #endif return 1; } DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_ciphers, ossl_init_add_all_ciphers) { /* Do nothing */ return 1; } static CRYPTO_ONCE add_all_digests = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_digests) { /* * OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time * pulling in all the ciphers during static linking */ #ifndef OPENSSL_NO_AUTOALGINIT OSSL_TRACE(INIT, "openssl_add_all_digests()\n"); openssl_add_all_digests_int(); #endif return 1; } DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_digests, ossl_init_add_all_digests) { /* Do nothing */ return 1; } static CRYPTO_ONCE config = CRYPTO_ONCE_STATIC_INIT; static int config_inited = 0; static const OPENSSL_INIT_SETTINGS *conf_settings = NULL; DEFINE_RUN_ONCE_STATIC(ossl_init_config) { int ret = ossl_config_int(NULL); config_inited = 1; return ret; } DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_config_settings, ossl_init_config) { int ret = ossl_config_int(conf_settings); config_inited = 1; return ret; } DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_config, ossl_init_config) { OSSL_TRACE(INIT, "ossl_no_config_int()\n"); ossl_no_config_int(); config_inited = 1; return 1; } static CRYPTO_ONCE async = CRYPTO_ONCE_STATIC_INIT; static int async_inited = 0; DEFINE_RUN_ONCE_STATIC(ossl_init_async) { OSSL_TRACE(INIT, "async_init()\n"); if (!async_init()) return 0; async_inited = 1; return 1; } #ifndef OPENSSL_NO_ENGINE static CRYPTO_ONCE engine_openssl = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_engine_openssl) { OSSL_TRACE(INIT, "engine_load_openssl_int()\n"); engine_load_openssl_int(); return 1; } # ifndef OPENSSL_NO_RDRAND static CRYPTO_ONCE engine_rdrand = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_engine_rdrand) { OSSL_TRACE(INIT, "engine_load_rdrand_int()\n"); engine_load_rdrand_int(); return 1; } # endif static CRYPTO_ONCE engine_dynamic = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_engine_dynamic) { OSSL_TRACE(INIT, "engine_load_dynamic_int()\n"); engine_load_dynamic_int(); return 1; } # ifndef OPENSSL_NO_STATIC_ENGINE # ifndef OPENSSL_NO_DEVCRYPTOENG static CRYPTO_ONCE engine_devcrypto = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_engine_devcrypto) { OSSL_TRACE(INIT, "engine_load_devcrypto_int()\n"); engine_load_devcrypto_int(); return 1; } # endif # if !defined(OPENSSL_NO_PADLOCKENG) static CRYPTO_ONCE engine_padlock = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_engine_padlock) { OSSL_TRACE(INIT, "engine_load_padlock_int()\n"); engine_load_padlock_int(); return 1; } # endif # if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG) static CRYPTO_ONCE engine_capi = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_engine_capi) { OSSL_TRACE(INIT, "engine_load_capi_int()\n"); engine_load_capi_int(); return 1; } # endif # if !defined(OPENSSL_NO_AFALGENG) static CRYPTO_ONCE engine_afalg = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_init_engine_afalg) { OSSL_TRACE(INIT, "engine_load_afalg_int()\n"); engine_load_afalg_int(); return 1; } # endif # endif #endif void OPENSSL_cleanup(void) { OPENSSL_INIT_STOP *currhandler, *lasthandler; /* * At some point we should consider looking at this function with a view to * moving most/all of this into onfree handlers in OSSL_LIB_CTX. */ /* If we've not been inited then no need to deinit */ if (!base_inited) return; /* Might be explicitly called and also by atexit */ if (stopped) return; stopped = 1; /* * Thread stop may not get automatically called by the thread library for * the very last thread in some situations, so call it directly. */ OPENSSL_thread_stop(); currhandler = stop_handlers; while (currhandler != NULL) { currhandler->handler(); lasthandler = currhandler; currhandler = currhandler->next; OPENSSL_free(lasthandler); } stop_handlers = NULL; CRYPTO_THREAD_lock_free(optsdone_lock); optsdone_lock = NULL; CRYPTO_THREAD_lock_free(init_lock); init_lock = NULL; CRYPTO_THREAD_cleanup_local(&in_init_config_local); /* * We assume we are single-threaded for this function, i.e. no race * conditions for the various "*_inited" vars below. */ #ifndef OPENSSL_NO_COMP OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_comp_zlib_cleanup()\n"); ossl_comp_zlib_cleanup(); OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_comp_brotli_cleanup()\n"); ossl_comp_brotli_cleanup(); OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_comp_zstd_cleanup()\n"); ossl_comp_zstd_cleanup(); #endif if (async_inited) { OSSL_TRACE(INIT, "OPENSSL_cleanup: async_deinit()\n"); async_deinit(); } /* * Note that cleanup order is important: * - ossl_rand_cleanup_int could call an ENGINE's RAND cleanup function so * must be called before engine_cleanup_int() * - ENGINEs use CRYPTO_EX_DATA and therefore, must be cleaned up * before the ex data handlers are wiped during default ossl_lib_ctx deinit. * - ossl_config_modules_free() can end up in ENGINE code so must be called * before engine_cleanup_int() * - ENGINEs and additional EVP algorithms might use added OIDs names so * ossl_obj_cleanup_int() must be called last */ OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_rand_cleanup_int()\n"); ossl_rand_cleanup_int(); OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_config_modules_free()\n"); ossl_config_modules_free(); #ifndef OPENSSL_NO_ENGINE OSSL_TRACE(INIT, "OPENSSL_cleanup: engine_cleanup_int()\n"); engine_cleanup_int(); #endif #ifndef OPENSSL_NO_DEPRECATED_3_0 OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_store_cleanup_int()\n"); ossl_store_cleanup_int(); #endif OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_lib_ctx_default_deinit()\n"); ossl_lib_ctx_default_deinit(); ossl_cleanup_thread(); OSSL_TRACE(INIT, "OPENSSL_cleanup: bio_cleanup()\n"); bio_cleanup(); OSSL_TRACE(INIT, "OPENSSL_cleanup: evp_cleanup_int()\n"); evp_cleanup_int(); OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_obj_cleanup_int()\n"); ossl_obj_cleanup_int(); OSSL_TRACE(INIT, "OPENSSL_cleanup: err_int()\n"); err_cleanup(); OSSL_TRACE(INIT, "OPENSSL_cleanup: CRYPTO_secure_malloc_done()\n"); CRYPTO_secure_malloc_done(); #ifndef OPENSSL_NO_CMP OSSL_TRACE(INIT, "OPENSSL_cleanup: OSSL_CMP_log_close()\n"); OSSL_CMP_log_close(); #endif OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_trace_cleanup()\n"); ossl_trace_cleanup(); base_inited = 0; } /* * If this function is called with a non NULL settings value then it must be * called prior to any threads making calls to any OpenSSL functions, * i.e. passing a non-null settings value is assumed to be single-threaded. */ int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings) { uint64_t tmp; int aloaddone = 0; /* Applications depend on 0 being returned when cleanup was already done */ if (stopped) { if (!(opts & OPENSSL_INIT_BASE_ONLY)) ERR_raise(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL); return 0; } /* * We ignore failures from this function. It is probably because we are * on a platform that doesn't support lockless atomic loads (we may not * have created optsdone_lock yet so we can't use it). This is just an * optimisation to skip the full checks in this function if we don't need * to, so we carry on regardless in the event of failure. * * There could be a race here with other threads, so that optsdone has not * been updated yet, even though the options have in fact been initialised. * This doesn't matter - it just means we will run the full function * unnecessarily - but all the critical code is contained in RUN_ONCE * functions anyway so we are safe. */ if (CRYPTO_atomic_load(&optsdone, &tmp, NULL)) { if ((tmp & opts) == opts) return 1; aloaddone = 1; } /* * At some point we should look at this function with a view to moving * most/all of this into OSSL_LIB_CTX. * * When the caller specifies OPENSSL_INIT_BASE_ONLY, that should be the * *only* option specified. With that option we return immediately after * doing the requested limited initialization. Note that * err_shelve_state() called by us via ossl_init_load_crypto_nodelete() * re-enters OPENSSL_init_crypto() with OPENSSL_INIT_BASE_ONLY, but with * base already initialized this is a harmless NOOP. * * If we remain the only caller of err_shelve_state() the recursion should * perhaps be removed, but if in doubt, it can be left in place. */ if (!RUN_ONCE(&base, ossl_init_base)) return 0; if (opts & OPENSSL_INIT_BASE_ONLY) return 1; /* * optsdone_lock should definitely be set up now, so we can now repeat the * same check from above but be sure that it will work even on platforms * without lockless CRYPTO_atomic_load */ if (!aloaddone) { if (!CRYPTO_atomic_load(&optsdone, &tmp, optsdone_lock)) return 0; if ((tmp & opts) == opts) return 1; } /* * Now we don't always set up exit handlers, the INIT_BASE_ONLY calls * should not have the side-effect of setting up exit handlers, and * therefore, this code block is below the INIT_BASE_ONLY-conditioned early * return above. */ if ((opts & OPENSSL_INIT_NO_ATEXIT) != 0) { if (!RUN_ONCE_ALT(&register_atexit, ossl_init_no_register_atexit, ossl_init_register_atexit)) return 0; } else if (!RUN_ONCE(&register_atexit, ossl_init_register_atexit)) { return 0; } if (!RUN_ONCE(&load_crypto_nodelete, ossl_init_load_crypto_nodelete)) return 0; if ((opts & OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS) && !RUN_ONCE_ALT(&load_crypto_strings, ossl_init_no_load_crypto_strings, ossl_init_load_crypto_strings)) return 0; if ((opts & OPENSSL_INIT_LOAD_CRYPTO_STRINGS) && !RUN_ONCE(&load_crypto_strings, ossl_init_load_crypto_strings)) return 0; if ((opts & OPENSSL_INIT_NO_ADD_ALL_CIPHERS) && !RUN_ONCE_ALT(&add_all_ciphers, ossl_init_no_add_all_ciphers, ossl_init_add_all_ciphers)) return 0; if ((opts & OPENSSL_INIT_ADD_ALL_CIPHERS) && !RUN_ONCE(&add_all_ciphers, ossl_init_add_all_ciphers)) return 0; if ((opts & OPENSSL_INIT_NO_ADD_ALL_DIGESTS) && !RUN_ONCE_ALT(&add_all_digests, ossl_init_no_add_all_digests, ossl_init_add_all_digests)) return 0; if ((opts & OPENSSL_INIT_ADD_ALL_DIGESTS) && !RUN_ONCE(&add_all_digests, ossl_init_add_all_digests)) return 0; if ((opts & OPENSSL_INIT_ATFORK) && !openssl_init_fork_handlers()) return 0; if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG) && !RUN_ONCE_ALT(&config, ossl_init_no_config, ossl_init_config)) return 0; if (opts & OPENSSL_INIT_LOAD_CONFIG) { int loading = CRYPTO_THREAD_get_local(&in_init_config_local) != NULL; /* If called recursively from OBJ_ calls, just skip it. */ if (!loading) { int ret; if (!CRYPTO_THREAD_set_local(&in_init_config_local, (void *)-1)) return 0; if (settings == NULL) { ret = RUN_ONCE(&config, ossl_init_config); } else { if (!CRYPTO_THREAD_write_lock(init_lock)) return 0; conf_settings = settings; ret = RUN_ONCE_ALT(&config, ossl_init_config_settings, ossl_init_config); conf_settings = NULL; CRYPTO_THREAD_unlock(init_lock); } if (ret <= 0) return 0; } } if ((opts & OPENSSL_INIT_ASYNC) && !RUN_ONCE(&async, ossl_init_async)) return 0; #ifndef OPENSSL_NO_ENGINE if ((opts & OPENSSL_INIT_ENGINE_OPENSSL) && !RUN_ONCE(&engine_openssl, ossl_init_engine_openssl)) return 0; # ifndef OPENSSL_NO_RDRAND if ((opts & OPENSSL_INIT_ENGINE_RDRAND) && !RUN_ONCE(&engine_rdrand, ossl_init_engine_rdrand)) return 0; # endif if ((opts & OPENSSL_INIT_ENGINE_DYNAMIC) && !RUN_ONCE(&engine_dynamic, ossl_init_engine_dynamic)) return 0; # ifndef OPENSSL_NO_STATIC_ENGINE # ifndef OPENSSL_NO_DEVCRYPTOENG if ((opts & OPENSSL_INIT_ENGINE_CRYPTODEV) && !RUN_ONCE(&engine_devcrypto, ossl_init_engine_devcrypto)) return 0; # endif # if !defined(OPENSSL_NO_PADLOCKENG) if ((opts & OPENSSL_INIT_ENGINE_PADLOCK) && !RUN_ONCE(&engine_padlock, ossl_init_engine_padlock)) return 0; # endif # if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG) if ((opts & OPENSSL_INIT_ENGINE_CAPI) && !RUN_ONCE(&engine_capi, ossl_init_engine_capi)) return 0; # endif # if !defined(OPENSSL_NO_AFALGENG) if ((opts & OPENSSL_INIT_ENGINE_AFALG) && !RUN_ONCE(&engine_afalg, ossl_init_engine_afalg)) return 0; # endif # endif if (opts & (OPENSSL_INIT_ENGINE_ALL_BUILTIN | OPENSSL_INIT_ENGINE_OPENSSL | OPENSSL_INIT_ENGINE_AFALG)) { ENGINE_register_all_complete(); } #endif if (!CRYPTO_atomic_or(&optsdone, opts, &tmp, optsdone_lock)) return 0; return 1; } int OPENSSL_atexit(void (*handler)(void)) { OPENSSL_INIT_STOP *newhand; #if !defined(OPENSSL_USE_NODELETE)\ && !defined(OPENSSL_NO_PINSHARED) { # if defined(DSO_WIN32) && !defined(_WIN32_WCE) HMODULE handle = NULL; BOOL ret; union { void *sym; void (*func)(void); } handlersym; handlersym.func = handler; /* * We don't use the DSO route for WIN32 because there is a better * way */ ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, handlersym.sym, &handle); if (!ret) return 0; # elif !defined(DSO_NONE) /* * Deliberately leak a reference to the handler. This will force the * library/code containing the handler to remain loaded until we run the * atexit handler. If -znodelete has been used then this is * unnecessary. */ DSO *dso = NULL; union { void *sym; void (*func)(void); } handlersym; handlersym.func = handler; ERR_set_mark(); dso = DSO_dsobyaddr(handlersym.sym, DSO_FLAG_NO_UNLOAD_ON_FREE); /* See same code above in ossl_init_base() for an explanation. */ OSSL_TRACE1(INIT, "atexit: obtained DSO reference? %s\n", (dso == NULL ? "No!" : "Yes.")); DSO_free(dso); ERR_pop_to_mark(); # endif } #endif if ((newhand = OPENSSL_malloc(sizeof(*newhand))) == NULL) return 0; newhand->handler = handler; newhand->next = stop_handlers; stop_handlers = newhand; return 1; }
./openssl/crypto/provider_local.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 <openssl/core.h> typedef struct { char *name; char *value; } INFOPAIR; DEFINE_STACK_OF(INFOPAIR) typedef struct { char *name; char *path; OSSL_provider_init_fn *init; STACK_OF(INFOPAIR) *parameters; unsigned int is_fallback:1; } OSSL_PROVIDER_INFO; extern const OSSL_PROVIDER_INFO ossl_predefined_providers[]; void ossl_provider_info_clear(OSSL_PROVIDER_INFO *info); int ossl_provider_info_add_to_store(OSSL_LIB_CTX *libctx, OSSL_PROVIDER_INFO *entry); int ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO *provinfo, const char *name, const char *value);
./openssl/crypto/provider_core.c
/* * 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 */ #include <assert.h> #include <openssl/core.h> #include <openssl/core_dispatch.h> #include <openssl/core_names.h> #include <openssl/provider.h> #include <openssl/params.h> #include <openssl/opensslv.h> #include "crypto/cryptlib.h" #ifndef FIPS_MODULE #include "crypto/decoder.h" /* ossl_decoder_store_cache_flush */ #include "crypto/encoder.h" /* ossl_encoder_store_cache_flush */ #include "crypto/store.h" /* ossl_store_loader_store_cache_flush */ #endif #include "crypto/evp.h" /* evp_method_store_cache_flush */ #include "crypto/rand.h" #include "internal/nelem.h" #include "internal/thread_once.h" #include "internal/provider.h" #include "internal/refcount.h" #include "internal/bio.h" #include "internal/core.h" #include "provider_local.h" #include "crypto/context.h" #ifndef FIPS_MODULE # include <openssl/self_test.h> #endif /* * This file defines and uses a number of different structures: * * OSSL_PROVIDER (provider_st): Used to represent all information related to a * single instance of a provider. * * provider_store_st: Holds information about the collection of providers that * are available within the current library context (OSSL_LIB_CTX). It also * holds configuration information about providers that could be loaded at some * future point. * * OSSL_PROVIDER_CHILD_CB: An instance of this structure holds the callbacks * that have been registered for a child library context and the associated * provider that registered those callbacks. * * Where a child library context exists then it has its own instance of the * provider store. Each provider that exists in the parent provider store, has * an associated child provider in the child library context's provider store. * As providers get activated or deactivated this needs to be mirrored in the * associated child providers. * * LOCKING * ======= * * There are a number of different locks used in this file and it is important * to understand how they should be used in order to avoid deadlocks. * * Fields within a structure can often be "write once" on creation, and then * "read many". Creation of a structure is done by a single thread, and * therefore no lock is required for the "write once/read many" fields. It is * safe for multiple threads to read these fields without a lock, because they * will never be changed. * * However some fields may be changed after a structure has been created and * shared between multiple threads. Where this is the case a lock is required. * * The locks available are: * * The provider flag_lock: Used to control updates to the various provider * "flags" (flag_initialized and flag_activated). * * The provider activatecnt_lock: Used to control updates to the provider * activatecnt value. * * The provider optbits_lock: Used to control access to the provider's * operation_bits and operation_bits_sz fields. * * The store default_path_lock: Used to control access to the provider store's * default search path value (default_path) * * The store lock: Used to control the stack of provider's held within the * provider store, as well as the stack of registered child provider callbacks. * * As a general rule-of-thumb it is best to: * - keep the scope of the code that is protected by a lock to the absolute * minimum possible; * - try to keep the scope of the lock to within a single function (i.e. avoid * making calls to other functions while holding a lock); * - try to only ever hold one lock at a time. * * Unfortunately, it is not always possible to stick to the above guidelines. * Where they are not adhered to there is always a danger of inadvertently * introducing the possibility of deadlock. The following rules MUST be adhered * to in order to avoid that: * - Holding multiple locks at the same time is only allowed for the * provider store lock, the provider activatecnt_lock and the provider flag_lock. * - When holding multiple locks they must be acquired in the following order of * precedence: * 1) provider store lock * 2) provider flag_lock * 3) provider activatecnt_lock * - When releasing locks they must be released in the reverse order to which * they were acquired * - No locks may be held when making an upcall. NOTE: Some common functions * can make upcalls as part of their normal operation. If you need to call * some other function while holding a lock make sure you know whether it * will make any upcalls or not. For example ossl_provider_up_ref() can call * ossl_provider_up_ref_parent() which can call the c_prov_up_ref() upcall. * - It is permissible to hold the store and flag locks when calling child * provider callbacks. No other locks may be held during such callbacks. */ static OSSL_PROVIDER *provider_new(const char *name, OSSL_provider_init_fn *init_function, STACK_OF(INFOPAIR) *parameters); /*- * Provider Object structure * ========================= */ #ifndef FIPS_MODULE typedef struct { OSSL_PROVIDER *prov; int (*create_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata); int (*remove_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata); int (*global_props_cb)(const char *props, void *cbdata); void *cbdata; } OSSL_PROVIDER_CHILD_CB; DEFINE_STACK_OF(OSSL_PROVIDER_CHILD_CB) #endif struct provider_store_st; /* Forward declaration */ struct ossl_provider_st { /* Flag bits */ unsigned int flag_initialized:1; unsigned int flag_activated:1; /* Getting and setting the flags require synchronization */ CRYPTO_RWLOCK *flag_lock; /* OpenSSL library side data */ CRYPTO_REF_COUNT refcnt; CRYPTO_RWLOCK *activatecnt_lock; /* For the activatecnt counter */ int activatecnt; char *name; char *path; DSO *module; OSSL_provider_init_fn *init_function; STACK_OF(INFOPAIR) *parameters; OSSL_LIB_CTX *libctx; /* The library context this instance is in */ struct provider_store_st *store; /* The store this instance belongs to */ #ifndef FIPS_MODULE /* * In the FIPS module inner provider, this isn't needed, since the * error upcalls are always direct calls to the outer provider. */ int error_lib; /* ERR library number, one for each provider */ # ifndef OPENSSL_NO_ERR ERR_STRING_DATA *error_strings; /* Copy of what the provider gives us */ # endif #endif /* Provider side functions */ OSSL_FUNC_provider_teardown_fn *teardown; OSSL_FUNC_provider_gettable_params_fn *gettable_params; OSSL_FUNC_provider_get_params_fn *get_params; OSSL_FUNC_provider_get_capabilities_fn *get_capabilities; OSSL_FUNC_provider_self_test_fn *self_test; OSSL_FUNC_provider_query_operation_fn *query_operation; OSSL_FUNC_provider_unquery_operation_fn *unquery_operation; /* * Cache of bit to indicate of query_operation() has been called on * a specific operation or not. */ unsigned char *operation_bits; size_t operation_bits_sz; CRYPTO_RWLOCK *opbits_lock; #ifndef FIPS_MODULE /* Whether this provider is the child of some other provider */ const OSSL_CORE_HANDLE *handle; unsigned int ischild:1; #endif /* Provider side data */ void *provctx; const OSSL_DISPATCH *dispatch; }; DEFINE_STACK_OF(OSSL_PROVIDER) static int ossl_provider_cmp(const OSSL_PROVIDER * const *a, const OSSL_PROVIDER * const *b) { return strcmp((*a)->name, (*b)->name); } /*- * Provider Object store * ===================== * * The Provider Object store is a library context object, and therefore needs * an index. */ struct provider_store_st { OSSL_LIB_CTX *libctx; STACK_OF(OSSL_PROVIDER) *providers; STACK_OF(OSSL_PROVIDER_CHILD_CB) *child_cbs; CRYPTO_RWLOCK *default_path_lock; CRYPTO_RWLOCK *lock; char *default_path; OSSL_PROVIDER_INFO *provinfo; size_t numprovinfo; size_t provinfosz; unsigned int use_fallbacks:1; unsigned int freeing:1; }; /* * provider_deactivate_free() is a wrapper around ossl_provider_deactivate() * and ossl_provider_free(), called as needed. * Since this is only called when the provider store is being emptied, we * don't need to care about any lock. */ static void provider_deactivate_free(OSSL_PROVIDER *prov) { if (prov->flag_activated) ossl_provider_deactivate(prov, 1); ossl_provider_free(prov); } #ifndef FIPS_MODULE static void ossl_provider_child_cb_free(OSSL_PROVIDER_CHILD_CB *cb) { OPENSSL_free(cb); } #endif static void infopair_free(INFOPAIR *pair) { OPENSSL_free(pair->name); OPENSSL_free(pair->value); OPENSSL_free(pair); } static INFOPAIR *infopair_copy(const INFOPAIR *src) { INFOPAIR *dest = OPENSSL_zalloc(sizeof(*dest)); if (dest == NULL) return NULL; if (src->name != NULL) { dest->name = OPENSSL_strdup(src->name); if (dest->name == NULL) goto err; } if (src->value != NULL) { dest->value = OPENSSL_strdup(src->value); if (dest->value == NULL) goto err; } return dest; err: OPENSSL_free(dest->name); OPENSSL_free(dest); return NULL; } void ossl_provider_info_clear(OSSL_PROVIDER_INFO *info) { OPENSSL_free(info->name); OPENSSL_free(info->path); sk_INFOPAIR_pop_free(info->parameters, infopair_free); } void ossl_provider_store_free(void *vstore) { struct provider_store_st *store = vstore; size_t i; if (store == NULL) return; store->freeing = 1; OPENSSL_free(store->default_path); sk_OSSL_PROVIDER_pop_free(store->providers, provider_deactivate_free); #ifndef FIPS_MODULE sk_OSSL_PROVIDER_CHILD_CB_pop_free(store->child_cbs, ossl_provider_child_cb_free); #endif CRYPTO_THREAD_lock_free(store->default_path_lock); CRYPTO_THREAD_lock_free(store->lock); for (i = 0; i < store->numprovinfo; i++) ossl_provider_info_clear(&store->provinfo[i]); OPENSSL_free(store->provinfo); OPENSSL_free(store); } void *ossl_provider_store_new(OSSL_LIB_CTX *ctx) { struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store)); if (store == NULL || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL || (store->default_path_lock = CRYPTO_THREAD_lock_new()) == NULL #ifndef FIPS_MODULE || (store->child_cbs = sk_OSSL_PROVIDER_CHILD_CB_new_null()) == NULL #endif || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) { ossl_provider_store_free(store); return NULL; } store->libctx = ctx; store->use_fallbacks = 1; return store; } static struct provider_store_st *get_provider_store(OSSL_LIB_CTX *libctx) { struct provider_store_st *store = NULL; store = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_STORE_INDEX); if (store == NULL) ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return store; } int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx) { struct provider_store_st *store; if ((store = get_provider_store(libctx)) != NULL) { if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; store->use_fallbacks = 0; CRYPTO_THREAD_unlock(store->lock); return 1; } return 0; } #define BUILTINS_BLOCK_SIZE 10 int ossl_provider_info_add_to_store(OSSL_LIB_CTX *libctx, OSSL_PROVIDER_INFO *entry) { struct provider_store_st *store = get_provider_store(libctx); int ret = 0; if (entry->name == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (store == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return 0; } if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; if (store->provinfosz == 0) { store->provinfo = OPENSSL_zalloc(sizeof(*store->provinfo) * BUILTINS_BLOCK_SIZE); if (store->provinfo == NULL) goto err; store->provinfosz = BUILTINS_BLOCK_SIZE; } else if (store->numprovinfo == store->provinfosz) { OSSL_PROVIDER_INFO *tmpbuiltins; size_t newsz = store->provinfosz + BUILTINS_BLOCK_SIZE; tmpbuiltins = OPENSSL_realloc(store->provinfo, sizeof(*store->provinfo) * newsz); if (tmpbuiltins == NULL) goto err; store->provinfo = tmpbuiltins; store->provinfosz = newsz; } store->provinfo[store->numprovinfo] = *entry; store->numprovinfo++; ret = 1; err: CRYPTO_THREAD_unlock(store->lock); return ret; } OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name, ossl_unused int noconfig) { struct provider_store_st *store = NULL; OSSL_PROVIDER *prov = NULL; if ((store = get_provider_store(libctx)) != NULL) { OSSL_PROVIDER tmpl = { 0, }; int i; #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG) /* * Make sure any providers are loaded from config before we try to find * them. */ if (!noconfig) { if (ossl_lib_ctx_is_default(libctx)) OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL); } #endif tmpl.name = (char *)name; if (!CRYPTO_THREAD_write_lock(store->lock)) return NULL; sk_OSSL_PROVIDER_sort(store->providers); if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) != -1) prov = sk_OSSL_PROVIDER_value(store->providers, i); CRYPTO_THREAD_unlock(store->lock); if (prov != NULL && !ossl_provider_up_ref(prov)) prov = NULL; } return prov; } /*- * Provider Object methods * ======================= */ static OSSL_PROVIDER *provider_new(const char *name, OSSL_provider_init_fn *init_function, STACK_OF(INFOPAIR) *parameters) { OSSL_PROVIDER *prov = NULL; if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL) return NULL; if (!CRYPTO_NEW_REF(&prov->refcnt, 1)) { OPENSSL_free(prov); return NULL; } #ifndef HAVE_ATOMICS if ((prov->activatecnt_lock = CRYPTO_THREAD_lock_new()) == NULL) { ossl_provider_free(prov); ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); return NULL; } #endif if ((prov->opbits_lock = CRYPTO_THREAD_lock_new()) == NULL || (prov->flag_lock = CRYPTO_THREAD_lock_new()) == NULL || (prov->parameters = sk_INFOPAIR_deep_copy(parameters, infopair_copy, infopair_free)) == NULL) { ossl_provider_free(prov); ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); return NULL; } if ((prov->name = OPENSSL_strdup(name)) == NULL) { ossl_provider_free(prov); return NULL; } prov->init_function = init_function; return prov; } int ossl_provider_up_ref(OSSL_PROVIDER *prov) { int ref = 0; if (CRYPTO_UP_REF(&prov->refcnt, &ref) <= 0) return 0; #ifndef FIPS_MODULE if (prov->ischild) { if (!ossl_provider_up_ref_parent(prov, 0)) { ossl_provider_free(prov); return 0; } } #endif return ref; } #ifndef FIPS_MODULE static int provider_up_ref_intern(OSSL_PROVIDER *prov, int activate) { if (activate) return ossl_provider_activate(prov, 1, 0); return ossl_provider_up_ref(prov); } static int provider_free_intern(OSSL_PROVIDER *prov, int deactivate) { if (deactivate) return ossl_provider_deactivate(prov, 1); ossl_provider_free(prov); return 1; } #endif /* * We assume that the requested provider does not already exist in the store. * The caller should check. If it does exist then adding it to the store later * will fail. */ OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name, OSSL_provider_init_fn *init_function, OSSL_PARAM *params, int noconfig) { struct provider_store_st *store = NULL; OSSL_PROVIDER_INFO template; OSSL_PROVIDER *prov = NULL; if ((store = get_provider_store(libctx)) == NULL) return NULL; memset(&template, 0, sizeof(template)); if (init_function == NULL) { const OSSL_PROVIDER_INFO *p; size_t i; /* Check if this is a predefined builtin provider */ for (p = ossl_predefined_providers; p->name != NULL; p++) { if (strcmp(p->name, name) == 0) { template = *p; break; } } if (p->name == NULL) { /* Check if this is a user added provider */ if (!CRYPTO_THREAD_read_lock(store->lock)) return NULL; for (i = 0, p = store->provinfo; i < store->numprovinfo; p++, i++) { if (strcmp(p->name, name) == 0) { template = *p; break; } } CRYPTO_THREAD_unlock(store->lock); } } else { template.init = init_function; } if (params != NULL) { int i; template.parameters = sk_INFOPAIR_new_null(); if (template.parameters == NULL) return NULL; for (i = 0; params[i].key != NULL; i++) { if (params[i].data_type != OSSL_PARAM_UTF8_STRING) continue; if (ossl_provider_info_add_parameter(&template, params[i].key, (char *)params[i].data) <= 0) return NULL; } } /* provider_new() generates an error, so no need here */ prov = provider_new(name, template.init, template.parameters); if (params != NULL) /* We copied the parameters, let's free them */ sk_INFOPAIR_pop_free(template.parameters, infopair_free); if (prov == NULL) return NULL; prov->libctx = libctx; #ifndef FIPS_MODULE prov->error_lib = ERR_get_next_error_library(); #endif /* * At this point, the provider is only partially "loaded". To be * fully "loaded", ossl_provider_activate() must also be called and it must * then be added to the provider store. */ return prov; } /* Assumes that the store lock is held */ static int create_provider_children(OSSL_PROVIDER *prov) { int ret = 1; #ifndef FIPS_MODULE struct provider_store_st *store = prov->store; OSSL_PROVIDER_CHILD_CB *child_cb; int i, max; max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); for (i = 0; i < max; i++) { /* * This is newly activated (activatecnt == 1), so we need to * create child providers as necessary. */ child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); ret &= child_cb->create_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata); } #endif return ret; } int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov, int retain_fallbacks) { struct provider_store_st *store; int idx; OSSL_PROVIDER tmpl = { 0, }; OSSL_PROVIDER *actualtmp = NULL; if (actualprov != NULL) *actualprov = NULL; if ((store = get_provider_store(prov->libctx)) == NULL) return 0; if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; tmpl.name = (char *)prov->name; idx = sk_OSSL_PROVIDER_find(store->providers, &tmpl); if (idx == -1) actualtmp = prov; else actualtmp = sk_OSSL_PROVIDER_value(store->providers, idx); if (idx == -1) { if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) goto err; prov->store = store; if (!create_provider_children(prov)) { sk_OSSL_PROVIDER_delete_ptr(store->providers, prov); goto err; } if (!retain_fallbacks) store->use_fallbacks = 0; } CRYPTO_THREAD_unlock(store->lock); if (actualprov != NULL) { if (!ossl_provider_up_ref(actualtmp)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); actualtmp = NULL; return 0; } *actualprov = actualtmp; } if (idx >= 0) { /* * The provider is already in the store. Probably two threads * independently initialised their own provider objects with the same * name and raced to put them in the store. This thread lost. We * deactivate the one we just created and use the one that already * exists instead. * If we get here then we know we did not create provider children * above, so we inform ossl_provider_deactivate not to attempt to remove * any. */ ossl_provider_deactivate(prov, 0); ossl_provider_free(prov); } #ifndef FIPS_MODULE else { /* * This can be done outside the lock. We tolerate other threads getting * the wrong result briefly when creating OSSL_DECODER_CTXs. */ ossl_decoder_cache_flush(prov->libctx); } #endif return 1; err: CRYPTO_THREAD_unlock(store->lock); return 0; } void ossl_provider_free(OSSL_PROVIDER *prov) { if (prov != NULL) { int ref = 0; CRYPTO_DOWN_REF(&prov->refcnt, &ref); /* * When the refcount drops to zero, we clean up the provider. * Note that this also does teardown, which may seem late, * considering that init happens on first activation. However, * there may be other structures hanging on to the provider after * the last deactivation and may therefore need full access to the * provider's services. Therefore, we deinit late. */ if (ref == 0) { if (prov->flag_initialized) { ossl_provider_teardown(prov); #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE if (prov->error_strings != NULL) { ERR_unload_strings(prov->error_lib, prov->error_strings); OPENSSL_free(prov->error_strings); prov->error_strings = NULL; } # endif #endif OPENSSL_free(prov->operation_bits); prov->operation_bits = NULL; prov->operation_bits_sz = 0; prov->flag_initialized = 0; } #ifndef FIPS_MODULE /* * We deregister thread handling whether or not the provider was * initialized. If init was attempted but was not successful then * the provider may still have registered a thread handler. */ ossl_init_thread_deregister(prov); DSO_free(prov->module); #endif OPENSSL_free(prov->name); OPENSSL_free(prov->path); sk_INFOPAIR_pop_free(prov->parameters, infopair_free); CRYPTO_THREAD_lock_free(prov->opbits_lock); CRYPTO_THREAD_lock_free(prov->flag_lock); #ifndef HAVE_ATOMICS CRYPTO_THREAD_lock_free(prov->activatecnt_lock); #endif CRYPTO_FREE_REF(&prov->refcnt); OPENSSL_free(prov); } #ifndef FIPS_MODULE else if (prov->ischild) { ossl_provider_free_parent(prov, 0); } #endif } } /* Setters */ int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path) { OPENSSL_free(prov->path); prov->path = NULL; if (module_path == NULL) return 1; if ((prov->path = OPENSSL_strdup(module_path)) != NULL) return 1; return 0; } static int infopair_add(STACK_OF(INFOPAIR) **infopairsk, const char *name, const char *value) { INFOPAIR *pair = NULL; if ((pair = OPENSSL_zalloc(sizeof(*pair))) == NULL || (pair->name = OPENSSL_strdup(name)) == NULL || (pair->value = OPENSSL_strdup(value)) == NULL) goto err; if ((*infopairsk == NULL && (*infopairsk = sk_INFOPAIR_new_null()) == NULL) || sk_INFOPAIR_push(*infopairsk, pair) <= 0) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB); goto err; } return 1; err: if (pair != NULL) { OPENSSL_free(pair->name); OPENSSL_free(pair->value); OPENSSL_free(pair); } return 0; } int ossl_provider_add_parameter(OSSL_PROVIDER *prov, const char *name, const char *value) { return infopair_add(&prov->parameters, name, value); } int ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO *provinfo, const char *name, const char *value) { return infopair_add(&provinfo->parameters, name, value); } /* * Provider activation. * * What "activation" means depends on the provider form; for built in * providers (in the library or the application alike), the provider * can already be considered to be loaded, all that's needed is to * initialize it. However, for dynamically loadable provider modules, * we must first load that module. * * Built in modules are distinguished from dynamically loaded modules * with an already assigned init function. */ static const OSSL_DISPATCH *core_dispatch; /* Define further down */ int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *libctx, const char *path) { struct provider_store_st *store; char *p = NULL; if (path != NULL) { p = OPENSSL_strdup(path); if (p == NULL) return 0; } if ((store = get_provider_store(libctx)) != NULL && CRYPTO_THREAD_write_lock(store->default_path_lock)) { OPENSSL_free(store->default_path); store->default_path = p; CRYPTO_THREAD_unlock(store->default_path_lock); return 1; } OPENSSL_free(p); return 0; } const char *OSSL_PROVIDER_get0_default_search_path(OSSL_LIB_CTX *libctx) { struct provider_store_st *store; char *path = NULL; if ((store = get_provider_store(libctx)) != NULL && CRYPTO_THREAD_read_lock(store->default_path_lock)) { path = store->default_path; CRYPTO_THREAD_unlock(store->default_path_lock); } return path; } /* * Internal version that doesn't affect the store flags, and thereby avoid * locking. Direct callers must remember to set the store flags when * appropriate. */ static int provider_init(OSSL_PROVIDER *prov) { const OSSL_DISPATCH *provider_dispatch = NULL; void *tmp_provctx = NULL; /* safety measure */ #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE OSSL_FUNC_provider_get_reason_strings_fn *p_get_reason_strings = NULL; # endif #endif int ok = 0; if (!ossl_assert(!prov->flag_initialized)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); goto end; } /* * If the init function isn't set, it indicates that this provider is * a loadable module. */ if (prov->init_function == NULL) { #ifdef FIPS_MODULE goto end; #else if (prov->module == NULL) { char *allocated_path = NULL; const char *module_path = NULL; char *merged_path = NULL; const char *load_dir = NULL; char *allocated_load_dir = NULL; struct provider_store_st *store; if ((prov->module = DSO_new()) == NULL) { /* DSO_new() generates an error already */ goto end; } if ((store = get_provider_store(prov->libctx)) == NULL || !CRYPTO_THREAD_read_lock(store->default_path_lock)) goto end; if (store->default_path != NULL) { allocated_load_dir = OPENSSL_strdup(store->default_path); CRYPTO_THREAD_unlock(store->default_path_lock); if (allocated_load_dir == NULL) goto end; load_dir = allocated_load_dir; } else { CRYPTO_THREAD_unlock(store->default_path_lock); } if (load_dir == NULL) { load_dir = ossl_safe_getenv("OPENSSL_MODULES"); if (load_dir == NULL) load_dir = MODULESDIR; } DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS, DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL); module_path = prov->path; if (module_path == NULL) module_path = allocated_path = DSO_convert_filename(prov->module, prov->name); if (module_path != NULL) merged_path = DSO_merge(prov->module, module_path, load_dir); if (merged_path == NULL || (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) { DSO_free(prov->module); prov->module = NULL; } OPENSSL_free(merged_path); OPENSSL_free(allocated_path); OPENSSL_free(allocated_load_dir); } if (prov->module == NULL) { /* DSO has already recorded errors, this is just a tracepoint */ ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_DSO_LIB, "name=%s", prov->name); goto end; } prov->init_function = (OSSL_provider_init_fn *) DSO_bind_func(prov->module, "OSSL_provider_init"); #endif } /* Check for and call the initialise function for the provider. */ if (prov->init_function == NULL) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_UNSUPPORTED, "name=%s, provider has no provider init function", prov->name); goto end; } if (!prov->init_function((OSSL_CORE_HANDLE *)prov, core_dispatch, &provider_dispatch, &tmp_provctx)) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL, "name=%s", prov->name); goto end; } prov->provctx = tmp_provctx; prov->dispatch = provider_dispatch; if (provider_dispatch != NULL) { for (; provider_dispatch->function_id != 0; provider_dispatch++) { switch (provider_dispatch->function_id) { case OSSL_FUNC_PROVIDER_TEARDOWN: prov->teardown = OSSL_FUNC_provider_teardown(provider_dispatch); break; case OSSL_FUNC_PROVIDER_GETTABLE_PARAMS: prov->gettable_params = OSSL_FUNC_provider_gettable_params(provider_dispatch); break; case OSSL_FUNC_PROVIDER_GET_PARAMS: prov->get_params = OSSL_FUNC_provider_get_params(provider_dispatch); break; case OSSL_FUNC_PROVIDER_SELF_TEST: prov->self_test = OSSL_FUNC_provider_self_test(provider_dispatch); break; case OSSL_FUNC_PROVIDER_GET_CAPABILITIES: prov->get_capabilities = OSSL_FUNC_provider_get_capabilities(provider_dispatch); break; case OSSL_FUNC_PROVIDER_QUERY_OPERATION: prov->query_operation = OSSL_FUNC_provider_query_operation(provider_dispatch); break; case OSSL_FUNC_PROVIDER_UNQUERY_OPERATION: prov->unquery_operation = OSSL_FUNC_provider_unquery_operation(provider_dispatch); break; #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE case OSSL_FUNC_PROVIDER_GET_REASON_STRINGS: p_get_reason_strings = OSSL_FUNC_provider_get_reason_strings(provider_dispatch); break; # endif #endif } } } #ifndef OPENSSL_NO_ERR # ifndef FIPS_MODULE if (p_get_reason_strings != NULL) { const OSSL_ITEM *reasonstrings = p_get_reason_strings(prov->provctx); size_t cnt, cnt2; /* * ERR_load_strings() handles ERR_STRING_DATA rather than OSSL_ITEM, * although they are essentially the same type. * Furthermore, ERR_load_strings() patches the array's error number * with the error library number, so we need to make a copy of that * array either way. */ cnt = 0; while (reasonstrings[cnt].id != 0) { if (ERR_GET_LIB(reasonstrings[cnt].id) != 0) goto end; cnt++; } cnt++; /* One for the terminating item */ /* Allocate one extra item for the "library" name */ prov->error_strings = OPENSSL_zalloc(sizeof(ERR_STRING_DATA) * (cnt + 1)); if (prov->error_strings == NULL) goto end; /* * Set the "library" name. */ prov->error_strings[0].error = ERR_PACK(prov->error_lib, 0, 0); prov->error_strings[0].string = prov->name; /* * Copy reasonstrings item 0..cnt-1 to prov->error_trings positions * 1..cnt. */ for (cnt2 = 1; cnt2 <= cnt; cnt2++) { prov->error_strings[cnt2].error = (int)reasonstrings[cnt2-1].id; prov->error_strings[cnt2].string = reasonstrings[cnt2-1].ptr; } ERR_load_strings(prov->error_lib, prov->error_strings); } # endif #endif /* With this flag set, this provider has become fully "loaded". */ prov->flag_initialized = 1; ok = 1; end: return ok; } /* * Deactivate a provider. If upcalls is 0 then we suppress any upcalls to a * parent provider. If removechildren is 0 then we suppress any calls to remove * child providers. * Return -1 on failure and the activation count on success */ static int provider_deactivate(OSSL_PROVIDER *prov, int upcalls, int removechildren) { int count; struct provider_store_st *store; #ifndef FIPS_MODULE int freeparent = 0; #endif int lock = 1; if (!ossl_assert(prov != NULL)) return -1; /* * No need to lock if we've got no store because we've not been shared with * other threads. */ store = get_provider_store(prov->libctx); if (store == NULL) lock = 0; if (lock && !CRYPTO_THREAD_read_lock(store->lock)) return -1; if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) { CRYPTO_THREAD_unlock(store->lock); return -1; } CRYPTO_atomic_add(&prov->activatecnt, -1, &count, prov->activatecnt_lock); #ifndef FIPS_MODULE if (count >= 1 && prov->ischild && upcalls) { /* * We have had a direct activation in this child libctx so we need to * now down the ref count in the parent provider. We do the actual down * ref outside of the flag_lock, since it could involve getting other * locks. */ freeparent = 1; } #endif if (count < 1) prov->flag_activated = 0; #ifndef FIPS_MODULE else removechildren = 0; #endif #ifndef FIPS_MODULE if (removechildren && store != NULL) { int i, max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); OSSL_PROVIDER_CHILD_CB *child_cb; for (i = 0; i < max; i++) { child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); child_cb->remove_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata); } } #endif if (lock) { CRYPTO_THREAD_unlock(prov->flag_lock); CRYPTO_THREAD_unlock(store->lock); /* * This can be done outside the lock. We tolerate other threads getting * the wrong result briefly when creating OSSL_DECODER_CTXs. */ #ifndef FIPS_MODULE if (count < 1) ossl_decoder_cache_flush(prov->libctx); #endif } #ifndef FIPS_MODULE if (freeparent) ossl_provider_free_parent(prov, 1); #endif /* We don't deinit here, that's done in ossl_provider_free() */ return count; } /* * Activate a provider. * Return -1 on failure and the activation count on success */ static int provider_activate(OSSL_PROVIDER *prov, int lock, int upcalls) { int count = -1; struct provider_store_st *store; int ret = 1; store = prov->store; /* * If the provider hasn't been added to the store, then we don't need * any locks because we've not shared it with other threads. */ if (store == NULL) { lock = 0; if (!provider_init(prov)) return -1; } #ifndef FIPS_MODULE if (prov->ischild && upcalls && !ossl_provider_up_ref_parent(prov, 1)) return -1; #endif if (lock && !CRYPTO_THREAD_read_lock(store->lock)) { #ifndef FIPS_MODULE if (prov->ischild && upcalls) ossl_provider_free_parent(prov, 1); #endif return -1; } if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) { CRYPTO_THREAD_unlock(store->lock); #ifndef FIPS_MODULE if (prov->ischild && upcalls) ossl_provider_free_parent(prov, 1); #endif return -1; } if (CRYPTO_atomic_add(&prov->activatecnt, 1, &count, prov->activatecnt_lock)) { prov->flag_activated = 1; if (count == 1 && store != NULL) { ret = create_provider_children(prov); } } if (lock) { CRYPTO_THREAD_unlock(prov->flag_lock); CRYPTO_THREAD_unlock(store->lock); /* * This can be done outside the lock. We tolerate other threads getting * the wrong result briefly when creating OSSL_DECODER_CTXs. */ #ifndef FIPS_MODULE if (count == 1) ossl_decoder_cache_flush(prov->libctx); #endif } if (!ret) return -1; return count; } static int provider_flush_store_cache(const OSSL_PROVIDER *prov) { struct provider_store_st *store; int freeing; if ((store = get_provider_store(prov->libctx)) == NULL) return 0; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; freeing = store->freeing; CRYPTO_THREAD_unlock(store->lock); if (!freeing) { int acc = evp_method_store_cache_flush(prov->libctx) #ifndef FIPS_MODULE + ossl_encoder_store_cache_flush(prov->libctx) + ossl_decoder_store_cache_flush(prov->libctx) + ossl_store_loader_store_cache_flush(prov->libctx) #endif ; #ifndef FIPS_MODULE return acc == 4; #else return acc == 1; #endif } return 1; } static int provider_remove_store_methods(OSSL_PROVIDER *prov) { struct provider_store_st *store; int freeing; if ((store = get_provider_store(prov->libctx)) == NULL) return 0; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; freeing = store->freeing; CRYPTO_THREAD_unlock(store->lock); if (!freeing) { int acc; if (!CRYPTO_THREAD_write_lock(prov->opbits_lock)) return 0; OPENSSL_free(prov->operation_bits); prov->operation_bits = NULL; prov->operation_bits_sz = 0; CRYPTO_THREAD_unlock(prov->opbits_lock); acc = evp_method_store_remove_all_provided(prov) #ifndef FIPS_MODULE + ossl_encoder_store_remove_all_provided(prov) + ossl_decoder_store_remove_all_provided(prov) + ossl_store_loader_store_remove_all_provided(prov) #endif ; #ifndef FIPS_MODULE return acc == 4; #else return acc == 1; #endif } return 1; } int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild) { int count; if (prov == NULL) return 0; #ifndef FIPS_MODULE /* * If aschild is true, then we only actually do the activation if the * provider is a child. If its not, this is still success. */ if (aschild && !prov->ischild) return 1; #endif if ((count = provider_activate(prov, 1, upcalls)) > 0) return count == 1 ? provider_flush_store_cache(prov) : 1; return 0; } int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren) { int count; if (prov == NULL || (count = provider_deactivate(prov, 1, removechildren)) < 0) return 0; return count == 0 ? provider_remove_store_methods(prov) : 1; } void *ossl_provider_ctx(const OSSL_PROVIDER *prov) { return prov != NULL ? prov->provctx : NULL; } /* * This function only does something once when store->use_fallbacks == 1, * and then sets store->use_fallbacks = 0, so the second call and so on is * effectively a no-op. */ static int provider_activate_fallbacks(struct provider_store_st *store) { int use_fallbacks; int activated_fallback_count = 0; int ret = 0; const OSSL_PROVIDER_INFO *p; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; use_fallbacks = store->use_fallbacks; CRYPTO_THREAD_unlock(store->lock); if (!use_fallbacks) return 1; if (!CRYPTO_THREAD_write_lock(store->lock)) return 0; /* Check again, just in case another thread changed it */ use_fallbacks = store->use_fallbacks; if (!use_fallbacks) { CRYPTO_THREAD_unlock(store->lock); return 1; } for (p = ossl_predefined_providers; p->name != NULL; p++) { OSSL_PROVIDER *prov = NULL; if (!p->is_fallback) continue; /* * We use the internal constructor directly here, * otherwise we get a call loop */ prov = provider_new(p->name, p->init, NULL); if (prov == NULL) goto err; prov->libctx = store->libctx; #ifndef FIPS_MODULE prov->error_lib = ERR_get_next_error_library(); #endif /* * We are calling provider_activate while holding the store lock. This * means the init function will be called while holding a lock. Normally * we try to avoid calling a user callback while holding a lock. * However, fallbacks are never third party providers so we accept this. */ if (provider_activate(prov, 0, 0) < 0) { ossl_provider_free(prov); goto err; } prov->store = store; if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) { ossl_provider_free(prov); goto err; } activated_fallback_count++; } if (activated_fallback_count > 0) { store->use_fallbacks = 0; ret = 1; } err: CRYPTO_THREAD_unlock(store->lock); return ret; } int ossl_provider_doall_activated(OSSL_LIB_CTX *ctx, int (*cb)(OSSL_PROVIDER *provider, void *cbdata), void *cbdata) { int ret = 0, curr, max, ref = 0; struct provider_store_st *store = get_provider_store(ctx); STACK_OF(OSSL_PROVIDER) *provs = NULL; #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG) /* * Make sure any providers are loaded from config before we try to use * them. */ if (ossl_lib_ctx_is_default(ctx)) OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL); #endif if (store == NULL) return 1; if (!provider_activate_fallbacks(store)) return 0; /* * Under lock, grab a copy of the provider list and up_ref each * provider so that they don't disappear underneath us. */ if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; provs = sk_OSSL_PROVIDER_dup(store->providers); if (provs == NULL) { CRYPTO_THREAD_unlock(store->lock); return 0; } max = sk_OSSL_PROVIDER_num(provs); /* * We work backwards through the stack so that we can safely delete items * as we go. */ for (curr = max - 1; curr >= 0; curr--) { OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr); if (!CRYPTO_THREAD_read_lock(prov->flag_lock)) goto err_unlock; if (prov->flag_activated) { /* * We call CRYPTO_UP_REF directly rather than ossl_provider_up_ref * to avoid upping the ref count on the parent provider, which we * must not do while holding locks. */ if (CRYPTO_UP_REF(&prov->refcnt, &ref) <= 0) { CRYPTO_THREAD_unlock(prov->flag_lock); goto err_unlock; } /* * It's already activated, but we up the activated count to ensure * it remains activated until after we've called the user callback. * In theory this could mean the parent provider goes inactive, * whilst still activated in the child for a short period. That's ok. */ if (!CRYPTO_atomic_add(&prov->activatecnt, 1, &ref, prov->activatecnt_lock)) { CRYPTO_DOWN_REF(&prov->refcnt, &ref); CRYPTO_THREAD_unlock(prov->flag_lock); goto err_unlock; } } else { sk_OSSL_PROVIDER_delete(provs, curr); max--; } CRYPTO_THREAD_unlock(prov->flag_lock); } CRYPTO_THREAD_unlock(store->lock); /* * Now, we sweep through all providers not under lock */ for (curr = 0; curr < max; curr++) { OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr); if (!cb(prov, cbdata)) { curr = -1; goto finish; } } curr = -1; ret = 1; goto finish; err_unlock: CRYPTO_THREAD_unlock(store->lock); finish: /* * The pop_free call doesn't do what we want on an error condition. We * either start from the first item in the stack, or part way through if * we only processed some of the items. */ for (curr++; curr < max; curr++) { OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr); if (!CRYPTO_atomic_add(&prov->activatecnt, -1, &ref, prov->activatecnt_lock)) { ret = 0; continue; } if (ref < 1) { /* * Looks like we need to deactivate properly. We could just have * done this originally, but it involves taking a write lock so * we avoid it. We up the count again and do a full deactivation */ if (CRYPTO_atomic_add(&prov->activatecnt, 1, &ref, prov->activatecnt_lock)) provider_deactivate(prov, 0, 1); else ret = 0; } /* * As above where we did the up-ref, we don't call ossl_provider_free * to avoid making upcalls. There should always be at least one ref * to the provider in the store, so this should never drop to 0. */ if (!CRYPTO_DOWN_REF(&prov->refcnt, &ref)) { ret = 0; continue; } /* * Not much we can do if this assert ever fails. So we don't use * ossl_assert here. */ assert(ref > 0); } sk_OSSL_PROVIDER_free(provs); return ret; } int OSSL_PROVIDER_available(OSSL_LIB_CTX *libctx, const char *name) { OSSL_PROVIDER *prov = NULL; int available = 0; struct provider_store_st *store = get_provider_store(libctx); if (store == NULL || !provider_activate_fallbacks(store)) return 0; prov = ossl_provider_find(libctx, name, 0); if (prov != NULL) { if (!CRYPTO_THREAD_read_lock(prov->flag_lock)) return 0; available = prov->flag_activated; CRYPTO_THREAD_unlock(prov->flag_lock); ossl_provider_free(prov); } return available; } /* Getters of Provider Object data */ const char *ossl_provider_name(const OSSL_PROVIDER *prov) { return prov->name; } const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov) { return prov->module; } const char *ossl_provider_module_name(const OSSL_PROVIDER *prov) { #ifdef FIPS_MODULE return NULL; #else return DSO_get_filename(prov->module); #endif } const char *ossl_provider_module_path(const OSSL_PROVIDER *prov) { #ifdef FIPS_MODULE return NULL; #else /* FIXME: Ensure it's a full path */ return DSO_get_filename(prov->module); #endif } void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov) { if (prov != NULL) return prov->provctx; return NULL; } const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov) { if (prov != NULL) return prov->dispatch; return NULL; } OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov) { return prov != NULL ? prov->libctx : NULL; } /* Wrappers around calls to the provider */ void ossl_provider_teardown(const OSSL_PROVIDER *prov) { if (prov->teardown != NULL #ifndef FIPS_MODULE && !prov->ischild #endif ) prov->teardown(prov->provctx); } const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov) { return prov->gettable_params == NULL ? NULL : prov->gettable_params(prov->provctx); } int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[]) { return prov->get_params == NULL ? 0 : prov->get_params(prov->provctx, params); } int ossl_provider_self_test(const OSSL_PROVIDER *prov) { int ret; if (prov->self_test == NULL) return 1; ret = prov->self_test(prov->provctx); if (ret == 0) (void)provider_remove_store_methods((OSSL_PROVIDER *)prov); return ret; } int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov, const char *capability, OSSL_CALLBACK *cb, void *arg) { return prov->get_capabilities == NULL ? 1 : prov->get_capabilities(prov->provctx, capability, cb, arg); } const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov, int operation_id, int *no_cache) { const OSSL_ALGORITHM *res; if (prov->query_operation == NULL) return NULL; res = prov->query_operation(prov->provctx, operation_id, no_cache); #if defined(OPENSSL_NO_CACHED_FETCH) /* Forcing the non-caching of queries */ if (no_cache != NULL) *no_cache = 1; #endif return res; } void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov, int operation_id, const OSSL_ALGORITHM *algs) { if (prov->unquery_operation != NULL) prov->unquery_operation(prov->provctx, operation_id, algs); } int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum) { size_t byte = bitnum / 8; unsigned char bit = (1 << (bitnum % 8)) & 0xFF; if (!CRYPTO_THREAD_write_lock(provider->opbits_lock)) return 0; if (provider->operation_bits_sz <= byte) { unsigned char *tmp = OPENSSL_realloc(provider->operation_bits, byte + 1); if (tmp == NULL) { CRYPTO_THREAD_unlock(provider->opbits_lock); return 0; } provider->operation_bits = tmp; memset(provider->operation_bits + provider->operation_bits_sz, '\0', byte + 1 - provider->operation_bits_sz); provider->operation_bits_sz = byte + 1; } provider->operation_bits[byte] |= bit; CRYPTO_THREAD_unlock(provider->opbits_lock); return 1; } int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum, int *result) { size_t byte = bitnum / 8; unsigned char bit = (1 << (bitnum % 8)) & 0xFF; if (!ossl_assert(result != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } *result = 0; if (!CRYPTO_THREAD_read_lock(provider->opbits_lock)) return 0; if (provider->operation_bits_sz > byte) *result = ((provider->operation_bits[byte] & bit) != 0); CRYPTO_THREAD_unlock(provider->opbits_lock); return 1; } #ifndef FIPS_MODULE const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov) { return prov->handle; } int ossl_provider_is_child(const OSSL_PROVIDER *prov) { return prov->ischild; } int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle) { prov->handle = handle; prov->ischild = 1; return 1; } int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx, const char *props) { #ifndef FIPS_MODULE struct provider_store_st *store = NULL; int i, max; OSSL_PROVIDER_CHILD_CB *child_cb; if ((store = get_provider_store(libctx)) == NULL) return 0; if (!CRYPTO_THREAD_read_lock(store->lock)) return 0; max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); for (i = 0; i < max; i++) { child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); child_cb->global_props_cb(props, child_cb->cbdata); } CRYPTO_THREAD_unlock(store->lock); #endif return 1; } static int ossl_provider_register_child_cb(const OSSL_CORE_HANDLE *handle, int (*create_cb)( const OSSL_CORE_HANDLE *provider, void *cbdata), int (*remove_cb)( const OSSL_CORE_HANDLE *provider, void *cbdata), int (*global_props_cb)( const char *props, void *cbdata), void *cbdata) { /* * This is really an OSSL_PROVIDER that we created and cast to * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back. */ OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle; OSSL_PROVIDER *prov; OSSL_LIB_CTX *libctx = thisprov->libctx; struct provider_store_st *store = NULL; int ret = 0, i, max; OSSL_PROVIDER_CHILD_CB *child_cb; char *propsstr = NULL; if ((store = get_provider_store(libctx)) == NULL) return 0; child_cb = OPENSSL_malloc(sizeof(*child_cb)); if (child_cb == NULL) return 0; child_cb->prov = thisprov; child_cb->create_cb = create_cb; child_cb->remove_cb = remove_cb; child_cb->global_props_cb = global_props_cb; child_cb->cbdata = cbdata; if (!CRYPTO_THREAD_write_lock(store->lock)) { OPENSSL_free(child_cb); return 0; } propsstr = evp_get_global_properties_str(libctx, 0); if (propsstr != NULL) { global_props_cb(propsstr, cbdata); OPENSSL_free(propsstr); } max = sk_OSSL_PROVIDER_num(store->providers); for (i = 0; i < max; i++) { int activated; prov = sk_OSSL_PROVIDER_value(store->providers, i); if (!CRYPTO_THREAD_read_lock(prov->flag_lock)) break; activated = prov->flag_activated; CRYPTO_THREAD_unlock(prov->flag_lock); /* * We hold the store lock while calling the user callback. This means * that the user callback must be short and simple and not do anything * likely to cause a deadlock. We don't hold the flag_lock during this * call. In theory this means that another thread could deactivate it * while we are calling create. This is ok because the other thread * will also call remove_cb, but won't be able to do so until we release * the store lock. */ if (activated && !create_cb((OSSL_CORE_HANDLE *)prov, cbdata)) break; } if (i == max) { /* Success */ ret = sk_OSSL_PROVIDER_CHILD_CB_push(store->child_cbs, child_cb); } if (i != max || ret <= 0) { /* Failed during creation. Remove everything we just added */ for (; i >= 0; i--) { prov = sk_OSSL_PROVIDER_value(store->providers, i); remove_cb((OSSL_CORE_HANDLE *)prov, cbdata); } OPENSSL_free(child_cb); ret = 0; } CRYPTO_THREAD_unlock(store->lock); return ret; } static void ossl_provider_deregister_child_cb(const OSSL_CORE_HANDLE *handle) { /* * This is really an OSSL_PROVIDER that we created and cast to * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back. */ OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle; OSSL_LIB_CTX *libctx = thisprov->libctx; struct provider_store_st *store = NULL; int i, max; OSSL_PROVIDER_CHILD_CB *child_cb; if ((store = get_provider_store(libctx)) == NULL) return; if (!CRYPTO_THREAD_write_lock(store->lock)) return; max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs); for (i = 0; i < max; i++) { child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i); if (child_cb->prov == thisprov) { /* Found an entry */ sk_OSSL_PROVIDER_CHILD_CB_delete(store->child_cbs, i); OPENSSL_free(child_cb); break; } } CRYPTO_THREAD_unlock(store->lock); } #endif /*- * Core functions for the provider * =============================== * * This is the set of functions that the core makes available to the provider */ /* * This returns a list of Provider Object parameters with their types, for * discovery. We do not expect that many providers will use this, but one * never knows. */ static const OSSL_PARAM param_types[] = { OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0), OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_PROV_NAME, OSSL_PARAM_UTF8_PTR, NULL, 0), #ifndef FIPS_MODULE OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_MODULE_FILENAME, OSSL_PARAM_UTF8_PTR, NULL, 0), #endif OSSL_PARAM_END }; /* * Forward declare all the functions that are provided aa dispatch. * This ensures that the compiler will complain if they aren't defined * with the correct signature. */ static OSSL_FUNC_core_gettable_params_fn core_gettable_params; static OSSL_FUNC_core_get_params_fn core_get_params; static OSSL_FUNC_core_get_libctx_fn core_get_libctx; static OSSL_FUNC_core_thread_start_fn core_thread_start; #ifndef FIPS_MODULE static OSSL_FUNC_core_new_error_fn core_new_error; static OSSL_FUNC_core_set_error_debug_fn core_set_error_debug; static OSSL_FUNC_core_vset_error_fn core_vset_error; static OSSL_FUNC_core_set_error_mark_fn core_set_error_mark; static OSSL_FUNC_core_clear_last_error_mark_fn core_clear_last_error_mark; static OSSL_FUNC_core_pop_error_to_mark_fn core_pop_error_to_mark; OSSL_FUNC_BIO_new_file_fn ossl_core_bio_new_file; OSSL_FUNC_BIO_new_membuf_fn ossl_core_bio_new_mem_buf; OSSL_FUNC_BIO_read_ex_fn ossl_core_bio_read_ex; OSSL_FUNC_BIO_write_ex_fn ossl_core_bio_write_ex; OSSL_FUNC_BIO_gets_fn ossl_core_bio_gets; OSSL_FUNC_BIO_puts_fn ossl_core_bio_puts; OSSL_FUNC_BIO_up_ref_fn ossl_core_bio_up_ref; OSSL_FUNC_BIO_free_fn ossl_core_bio_free; OSSL_FUNC_BIO_vprintf_fn ossl_core_bio_vprintf; OSSL_FUNC_BIO_vsnprintf_fn BIO_vsnprintf; static OSSL_FUNC_self_test_cb_fn core_self_test_get_callback; static OSSL_FUNC_get_entropy_fn rand_get_entropy; static OSSL_FUNC_get_user_entropy_fn rand_get_user_entropy; static OSSL_FUNC_cleanup_entropy_fn rand_cleanup_entropy; static OSSL_FUNC_cleanup_user_entropy_fn rand_cleanup_user_entropy; static OSSL_FUNC_get_nonce_fn rand_get_nonce; static OSSL_FUNC_get_user_nonce_fn rand_get_user_nonce; static OSSL_FUNC_cleanup_nonce_fn rand_cleanup_nonce; static OSSL_FUNC_cleanup_user_nonce_fn rand_cleanup_user_nonce; #endif OSSL_FUNC_CRYPTO_malloc_fn CRYPTO_malloc; OSSL_FUNC_CRYPTO_zalloc_fn CRYPTO_zalloc; OSSL_FUNC_CRYPTO_free_fn CRYPTO_free; OSSL_FUNC_CRYPTO_clear_free_fn CRYPTO_clear_free; OSSL_FUNC_CRYPTO_realloc_fn CRYPTO_realloc; OSSL_FUNC_CRYPTO_clear_realloc_fn CRYPTO_clear_realloc; OSSL_FUNC_CRYPTO_secure_malloc_fn CRYPTO_secure_malloc; OSSL_FUNC_CRYPTO_secure_zalloc_fn CRYPTO_secure_zalloc; OSSL_FUNC_CRYPTO_secure_free_fn CRYPTO_secure_free; OSSL_FUNC_CRYPTO_secure_clear_free_fn CRYPTO_secure_clear_free; OSSL_FUNC_CRYPTO_secure_allocated_fn CRYPTO_secure_allocated; OSSL_FUNC_OPENSSL_cleanse_fn OPENSSL_cleanse; #ifndef FIPS_MODULE OSSL_FUNC_provider_register_child_cb_fn ossl_provider_register_child_cb; OSSL_FUNC_provider_deregister_child_cb_fn ossl_provider_deregister_child_cb; static OSSL_FUNC_provider_name_fn core_provider_get0_name; static OSSL_FUNC_provider_get0_provider_ctx_fn core_provider_get0_provider_ctx; static OSSL_FUNC_provider_get0_dispatch_fn core_provider_get0_dispatch; static OSSL_FUNC_provider_up_ref_fn core_provider_up_ref_intern; static OSSL_FUNC_provider_free_fn core_provider_free_intern; static OSSL_FUNC_core_obj_add_sigid_fn core_obj_add_sigid; static OSSL_FUNC_core_obj_create_fn core_obj_create; #endif static const OSSL_PARAM *core_gettable_params(const OSSL_CORE_HANDLE *handle) { return param_types; } static int core_get_params(const OSSL_CORE_HANDLE *handle, OSSL_PARAM params[]) { int i; OSSL_PARAM *p; /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_VERSION)) != NULL) OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR); if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_PROV_NAME)) != NULL) OSSL_PARAM_set_utf8_ptr(p, prov->name); #ifndef FIPS_MODULE if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_MODULE_FILENAME)) != NULL) OSSL_PARAM_set_utf8_ptr(p, ossl_provider_module_path(prov)); #endif if (prov->parameters == NULL) return 1; for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) { INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i); if ((p = OSSL_PARAM_locate(params, pair->name)) != NULL) OSSL_PARAM_set_utf8_ptr(p, pair->value); } return 1; } static OPENSSL_CORE_CTX *core_get_libctx(const OSSL_CORE_HANDLE *handle) { /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; /* * Using ossl_provider_libctx would be wrong as that returns * NULL for |prov| == NULL and NULL libctx has a special meaning * that does not apply here. Here |prov| == NULL can happen only in * case of a coding error. */ assert(prov != NULL); return (OPENSSL_CORE_CTX *)prov->libctx; } static int core_thread_start(const OSSL_CORE_HANDLE *handle, OSSL_thread_stop_handler_fn handfn, void *arg) { /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; return ossl_init_thread_start(prov, arg, handfn); } /* * The FIPS module inner provider doesn't implement these. They aren't * needed there, since the FIPS module upcalls are always the outer provider * ones. */ #ifndef FIPS_MODULE /* * These error functions should use |handle| to select the proper * library context to report in the correct error stack if error * stacks become tied to the library context. * We cannot currently do that since there's no support for it in the * ERR subsystem. */ static void core_new_error(const OSSL_CORE_HANDLE *handle) { ERR_new(); } static void core_set_error_debug(const OSSL_CORE_HANDLE *handle, const char *file, int line, const char *func) { ERR_set_debug(file, line, func); } static void core_vset_error(const OSSL_CORE_HANDLE *handle, uint32_t reason, const char *fmt, va_list args) { /* * We created this object originally and we know it is actually an * OSSL_PROVIDER *, so the cast is safe */ OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle; /* * If the uppermost 8 bits are non-zero, it's an OpenSSL library * error and will be treated as such. Otherwise, it's a new style * provider error and will be treated as such. */ if (ERR_GET_LIB(reason) != 0) { ERR_vset_error(ERR_GET_LIB(reason), ERR_GET_REASON(reason), fmt, args); } else { ERR_vset_error(prov->error_lib, (int)reason, fmt, args); } } static int core_set_error_mark(const OSSL_CORE_HANDLE *handle) { return ERR_set_mark(); } static int core_clear_last_error_mark(const OSSL_CORE_HANDLE *handle) { return ERR_clear_last_mark(); } static int core_pop_error_to_mark(const OSSL_CORE_HANDLE *handle) { return ERR_pop_to_mark(); } static void core_self_test_get_callback(OPENSSL_CORE_CTX *libctx, OSSL_CALLBACK **cb, void **cbarg) { OSSL_SELF_TEST_get_callback((OSSL_LIB_CTX *)libctx, cb, cbarg); } static size_t rand_get_entropy(const OSSL_CORE_HANDLE *handle, unsigned char **pout, int entropy, size_t min_len, size_t max_len) { return ossl_rand_get_entropy((OSSL_LIB_CTX *)core_get_libctx(handle), pout, entropy, min_len, max_len); } static size_t rand_get_user_entropy(const OSSL_CORE_HANDLE *handle, unsigned char **pout, int entropy, size_t min_len, size_t max_len) { return ossl_rand_get_user_entropy((OSSL_LIB_CTX *)core_get_libctx(handle), pout, entropy, min_len, max_len); } static void rand_cleanup_entropy(const OSSL_CORE_HANDLE *handle, unsigned char *buf, size_t len) { ossl_rand_cleanup_entropy((OSSL_LIB_CTX *)core_get_libctx(handle), buf, len); } static void rand_cleanup_user_entropy(const OSSL_CORE_HANDLE *handle, unsigned char *buf, size_t len) { ossl_rand_cleanup_user_entropy((OSSL_LIB_CTX *)core_get_libctx(handle), buf, len); } static size_t rand_get_nonce(const OSSL_CORE_HANDLE *handle, unsigned char **pout, size_t min_len, size_t max_len, const void *salt, size_t salt_len) { return ossl_rand_get_nonce((OSSL_LIB_CTX *)core_get_libctx(handle), pout, min_len, max_len, salt, salt_len); } static size_t rand_get_user_nonce(const OSSL_CORE_HANDLE *handle, unsigned char **pout, size_t min_len, size_t max_len, const void *salt, size_t salt_len) { return ossl_rand_get_user_nonce((OSSL_LIB_CTX *)core_get_libctx(handle), pout, min_len, max_len, salt, salt_len); } static void rand_cleanup_nonce(const OSSL_CORE_HANDLE *handle, unsigned char *buf, size_t len) { ossl_rand_cleanup_nonce((OSSL_LIB_CTX *)core_get_libctx(handle), buf, len); } static void rand_cleanup_user_nonce(const OSSL_CORE_HANDLE *handle, unsigned char *buf, size_t len) { ossl_rand_cleanup_user_nonce((OSSL_LIB_CTX *)core_get_libctx(handle), buf, len); } static const char *core_provider_get0_name(const OSSL_CORE_HANDLE *prov) { return OSSL_PROVIDER_get0_name((const OSSL_PROVIDER *)prov); } static void *core_provider_get0_provider_ctx(const OSSL_CORE_HANDLE *prov) { return OSSL_PROVIDER_get0_provider_ctx((const OSSL_PROVIDER *)prov); } static const OSSL_DISPATCH * core_provider_get0_dispatch(const OSSL_CORE_HANDLE *prov) { return OSSL_PROVIDER_get0_dispatch((const OSSL_PROVIDER *)prov); } static int core_provider_up_ref_intern(const OSSL_CORE_HANDLE *prov, int activate) { return provider_up_ref_intern((OSSL_PROVIDER *)prov, activate); } static int core_provider_free_intern(const OSSL_CORE_HANDLE *prov, int deactivate) { return provider_free_intern((OSSL_PROVIDER *)prov, deactivate); } static int core_obj_add_sigid(const OSSL_CORE_HANDLE *prov, const char *sign_name, const char *digest_name, const char *pkey_name) { int sign_nid = OBJ_txt2nid(sign_name); int digest_nid = NID_undef; int pkey_nid = OBJ_txt2nid(pkey_name); if (digest_name != NULL && digest_name[0] != '\0' && (digest_nid = OBJ_txt2nid(digest_name)) == NID_undef) return 0; if (sign_nid == NID_undef) return 0; /* * Check if it already exists. This is a success if so (even if we don't * have nids for the digest/pkey) */ if (OBJ_find_sigid_algs(sign_nid, NULL, NULL)) return 1; if (pkey_nid == NID_undef) return 0; return OBJ_add_sigid(sign_nid, digest_nid, pkey_nid); } static int core_obj_create(const OSSL_CORE_HANDLE *prov, const char *oid, const char *sn, const char *ln) { /* Check if it already exists and create it if not */ return OBJ_txt2nid(oid) != NID_undef || OBJ_create(oid, sn, ln) != NID_undef; } #endif /* FIPS_MODULE */ /* * Functions provided by the core. */ static const OSSL_DISPATCH core_dispatch_[] = { { OSSL_FUNC_CORE_GETTABLE_PARAMS, (void (*)(void))core_gettable_params }, { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params }, { OSSL_FUNC_CORE_GET_LIBCTX, (void (*)(void))core_get_libctx }, { OSSL_FUNC_CORE_THREAD_START, (void (*)(void))core_thread_start }, #ifndef FIPS_MODULE { OSSL_FUNC_CORE_NEW_ERROR, (void (*)(void))core_new_error }, { OSSL_FUNC_CORE_SET_ERROR_DEBUG, (void (*)(void))core_set_error_debug }, { OSSL_FUNC_CORE_VSET_ERROR, (void (*)(void))core_vset_error }, { OSSL_FUNC_CORE_SET_ERROR_MARK, (void (*)(void))core_set_error_mark }, { OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK, (void (*)(void))core_clear_last_error_mark }, { OSSL_FUNC_CORE_POP_ERROR_TO_MARK, (void (*)(void))core_pop_error_to_mark }, { OSSL_FUNC_BIO_NEW_FILE, (void (*)(void))ossl_core_bio_new_file }, { OSSL_FUNC_BIO_NEW_MEMBUF, (void (*)(void))ossl_core_bio_new_mem_buf }, { OSSL_FUNC_BIO_READ_EX, (void (*)(void))ossl_core_bio_read_ex }, { OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))ossl_core_bio_write_ex }, { OSSL_FUNC_BIO_GETS, (void (*)(void))ossl_core_bio_gets }, { OSSL_FUNC_BIO_PUTS, (void (*)(void))ossl_core_bio_puts }, { OSSL_FUNC_BIO_CTRL, (void (*)(void))ossl_core_bio_ctrl }, { OSSL_FUNC_BIO_UP_REF, (void (*)(void))ossl_core_bio_up_ref }, { OSSL_FUNC_BIO_FREE, (void (*)(void))ossl_core_bio_free }, { OSSL_FUNC_BIO_VPRINTF, (void (*)(void))ossl_core_bio_vprintf }, { OSSL_FUNC_BIO_VSNPRINTF, (void (*)(void))BIO_vsnprintf }, { OSSL_FUNC_SELF_TEST_CB, (void (*)(void))core_self_test_get_callback }, { OSSL_FUNC_GET_ENTROPY, (void (*)(void))rand_get_entropy }, { OSSL_FUNC_GET_USER_ENTROPY, (void (*)(void))rand_get_user_entropy }, { OSSL_FUNC_CLEANUP_ENTROPY, (void (*)(void))rand_cleanup_entropy }, { OSSL_FUNC_CLEANUP_USER_ENTROPY, (void (*)(void))rand_cleanup_user_entropy }, { OSSL_FUNC_GET_NONCE, (void (*)(void))rand_get_nonce }, { OSSL_FUNC_GET_USER_NONCE, (void (*)(void))rand_get_user_nonce }, { OSSL_FUNC_CLEANUP_NONCE, (void (*)(void))rand_cleanup_nonce }, { OSSL_FUNC_CLEANUP_USER_NONCE, (void (*)(void))rand_cleanup_user_nonce }, #endif { OSSL_FUNC_CRYPTO_MALLOC, (void (*)(void))CRYPTO_malloc }, { OSSL_FUNC_CRYPTO_ZALLOC, (void (*)(void))CRYPTO_zalloc }, { OSSL_FUNC_CRYPTO_FREE, (void (*)(void))CRYPTO_free }, { OSSL_FUNC_CRYPTO_CLEAR_FREE, (void (*)(void))CRYPTO_clear_free }, { OSSL_FUNC_CRYPTO_REALLOC, (void (*)(void))CRYPTO_realloc }, { OSSL_FUNC_CRYPTO_CLEAR_REALLOC, (void (*)(void))CRYPTO_clear_realloc }, { OSSL_FUNC_CRYPTO_SECURE_MALLOC, (void (*)(void))CRYPTO_secure_malloc }, { OSSL_FUNC_CRYPTO_SECURE_ZALLOC, (void (*)(void))CRYPTO_secure_zalloc }, { OSSL_FUNC_CRYPTO_SECURE_FREE, (void (*)(void))CRYPTO_secure_free }, { OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE, (void (*)(void))CRYPTO_secure_clear_free }, { OSSL_FUNC_CRYPTO_SECURE_ALLOCATED, (void (*)(void))CRYPTO_secure_allocated }, { OSSL_FUNC_OPENSSL_CLEANSE, (void (*)(void))OPENSSL_cleanse }, #ifndef FIPS_MODULE { OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB, (void (*)(void))ossl_provider_register_child_cb }, { OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB, (void (*)(void))ossl_provider_deregister_child_cb }, { OSSL_FUNC_PROVIDER_NAME, (void (*)(void))core_provider_get0_name }, { OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX, (void (*)(void))core_provider_get0_provider_ctx }, { OSSL_FUNC_PROVIDER_GET0_DISPATCH, (void (*)(void))core_provider_get0_dispatch }, { OSSL_FUNC_PROVIDER_UP_REF, (void (*)(void))core_provider_up_ref_intern }, { OSSL_FUNC_PROVIDER_FREE, (void (*)(void))core_provider_free_intern }, { OSSL_FUNC_CORE_OBJ_ADD_SIGID, (void (*)(void))core_obj_add_sigid }, { OSSL_FUNC_CORE_OBJ_CREATE, (void (*)(void))core_obj_create }, #endif OSSL_DISPATCH_END }; static const OSSL_DISPATCH *core_dispatch = core_dispatch_;
./openssl/crypto/core_namemap.c
/* * 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 */ #include "internal/namemap.h" #include <openssl/lhash.h> #include "crypto/lhash.h" /* ossl_lh_strcasehash */ #include "internal/tsan_assist.h" #include "internal/sizes.h" #include "crypto/context.h" /*- * The namenum entry * ================= */ typedef struct { char *name; int number; } NAMENUM_ENTRY; DEFINE_LHASH_OF_EX(NAMENUM_ENTRY); /*- * The namemap itself * ================== */ struct ossl_namemap_st { /* Flags */ unsigned int stored:1; /* If 1, it's stored in a library context */ CRYPTO_RWLOCK *lock; LHASH_OF(NAMENUM_ENTRY) *namenum; /* Name->number mapping */ TSAN_QUALIFIER int max_number; /* Current max number */ }; /* LHASH callbacks */ static unsigned long namenum_hash(const NAMENUM_ENTRY *n) { return ossl_lh_strcasehash(n->name); } static int namenum_cmp(const NAMENUM_ENTRY *a, const NAMENUM_ENTRY *b) { return OPENSSL_strcasecmp(a->name, b->name); } static void namenum_free(NAMENUM_ENTRY *n) { if (n != NULL) OPENSSL_free(n->name); OPENSSL_free(n); } /* OSSL_LIB_CTX_METHOD functions for a namemap stored in a library context */ void *ossl_stored_namemap_new(OSSL_LIB_CTX *libctx) { OSSL_NAMEMAP *namemap = ossl_namemap_new(); if (namemap != NULL) namemap->stored = 1; return namemap; } void ossl_stored_namemap_free(void *vnamemap) { OSSL_NAMEMAP *namemap = vnamemap; if (namemap != NULL) { /* Pretend it isn't stored, or ossl_namemap_free() will do nothing */ namemap->stored = 0; ossl_namemap_free(namemap); } } /*- * API functions * ============= */ int ossl_namemap_empty(OSSL_NAMEMAP *namemap) { #ifdef TSAN_REQUIRES_LOCKING /* No TSAN support */ int rv; if (namemap == NULL) return 1; if (!CRYPTO_THREAD_read_lock(namemap->lock)) return -1; rv = namemap->max_number == 0; CRYPTO_THREAD_unlock(namemap->lock); return rv; #else /* Have TSAN support */ return namemap == NULL || tsan_load(&namemap->max_number) == 0; #endif } typedef struct doall_names_data_st { int number; const char **names; int found; } DOALL_NAMES_DATA; static void do_name(const NAMENUM_ENTRY *namenum, DOALL_NAMES_DATA *data) { if (namenum->number == data->number) data->names[data->found++] = namenum->name; } IMPLEMENT_LHASH_DOALL_ARG_CONST(NAMENUM_ENTRY, DOALL_NAMES_DATA); /* * Call the callback for all names in the namemap with the given number. * A return value 1 means that the callback was called for all names. A * return value of 0 means that the callback was not called for any names. */ int ossl_namemap_doall_names(const OSSL_NAMEMAP *namemap, int number, void (*fn)(const char *name, void *data), void *data) { DOALL_NAMES_DATA cbdata; size_t num_names; int i; cbdata.number = number; cbdata.found = 0; if (namemap == NULL) return 0; /* * We collect all the names first under a read lock. Subsequently we call * the user function, so that we're not holding the read lock when in user * code. This could lead to deadlocks. */ if (!CRYPTO_THREAD_read_lock(namemap->lock)) return 0; num_names = lh_NAMENUM_ENTRY_num_items(namemap->namenum); if (num_names == 0) { CRYPTO_THREAD_unlock(namemap->lock); return 0; } cbdata.names = OPENSSL_malloc(sizeof(*cbdata.names) * num_names); if (cbdata.names == NULL) { CRYPTO_THREAD_unlock(namemap->lock); return 0; } lh_NAMENUM_ENTRY_doall_DOALL_NAMES_DATA(namemap->namenum, do_name, &cbdata); CRYPTO_THREAD_unlock(namemap->lock); for (i = 0; i < cbdata.found; i++) fn(cbdata.names[i], data); OPENSSL_free(cbdata.names); return 1; } /* This function is not thread safe, the namemap must be locked */ static int namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name) { NAMENUM_ENTRY *namenum_entry, namenum_tmpl; namenum_tmpl.name = (char *)name; namenum_tmpl.number = 0; namenum_entry = lh_NAMENUM_ENTRY_retrieve(namemap->namenum, &namenum_tmpl); return namenum_entry != NULL ? namenum_entry->number : 0; } int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name) { int number; #ifndef FIPS_MODULE if (namemap == NULL) namemap = ossl_namemap_stored(NULL); #endif if (namemap == NULL) return 0; if (!CRYPTO_THREAD_read_lock(namemap->lock)) return 0; number = namemap_name2num(namemap, name); CRYPTO_THREAD_unlock(namemap->lock); return number; } int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap, const char *name, size_t name_len) { char *tmp; int ret; if (name == NULL || (tmp = OPENSSL_strndup(name, name_len)) == NULL) return 0; ret = ossl_namemap_name2num(namemap, tmp); OPENSSL_free(tmp); return ret; } struct num2name_data_st { size_t idx; /* Countdown */ const char *name; /* Result */ }; static void do_num2name(const char *name, void *vdata) { struct num2name_data_st *data = vdata; if (data->idx > 0) data->idx--; else if (data->name == NULL) data->name = name; } const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number, size_t idx) { struct num2name_data_st data; data.idx = idx; data.name = NULL; if (!ossl_namemap_doall_names(namemap, number, do_num2name, &data)) return NULL; return data.name; } /* This function is not thread safe, the namemap must be locked */ static int namemap_add_name(OSSL_NAMEMAP *namemap, int number, const char *name) { NAMENUM_ENTRY *namenum = NULL; int tmp_number; /* If it already exists, we don't add it */ if ((tmp_number = namemap_name2num(namemap, name)) != 0) return tmp_number; if ((namenum = OPENSSL_zalloc(sizeof(*namenum))) == NULL) return 0; if ((namenum->name = OPENSSL_strdup(name)) == NULL) goto err; /* The tsan_counter use here is safe since we're under lock */ namenum->number = number != 0 ? number : 1 + tsan_counter(&namemap->max_number); (void)lh_NAMENUM_ENTRY_insert(namemap->namenum, namenum); if (lh_NAMENUM_ENTRY_error(namemap->namenum)) goto err; return namenum->number; err: namenum_free(namenum); return 0; } int ossl_namemap_add_name(OSSL_NAMEMAP *namemap, int number, const char *name) { int tmp_number; #ifndef FIPS_MODULE if (namemap == NULL) namemap = ossl_namemap_stored(NULL); #endif if (name == NULL || *name == 0 || namemap == NULL) return 0; if (!CRYPTO_THREAD_write_lock(namemap->lock)) return 0; tmp_number = namemap_add_name(namemap, number, name); CRYPTO_THREAD_unlock(namemap->lock); return tmp_number; } int ossl_namemap_add_names(OSSL_NAMEMAP *namemap, int number, const char *names, const char separator) { char *tmp, *p, *q, *endp; /* Check that we have a namemap */ if (!ossl_assert(namemap != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((tmp = OPENSSL_strdup(names)) == NULL) return 0; if (!CRYPTO_THREAD_write_lock(namemap->lock)) { OPENSSL_free(tmp); return 0; } /* * Check that no name is an empty string, and that all names have at * most one numeric identity together. */ for (p = tmp; *p != '\0'; p = q) { int this_number; size_t l; if ((q = strchr(p, separator)) == NULL) { l = strlen(p); /* offset to \0 */ q = p + l; } else { l = q - p; /* offset to the next separator */ *q++ = '\0'; } if (*p == '\0') { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_BAD_ALGORITHM_NAME); number = 0; goto end; } this_number = namemap_name2num(namemap, p); if (number == 0) { number = this_number; } else if (this_number != 0 && this_number != number) { ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_CONFLICTING_NAMES, "\"%s\" has an existing different identity %d (from \"%s\")", p, this_number, names); number = 0; goto end; } } endp = p; /* Now that we have checked, register all names */ for (p = tmp; p < endp; p = q) { int this_number; q = p + strlen(p) + 1; this_number = namemap_add_name(namemap, number, p); if (number == 0) { number = this_number; } else if (this_number != number) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR, "Got number %d when expecting %d", this_number, number); number = 0; goto end; } } end: CRYPTO_THREAD_unlock(namemap->lock); OPENSSL_free(tmp); return number; } /*- * Pre-population * ============== */ #ifndef FIPS_MODULE #include <openssl/evp.h> /* Creates an initial namemap with names found in the legacy method db */ static void get_legacy_evp_names(int base_nid, int nid, const char *pem_name, void *arg) { int num = 0; ASN1_OBJECT *obj; if (base_nid != NID_undef) { num = ossl_namemap_add_name(arg, num, OBJ_nid2sn(base_nid)); num = ossl_namemap_add_name(arg, num, OBJ_nid2ln(base_nid)); } if (nid != NID_undef) { num = ossl_namemap_add_name(arg, num, OBJ_nid2sn(nid)); num = ossl_namemap_add_name(arg, num, OBJ_nid2ln(nid)); if ((obj = OBJ_nid2obj(nid)) != NULL) { char txtoid[OSSL_MAX_NAME_SIZE]; if (OBJ_obj2txt(txtoid, sizeof(txtoid), obj, 1) > 0) num = ossl_namemap_add_name(arg, num, txtoid); } } if (pem_name != NULL) num = ossl_namemap_add_name(arg, num, pem_name); } static void get_legacy_cipher_names(const OBJ_NAME *on, void *arg) { const EVP_CIPHER *cipher = (void *)OBJ_NAME_get(on->name, on->type); if (cipher != NULL) get_legacy_evp_names(NID_undef, EVP_CIPHER_get_type(cipher), NULL, arg); } static void get_legacy_md_names(const OBJ_NAME *on, void *arg) { const EVP_MD *md = (void *)OBJ_NAME_get(on->name, on->type); if (md != NULL) get_legacy_evp_names(0, EVP_MD_get_type(md), NULL, arg); } static void get_legacy_pkey_meth_names(const EVP_PKEY_ASN1_METHOD *ameth, void *arg) { int nid = 0, base_nid = 0, flags = 0; const char *pem_name = NULL; EVP_PKEY_asn1_get0_info(&nid, &base_nid, &flags, NULL, &pem_name, ameth); if (nid != NID_undef) { if ((flags & ASN1_PKEY_ALIAS) == 0) { switch (nid) { case EVP_PKEY_DHX: /* We know that the name "DHX" is used too */ get_legacy_evp_names(0, nid, "DHX", arg); /* FALLTHRU */ default: get_legacy_evp_names(0, nid, pem_name, arg); } } else { /* * Treat aliases carefully, some of them are undesirable, or * should not be treated as such for providers. */ switch (nid) { case EVP_PKEY_SM2: /* * SM2 is a separate keytype with providers, not an alias for * EC. */ get_legacy_evp_names(0, nid, pem_name, arg); break; default: /* Use the short name of the base nid as the common reference */ get_legacy_evp_names(base_nid, nid, pem_name, arg); } } } } #endif /*- * Constructors / destructors * ========================== */ OSSL_NAMEMAP *ossl_namemap_stored(OSSL_LIB_CTX *libctx) { #ifndef FIPS_MODULE int nms; #endif OSSL_NAMEMAP *namemap = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_NAMEMAP_INDEX); if (namemap == NULL) return NULL; #ifndef FIPS_MODULE nms = ossl_namemap_empty(namemap); if (nms < 0) { /* * Could not get lock to make the count, so maybe internal objects * weren't added. This seems safest. */ return NULL; } if (nms == 1) { int i, end; /* Before pilfering, we make sure the legacy database is populated */ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS, NULL); OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH, get_legacy_cipher_names, namemap); OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, get_legacy_md_names, namemap); /* We also pilfer data from the legacy EVP_PKEY_ASN1_METHODs */ for (i = 0, end = EVP_PKEY_asn1_get_count(); i < end; i++) get_legacy_pkey_meth_names(EVP_PKEY_asn1_get0(i), namemap); } #endif return namemap; } OSSL_NAMEMAP *ossl_namemap_new(void) { OSSL_NAMEMAP *namemap; if ((namemap = OPENSSL_zalloc(sizeof(*namemap))) != NULL && (namemap->lock = CRYPTO_THREAD_lock_new()) != NULL && (namemap->namenum = lh_NAMENUM_ENTRY_new(namenum_hash, namenum_cmp)) != NULL) return namemap; ossl_namemap_free(namemap); return NULL; } void ossl_namemap_free(OSSL_NAMEMAP *namemap) { if (namemap == NULL || namemap->stored) return; lh_NAMENUM_ENTRY_doall(namemap->namenum, namenum_free); lh_NAMENUM_ENTRY_free(namemap->namenum); CRYPTO_THREAD_lock_free(namemap->lock); OPENSSL_free(namemap); }
./openssl/crypto/provider_child.c
/* * 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 */ #include <assert.h> #include <openssl/crypto.h> #include <openssl/core_dispatch.h> #include <openssl/core_names.h> #include <openssl/provider.h> #include <openssl/evp.h> #include "internal/provider.h" #include "internal/cryptlib.h" #include "crypto/evp.h" #include "crypto/context.h" DEFINE_STACK_OF(OSSL_PROVIDER) struct child_prov_globals { const OSSL_CORE_HANDLE *handle; const OSSL_CORE_HANDLE *curr_prov; CRYPTO_RWLOCK *lock; OSSL_FUNC_core_get_libctx_fn *c_get_libctx; OSSL_FUNC_provider_register_child_cb_fn *c_provider_register_child_cb; OSSL_FUNC_provider_deregister_child_cb_fn *c_provider_deregister_child_cb; OSSL_FUNC_provider_name_fn *c_prov_name; OSSL_FUNC_provider_get0_provider_ctx_fn *c_prov_get0_provider_ctx; OSSL_FUNC_provider_get0_dispatch_fn *c_prov_get0_dispatch; OSSL_FUNC_provider_up_ref_fn *c_prov_up_ref; OSSL_FUNC_provider_free_fn *c_prov_free; }; void *ossl_child_prov_ctx_new(OSSL_LIB_CTX *libctx) { return OPENSSL_zalloc(sizeof(struct child_prov_globals)); } void ossl_child_prov_ctx_free(void *vgbl) { struct child_prov_globals *gbl = vgbl; CRYPTO_THREAD_lock_free(gbl->lock); OPENSSL_free(gbl); } static OSSL_provider_init_fn ossl_child_provider_init; static int ossl_child_provider_init(const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in, const OSSL_DISPATCH **out, void **provctx) { OSSL_FUNC_core_get_libctx_fn *c_get_libctx = NULL; OSSL_LIB_CTX *ctx; struct child_prov_globals *gbl; for (; in->function_id != 0; in++) { switch (in->function_id) { case OSSL_FUNC_CORE_GET_LIBCTX: c_get_libctx = OSSL_FUNC_core_get_libctx(in); break; default: /* Just ignore anything we don't understand */ break; } } if (c_get_libctx == NULL) return 0; /* * We need an OSSL_LIB_CTX but c_get_libctx returns OPENSSL_CORE_CTX. We are * a built-in provider and so we can get away with this cast. Normal * providers can't do this. */ ctx = (OSSL_LIB_CTX *)c_get_libctx(handle); gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX); if (gbl == NULL) return 0; *provctx = gbl->c_prov_get0_provider_ctx(gbl->curr_prov); *out = gbl->c_prov_get0_dispatch(gbl->curr_prov); return 1; } static int provider_create_child_cb(const OSSL_CORE_HANDLE *prov, void *cbdata) { OSSL_LIB_CTX *ctx = cbdata; struct child_prov_globals *gbl; const char *provname; OSSL_PROVIDER *cprov; int ret = 0; gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX); if (gbl == NULL) return 0; if (!CRYPTO_THREAD_write_lock(gbl->lock)) return 0; provname = gbl->c_prov_name(prov); /* * We're operating under a lock so we can store the "current" provider in * the global data. */ gbl->curr_prov = prov; if ((cprov = ossl_provider_find(ctx, provname, 1)) != NULL) { /* * We free the newly created ref. We rely on the provider sticking around * in the provider store. */ ossl_provider_free(cprov); /* * The provider already exists. It could be a previously created child, * or it could have been explicitly loaded. If explicitly loaded we * ignore it - i.e. we don't start treating it like a child. */ if (!ossl_provider_activate(cprov, 0, 1)) goto err; } else { /* * Create it - passing 1 as final param so we don't try and recursively * init children */ if ((cprov = ossl_provider_new(ctx, provname, ossl_child_provider_init, NULL, 1)) == NULL) goto err; if (!ossl_provider_activate(cprov, 0, 0)) { ossl_provider_free(cprov); goto err; } if (!ossl_provider_set_child(cprov, prov) || !ossl_provider_add_to_store(cprov, NULL, 0)) { ossl_provider_deactivate(cprov, 0); ossl_provider_free(cprov); goto err; } } ret = 1; err: CRYPTO_THREAD_unlock(gbl->lock); return ret; } static int provider_remove_child_cb(const OSSL_CORE_HANDLE *prov, void *cbdata) { OSSL_LIB_CTX *ctx = cbdata; struct child_prov_globals *gbl; const char *provname; OSSL_PROVIDER *cprov; gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX); if (gbl == NULL) return 0; provname = gbl->c_prov_name(prov); cprov = ossl_provider_find(ctx, provname, 1); if (cprov == NULL) return 0; /* * ossl_provider_find ups the ref count, so we free it again here. We can * rely on the provider store reference count. */ ossl_provider_free(cprov); if (ossl_provider_is_child(cprov) && !ossl_provider_deactivate(cprov, 1)) return 0; return 1; } static int provider_global_props_cb(const char *props, void *cbdata) { OSSL_LIB_CTX *ctx = cbdata; return evp_set_default_properties_int(ctx, props, 0, 1); } int ossl_provider_init_as_child(OSSL_LIB_CTX *ctx, const OSSL_CORE_HANDLE *handle, const OSSL_DISPATCH *in) { struct child_prov_globals *gbl; if (ctx == NULL) return 0; gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX); if (gbl == NULL) return 0; gbl->handle = handle; for (; in->function_id != 0; in++) { switch (in->function_id) { case OSSL_FUNC_CORE_GET_LIBCTX: gbl->c_get_libctx = OSSL_FUNC_core_get_libctx(in); break; case OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB: gbl->c_provider_register_child_cb = OSSL_FUNC_provider_register_child_cb(in); break; case OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB: gbl->c_provider_deregister_child_cb = OSSL_FUNC_provider_deregister_child_cb(in); break; case OSSL_FUNC_PROVIDER_NAME: gbl->c_prov_name = OSSL_FUNC_provider_name(in); break; case OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX: gbl->c_prov_get0_provider_ctx = OSSL_FUNC_provider_get0_provider_ctx(in); break; case OSSL_FUNC_PROVIDER_GET0_DISPATCH: gbl->c_prov_get0_dispatch = OSSL_FUNC_provider_get0_dispatch(in); break; case OSSL_FUNC_PROVIDER_UP_REF: gbl->c_prov_up_ref = OSSL_FUNC_provider_up_ref(in); break; case OSSL_FUNC_PROVIDER_FREE: gbl->c_prov_free = OSSL_FUNC_provider_free(in); break; default: /* Just ignore anything we don't understand */ break; } } if (gbl->c_get_libctx == NULL || gbl->c_provider_register_child_cb == NULL || gbl->c_prov_name == NULL || gbl->c_prov_get0_provider_ctx == NULL || gbl->c_prov_get0_dispatch == NULL || gbl->c_prov_up_ref == NULL || gbl->c_prov_free == NULL) return 0; gbl->lock = CRYPTO_THREAD_lock_new(); if (gbl->lock == NULL) return 0; if (!gbl->c_provider_register_child_cb(gbl->handle, provider_create_child_cb, provider_remove_child_cb, provider_global_props_cb, ctx)) return 0; return 1; } void ossl_provider_deinit_child(OSSL_LIB_CTX *ctx) { struct child_prov_globals *gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX); if (gbl == NULL) return; gbl->c_provider_deregister_child_cb(gbl->handle); } /* * ossl_provider_up_ref_parent() and ossl_provider_free_parent() do * nothing in "self-referencing" child providers, i.e. when the parent * of the child provider is the same as the provider where this child * provider was created. * This allows the teardown function in the parent provider to be called * at the correct moment. * For child providers in other providers, the reference count is done to * ensure that cross referencing is recorded. These should be cleared up * through that providers teardown, as part of freeing its child libctx. */ int ossl_provider_up_ref_parent(OSSL_PROVIDER *prov, int activate) { struct child_prov_globals *gbl; const OSSL_CORE_HANDLE *parent_handle; gbl = ossl_lib_ctx_get_data(ossl_provider_libctx(prov), OSSL_LIB_CTX_CHILD_PROVIDER_INDEX); if (gbl == NULL) return 0; parent_handle = ossl_provider_get_parent(prov); if (parent_handle == gbl->handle) return 1; return gbl->c_prov_up_ref(parent_handle, activate); } int ossl_provider_free_parent(OSSL_PROVIDER *prov, int deactivate) { struct child_prov_globals *gbl; const OSSL_CORE_HANDLE *parent_handle; gbl = ossl_lib_ctx_get_data(ossl_provider_libctx(prov), OSSL_LIB_CTX_CHILD_PROVIDER_INDEX); if (gbl == NULL) return 0; parent_handle = ossl_provider_get_parent(prov); if (parent_handle == gbl->handle) return 1; return gbl->c_prov_free(ossl_provider_get_parent(prov), deactivate); }
./openssl/crypto/cryptlib.c
/* * Copyright 1998-2023 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, 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 */ #include "internal/e_os.h" #include "crypto/cryptlib.h" #include <openssl/safestack.h> #if defined(_WIN32) && !defined(OPENSSL_SYS_UEFI) # include <tchar.h> # include <signal.h> # ifdef __WATCOMC__ # if defined(_UNICODE) || defined(__UNICODE__) # define _vsntprintf _vsnwprintf # else # define _vsntprintf _vsnprintf # endif # endif # ifdef _MSC_VER # define alloca _alloca # endif # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333 # ifdef OPENSSL_SYS_WIN_CORE int OPENSSL_isservice(void) { /* OneCore API cannot interact with GUI */ return 1; } # else int OPENSSL_isservice(void) { HWINSTA h; DWORD len; WCHAR *name; static union { void *p; FARPROC f; } _OPENSSL_isservice = { NULL }; if (_OPENSSL_isservice.p == NULL) { HANDLE mod = GetModuleHandle(NULL); FARPROC f = NULL; if (mod != NULL) f = GetProcAddress(mod, "_OPENSSL_isservice"); if (f == NULL) _OPENSSL_isservice.p = (void *)-1; else _OPENSSL_isservice.f = f; } if (_OPENSSL_isservice.p != (void *)-1) return (*_OPENSSL_isservice.f) (); h = GetProcessWindowStation(); if (h == NULL) return -1; if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) return -1; if (len > 512) return -1; /* paranoia */ len++, len &= ~1; /* paranoia */ name = (WCHAR *)alloca(len + sizeof(WCHAR)); if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len)) return -1; len++, len &= ~1; /* paranoia */ name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */ # if 1 /* * This doesn't cover "interactive" services [working with real * WinSta0's] nor programs started non-interactively by Task Scheduler * [those are working with SAWinSta]. */ if (wcsstr(name, L"Service-0x")) return 1; # else /* This covers all non-interactive programs such as services. */ if (!wcsstr(name, L"WinSta0")) return 1; # endif else return 0; } # endif # else int OPENSSL_isservice(void) { return 0; } # endif void OPENSSL_showfatal(const char *fmta, ...) { va_list ap; TCHAR buf[256]; const TCHAR *fmt; /* * First check if it's a console application, in which case the * error message would be printed to standard error. * Windows CE does not have a concept of a console application, * so we need to guard the check. */ # ifdef STD_ERROR_HANDLE HANDLE h; if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL && GetFileType(h) != FILE_TYPE_UNKNOWN) { /* must be console application */ int len; DWORD out; va_start(ap, fmta); len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap); WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL); va_end(ap); return; } # endif if (sizeof(TCHAR) == sizeof(char)) fmt = (const TCHAR *)fmta; else do { int keepgoing; size_t len_0 = strlen(fmta) + 1, i; WCHAR *fmtw; fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR)); if (fmtw == NULL) { fmt = (const TCHAR *)L"no stack?"; break; } if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0)) for (i = 0; i < len_0; i++) fmtw[i] = (WCHAR)fmta[i]; for (i = 0; i < len_0; i++) { if (fmtw[i] == L'%') do { keepgoing = 0; switch (fmtw[i + 1]) { case L'0': case L'1': case L'2': case L'3': case L'4': case L'5': case L'6': case L'7': case L'8': case L'9': case L'.': case L'*': case L'-': i++; keepgoing = 1; break; case L's': fmtw[i + 1] = L'S'; break; case L'S': fmtw[i + 1] = L's'; break; case L'c': fmtw[i + 1] = L'C'; break; case L'C': fmtw[i + 1] = L'c'; break; } } while (keepgoing); } fmt = (const TCHAR *)fmtw; } while (0); va_start(ap, fmta); _vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap); buf[OSSL_NELEM(buf) - 1] = _T('\0'); va_end(ap); # if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333 # ifdef OPENSSL_SYS_WIN_CORE /* ONECORE is always NONGUI and NT >= 0x0601 */ # if !defined(NDEBUG) /* * We are in a situation where we tried to report a critical * error and this failed for some reason. As a last resort, * in debug builds, send output to the debugger or any other * tool like DebugView which can monitor the output. */ OutputDebugString(buf); # endif # else /* this -------------v--- guards NT-specific calls */ if (check_winnt() && OPENSSL_isservice() > 0) { HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL")); if (hEventLog != NULL) { const TCHAR *pmsg = buf; if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL, 1, 0, &pmsg, NULL)) { # if !defined(NDEBUG) /* * We are in a situation where we tried to report a critical * error and this failed for some reason. As a last resort, * in debug builds, send output to the debugger or any other * tool like DebugView which can monitor the output. */ OutputDebugString(pmsg); # endif } (void)DeregisterEventSource(hEventLog); } } else { MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR); } # endif # else MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR); # endif } #else void OPENSSL_showfatal(const char *fmta, ...) { #ifndef OPENSSL_NO_STDIO va_list ap; va_start(ap, fmta); vfprintf(stderr, fmta, ap); va_end(ap); #endif } int OPENSSL_isservice(void) { return 0; } #endif void OPENSSL_die(const char *message, const char *file, int line) { OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n", file, line, message); #if !defined(_WIN32) || defined(OPENSSL_SYS_UEFI) abort(); #else /* * Win32 abort() customarily shows a dialog, but we just did that... */ # if !defined(_WIN32_WCE) raise(SIGABRT); # endif _exit(3); #endif } #if defined(__TANDEM) && defined(OPENSSL_VPROC) /* * Define a VPROC function for HP NonStop build crypto library. * This is used by platform version identification tools. * Do not inline this procedure or make it static. */ # define OPENSSL_VPROC_STRING_(x) x##_CRYPTO # define OPENSSL_VPROC_STRING(x) OPENSSL_VPROC_STRING_(x) # define OPENSSL_VPROC_FUNC OPENSSL_VPROC_STRING(OPENSSL_VPROC) void OPENSSL_VPROC_FUNC(void) {} #endif /* __TANDEM */
./openssl/crypto/o_fopen.c
/* * 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 */ # if defined(__linux) || defined(__sun) || defined(__hpux) /* * Following definition aliases fopen to fopen64 on above mentioned * platforms. This makes it possible to open and sequentially access files * larger than 2GB from 32-bit application. It does not allow one to traverse * them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit * platform permits that, not with fseek/ftell. Not to mention that breaking * 2GB limit for seeking would require surgery to *our* API. But sequential * access suffices for practical cases when you can run into large files, * such as fingerprinting, so we can let API alone. For reference, the list * of 32-bit platforms which allow for sequential access of large files * without extra "magic" comprise *BSD, Darwin, IRIX... */ # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif # endif #include "internal/e_os.h" #include "internal/cryptlib.h" #if !defined(OPENSSL_NO_STDIO) # include <stdio.h> # ifdef __DJGPP__ # include <unistd.h> # endif FILE *openssl_fopen(const char *filename, const char *mode) { FILE *file = NULL; # if defined(_WIN32) && defined(CP_UTF8) int sz, len_0 = (int)strlen(filename) + 1; DWORD flags; /* * Basically there are three cases to cover: a) filename is * pure ASCII string; b) actual UTF-8 encoded string and * c) locale-ized string, i.e. one containing 8-bit * characters that are meaningful in current system locale. * If filename is pure ASCII or real UTF-8 encoded string, * MultiByteToWideChar succeeds and _wfopen works. If * filename is locale-ized string, chances are that * MultiByteToWideChar fails reporting * ERROR_NO_UNICODE_TRANSLATION, in which case we fall * back to fopen... */ if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS), filename, len_0, NULL, 0)) > 0 || (GetLastError() == ERROR_INVALID_FLAGS && (sz = MultiByteToWideChar(CP_UTF8, (flags = 0), filename, len_0, NULL, 0)) > 0) ) { WCHAR wmode[8]; WCHAR *wfilename = _alloca(sz * sizeof(WCHAR)); if (MultiByteToWideChar(CP_UTF8, flags, filename, len_0, wfilename, sz) && MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1, wmode, OSSL_NELEM(wmode)) && (file = _wfopen(wfilename, wmode)) == NULL && (errno == ENOENT || errno == EBADF) ) { /* * UTF-8 decode succeeded, but no file, filename * could still have been locale-ized... */ file = fopen(filename, mode); } } else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) { file = fopen(filename, mode); } # elif defined(__DJGPP__) { char *newname = NULL; if (pathconf(filename, _PC_NAME_MAX) <= 12) { /* 8.3 file system? */ char *iterator; char lastchar; if ((newname = OPENSSL_malloc(strlen(filename) + 1)) == NULL) return NULL; for (iterator = newname, lastchar = '\0'; *filename; filename++, iterator++) { if (lastchar == '/' && filename[0] == '.' && filename[1] != '.' && filename[1] != '/') { /* Leading dots are not permitted in plain DOS. */ *iterator = '_'; } else { *iterator = *filename; } lastchar = *filename; } *iterator = '\0'; filename = newname; } file = fopen(filename, mode); OPENSSL_free(newname); } # else file = fopen(filename, mode); # endif return file; } #else void *openssl_fopen(const char *filename, const char *mode) { return NULL; } #endif
./openssl/crypto/armcap.c
/* * Copyright 2011-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 <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/crypto.h> #ifdef __APPLE__ #include <sys/sysctl.h> #else #include <setjmp.h> #include <signal.h> #endif #include "internal/cryptlib.h" #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #endif #include "arm_arch.h" unsigned int OPENSSL_armcap_P = 0; unsigned int OPENSSL_arm_midr = 0; unsigned int OPENSSL_armv8_rsa_neonized = 0; #ifdef _WIN32 void OPENSSL_cpuid_setup(void) { OPENSSL_armcap_P |= ARMV7_NEON; OPENSSL_armv8_rsa_neonized = 1; if (IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE)) { // These are all covered by one call in Windows OPENSSL_armcap_P |= ARMV8_AES; OPENSSL_armcap_P |= ARMV8_PMULL; OPENSSL_armcap_P |= ARMV8_SHA1; OPENSSL_armcap_P |= ARMV8_SHA256; } } uint32_t OPENSSL_rdtsc(void) { return 0; } #elif __ARM_MAX_ARCH__ < 7 void OPENSSL_cpuid_setup(void) { } uint32_t OPENSSL_rdtsc(void) { return 0; } #else /* !_WIN32 && __ARM_MAX_ARCH__ >= 7 */ /* 3 ways of handling things here: __APPLE__, getauxval() or SIGILL detect */ /* First determine if getauxval() is available (OSSL_IMPLEMENT_GETAUXVAL) */ # if defined(__GNUC__) && __GNUC__>=2 void OPENSSL_cpuid_setup(void) __attribute__ ((constructor)); # endif # if defined(__GLIBC__) && defined(__GLIBC_PREREQ) # if __GLIBC_PREREQ(2, 16) # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif # elif defined(__ANDROID_API__) /* see https://developer.android.google.cn/ndk/guides/cpu-features */ # if __ANDROID_API__ >= 18 # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif # endif # if defined(__FreeBSD__) # include <sys/param.h> # if __FreeBSD_version >= 1200000 # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL static unsigned long getauxval(unsigned long key) { unsigned long val = 0ul; if (elf_aux_info((int)key, &val, sizeof(val)) != 0) return 0ul; return val; } # endif # endif /* * Android: according to https://developer.android.com/ndk/guides/cpu-features, * getauxval is supported starting with API level 18 */ # if defined(__ANDROID__) && defined(__ANDROID_API__) && __ANDROID_API__ >= 18 # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif /* * ARM puts the feature bits for Crypto Extensions in AT_HWCAP2, whereas * AArch64 used AT_HWCAP. */ # ifndef AT_HWCAP # define AT_HWCAP 16 # endif # ifndef AT_HWCAP2 # define AT_HWCAP2 26 # endif # if defined(__arm__) || defined (__arm) # define OSSL_HWCAP AT_HWCAP # define OSSL_HWCAP_NEON (1 << 12) # define OSSL_HWCAP_CE AT_HWCAP2 # define OSSL_HWCAP_CE_AES (1 << 0) # define OSSL_HWCAP_CE_PMULL (1 << 1) # define OSSL_HWCAP_CE_SHA1 (1 << 2) # define OSSL_HWCAP_CE_SHA256 (1 << 3) # elif defined(__aarch64__) # define OSSL_HWCAP AT_HWCAP # define OSSL_HWCAP_NEON (1 << 1) # define OSSL_HWCAP_CE AT_HWCAP # define OSSL_HWCAP_CE_AES (1 << 3) # define OSSL_HWCAP_CE_PMULL (1 << 4) # define OSSL_HWCAP_CE_SHA1 (1 << 5) # define OSSL_HWCAP_CE_SHA256 (1 << 6) # define OSSL_HWCAP_CPUID (1 << 11) # define OSSL_HWCAP_SHA3 (1 << 17) # define OSSL_HWCAP_CE_SM3 (1 << 18) # define OSSL_HWCAP_CE_SM4 (1 << 19) # define OSSL_HWCAP_CE_SHA512 (1 << 21) # define OSSL_HWCAP_SVE (1 << 22) /* AT_HWCAP2 */ # define OSSL_HWCAP2 26 # define OSSL_HWCAP2_SVE2 (1 << 1) # define OSSL_HWCAP2_RNG (1 << 16) # endif uint32_t _armv7_tick(void); uint32_t OPENSSL_rdtsc(void) { if (OPENSSL_armcap_P & ARMV7_TICK) return _armv7_tick(); else return 0; } # ifdef __aarch64__ size_t OPENSSL_rndr_asm(unsigned char *buf, size_t len); size_t OPENSSL_rndrrs_asm(unsigned char *buf, size_t len); size_t OPENSSL_rndr_bytes(unsigned char *buf, size_t len); size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len); static size_t OPENSSL_rndr_wrapper(size_t (*func)(unsigned char *, size_t), unsigned char *buf, size_t len) { size_t buffer_size = 0; int i; for (i = 0; i < 8; i++) { buffer_size = func(buf, len); if (buffer_size == len) break; usleep(5000); /* 5000 microseconds (5 milliseconds) */ } return buffer_size; } size_t OPENSSL_rndr_bytes(unsigned char *buf, size_t len) { return OPENSSL_rndr_wrapper(OPENSSL_rndr_asm, buf, len); } size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len) { return OPENSSL_rndr_wrapper(OPENSSL_rndrrs_asm, buf, len); } # endif # if !defined(__APPLE__) && !defined(OSSL_IMPLEMENT_GETAUXVAL) static sigset_t all_masked; static sigjmp_buf ill_jmp; static void ill_handler(int sig) { siglongjmp(ill_jmp, sig); } /* * Following subroutines could have been inlined, but not all * ARM compilers support inline assembler, and we'd then have to * worry about the compiler optimising out the detection code... */ void _armv7_neon_probe(void); void _armv8_aes_probe(void); void _armv8_sha1_probe(void); void _armv8_sha256_probe(void); void _armv8_pmull_probe(void); # ifdef __aarch64__ void _armv8_sm3_probe(void); void _armv8_sm4_probe(void); void _armv8_sha512_probe(void); void _armv8_eor3_probe(void); void _armv8_sve_probe(void); void _armv8_sve2_probe(void); void _armv8_rng_probe(void); # endif # endif /* !__APPLE__ && !OSSL_IMPLEMENT_GETAUXVAL */ /* We only call _armv8_cpuid_probe() if (OPENSSL_armcap_P & ARMV8_CPUID) != 0 */ unsigned int _armv8_cpuid_probe(void); # if defined(__APPLE__) /* * Checks the specified integer sysctl, returning `value` if it's 1, otherwise returning 0. */ static unsigned int sysctl_query(const char *name, unsigned int value) { unsigned int sys_value = 0; size_t len = sizeof(sys_value); return (sysctlbyname(name, &sys_value, &len, NULL, 0) == 0 && sys_value == 1) ? value : 0; } # elif !defined(OSSL_IMPLEMENT_GETAUXVAL) /* * Calls a provided probe function, which may SIGILL. If it doesn't, return `value`, otherwise return 0. */ static unsigned int arm_probe_for(void (*probe)(void), volatile unsigned int value) { if (sigsetjmp(ill_jmp, 1) == 0) { probe(); return value; } else { /* The probe function gave us SIGILL */ return 0; } } # endif void OPENSSL_cpuid_setup(void) { const char *e; # if !defined(__APPLE__) && !defined(OSSL_IMPLEMENT_GETAUXVAL) struct sigaction ill_oact, ill_act; sigset_t oset; # endif static int trigger = 0; if (trigger) return; trigger = 1; OPENSSL_armcap_P = 0; if ((e = getenv("OPENSSL_armcap"))) { OPENSSL_armcap_P = (unsigned int)strtoul(e, NULL, 0); return; } # if defined(__APPLE__) # if !defined(__aarch64__) /* * Capability probing by catching SIGILL appears to be problematic * on iOS. But since Apple universe is "monocultural", it's actually * possible to simply set pre-defined processor capability mask. */ if (1) { OPENSSL_armcap_P = ARMV7_NEON; return; } # else { /* * From * https://github.com/llvm/llvm-project/blob/412237dcd07e5a2afbb1767858262a5f037149a3/llvm/lib/Target/AArch64/AArch64.td#L719 * all of these have been available on 64-bit Apple Silicon from the * beginning (the A7). */ OPENSSL_armcap_P |= ARMV7_NEON | ARMV8_PMULL | ARMV8_AES | ARMV8_SHA1 | ARMV8_SHA256; /* More recent extensions are indicated by sysctls */ OPENSSL_armcap_P |= sysctl_query("hw.optional.armv8_2_sha512", ARMV8_SHA512); OPENSSL_armcap_P |= sysctl_query("hw.optional.armv8_2_sha3", ARMV8_SHA3); if (OPENSSL_armcap_P & ARMV8_SHA3) { char uarch[64]; size_t len = sizeof(uarch); if ((sysctlbyname("machdep.cpu.brand_string", uarch, &len, NULL, 0) == 0) && ((strncmp(uarch, "Apple M1", 8) == 0) || (strncmp(uarch, "Apple M2", 8) == 0) || (strncmp(uarch, "Apple M3", 8) == 0))) { OPENSSL_armcap_P |= ARMV8_UNROLL8_EOR3; OPENSSL_armcap_P |= ARMV8_HAVE_SHA3_AND_WORTH_USING; } } } # endif /* __aarch64__ */ # elif defined(OSSL_IMPLEMENT_GETAUXVAL) if (getauxval(OSSL_HWCAP) & OSSL_HWCAP_NEON) { unsigned long hwcap = getauxval(OSSL_HWCAP_CE); OPENSSL_armcap_P |= ARMV7_NEON; if (hwcap & OSSL_HWCAP_CE_AES) OPENSSL_armcap_P |= ARMV8_AES; if (hwcap & OSSL_HWCAP_CE_PMULL) OPENSSL_armcap_P |= ARMV8_PMULL; if (hwcap & OSSL_HWCAP_CE_SHA1) OPENSSL_armcap_P |= ARMV8_SHA1; if (hwcap & OSSL_HWCAP_CE_SHA256) OPENSSL_armcap_P |= ARMV8_SHA256; # ifdef __aarch64__ if (hwcap & OSSL_HWCAP_CE_SM4) OPENSSL_armcap_P |= ARMV8_SM4; if (hwcap & OSSL_HWCAP_CE_SHA512) OPENSSL_armcap_P |= ARMV8_SHA512; if (hwcap & OSSL_HWCAP_CPUID) OPENSSL_armcap_P |= ARMV8_CPUID; if (hwcap & OSSL_HWCAP_CE_SM3) OPENSSL_armcap_P |= ARMV8_SM3; if (hwcap & OSSL_HWCAP_SHA3) OPENSSL_armcap_P |= ARMV8_SHA3; # endif } # ifdef __aarch64__ if (getauxval(OSSL_HWCAP) & OSSL_HWCAP_SVE) OPENSSL_armcap_P |= ARMV8_SVE; if (getauxval(OSSL_HWCAP2) & OSSL_HWCAP2_SVE2) OPENSSL_armcap_P |= ARMV8_SVE2; if (getauxval(OSSL_HWCAP2) & OSSL_HWCAP2_RNG) OPENSSL_armcap_P |= ARMV8_RNG; # endif # else /* !__APPLE__ && !OSSL_IMPLEMENT_GETAUXVAL */ /* If all else fails, do brute force SIGILL-based feature detection */ sigfillset(&all_masked); sigdelset(&all_masked, SIGILL); sigdelset(&all_masked, SIGTRAP); sigdelset(&all_masked, SIGFPE); sigdelset(&all_masked, SIGBUS); sigdelset(&all_masked, SIGSEGV); memset(&ill_act, 0, sizeof(ill_act)); ill_act.sa_handler = ill_handler; ill_act.sa_mask = all_masked; sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset); sigaction(SIGILL, &ill_act, &ill_oact); OPENSSL_armcap_P |= arm_probe_for(_armv7_neon_probe, ARMV7_NEON); if (OPENSSL_armcap_P & ARMV7_NEON) { OPENSSL_armcap_P |= arm_probe_for(_armv8_pmull_probe, ARMV8_PMULL | ARMV8_AES); if (!(OPENSSL_armcap_P & ARMV8_AES)) { OPENSSL_armcap_P |= arm_probe_for(_armv8_aes_probe, ARMV8_AES); } OPENSSL_armcap_P |= arm_probe_for(_armv8_sha1_probe, ARMV8_SHA1); OPENSSL_armcap_P |= arm_probe_for(_armv8_sha256_probe, ARMV8_SHA256); # if defined(__aarch64__) OPENSSL_armcap_P |= arm_probe_for(_armv8_sm3_probe, ARMV8_SM3); OPENSSL_armcap_P |= arm_probe_for(_armv8_sm4_probe, ARMV8_SM4); OPENSSL_armcap_P |= arm_probe_for(_armv8_sha512_probe, ARMV8_SHA512); OPENSSL_armcap_P |= arm_probe_for(_armv8_eor3_probe, ARMV8_SHA3); # endif } # ifdef __aarch64__ OPENSSL_armcap_P |= arm_probe_for(_armv8_sve_probe, ARMV8_SVE); OPENSSL_armcap_P |= arm_probe_for(_armv8_sve2_probe, ARMV8_SVE2); OPENSSL_armcap_P |= arm_probe_for(_armv8_rng_probe, ARMV8_RNG); # endif /* * Probing for ARMV7_TICK is known to produce unreliable results, * so we only use the feature when the user explicitly enables it * with OPENSSL_armcap. */ sigaction(SIGILL, &ill_oact, NULL); sigprocmask(SIG_SETMASK, &oset, NULL); # endif /* __APPLE__, OSSL_IMPLEMENT_GETAUXVAL */ # ifdef __aarch64__ if (OPENSSL_armcap_P & ARMV8_CPUID) OPENSSL_arm_midr = _armv8_cpuid_probe(); if ((MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_CORTEX_A72) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_N1)) && (OPENSSL_armcap_P & ARMV7_NEON)) { OPENSSL_armv8_rsa_neonized = 1; } if ((MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_V1) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_N2) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_V2)) && (OPENSSL_armcap_P & ARMV8_SHA3)) OPENSSL_armcap_P |= ARMV8_UNROLL8_EOR3; if ((MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_V1) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_V2)) && (OPENSSL_armcap_P & ARMV8_SHA3)) OPENSSL_armcap_P |= ARMV8_UNROLL12_EOR3; if ((MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M1_FIRESTORM) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M1_ICESTORM) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M1_FIRESTORM_PRO) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M1_ICESTORM_PRO) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M1_FIRESTORM_MAX) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M1_ICESTORM_MAX) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_AVALANCHE) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_BLIZZARD) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_AVALANCHE_PRO) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_BLIZZARD_PRO) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_AVALANCHE_MAX) || MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_APPLE, APPLE_CPU_PART_M2_BLIZZARD_MAX)) && (OPENSSL_armcap_P & ARMV8_SHA3)) OPENSSL_armcap_P |= ARMV8_HAVE_SHA3_AND_WORTH_USING; # endif } #endif /* _WIN32, __ARM_MAX_ARCH__ >= 7 */
./openssl/crypto/o_time.c
/* * Copyright 2001-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/e_os2.h> #include <string.h> #include <openssl/crypto.h> struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result) { struct tm *ts = NULL; #if defined(OPENSSL_THREADS) && defined(OPENSSL_SYS_VMS) { /* * On VMS, gmtime_r() takes a 32-bit pointer as second argument. * Since we can't know that |result| is in a space that can easily * translate to a 32-bit pointer, we must store temporarily on stack * and copy the result. The stack is always reachable with 32-bit * pointers. */ #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE # pragma pointer_size save # pragma pointer_size 32 #endif struct tm data, *ts2 = &data; #if defined OPENSSL_SYS_VMS && __INITIAL_POINTER_SIZE # pragma pointer_size restore #endif if (gmtime_r(timer, ts2) == NULL) return NULL; memcpy(result, ts2, sizeof(struct tm)); ts = result; } #elif defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_MACOSX) if (gmtime_r(timer, result) == NULL) return NULL; ts = result; #elif defined (OPENSSL_SYS_WINDOWS) && defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(_WIN32_WCE) if (gmtime_s(result, timer)) return NULL; ts = result; #else ts = gmtime(timer); if (ts == NULL) return NULL; memcpy(result, ts, sizeof(struct tm)); ts = result; #endif return ts; } /* * Take a tm structure and add an offset to it. This avoids any OS issues * with restricted date types and overflows which cause the year 2038 * problem. */ #define SECS_PER_DAY (24 * 60 * 60) static long date_to_julian(int y, int m, int d); static void julian_to_date(long jd, int *y, int *m, int *d); static int julian_adj(const struct tm *tm, int off_day, long offset_sec, long *pday, int *psec); int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec) { int time_sec, time_year, time_month, time_day; long time_jd; /* Convert time and offset into Julian day and seconds */ if (!julian_adj(tm, off_day, offset_sec, &time_jd, &time_sec)) return 0; /* Convert Julian day back to date */ julian_to_date(time_jd, &time_year, &time_month, &time_day); if (time_year < 1900 || time_year > 9999) return 0; /* Update tm structure */ tm->tm_year = time_year - 1900; tm->tm_mon = time_month - 1; tm->tm_mday = time_day; tm->tm_hour = time_sec / 3600; tm->tm_min = (time_sec / 60) % 60; tm->tm_sec = time_sec % 60; return 1; } int OPENSSL_gmtime_diff(int *pday, int *psec, const struct tm *from, const struct tm *to) { int from_sec, to_sec, diff_sec; long from_jd, to_jd, diff_day; if (!julian_adj(from, 0, 0, &from_jd, &from_sec)) return 0; if (!julian_adj(to, 0, 0, &to_jd, &to_sec)) return 0; diff_day = to_jd - from_jd; diff_sec = to_sec - from_sec; /* Adjust differences so both positive or both negative */ if (diff_day > 0 && diff_sec < 0) { diff_day--; diff_sec += SECS_PER_DAY; } if (diff_day < 0 && diff_sec > 0) { diff_day++; diff_sec -= SECS_PER_DAY; } if (pday) *pday = (int)diff_day; if (psec) *psec = diff_sec; return 1; } /* Convert tm structure and offset into julian day and seconds */ static int julian_adj(const struct tm *tm, int off_day, long offset_sec, long *pday, int *psec) { int offset_hms; long offset_day, time_jd; int time_year, time_month, time_day; /* split offset into days and day seconds */ offset_day = offset_sec / SECS_PER_DAY; /* Avoid sign issues with % operator */ offset_hms = offset_sec - (offset_day * SECS_PER_DAY); offset_day += off_day; /* Add current time seconds to offset */ offset_hms += tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec; /* Adjust day seconds if overflow */ if (offset_hms >= SECS_PER_DAY) { offset_day++; offset_hms -= SECS_PER_DAY; } else if (offset_hms < 0) { offset_day--; offset_hms += SECS_PER_DAY; } /* * Convert date of time structure into a Julian day number. */ time_year = tm->tm_year + 1900; time_month = tm->tm_mon + 1; time_day = tm->tm_mday; time_jd = date_to_julian(time_year, time_month, time_day); /* Work out Julian day of new date */ time_jd += offset_day; if (time_jd < 0) return 0; *pday = time_jd; *psec = offset_hms; return 1; } /* * Convert date to and from julian day Uses Fliegel & Van Flandern algorithm */ static long date_to_julian(int y, int m, int d) { return (1461 * (y + 4800 + (m - 14) / 12)) / 4 + (367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 - (3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075; } static void julian_to_date(long jd, int *y, int *m, int *d) { long L = jd + 68569; long n = (4 * L) / 146097; long i, j; L = L - (146097 * n + 3) / 4; i = (4000 * (L + 1)) / 1461001; L = L - (1461 * i) / 4 + 31; j = (80 * L) / 2447; *d = L - (2447 * j) / 80; L = j / 11; *m = j + 2 - (12 * L); *y = 100 * (n - 49) + i + L; }
./openssl/crypto/loongarch_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_LOONGARCH_ARCH_H # define OSSL_CRYPTO_LOONGARCH_ARCH_H # ifndef __ASSEMBLER__ extern unsigned int OPENSSL_loongarch_hwcap_P; # endif # define LOONGARCH_HWCAP_LSX (1 << 4) # define LOONGARCH_HWCAP_LASX (1 << 5) #endif
./openssl/crypto/sleep.c
/* * 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/crypto.h> #include "internal/e_os.h" /* system-specific variants defining OSSL_sleep() */ #if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) #include <unistd.h> void OSSL_sleep(uint64_t millis) { # ifdef OPENSSL_SYS_VXWORKS struct timespec ts; ts.tv_sec = (long int) (millis / 1000); ts.tv_nsec = (long int) (millis % 1000) * 1000000ul; nanosleep(&ts, NULL); # elif defined(__TANDEM) # if !defined(_REENTRANT) # include <cextdecs.h(PROCESS_DELAY_)> /* HPNS does not support usleep for non threaded apps */ PROCESS_DELAY_(millis * 1000); # elif defined(_SPT_MODEL_) # include <spthread.h> # include <spt_extensions.h> usleep(millis * 1000); # else usleep(millis * 1000); # endif # else unsigned int s = (unsigned int)(millis / 1000); unsigned int us = (unsigned int)((millis % 1000) * 1000); sleep(s); usleep(us); # endif } #elif defined(_WIN32) && !defined(OPENSSL_SYS_UEFI) # include <windows.h> void OSSL_sleep(uint64_t millis) { /* * Windows' Sleep() takes a DWORD argument, which is smaller than * a uint64_t, so we need to limit it to 49 days, which should be enough. */ DWORD limited_millis = (DWORD)-1; if (millis < limited_millis) limited_millis = (DWORD)millis; Sleep(limited_millis); } #else /* Fallback to a busy wait */ # include "internal/time.h" static void ossl_sleep_secs(uint64_t secs) { /* * sleep() takes an unsigned int argument, which is smaller than * a uint64_t, so it needs to be limited to 136 years which * should be enough even for Sleeping Beauty. */ unsigned int limited_secs = UINT_MAX; if (secs < limited_secs) limited_secs = (unsigned int)secs; sleep(limited_secs); } static void ossl_sleep_millis(uint64_t millis) { const OSSL_TIME finish = ossl_time_add(ossl_time_now(), ossl_ms2time(millis)); while (ossl_time_compare(ossl_time_now(), finish) < 0) /* busy wait */ ; } void OSSL_sleep(uint64_t millis) { ossl_sleep_secs(millis / 1000); ossl_sleep_millis(millis % 1000); } #endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
./openssl/crypto/uid.c
/* * Copyright 2001-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/crypto.h> #include <openssl/opensslconf.h> #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI) || defined(__wasi__) int OPENSSL_issetugid(void) { return 0; } #elif defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ > 2) || defined(__DragonFly__) || (defined(__GLIBC__) && defined(__FreeBSD_kernel__)) # include <unistd.h> int OPENSSL_issetugid(void) { return issetugid(); } #else # include <unistd.h> # include <sys/types.h> # if defined(__GLIBC__) && defined(__GLIBC_PREREQ) # if __GLIBC_PREREQ(2, 16) # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif # elif defined(__ANDROID_API__) /* see https://developer.android.google.cn/ndk/guides/cpu-features */ # if __ANDROID_API__ >= 18 # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif # endif int OPENSSL_issetugid(void) { # ifdef OSSL_IMPLEMENT_GETAUXVAL return getauxval(AT_SECURE) != 0; # else return getuid() != geteuid() || getgid() != getegid(); # endif } #endif
./openssl/crypto/getenv.c
/* * 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 */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include <stdlib.h> #include "internal/cryptlib.h" #include "internal/e_os.h" char *ossl_safe_getenv(const char *name) { #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE) if (GetEnvironmentVariableW(L"OPENSSL_WIN32_UTF8", NULL, 0) != 0) { char *val = NULL; int vallen = 0; WCHAR *namew = NULL; WCHAR *valw = NULL; DWORD envlen = 0; DWORD dwFlags = MB_ERR_INVALID_CHARS; int rsize, fsize; UINT curacp; curacp = GetACP(); /* * For the code pages listed below, dwFlags must be set to 0. * Otherwise, the function fails with ERROR_INVALID_FLAGS. */ if (curacp == 50220 || curacp == 50221 || curacp == 50222 || curacp == 50225 || curacp == 50227 || curacp == 50229 || (57002 <= curacp && curacp <=57011) || curacp == 65000 || curacp == 42) dwFlags = 0; /* query for buffer len */ rsize = MultiByteToWideChar(curacp, dwFlags, name, -1, NULL, 0); /* if name is valid string and can be converted to wide string */ if (rsize > 0) namew = _malloca(rsize * sizeof(WCHAR)); if (NULL != namew) { /* convert name to wide string */ fsize = MultiByteToWideChar(curacp, dwFlags, name, -1, namew, rsize); /* if conversion is ok, then determine value string size in wchars */ if (fsize > 0) envlen = GetEnvironmentVariableW(namew, NULL, 0); } if (envlen > 0) valw = _malloca(envlen * sizeof(WCHAR)); if (NULL != valw) { /* if can get env value as wide string */ if (GetEnvironmentVariableW(namew, valw, envlen) < envlen) { /* determine value string size in utf-8 */ vallen = WideCharToMultiByte(CP_UTF8, 0, valw, -1, NULL, 0, NULL, NULL); } } if (vallen > 0) val = OPENSSL_malloc(vallen); if (NULL != val) { /* convert value string from wide to utf-8 */ if (WideCharToMultiByte(CP_UTF8, 0, valw, -1, val, vallen, NULL, NULL) == 0) { OPENSSL_free(val); val = NULL; } } if (NULL != namew) _freea(namew); if (NULL != valw) _freea(valw); return val; } #endif #if defined(__GLIBC__) && defined(__GLIBC_PREREQ) # if __GLIBC_PREREQ(2, 17) # define SECURE_GETENV return secure_getenv(name); # endif #endif #ifndef SECURE_GETENV if (OPENSSL_issetugid()) return NULL; return getenv(name); #endif }
./openssl/crypto/core_fetch.c
/* * 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 <stddef.h> #include <openssl/core.h> #include "internal/cryptlib.h" #include "internal/core.h" #include "internal/property.h" #include "internal/provider.h" struct construct_data_st { OSSL_LIB_CTX *libctx; OSSL_METHOD_STORE *store; int operation_id; int force_store; OSSL_METHOD_CONSTRUCT_METHOD *mcm; void *mcm_data; }; static int is_temporary_method_store(int no_store, void *cbdata) { struct construct_data_st *data = cbdata; return no_store && !data->force_store; } static int ossl_method_construct_reserve_store(int no_store, void *cbdata) { struct construct_data_st *data = cbdata; if (is_temporary_method_store(no_store, data) && data->store == NULL) { /* * If we have been told not to store the method "permanently", we * ask for a temporary store, and store the method there. * The owner of |data->mcm| is completely responsible for managing * that temporary store. */ if ((data->store = data->mcm->get_tmp_store(data->mcm_data)) == NULL) return 0; } return data->mcm->lock_store(data->store, data->mcm_data); } static int ossl_method_construct_unreserve_store(void *cbdata) { struct construct_data_st *data = cbdata; return data->mcm->unlock_store(data->store, data->mcm_data); } static int ossl_method_construct_precondition(OSSL_PROVIDER *provider, int operation_id, int no_store, void *cbdata, int *result) { if (!ossl_assert(result != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* Assume that no bits are set */ *result = 0; /* No flag bits for temporary stores */ if (!is_temporary_method_store(no_store, cbdata) && !ossl_provider_test_operation_bit(provider, operation_id, result)) return 0; /* * The result we get tells if methods have already been constructed. * However, we want to tell whether construction should happen (true) * or not (false), which is the opposite of what we got. */ *result = !*result; return 1; } static int ossl_method_construct_postcondition(OSSL_PROVIDER *provider, int operation_id, int no_store, void *cbdata, int *result) { if (!ossl_assert(result != NULL)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } *result = 1; /* No flag bits for temporary stores */ return is_temporary_method_store(no_store, cbdata) || ossl_provider_set_operation_bit(provider, operation_id); } static void ossl_method_construct_this(OSSL_PROVIDER *provider, const OSSL_ALGORITHM *algo, int no_store, void *cbdata) { struct construct_data_st *data = cbdata; void *method = NULL; if ((method = data->mcm->construct(algo, provider, data->mcm_data)) == NULL) return; /* * Note regarding putting the method in stores: * * we don't need to care if it actually got in or not here. * If it didn't get in, it will simply not be available when * ossl_method_construct() tries to get it from the store. * * It is *expected* that the put function increments the refcnt * of the passed method. */ data->mcm->put(data->store, method, provider, algo->algorithm_names, algo->property_definition, data->mcm_data); /* refcnt-- because we're dropping the reference */ data->mcm->destruct(method, data->mcm_data); } void *ossl_method_construct(OSSL_LIB_CTX *libctx, int operation_id, OSSL_PROVIDER **provider_rw, int force_store, OSSL_METHOD_CONSTRUCT_METHOD *mcm, void *mcm_data) { void *method = NULL; OSSL_PROVIDER *provider = provider_rw != NULL ? *provider_rw : NULL; struct construct_data_st cbdata; /* * We might be tempted to try to look into the method store without * constructing to see if we can find our method there already. * Unfortunately that does not work well if the query contains * optional properties as newly loaded providers can match them better. * We trust that ossl_method_construct_precondition() and * ossl_method_construct_postcondition() make sure that the * ossl_algorithm_do_all() does very little when methods from * a provider have already been constructed. */ cbdata.store = NULL; cbdata.force_store = force_store; cbdata.mcm = mcm; cbdata.mcm_data = mcm_data; ossl_algorithm_do_all(libctx, operation_id, provider, ossl_method_construct_precondition, ossl_method_construct_reserve_store, ossl_method_construct_this, ossl_method_construct_unreserve_store, ossl_method_construct_postcondition, &cbdata); /* If there is a temporary store, try there first */ if (cbdata.store != NULL) method = mcm->get(cbdata.store, (const OSSL_PROVIDER **)provider_rw, mcm_data); /* If no method was found yet, try the global store */ if (method == NULL) method = mcm->get(NULL, (const OSSL_PROVIDER **)provider_rw, mcm_data); return method; }
./openssl/crypto/cpt_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/cryptoerr.h> #include "crypto/cryptoerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CRYPTO_str_reasons[] = { {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_BAD_ALGORITHM_NAME), "bad algorithm name"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_CONFLICTING_NAMES), "conflicting names"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_HEX_STRING_TOO_SHORT), "hex string too short"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ILLEGAL_HEX_DIGIT), "illegal hex digit"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INSUFFICIENT_DATA_SPACE), "insufficient data space"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INSUFFICIENT_PARAM_SIZE), "insufficient param size"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INSUFFICIENT_SECURE_DATA_SPACE), "insufficient secure data space"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INTEGER_OVERFLOW), "integer overflow"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INVALID_NEGATIVE_VALUE), "invalid negative value"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INVALID_NULL_ARGUMENT), "invalid null argument"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INVALID_OSSL_PARAM_TYPE), "invalid ossl param type"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_NO_PARAMS_TO_MERGE), "no params to merge"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_NO_SPACE_FOR_TERMINATING_NULL), "no space for terminating null"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ODD_NUMBER_OF_DIGITS), "odd number of digits"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_CANNOT_BE_REPRESENTED_EXACTLY), "param cannot be represented exactly"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_NOT_INTEGER_TYPE), "param not integer type"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_OF_INCOMPATIBLE_TYPE), "param of incompatible type"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_UNSIGNED_INTEGER_NEGATIVE_VALUE_UNSUPPORTED), "param unsigned integer negative value unsupported"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_UNSUPPORTED_FLOATING_POINT_FORMAT), "param unsupported floating point format"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_VALUE_TOO_LARGE_FOR_DESTINATION), "param value too large for destination"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PROVIDER_ALREADY_EXISTS), "provider already exists"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PROVIDER_SECTION_ERROR), "provider section error"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_RANDOM_SECTION_ERROR), "random section error"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_SECURE_MALLOC_FAILURE), "secure malloc failure"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_STRING_TOO_LONG), "string too long"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_TOO_MANY_BYTES), "too many bytes"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_TOO_MANY_RECORDS), "too many records"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_TOO_SMALL_BUFFER), "too small buffer"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION), "unknown name in random section"}, {ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ZERO_LENGTH_NUMBER), "zero length number"}, {0, NULL} }; #endif int ossl_err_load_CRYPTO_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CRYPTO_str_reasons[0].error) == NULL) ERR_load_strings_const(CRYPTO_str_reasons); #endif return 1; }
./openssl/crypto/params_from_text.c
/* * 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 */ #include "internal/common.h" /* for HAS_PREFIX */ #include <openssl/ebcdic.h> #include <openssl/err.h> #include <openssl/params.h> /* * When processing text to params, we're trying to be smart with numbers. * Instead of handling each specific separate integer type, we use a bignum * and ensure that it isn't larger than the expected size, and we then make * sure it is the expected size... if there is one given. * (if the size can be arbitrary, then we give whatever we have) */ static int prepare_from_text(const OSSL_PARAM *paramdefs, const char *key, const char *value, size_t value_n, /* Output parameters */ const OSSL_PARAM **paramdef, int *ishex, size_t *buf_n, BIGNUM **tmpbn, int *found) { const OSSL_PARAM *p; size_t buf_bits; int r; /* * ishex is used to translate legacy style string controls in hex format * to octet string parameters. */ *ishex = CHECK_AND_SKIP_PREFIX(key, "hex"); p = *paramdef = OSSL_PARAM_locate_const(paramdefs, key); if (found != NULL) *found = p != NULL; if (p == NULL) return 0; switch (p->data_type) { case OSSL_PARAM_INTEGER: case OSSL_PARAM_UNSIGNED_INTEGER: if (*ishex) r = BN_hex2bn(tmpbn, value); else r = BN_asc2bn(tmpbn, value); if (r == 0 || *tmpbn == NULL) return 0; if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER && BN_is_negative(*tmpbn)) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_INVALID_NEGATIVE_VALUE); return 0; } /* * 2's complement negate, part 1 * * BN_bn2nativepad puts the absolute value of the number in the * buffer, i.e. if it's negative, we need to deal with it. We do * it by subtracting 1 here and inverting the bytes in * construct_from_text() below. * To subtract 1 from an absolute value of a negative number we * actually have to add 1: -3 - 1 = -4, |-3| = 3 + 1 = 4. */ if (p->data_type == OSSL_PARAM_INTEGER && BN_is_negative(*tmpbn) && !BN_add_word(*tmpbn, 1)) { return 0; } buf_bits = (size_t)BN_num_bits(*tmpbn); /* * Compensate for cases where the most significant bit in * the resulting OSSL_PARAM buffer will be set after the * BN_bn2nativepad() call, as the implied sign may not be * correct after the second part of the 2's complement * negation has been performed. * We fix these cases by extending the buffer by one byte * (8 bits), which will give some padding. The second part * of the 2's complement negation will do the rest. */ if (p->data_type == OSSL_PARAM_INTEGER && buf_bits % 8 == 0) buf_bits += 8; *buf_n = (buf_bits + 7) / 8; /* * A zero data size means "arbitrary size", so only do the * range checking if a size is specified. */ if (p->data_size > 0) { if (buf_bits > p->data_size * 8) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER); /* Since this is a different error, we don't break */ return 0; } /* Change actual size to become the desired size. */ *buf_n = p->data_size; } break; case OSSL_PARAM_UTF8_STRING: if (*ishex) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } *buf_n = strlen(value) + 1; break; case OSSL_PARAM_OCTET_STRING: if (*ishex) { *buf_n = strlen(value) >> 1; } else { *buf_n = value_n; } break; } return 1; } static int construct_from_text(OSSL_PARAM *to, const OSSL_PARAM *paramdef, const char *value, size_t value_n, int ishex, void *buf, size_t buf_n, BIGNUM *tmpbn) { if (buf == NULL) return 0; if (buf_n > 0) { switch (paramdef->data_type) { case OSSL_PARAM_INTEGER: case OSSL_PARAM_UNSIGNED_INTEGER: /* { if ((new_value = OPENSSL_malloc(new_value_n)) == NULL) { BN_free(a); break; } */ BN_bn2nativepad(tmpbn, buf, buf_n); /* * 2's complement negation, part two. * * Because we did the first part on the BIGNUM itself, we can just * invert all the bytes here and be done with it. */ if (paramdef->data_type == OSSL_PARAM_INTEGER && BN_is_negative(tmpbn)) { unsigned char *cp; size_t i = buf_n; for (cp = buf; i-- > 0; cp++) *cp ^= 0xFF; } break; case OSSL_PARAM_UTF8_STRING: #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, value, buf_n); #else strncpy(buf, value, buf_n); #endif /* Don't count the terminating NUL byte as data */ buf_n--; break; case OSSL_PARAM_OCTET_STRING: if (ishex) { size_t l = 0; if (!OPENSSL_hexstr2buf_ex(buf, buf_n, &l, value, ':')) return 0; } else { memcpy(buf, value, buf_n); } break; } } *to = *paramdef; to->data = buf; to->data_size = buf_n; to->return_size = OSSL_PARAM_UNMODIFIED; return 1; } int OSSL_PARAM_allocate_from_text(OSSL_PARAM *to, const OSSL_PARAM *paramdefs, const char *key, const char *value, size_t value_n, int *found) { const OSSL_PARAM *paramdef = NULL; int ishex = 0; void *buf = NULL; size_t buf_n = 0; BIGNUM *tmpbn = NULL; int ok = 0; if (to == NULL || paramdefs == NULL) return 0; if (!prepare_from_text(paramdefs, key, value, value_n, &paramdef, &ishex, &buf_n, &tmpbn, found)) goto err; if ((buf = OPENSSL_zalloc(buf_n > 0 ? buf_n : 1)) == NULL) goto err; ok = construct_from_text(to, paramdef, value, value_n, ishex, buf, buf_n, tmpbn); BN_free(tmpbn); if (!ok) OPENSSL_free(buf); return ok; err: BN_free(tmpbn); return 0; }
./openssl/crypto/core_algorithm.c
/* * 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 <openssl/core.h> #include <openssl/core_dispatch.h> #include "internal/core.h" #include "internal/property.h" #include "internal/provider.h" struct algorithm_data_st { OSSL_LIB_CTX *libctx; int operation_id; /* May be zero for finding them all */ 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 *, const OSSL_ALGORITHM *, 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; }; /* * Process one OSSL_ALGORITHM array, for the operation |cur_operation|, * by constructing methods for all its implementations and adding those * to the appropriate method store. * Which method store is appropriate is given by |no_store| ("permanent" * if 0, temporary if 1) and other data in |data->data|. * * Returns: * -1 to quit adding algorithm implementations immediately * 0 if not successful, but adding should continue * 1 if successful so far, and adding should continue */ static int algorithm_do_map(OSSL_PROVIDER *provider, const OSSL_ALGORITHM *map, int cur_operation, int no_store, void *cbdata) { struct algorithm_data_st *data = cbdata; int ret = 0; if (!data->reserve_store(no_store, data->data)) /* Error, bail out! */ return -1; /* Do we fulfill pre-conditions? */ if (data->pre == NULL) { /* If there is no pre-condition function, assume "yes" */ ret = 1; } else if (!data->pre(provider, cur_operation, no_store, data->data, &ret)) { /* Error, bail out! */ ret = -1; goto end; } /* * If pre-condition not fulfilled don't add this set of implementations, * but do continue with the next. This simply means that another thread * got to it first. */ if (ret == 0) { ret = 1; goto end; } if (map != NULL) { const OSSL_ALGORITHM *thismap; for (thismap = map; thismap->algorithm_names != NULL; thismap++) data->fn(provider, thismap, no_store, data->data); } /* Do we fulfill post-conditions? */ if (data->post == NULL) { /* If there is no post-condition function, assume "yes" */ ret = 1; } else if (!data->post(provider, cur_operation, no_store, data->data, &ret)) { /* Error, bail out! */ ret = -1; } end: data->unreserve_store(data->data); return ret; } /* * Given a provider, process one operation given by |data->operation_id|, or * if that's zero, process all known operations. * For each such operation, query the associated OSSL_ALGORITHM array from * the provider, then process that array with |algorithm_do_map()|. */ static int algorithm_do_this(OSSL_PROVIDER *provider, void *cbdata) { struct algorithm_data_st *data = cbdata; int first_operation = 1; int last_operation = OSSL_OP__HIGHEST; int cur_operation; int ok = 1; if (data->operation_id != 0) first_operation = last_operation = data->operation_id; for (cur_operation = first_operation; cur_operation <= last_operation; cur_operation++) { int no_store = 0; /* Assume caching is ok */ const OSSL_ALGORITHM *map = NULL; int ret = 0; map = ossl_provider_query_operation(provider, cur_operation, &no_store); ret = algorithm_do_map(provider, map, cur_operation, no_store, data); ossl_provider_unquery_operation(provider, cur_operation, map); if (ret < 0) /* Hard error, bail out immediately! */ return 0; /* If post-condition not fulfilled, set general failure */ if (!ret) ok = 0; } return ok; } 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) { struct algorithm_data_st cbdata = { 0, }; cbdata.libctx = libctx; cbdata.operation_id = operation_id; cbdata.pre = pre; cbdata.reserve_store = reserve_store; cbdata.fn = fn; cbdata.unreserve_store = unreserve_store; cbdata.post = post; cbdata.data = data; if (provider == NULL) { ossl_provider_doall_activated(libctx, algorithm_do_this, &cbdata); } else { OSSL_LIB_CTX *libctx2 = ossl_provider_libctx(provider); /* * If a provider is given, its library context MUST match the library * context we're passed. If this turns out not to be true, there is * a programming error in the functions up the call stack. */ if (!ossl_assert(ossl_lib_ctx_get_concrete(libctx) == ossl_lib_ctx_get_concrete(libctx2))) return; cbdata.libctx = libctx2; algorithm_do_this(provider, &cbdata); } } char *ossl_algorithm_get1_first_name(const OSSL_ALGORITHM *algo) { const char *first_name_end = NULL; size_t first_name_len = 0; char *ret; if (algo->algorithm_names == NULL) return NULL; first_name_end = strchr(algo->algorithm_names, ':'); if (first_name_end == NULL) first_name_len = strlen(algo->algorithm_names); else first_name_len = first_name_end - algo->algorithm_names; ret = OPENSSL_strndup(algo->algorithm_names, first_name_len); return ret; }
./openssl/crypto/ctype.c
/* * Copyright 2017-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 <string.h> #include <stdio.h> #include "crypto/ctype.h" #include <openssl/ebcdic.h> /* * Define the character classes for each character in the seven bit ASCII * character set. This is independent of the host's character set, characters * are converted to ASCII before being used as an index in to this table. * Characters outside of the seven bit ASCII range are detected before indexing. */ static const unsigned short ctype_char_map[128] = { /* 00 nul */ CTYPE_MASK_cntrl, /* 01 soh */ CTYPE_MASK_cntrl, /* 02 stx */ CTYPE_MASK_cntrl, /* 03 etx */ CTYPE_MASK_cntrl, /* 04 eot */ CTYPE_MASK_cntrl, /* 05 enq */ CTYPE_MASK_cntrl, /* 06 ack */ CTYPE_MASK_cntrl, /* 07 \a */ CTYPE_MASK_cntrl, /* 08 \b */ CTYPE_MASK_cntrl, /* 09 \t */ CTYPE_MASK_blank | CTYPE_MASK_cntrl | CTYPE_MASK_space, /* 0A \n */ CTYPE_MASK_cntrl | CTYPE_MASK_space, /* 0B \v */ CTYPE_MASK_cntrl | CTYPE_MASK_space, /* 0C \f */ CTYPE_MASK_cntrl | CTYPE_MASK_space, /* 0D \r */ CTYPE_MASK_cntrl | CTYPE_MASK_space, /* 0E so */ CTYPE_MASK_cntrl, /* 0F si */ CTYPE_MASK_cntrl, /* 10 dle */ CTYPE_MASK_cntrl, /* 11 dc1 */ CTYPE_MASK_cntrl, /* 12 dc2 */ CTYPE_MASK_cntrl, /* 13 dc3 */ CTYPE_MASK_cntrl, /* 14 dc4 */ CTYPE_MASK_cntrl, /* 15 nak */ CTYPE_MASK_cntrl, /* 16 syn */ CTYPE_MASK_cntrl, /* 17 etb */ CTYPE_MASK_cntrl, /* 18 can */ CTYPE_MASK_cntrl, /* 19 em */ CTYPE_MASK_cntrl, /* 1A sub */ CTYPE_MASK_cntrl, /* 1B esc */ CTYPE_MASK_cntrl, /* 1C fs */ CTYPE_MASK_cntrl, /* 1D gs */ CTYPE_MASK_cntrl, /* 1E rs */ CTYPE_MASK_cntrl, /* 1F us */ CTYPE_MASK_cntrl, /* 20 */ CTYPE_MASK_blank | CTYPE_MASK_print | CTYPE_MASK_space | CTYPE_MASK_asn1print, /* 21 ! */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 22 " */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 23 # */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 24 $ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 25 % */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 26 & */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 27 ' */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 28 ( */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 29 ) */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 2A * */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 2B + */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 2C , */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 2D - */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 2E . */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 2F / */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 30 0 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 31 1 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 32 2 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 33 3 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 34 4 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 35 5 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 36 6 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 37 7 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 38 8 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 39 9 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 3A : */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 3B ; */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 3C < */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 3D = */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 3E > */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 3F ? */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct | CTYPE_MASK_asn1print, /* 40 @ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 41 A */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 42 B */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 43 C */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 44 D */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 45 E */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 46 F */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 47 G */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 48 H */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 49 I */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 4A J */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 4B K */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 4C L */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 4D M */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 4E N */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 4F O */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 50 P */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 51 Q */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 52 R */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 53 S */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 54 T */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 55 U */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 56 V */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 57 W */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 58 X */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 59 Y */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 5A Z */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 5B [ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 5C \ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 5D ] */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 5E ^ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 5F _ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 60 ` */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 61 a */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 62 b */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 63 c */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 64 d */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 65 e */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 66 f */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 67 g */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 68 h */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 69 i */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 6A j */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 6B k */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 6C l */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 6D m */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 6E n */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 6F o */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 70 p */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 71 q */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 72 r */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 73 s */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 74 t */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 75 u */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 76 v */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 77 w */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 78 x */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 79 y */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 7A z */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print | CTYPE_MASK_base64 | CTYPE_MASK_asn1print, /* 7B { */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 7C | */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 7D } */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 7E ~ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct, /* 7F del */ CTYPE_MASK_cntrl }; #ifdef CHARSET_EBCDIC int ossl_toascii(int c) { if (c < -128 || c > 256 || c == EOF) return c; /* * Adjust negatively signed characters. * This is not required for ASCII because any character that sign extends * is not seven bit and all of the checks are on the seven bit characters. * I.e. any check must fail on sign extension. */ if (c < 0) c += 256; return os_toascii[c]; } int ossl_fromascii(int c) { if (c < -128 || c > 256 || c == EOF) return c; if (c < 0) c += 256; return os_toebcdic[c]; } #endif int ossl_ctype_check(int c, unsigned int mask) { const int max = sizeof(ctype_char_map) / sizeof(*ctype_char_map); const int a = ossl_toascii(c); return a >= 0 && a < max && (ctype_char_map[a] & mask) != 0; } /* * Implement some of the simpler functions directly to avoid the overhead of * accessing memory via ctype_char_map[]. */ #define ASCII_IS_DIGIT(c) (c >= 0x30 && c <= 0x39) #define ASCII_IS_UPPER(c) (c >= 0x41 && c <= 0x5A) #define ASCII_IS_LOWER(c) (c >= 0x61 && c <= 0x7A) int ossl_isdigit(int c) { int a = ossl_toascii(c); return ASCII_IS_DIGIT(a); } int ossl_isupper(int c) { int a = ossl_toascii(c); return ASCII_IS_UPPER(a); } int ossl_islower(int c) { int a = ossl_toascii(c); return ASCII_IS_LOWER(a); } #if defined(CHARSET_EBCDIC) && !defined(CHARSET_EBCDIC_TEST) static const int case_change = 0x40; #else static const int case_change = 0x20; #endif int ossl_tolower(int c) { int a = ossl_toascii(c); return ASCII_IS_UPPER(a) ? c ^ case_change : c; } int ossl_toupper(int c) { int a = ossl_toascii(c); return ASCII_IS_LOWER(a) ? c ^ case_change : c; } int ossl_ascii_isdigit(int c) { return ASCII_IS_DIGIT(c); }
./openssl/crypto/LPdir_nyi.c
/* * Copyright 2004-2016 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 LPDIR_H # include "LPdir.h" #endif struct LP_dir_context_st { void *dummy; }; const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory) { errno = EINVAL; return 0; } int LP_find_file_end(LP_DIR_CTX **ctx) { errno = EINVAL; return 0; }
./openssl/crypto/param_build.c
/* * Copyright 2019-2023 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 */ #include <string.h> #include <openssl/err.h> #include <openssl/cryptoerr.h> #include <openssl/params.h> #include <openssl/types.h> #include <openssl/safestack.h> #include "internal/param_build_set.h" /* * Special internal param type to indicate the end of an allocate OSSL_PARAM * array. */ typedef struct { const char *key; int type; int secure; size_t size; size_t alloc_blocks; const BIGNUM *bn; const void *string; union { /* * These fields are never directly addressed, but their sizes are * important so that all native types can be copied here without overrun. */ ossl_intmax_t i; ossl_uintmax_t u; double d; } num; } OSSL_PARAM_BLD_DEF; DEFINE_STACK_OF(OSSL_PARAM_BLD_DEF) struct ossl_param_bld_st { size_t total_blocks; size_t secure_blocks; STACK_OF(OSSL_PARAM_BLD_DEF) *params; }; static OSSL_PARAM_BLD_DEF *param_push(OSSL_PARAM_BLD *bld, const char *key, size_t size, size_t alloc, int type, int secure) { OSSL_PARAM_BLD_DEF *pd = OPENSSL_zalloc(sizeof(*pd)); if (pd == NULL) return NULL; pd->key = key; pd->type = type; pd->size = size; pd->alloc_blocks = ossl_param_bytes_to_blocks(alloc); if ((pd->secure = secure) != 0) bld->secure_blocks += pd->alloc_blocks; else bld->total_blocks += pd->alloc_blocks; if (sk_OSSL_PARAM_BLD_DEF_push(bld->params, pd) <= 0) { OPENSSL_free(pd); pd = NULL; } return pd; } static int param_push_num(OSSL_PARAM_BLD *bld, const char *key, void *num, size_t size, int type) { OSSL_PARAM_BLD_DEF *pd = param_push(bld, key, size, size, type, 0); if (pd == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (size > sizeof(pd->num)) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_BYTES); return 0; } memcpy(&pd->num, num, size); return 1; } OSSL_PARAM_BLD *OSSL_PARAM_BLD_new(void) { OSSL_PARAM_BLD *r = OPENSSL_zalloc(sizeof(OSSL_PARAM_BLD)); if (r != NULL) { r->params = sk_OSSL_PARAM_BLD_DEF_new_null(); if (r->params == NULL) { OPENSSL_free(r); r = NULL; } } return r; } static void free_all_params(OSSL_PARAM_BLD *bld) { int i, n = sk_OSSL_PARAM_BLD_DEF_num(bld->params); for (i = 0; i < n; i++) OPENSSL_free(sk_OSSL_PARAM_BLD_DEF_pop(bld->params)); } void OSSL_PARAM_BLD_free(OSSL_PARAM_BLD *bld) { if (bld == NULL) return; free_all_params(bld); sk_OSSL_PARAM_BLD_DEF_free(bld->params); OPENSSL_free(bld); } int OSSL_PARAM_BLD_push_int(OSSL_PARAM_BLD *bld, const char *key, int num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER); } int OSSL_PARAM_BLD_push_uint(OSSL_PARAM_BLD *bld, const char *key, unsigned int num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_UNSIGNED_INTEGER); } int OSSL_PARAM_BLD_push_long(OSSL_PARAM_BLD *bld, const char *key, long int num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER); } int OSSL_PARAM_BLD_push_ulong(OSSL_PARAM_BLD *bld, const char *key, unsigned long int num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_UNSIGNED_INTEGER); } int OSSL_PARAM_BLD_push_int32(OSSL_PARAM_BLD *bld, const char *key, int32_t num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER); } int OSSL_PARAM_BLD_push_uint32(OSSL_PARAM_BLD *bld, const char *key, uint32_t num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_UNSIGNED_INTEGER); } int OSSL_PARAM_BLD_push_int64(OSSL_PARAM_BLD *bld, const char *key, int64_t num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER); } int OSSL_PARAM_BLD_push_uint64(OSSL_PARAM_BLD *bld, const char *key, uint64_t num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_UNSIGNED_INTEGER); } int OSSL_PARAM_BLD_push_size_t(OSSL_PARAM_BLD *bld, const char *key, size_t num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_UNSIGNED_INTEGER); } int OSSL_PARAM_BLD_push_time_t(OSSL_PARAM_BLD *bld, const char *key, time_t num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER); } int OSSL_PARAM_BLD_push_double(OSSL_PARAM_BLD *bld, const char *key, double num) { return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_REAL); } static int push_BN(OSSL_PARAM_BLD *bld, const char *key, const BIGNUM *bn, size_t sz, int type) { int n, secure = 0; OSSL_PARAM_BLD_DEF *pd; if (!ossl_assert(type == OSSL_PARAM_UNSIGNED_INTEGER || type == OSSL_PARAM_INTEGER)) return 0; if (bn != NULL) { if (type == OSSL_PARAM_UNSIGNED_INTEGER && BN_is_negative(bn)) { ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_UNSUPPORTED, "Negative big numbers are unsupported for OSSL_PARAM_UNSIGNED_INTEGER"); return 0; } n = BN_num_bytes(bn); if (n < 0) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ZERO_LENGTH_NUMBER); return 0; } if (sz < (size_t)n) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER); return 0; } if (BN_get_flags(bn, BN_FLG_SECURE) == BN_FLG_SECURE) secure = 1; /* The BIGNUM is zero, we must transfer at least one byte */ if (sz == 0) sz++; } pd = param_push(bld, key, sz, sz, type, secure); if (pd == NULL) return 0; pd->bn = bn; return 1; } int OSSL_PARAM_BLD_push_BN(OSSL_PARAM_BLD *bld, const char *key, const BIGNUM *bn) { if (bn != NULL && BN_is_negative(bn)) return push_BN(bld, key, bn, BN_num_bytes(bn) + 1, OSSL_PARAM_INTEGER); return push_BN(bld, key, bn, bn == NULL ? 0 : BN_num_bytes(bn), OSSL_PARAM_UNSIGNED_INTEGER); } int OSSL_PARAM_BLD_push_BN_pad(OSSL_PARAM_BLD *bld, const char *key, const BIGNUM *bn, size_t sz) { if (bn != NULL && BN_is_negative(bn)) return push_BN(bld, key, bn, BN_num_bytes(bn), OSSL_PARAM_INTEGER); return push_BN(bld, key, bn, sz, OSSL_PARAM_UNSIGNED_INTEGER); } int OSSL_PARAM_BLD_push_utf8_string(OSSL_PARAM_BLD *bld, const char *key, const char *buf, size_t bsize) { OSSL_PARAM_BLD_DEF *pd; int secure; if (bsize == 0) bsize = strlen(buf); secure = CRYPTO_secure_allocated(buf); pd = param_push(bld, key, bsize, bsize + 1, OSSL_PARAM_UTF8_STRING, secure); if (pd == NULL) return 0; pd->string = buf; return 1; } int OSSL_PARAM_BLD_push_utf8_ptr(OSSL_PARAM_BLD *bld, const char *key, char *buf, size_t bsize) { OSSL_PARAM_BLD_DEF *pd; if (bsize == 0) bsize = strlen(buf); pd = param_push(bld, key, bsize, sizeof(buf), OSSL_PARAM_UTF8_PTR, 0); if (pd == NULL) return 0; pd->string = buf; return 1; } int OSSL_PARAM_BLD_push_octet_string(OSSL_PARAM_BLD *bld, const char *key, const void *buf, size_t bsize) { OSSL_PARAM_BLD_DEF *pd; int secure; secure = CRYPTO_secure_allocated(buf); pd = param_push(bld, key, bsize, bsize, OSSL_PARAM_OCTET_STRING, secure); if (pd == NULL) return 0; pd->string = buf; return 1; } int OSSL_PARAM_BLD_push_octet_ptr(OSSL_PARAM_BLD *bld, const char *key, void *buf, size_t bsize) { OSSL_PARAM_BLD_DEF *pd; pd = param_push(bld, key, bsize, sizeof(buf), OSSL_PARAM_OCTET_PTR, 0); if (pd == NULL) return 0; pd->string = buf; return 1; } static OSSL_PARAM *param_bld_convert(OSSL_PARAM_BLD *bld, OSSL_PARAM *param, OSSL_PARAM_ALIGNED_BLOCK *blk, OSSL_PARAM_ALIGNED_BLOCK *secure) { int i, num = sk_OSSL_PARAM_BLD_DEF_num(bld->params); OSSL_PARAM_BLD_DEF *pd; void *p; for (i = 0; i < num; i++) { pd = sk_OSSL_PARAM_BLD_DEF_value(bld->params, i); param[i].key = pd->key; param[i].data_type = pd->type; param[i].data_size = pd->size; param[i].return_size = OSSL_PARAM_UNMODIFIED; if (pd->secure) { p = secure; secure += pd->alloc_blocks; } else { p = blk; blk += pd->alloc_blocks; } param[i].data = p; if (pd->bn != NULL) { /* BIGNUM */ if (pd->type == OSSL_PARAM_UNSIGNED_INTEGER) BN_bn2nativepad(pd->bn, (unsigned char *)p, pd->size); else BN_signed_bn2native(pd->bn, (unsigned char *)p, pd->size); } else if (pd->type == OSSL_PARAM_OCTET_PTR || pd->type == OSSL_PARAM_UTF8_PTR) { /* PTR */ *(const void **)p = pd->string; } else if (pd->type == OSSL_PARAM_OCTET_STRING || pd->type == OSSL_PARAM_UTF8_STRING) { if (pd->string != NULL) memcpy(p, pd->string, pd->size); else memset(p, 0, pd->size); if (pd->type == OSSL_PARAM_UTF8_STRING) ((char *)p)[pd->size] = '\0'; } else { /* Number, but could also be a NULL BIGNUM */ if (pd->size > sizeof(pd->num)) memset(p, 0, pd->size); else if (pd->size > 0) memcpy(p, &pd->num, pd->size); } } param[i] = OSSL_PARAM_construct_end(); return param + i; } OSSL_PARAM *OSSL_PARAM_BLD_to_param(OSSL_PARAM_BLD *bld) { OSSL_PARAM_ALIGNED_BLOCK *blk, *s = NULL; OSSL_PARAM *params, *last; const int num = sk_OSSL_PARAM_BLD_DEF_num(bld->params); const size_t p_blks = ossl_param_bytes_to_blocks((1 + num) * sizeof(*params)); const size_t total = OSSL_PARAM_ALIGN_SIZE * (p_blks + bld->total_blocks); const size_t ss = OSSL_PARAM_ALIGN_SIZE * bld->secure_blocks; if (ss > 0) { s = OPENSSL_secure_malloc(ss); if (s == NULL) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_SECURE_MALLOC_FAILURE); return NULL; } } params = OPENSSL_malloc(total); if (params == NULL) { OPENSSL_secure_free(s); return NULL; } blk = p_blks + (OSSL_PARAM_ALIGNED_BLOCK *)(params); last = param_bld_convert(bld, params, blk, s); ossl_param_set_secure_block(last, s, ss); /* Reset builder for reuse */ bld->total_blocks = 0; bld->secure_blocks = 0; free_all_params(bld); return params; }
./openssl/crypto/info.c
/* * 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 */ #include <openssl/crypto.h> #include "crypto/rand.h" #include "crypto/dso_conf.h" #include "internal/thread_once.h" #include "internal/cryptlib.h" #include "internal/e_os.h" #include "buildinf.h" #if defined(__arm__) || defined(__arm) || defined(__aarch64__) # include "arm_arch.h" # define CPU_INFO_STR_LEN 128 #elif defined(__s390__) || defined(__s390x__) # include "s390x_arch.h" # define CPU_INFO_STR_LEN 2048 #else # define CPU_INFO_STR_LEN 128 #endif /* extern declaration to avoid warning */ extern char ossl_cpu_info_str[]; static char *seed_sources = NULL; char ossl_cpu_info_str[CPU_INFO_STR_LEN] = ""; #define CPUINFO_PREFIX "CPUINFO: " static CRYPTO_ONCE init_info = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(init_info_strings) { #if defined(OPENSSL_CPUID_OBJ) # if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64) const char *env; BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), CPUINFO_PREFIX "OPENSSL_ia32cap=0x%llx:0x%llx", (unsigned long long)OPENSSL_ia32cap_P[0] | (unsigned long long)OPENSSL_ia32cap_P[1] << 32, (unsigned long long)OPENSSL_ia32cap_P[2] | (unsigned long long)OPENSSL_ia32cap_P[3] << 32); if ((env = getenv("OPENSSL_ia32cap")) != NULL) BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), " env:%s", env); # elif defined(__arm__) || defined(__arm) || defined(__aarch64__) const char *env; BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), CPUINFO_PREFIX "OPENSSL_armcap=0x%x", OPENSSL_armcap_P); if ((env = getenv("OPENSSL_armcap")) != NULL) BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), " env:%s", env); # elif defined(__s390__) || defined(__s390x__) const char *env; BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str), CPUINFO_PREFIX "OPENSSL_s390xcap=" "stfle:0x%llx:0x%llx:0x%llx:0x%llx:" "kimd:0x%llx:0x%llx:" "klmd:0x%llx:0x%llx:" "km:0x%llx:0x%llx:" "kmc:0x%llx:0x%llx:" "kmac:0x%llx:0x%llx:" "kmctr:0x%llx:0x%llx:" "kmo:0x%llx:0x%llx:" "kmf:0x%llx:0x%llx:" "prno:0x%llx:0x%llx:" "kma:0x%llx:0x%llx:" "pcc:0x%llx:0x%llx:" "kdsa:0x%llx:0x%llx", OPENSSL_s390xcap_P.stfle[0], OPENSSL_s390xcap_P.stfle[1], OPENSSL_s390xcap_P.stfle[2], OPENSSL_s390xcap_P.stfle[3], OPENSSL_s390xcap_P.kimd[0], OPENSSL_s390xcap_P.kimd[1], OPENSSL_s390xcap_P.klmd[0], OPENSSL_s390xcap_P.klmd[1], OPENSSL_s390xcap_P.km[0], OPENSSL_s390xcap_P.km[1], OPENSSL_s390xcap_P.kmc[0], OPENSSL_s390xcap_P.kmc[1], OPENSSL_s390xcap_P.kmac[0], OPENSSL_s390xcap_P.kmac[1], OPENSSL_s390xcap_P.kmctr[0], OPENSSL_s390xcap_P.kmctr[1], OPENSSL_s390xcap_P.kmo[0], OPENSSL_s390xcap_P.kmo[1], OPENSSL_s390xcap_P.kmf[0], OPENSSL_s390xcap_P.kmf[1], OPENSSL_s390xcap_P.prno[0], OPENSSL_s390xcap_P.prno[1], OPENSSL_s390xcap_P.kma[0], OPENSSL_s390xcap_P.kma[1], OPENSSL_s390xcap_P.pcc[0], OPENSSL_s390xcap_P.pcc[1], OPENSSL_s390xcap_P.kdsa[0], OPENSSL_s390xcap_P.kdsa[1]); if ((env = getenv("OPENSSL_s390xcap")) != NULL) BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str), sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str), " env:%s", env); # endif #endif { static char seeds[512] = ""; #define add_seeds_string(str) \ do { \ if (seeds[0] != '\0') \ OPENSSL_strlcat(seeds, " ", sizeof(seeds)); \ OPENSSL_strlcat(seeds, str, sizeof(seeds)); \ } while (0) #define add_seeds_stringlist(label, strlist) \ do { \ add_seeds_string(label "("); \ { \ const char *dev[] = { strlist, NULL }; \ const char **p; \ int first = 1; \ \ for (p = dev; *p != NULL; p++) { \ if (!first) \ OPENSSL_strlcat(seeds, " ", sizeof(seeds)); \ first = 0; \ OPENSSL_strlcat(seeds, *p, sizeof(seeds)); \ } \ } \ OPENSSL_strlcat(seeds, ")", sizeof(seeds)); \ } while (0) #ifdef OPENSSL_RAND_SEED_NONE add_seeds_string("none"); #endif #ifdef OPENSSL_RAND_SEED_RDTSC add_seeds_string("rdtsc"); #endif #ifdef OPENSSL_RAND_SEED_RDCPU # ifdef __aarch64__ add_seeds_string("rndr ( rndrrs rndr )"); # else add_seeds_string("rdrand ( rdseed rdrand )"); # endif #endif #ifdef OPENSSL_RAND_SEED_LIBRANDOM add_seeds_string("C-library-random"); #endif #ifdef OPENSSL_RAND_SEED_GETRANDOM add_seeds_string("getrandom-syscall"); #endif #ifdef OPENSSL_RAND_SEED_DEVRANDOM add_seeds_stringlist("random-device", DEVRANDOM); #endif #ifdef OPENSSL_RAND_SEED_EGD add_seeds_stringlist("EGD", DEVRANDOM_EGD); #endif #ifdef OPENSSL_RAND_SEED_OS add_seeds_string("os-specific"); #endif seed_sources = seeds; } return 1; } const char *OPENSSL_info(int t) { /* * We don't care about the result. Worst case scenario, the strings * won't be initialised, i.e. remain NULL, which means that the info * isn't available anyway... */ (void)RUN_ONCE(&init_info, init_info_strings); switch (t) { case OPENSSL_INFO_CONFIG_DIR: return OPENSSLDIR; case OPENSSL_INFO_ENGINES_DIR: return ENGINESDIR; case OPENSSL_INFO_MODULES_DIR: return MODULESDIR; case OPENSSL_INFO_DSO_EXTENSION: return DSO_EXTENSION; case OPENSSL_INFO_DIR_FILENAME_SEPARATOR: #if defined(_WIN32) return "\\"; #elif defined(__VMS) return ""; #else /* Assume POSIX */ return "/"; #endif case OPENSSL_INFO_LIST_SEPARATOR: { static const char list_sep[] = { LIST_SEPARATOR_CHAR, '\0' }; return list_sep; } case OPENSSL_INFO_SEED_SOURCE: return seed_sources; case OPENSSL_INFO_CPU_SETTINGS: /* * If successfully initialized, ossl_cpu_info_str will start * with CPUINFO_PREFIX, if failed it will be an empty string. * Strip away the CPUINFO_PREFIX which we don't need here. */ if (ossl_cpu_info_str[0] != '\0') return ossl_cpu_info_str + strlen(CPUINFO_PREFIX); break; default: break; } /* Not an error */ return NULL; }
./openssl/crypto/vms_rms.h
/* * Copyright 2011-2016 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 */ #ifdef NAML$C_MAXRSS # define CC_RMS_NAMX cc$rms_naml # define FAB_NAMX fab$l_naml # define FAB_OR_NAML( fab, naml) naml # define FAB_OR_NAML_DNA naml$l_long_defname # define FAB_OR_NAML_DNS naml$l_long_defname_size # define FAB_OR_NAML_FNA naml$l_long_filename # define FAB_OR_NAML_FNS naml$l_long_filename_size # define NAMX_ESA naml$l_long_expand # define NAMX_ESL naml$l_long_expand_size # define NAMX_ESS naml$l_long_expand_alloc # define NAMX_NOP naml$b_nop # define SET_NAMX_NO_SHORT_UPCASE( nam) nam.naml$v_no_short_upcase = 1 # if __INITIAL_POINTER_SIZE == 64 # define NAMX_DNA_FNA_SET(fab) fab.fab$l_dna = (__char_ptr32) -1; \ fab.fab$l_fna = (__char_ptr32) -1; # else /* __INITIAL_POINTER_SIZE == 64 */ # define NAMX_DNA_FNA_SET(fab) fab.fab$l_dna = (char *) -1; \ fab.fab$l_fna = (char *) -1; # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ # define NAMX_MAXRSS NAML$C_MAXRSS # define NAMX_STRUCT NAML #else /* def NAML$C_MAXRSS */ # define CC_RMS_NAMX cc$rms_nam # define FAB_NAMX fab$l_nam # define FAB_OR_NAML( fab, naml) fab # define FAB_OR_NAML_DNA fab$l_dna # define FAB_OR_NAML_DNS fab$b_dns # define FAB_OR_NAML_FNA fab$l_fna # define FAB_OR_NAML_FNS fab$b_fns # define NAMX_ESA nam$l_esa # define NAMX_ESL nam$b_esl # define NAMX_ESS nam$b_ess # define NAMX_NOP nam$b_nop # define NAMX_DNA_FNA_SET(fab) # define NAMX_MAXRSS NAM$C_MAXRSS # define NAMX_STRUCT NAM # ifdef NAM$M_NO_SHORT_UPCASE # define SET_NAMX_NO_SHORT_UPCASE( nam) naml.naml$v_no_short_upcase = 1 # else /* def NAM$M_NO_SHORT_UPCASE */ # define SET_NAMX_NO_SHORT_UPCASE( nam) # endif /* def NAM$M_NO_SHORT_UPCASE [else] */ #endif /* def NAML$C_MAXRSS [else] */
./openssl/crypto/provider_conf.c
/* * 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 */ #include <string.h> #include <openssl/trace.h> #include <openssl/err.h> #include <openssl/conf.h> #include <openssl/safestack.h> #include <openssl/provider.h> #include "internal/provider.h" #include "internal/cryptlib.h" #include "provider_local.h" #include "crypto/context.h" DEFINE_STACK_OF(OSSL_PROVIDER) /* PROVIDER config module */ typedef struct { CRYPTO_RWLOCK *lock; STACK_OF(OSSL_PROVIDER) *activated_providers; } PROVIDER_CONF_GLOBAL; void *ossl_prov_conf_ctx_new(OSSL_LIB_CTX *libctx) { PROVIDER_CONF_GLOBAL *pcgbl = OPENSSL_zalloc(sizeof(*pcgbl)); if (pcgbl == NULL) return NULL; pcgbl->lock = CRYPTO_THREAD_lock_new(); if (pcgbl->lock == NULL) { OPENSSL_free(pcgbl); return NULL; } return pcgbl; } void ossl_prov_conf_ctx_free(void *vpcgbl) { PROVIDER_CONF_GLOBAL *pcgbl = vpcgbl; sk_OSSL_PROVIDER_pop_free(pcgbl->activated_providers, ossl_provider_free); OSSL_TRACE(CONF, "Cleaned up providers\n"); CRYPTO_THREAD_lock_free(pcgbl->lock); OPENSSL_free(pcgbl); } static const char *skip_dot(const char *name) { const char *p = strchr(name, '.'); if (p != NULL) return p + 1; return name; } /* * Parse the provider params section * Returns: * 1 for success * 0 for non-fatal errors * < 0 for fatal errors */ static int provider_conf_params_internal(OSSL_PROVIDER *prov, OSSL_PROVIDER_INFO *provinfo, const char *name, const char *value, const CONF *cnf, STACK_OF(OPENSSL_CSTRING) *visited) { STACK_OF(CONF_VALUE) *sect; int ok = 1; int rc = 0; sect = NCONF_get_section(cnf, value); if (sect != NULL) { int i; char buffer[512]; size_t buffer_len = 0; OSSL_TRACE1(CONF, "Provider params: start section %s\n", value); /* * Check to see if the provided section value has already * been visited. If it has, then we have a recursive lookup * in the configuration which isn't valid. As such we should error * out */ for (i = 0; i < sk_OPENSSL_CSTRING_num(visited); i++) { if (sk_OPENSSL_CSTRING_value(visited, i) == value) { ERR_raise(ERR_LIB_CONF, CONF_R_RECURSIVE_SECTION_REFERENCE); return -1; } } /* * We've not visited this node yet, so record it on the stack */ if (!sk_OPENSSL_CSTRING_push(visited, value)) return -1; if (name != NULL) { OPENSSL_strlcpy(buffer, name, sizeof(buffer)); OPENSSL_strlcat(buffer, ".", sizeof(buffer)); buffer_len = strlen(buffer); } for (i = 0; i < sk_CONF_VALUE_num(sect); i++) { CONF_VALUE *sectconf = sk_CONF_VALUE_value(sect, i); if (buffer_len + strlen(sectconf->name) >= sizeof(buffer)) { sk_OPENSSL_CSTRING_pop(visited); return -1; } buffer[buffer_len] = '\0'; OPENSSL_strlcat(buffer, sectconf->name, sizeof(buffer)); rc = provider_conf_params_internal(prov, provinfo, buffer, sectconf->value, cnf, visited); if (rc < 0) { sk_OPENSSL_CSTRING_pop(visited); return rc; } } sk_OPENSSL_CSTRING_pop(visited); OSSL_TRACE1(CONF, "Provider params: finish section %s\n", value); } else { OSSL_TRACE2(CONF, "Provider params: %s = %s\n", name, value); if (prov != NULL) ok = ossl_provider_add_parameter(prov, name, value); else ok = ossl_provider_info_add_parameter(provinfo, name, value); } return ok; } /* * recursively parse the provider configuration section * of the config file. * Returns * 1 on success * 0 on non-fatal error * < 0 on fatal errors */ static int provider_conf_params(OSSL_PROVIDER *prov, OSSL_PROVIDER_INFO *provinfo, const char *name, const char *value, const CONF *cnf) { int rc; STACK_OF(OPENSSL_CSTRING) *visited = sk_OPENSSL_CSTRING_new_null(); if (visited == NULL) return -1; rc = provider_conf_params_internal(prov, provinfo, name, value, cnf, visited); sk_OPENSSL_CSTRING_free(visited); return rc; } static int prov_already_activated(const char *name, STACK_OF(OSSL_PROVIDER) *activated) { int i, max; if (activated == NULL) return 0; max = sk_OSSL_PROVIDER_num(activated); for (i = 0; i < max; i++) { OSSL_PROVIDER *tstprov = sk_OSSL_PROVIDER_value(activated, i); if (strcmp(OSSL_PROVIDER_get0_name(tstprov), name) == 0) { return 1; } } return 0; } /* * Attempt to activate a provider * Returns: * 1 on successful activation * 0 on failed activation for non-fatal error * < 0 on failed activation for fatal errors */ static int provider_conf_activate(OSSL_LIB_CTX *libctx, const char *name, const char *value, const char *path, int soft, const CONF *cnf) { PROVIDER_CONF_GLOBAL *pcgbl = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_CONF_INDEX); OSSL_PROVIDER *prov = NULL, *actual = NULL; int ok = 0; if (pcgbl == NULL || !CRYPTO_THREAD_write_lock(pcgbl->lock)) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return -1; } if (!prov_already_activated(name, pcgbl->activated_providers)) { /* * There is an attempt to activate a provider, so we should disable * loading of fallbacks. Otherwise a misconfiguration could mean the * intended provider does not get loaded. Subsequent fetches could * then fallback to the default provider - which may be the wrong * thing. */ if (!ossl_provider_disable_fallback_loading(libctx)) { CRYPTO_THREAD_unlock(pcgbl->lock); ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR); return -1; } prov = ossl_provider_find(libctx, name, 1); if (prov == NULL) prov = ossl_provider_new(libctx, name, NULL, NULL, 1); if (prov == NULL) { CRYPTO_THREAD_unlock(pcgbl->lock); if (soft) ERR_clear_error(); return (soft == 0) ? -1 : 0; } if (path != NULL) ossl_provider_set_module_path(prov, path); ok = provider_conf_params(prov, NULL, NULL, value, cnf); if (ok == 1) { if (!ossl_provider_activate(prov, 1, 0)) { ok = 0; } else if (!ossl_provider_add_to_store(prov, &actual, 0)) { ossl_provider_deactivate(prov, 1); ok = 0; } else if (actual != prov && !ossl_provider_activate(actual, 1, 0)) { ossl_provider_free(actual); ok = 0; } else { if (pcgbl->activated_providers == NULL) pcgbl->activated_providers = sk_OSSL_PROVIDER_new_null(); if (pcgbl->activated_providers == NULL || !sk_OSSL_PROVIDER_push(pcgbl->activated_providers, actual)) { ossl_provider_deactivate(actual, 1); ossl_provider_free(actual); ok = 0; } else { ok = 1; } } } if (ok <= 0) ossl_provider_free(prov); } CRYPTO_THREAD_unlock(pcgbl->lock); return ok; } static int provider_conf_parse_bool_setting(const char *confname, const char *confvalue, int *val) { if (confvalue == NULL) { ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_SECTION_ERROR, "directive %s set to unrecognized value", confname); return 0; } if ((strcmp(confvalue, "1") == 0) || (strcmp(confvalue, "yes") == 0) || (strcmp(confvalue, "YES") == 0) || (strcmp(confvalue, "true") == 0) || (strcmp(confvalue, "TRUE") == 0) || (strcmp(confvalue, "on") == 0) || (strcmp(confvalue, "ON") == 0)) { *val = 1; } else if ((strcmp(confvalue, "0") == 0) || (strcmp(confvalue, "no") == 0) || (strcmp(confvalue, "NO") == 0) || (strcmp(confvalue, "false") == 0) || (strcmp(confvalue, "FALSE") == 0) || (strcmp(confvalue, "off") == 0) || (strcmp(confvalue, "OFF") == 0)) { *val = 0; } else { ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_SECTION_ERROR, "directive %s set to unrecognized value", confname); return 0; } return 1; } static int provider_conf_load(OSSL_LIB_CTX *libctx, const char *name, const char *value, const CONF *cnf) { int i; STACK_OF(CONF_VALUE) *ecmds; int soft = 0; const char *path = NULL; int activate = 0; int ok = 0; int added = 0; name = skip_dot(name); OSSL_TRACE1(CONF, "Configuring provider %s\n", name); /* Value is a section containing PROVIDER commands */ ecmds = NCONF_get_section(cnf, value); if (!ecmds) { ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_SECTION_ERROR, "section=%s not found", value); return 0; } /* Find the needed data first */ for (i = 0; i < sk_CONF_VALUE_num(ecmds); i++) { CONF_VALUE *ecmd = sk_CONF_VALUE_value(ecmds, i); const char *confname = skip_dot(ecmd->name); const char *confvalue = ecmd->value; OSSL_TRACE2(CONF, "Provider command: %s = %s\n", confname, confvalue); /* First handle some special pseudo confs */ /* Override provider name to use */ if (strcmp(confname, "identity") == 0) { name = confvalue; } else if (strcmp(confname, "soft_load") == 0) { if (!provider_conf_parse_bool_setting(confname, confvalue, &soft)) return 0; /* Load a dynamic PROVIDER */ } else if (strcmp(confname, "module") == 0) { path = confvalue; } else if (strcmp(confname, "activate") == 0) { if (!provider_conf_parse_bool_setting(confname, confvalue, &activate)) return 0; } } if (activate) { ok = provider_conf_activate(libctx, name, value, path, soft, cnf); } else { OSSL_PROVIDER_INFO entry; memset(&entry, 0, sizeof(entry)); ok = 1; if (name != NULL) { entry.name = OPENSSL_strdup(name); if (entry.name == NULL) ok = 0; } if (ok && path != NULL) { entry.path = OPENSSL_strdup(path); if (entry.path == NULL) ok = 0; } if (ok) ok = provider_conf_params(NULL, &entry, NULL, value, cnf); if (ok >= 1 && (entry.path != NULL || entry.parameters != NULL)) { ok = ossl_provider_info_add_to_store(libctx, &entry); added = 1; } if (added == 0) ossl_provider_info_clear(&entry); } /* * Provider activation returns a tristate: * 1 for successful activation * 0 for non-fatal activation failure * < 0 for fatal activation failure * We return success (1) for activation, (1) for non-fatal activation * failure, and (0) for fatal activation failure */ return ok >= 0; } static int provider_conf_init(CONF_IMODULE *md, const CONF *cnf) { STACK_OF(CONF_VALUE) *elist; CONF_VALUE *cval; int i; OSSL_TRACE1(CONF, "Loading providers module: section %s\n", CONF_imodule_get_value(md)); /* Value is a section containing PROVIDERs to configure */ elist = NCONF_get_section(cnf, CONF_imodule_get_value(md)); if (!elist) { ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_SECTION_ERROR); return 0; } for (i = 0; i < sk_CONF_VALUE_num(elist); i++) { cval = sk_CONF_VALUE_value(elist, i); if (!provider_conf_load(NCONF_get0_libctx((CONF *)cnf), cval->name, cval->value, cnf)) return 0; } return 1; } void ossl_provider_add_conf_module(void) { OSSL_TRACE(CONF, "Adding config module 'providers'\n"); CONF_module_add("providers", provider_conf_init, NULL); }
./openssl/crypto/s390xcap.c
/* * Copyright 2010-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 <stdio.h> #include <stdlib.h> #include <string.h> #include <setjmp.h> #include <signal.h> #include "internal/cryptlib.h" #include "crypto/ctype.h" #include "s390x_arch.h" #if defined(OPENSSL_SYS_LINUX) && !defined(FIPS_MODULE) # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <asm/zcrypt.h> # include <sys/ioctl.h> # include <unistd.h> #endif #if defined(__GLIBC__) && defined(__GLIBC_PREREQ) # if __GLIBC_PREREQ(2, 16) # include <sys/auxv.h> # if defined(HWCAP_S390_STFLE) && defined(HWCAP_S390_VX) # define OSSL_IMPLEMENT_GETAUXVAL # endif # endif #endif #define LEN 128 #define STR_(S) #S #define STR(S) STR_(S) #define TOK_FUNC(NAME) \ (sscanf(tok_begin, \ " " STR(NAME) " : %" STR(LEN) "[^:] : " \ "%" STR(LEN) "s %" STR(LEN) "s ", \ tok[0], tok[1], tok[2]) == 2) { \ \ off = (tok[0][0] == '~') ? 1 : 0; \ if (sscanf(tok[0] + off, "%llx", &cap->NAME[0]) != 1) \ goto ret; \ if (off) \ cap->NAME[0] = ~cap->NAME[0]; \ \ off = (tok[1][0] == '~') ? 1 : 0; \ if (sscanf(tok[1] + off, "%llx", &cap->NAME[1]) != 1) \ goto ret; \ if (off) \ cap->NAME[1] = ~cap->NAME[1]; \ } #define TOK_CPU_ALIAS(NAME, STRUCT_NAME) \ (sscanf(tok_begin, \ " %" STR(LEN) "s %" STR(LEN) "s ", \ tok[0], tok[1]) == 1 \ && !strcmp(tok[0], #NAME)) { \ memcpy(cap, &STRUCT_NAME, sizeof(*cap)); \ } #define TOK_CPU(NAME) TOK_CPU_ALIAS(NAME, NAME) #ifndef OSSL_IMPLEMENT_GETAUXVAL static sigjmp_buf ill_jmp; static void ill_handler(int sig) { siglongjmp(ill_jmp, sig); } void OPENSSL_vx_probe(void); #endif static const char *env; static int parse_env(struct OPENSSL_s390xcap_st *cap, int *cex); void OPENSSL_s390x_facilities(void); void OPENSSL_s390x_functions(void); struct OPENSSL_s390xcap_st OPENSSL_s390xcap_P; #ifdef S390X_MOD_EXP static int probe_cex(void); int OPENSSL_s390xcex; #if defined(__GNUC__) __attribute__ ((visibility("hidden"))) #endif void OPENSSL_s390x_cleanup(void); #if defined(__GNUC__) __attribute__ ((visibility("hidden"))) #endif void OPENSSL_s390x_cleanup(void) { if (OPENSSL_s390xcex != -1) { (void)close(OPENSSL_s390xcex); OPENSSL_s390xcex = -1; } } #endif #if defined(__GNUC__) && defined(__linux) __attribute__ ((visibility("hidden"))) #endif void OPENSSL_cpuid_setup(void) { struct OPENSSL_s390xcap_st cap; int cex = 1; if (OPENSSL_s390xcap_P.stfle[0]) return; /* set a bit that will not be tested later */ OPENSSL_s390xcap_P.stfle[0] |= S390X_CAPBIT(0); #if defined(OSSL_IMPLEMENT_GETAUXVAL) { const unsigned long hwcap = getauxval(AT_HWCAP); /* protection against missing store-facility-list-extended */ if (hwcap & HWCAP_S390_STFLE) OPENSSL_s390x_facilities(); /* protection against disabled vector facility */ if (!(hwcap & HWCAP_S390_VX)) { OPENSSL_s390xcap_P.stfle[2] &= ~(S390X_CAPBIT(S390X_VX) | S390X_CAPBIT(S390X_VXD) | S390X_CAPBIT(S390X_VXE)); } } #else { sigset_t oset; struct sigaction ill_act, oact_ill, oact_fpe; memset(&ill_act, 0, sizeof(ill_act)); ill_act.sa_handler = ill_handler; sigfillset(&ill_act.sa_mask); sigdelset(&ill_act.sa_mask, SIGILL); sigdelset(&ill_act.sa_mask, SIGFPE); sigdelset(&ill_act.sa_mask, SIGTRAP); sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset); sigaction(SIGILL, &ill_act, &oact_ill); sigaction(SIGFPE, &ill_act, &oact_fpe); /* protection against missing store-facility-list-extended */ if (sigsetjmp(ill_jmp, 1) == 0) OPENSSL_s390x_facilities(); /* protection against disabled vector facility */ if ((OPENSSL_s390xcap_P.stfle[2] & S390X_CAPBIT(S390X_VX)) && (sigsetjmp(ill_jmp, 1) == 0)) { OPENSSL_vx_probe(); } else { OPENSSL_s390xcap_P.stfle[2] &= ~(S390X_CAPBIT(S390X_VX) | S390X_CAPBIT(S390X_VXD) | S390X_CAPBIT(S390X_VXE)); } sigaction(SIGFPE, &oact_fpe, NULL); sigaction(SIGILL, &oact_ill, NULL); sigprocmask(SIG_SETMASK, &oset, NULL); } #endif env = getenv("OPENSSL_s390xcap"); if (env != NULL) { if (!parse_env(&cap, &cex)) env = NULL; } if (env != NULL) { OPENSSL_s390xcap_P.stfle[0] &= cap.stfle[0]; OPENSSL_s390xcap_P.stfle[1] &= cap.stfle[1]; OPENSSL_s390xcap_P.stfle[2] &= cap.stfle[2]; } OPENSSL_s390x_functions(); /* check OPENSSL_s390xcap_P.stfle */ if (env != NULL) { OPENSSL_s390xcap_P.kimd[0] &= cap.kimd[0]; OPENSSL_s390xcap_P.kimd[1] &= cap.kimd[1]; OPENSSL_s390xcap_P.klmd[0] &= cap.klmd[0]; OPENSSL_s390xcap_P.klmd[1] &= cap.klmd[1]; OPENSSL_s390xcap_P.km[0] &= cap.km[0]; OPENSSL_s390xcap_P.km[1] &= cap.km[1]; OPENSSL_s390xcap_P.kmc[0] &= cap.kmc[0]; OPENSSL_s390xcap_P.kmc[1] &= cap.kmc[1]; OPENSSL_s390xcap_P.kmac[0] &= cap.kmac[0]; OPENSSL_s390xcap_P.kmac[1] &= cap.kmac[1]; OPENSSL_s390xcap_P.kmctr[0] &= cap.kmctr[0]; OPENSSL_s390xcap_P.kmctr[1] &= cap.kmctr[1]; OPENSSL_s390xcap_P.kmo[0] &= cap.kmo[0]; OPENSSL_s390xcap_P.kmo[1] &= cap.kmo[1]; OPENSSL_s390xcap_P.kmf[0] &= cap.kmf[0]; OPENSSL_s390xcap_P.kmf[1] &= cap.kmf[1]; OPENSSL_s390xcap_P.prno[0] &= cap.prno[0]; OPENSSL_s390xcap_P.prno[1] &= cap.prno[1]; OPENSSL_s390xcap_P.kma[0] &= cap.kma[0]; OPENSSL_s390xcap_P.kma[1] &= cap.kma[1]; OPENSSL_s390xcap_P.pcc[0] &= cap.pcc[0]; OPENSSL_s390xcap_P.pcc[1] &= cap.pcc[1]; OPENSSL_s390xcap_P.kdsa[0] &= cap.kdsa[0]; OPENSSL_s390xcap_P.kdsa[1] &= cap.kdsa[1]; } #ifdef S390X_MOD_EXP if (cex == 0) { OPENSSL_s390xcex = -1; } else { OPENSSL_s390xcex = open("/dev/z90crypt", O_RDWR | O_CLOEXEC); if (probe_cex() == 1) OPENSSL_atexit(OPENSSL_s390x_cleanup); } #endif } #ifdef S390X_MOD_EXP static int probe_cex(void) { struct ica_rsa_modexpo me; const unsigned char inval[16] = { 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,2 }; const unsigned char modulus[16] = { 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,3 }; unsigned char res[16]; int olderrno; int rc = 1; me.inputdata = (unsigned char *)inval; me.inputdatalength = sizeof(inval); me.outputdata = (unsigned char *)res; me.outputdatalength = sizeof(res); me.b_key = (unsigned char *)inval; me.n_modulus = (unsigned char *)modulus; olderrno = errno; if (ioctl(OPENSSL_s390xcex, ICARSAMODEXPO, &me) == -1) { (void)close(OPENSSL_s390xcex); OPENSSL_s390xcex = -1; rc = 0; } errno = olderrno; return rc; } #endif static int parse_env(struct OPENSSL_s390xcap_st *cap, int *cex) { /*- * CPU model data * (only the STFLE- and QUERY-bits relevant to libcrypto are set) */ /*- * z900 (2000) - z/Architecture POP SA22-7832-00 * Facility detection would fail on real hw (no STFLE). */ static const struct OPENSSL_s390xcap_st z900 = { /*.stfle = */{0ULL, 0ULL, 0ULL, 0ULL}, /*.kimd = */{0ULL, 0ULL}, /*.klmd = */{0ULL, 0ULL}, /*.km = */{0ULL, 0ULL}, /*.kmc = */{0ULL, 0ULL}, /*.kmac = */{0ULL, 0ULL}, /*.kmctr = */{0ULL, 0ULL}, /*.kmo = */{0ULL, 0ULL}, /*.kmf = */{0ULL, 0ULL}, /*.prno = */{0ULL, 0ULL}, /*.kma = */{0ULL, 0ULL}, /*.pcc = */{0ULL, 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * z990 (2003) - z/Architecture POP SA22-7832-02 * Implements MSA. Facility detection would fail on real hw (no STFLE). */ static const struct OPENSSL_s390xcap_st z990 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA), 0ULL, 0ULL, 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1), 0ULL}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kmctr = */{0ULL, 0ULL}, /*.kmo = */{0ULL, 0ULL}, /*.kmf = */{0ULL, 0ULL}, /*.prno = */{0ULL, 0ULL}, /*.kma = */{0ULL, 0ULL}, /*.pcc = */{0ULL, 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * z9 (2005) - z/Architecture POP SA22-7832-04 * Implements MSA and MSA1. */ static const struct OPENSSL_s390xcap_st z9 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA) | S390X_CAPBIT(S390X_STCKF), 0ULL, 0ULL, 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256), 0ULL}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kmctr = */{0ULL, 0ULL}, /*.kmo = */{0ULL, 0ULL}, /*.kmf = */{0ULL, 0ULL}, /*.prno = */{0ULL, 0ULL}, /*.kma = */{0ULL, 0ULL}, /*.pcc = */{0ULL, 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * z10 (2008) - z/Architecture POP SA22-7832-06 * Implements MSA and MSA1-2. */ static const struct OPENSSL_s390xcap_st z10 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA) | S390X_CAPBIT(S390X_STCKF), 0ULL, 0ULL, 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), 0ULL}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kmctr = */{0ULL, 0ULL}, /*.kmo = */{0ULL, 0ULL}, /*.kmf = */{0ULL, 0ULL}, /*.prno = */{0ULL, 0ULL}, /*.kma = */{0ULL, 0ULL}, /*.pcc = */{0ULL, 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * z196 (2010) - z/Architecture POP SA22-7832-08 * Implements MSA and MSA1-4. */ static const struct OPENSSL_s390xcap_st z196 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA) | S390X_CAPBIT(S390X_STCKF), S390X_CAPBIT(S390X_MSA3) | S390X_CAPBIT(S390X_MSA4), 0ULL, 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), S390X_CAPBIT(S390X_GHASH)}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256) | S390X_CAPBIT(S390X_XTS_AES_128) | S390X_CAPBIT(S390X_XTS_AES_256), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmctr = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmo = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmf = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.prno = */{0ULL, 0ULL}, /*.kma = */{0ULL, 0ULL}, /*.pcc = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * zEC12 (2012) - z/Architecture POP SA22-7832-09 * Implements MSA and MSA1-4. */ static const struct OPENSSL_s390xcap_st zEC12 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA) | S390X_CAPBIT(S390X_STCKF), S390X_CAPBIT(S390X_MSA3) | S390X_CAPBIT(S390X_MSA4), 0ULL, 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), S390X_CAPBIT(S390X_GHASH)}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256) | S390X_CAPBIT(S390X_XTS_AES_128) | S390X_CAPBIT(S390X_XTS_AES_256), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmctr = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmo = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmf = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.prno = */{0ULL, 0ULL}, /*.kma = */{0ULL, 0ULL}, /*.pcc = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * z13 (2015) - z/Architecture POP SA22-7832-10 * Implements MSA and MSA1-5. */ static const struct OPENSSL_s390xcap_st z13 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA) | S390X_CAPBIT(S390X_STCKF) | S390X_CAPBIT(S390X_MSA5), S390X_CAPBIT(S390X_MSA3) | S390X_CAPBIT(S390X_MSA4), S390X_CAPBIT(S390X_VX), 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), S390X_CAPBIT(S390X_GHASH)}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256) | S390X_CAPBIT(S390X_XTS_AES_128) | S390X_CAPBIT(S390X_XTS_AES_256), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmctr = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmo = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmf = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.prno = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_512_DRNG), 0ULL}, /*.kma = */{0ULL, 0ULL}, /*.pcc = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * z14 (2017) - z/Architecture POP SA22-7832-11 * Implements MSA and MSA1-8. */ static const struct OPENSSL_s390xcap_st z14 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA) | S390X_CAPBIT(S390X_STCKF) | S390X_CAPBIT(S390X_MSA5), S390X_CAPBIT(S390X_MSA3) | S390X_CAPBIT(S390X_MSA4), S390X_CAPBIT(S390X_VX) | S390X_CAPBIT(S390X_VXD) | S390X_CAPBIT(S390X_VXE) | S390X_CAPBIT(S390X_MSA8), 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512) | S390X_CAPBIT(S390X_SHA3_224) | S390X_CAPBIT(S390X_SHA3_256) | S390X_CAPBIT(S390X_SHA3_384) | S390X_CAPBIT(S390X_SHA3_512) | S390X_CAPBIT(S390X_SHAKE_128) | S390X_CAPBIT(S390X_SHAKE_256), S390X_CAPBIT(S390X_GHASH)}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512) | S390X_CAPBIT(S390X_SHA3_224) | S390X_CAPBIT(S390X_SHA3_256) | S390X_CAPBIT(S390X_SHA3_384) | S390X_CAPBIT(S390X_SHA3_512) | S390X_CAPBIT(S390X_SHAKE_128) | S390X_CAPBIT(S390X_SHAKE_256), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256) | S390X_CAPBIT(S390X_XTS_AES_128) | S390X_CAPBIT(S390X_XTS_AES_256), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmctr = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmo = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmf = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.prno = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_512_DRNG), S390X_CAPBIT(S390X_TRNG)}, /*.kma = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.pcc = */{S390X_CAPBIT(S390X_QUERY), 0ULL}, /*.kdsa = */{0ULL, 0ULL}, }; /*- * z15 (2019) - z/Architecture POP SA22-7832-12 * Implements MSA and MSA1-9. */ static const struct OPENSSL_s390xcap_st z15 = { /*.stfle = */{S390X_CAPBIT(S390X_MSA) | S390X_CAPBIT(S390X_STCKF) | S390X_CAPBIT(S390X_MSA5), S390X_CAPBIT(S390X_MSA3) | S390X_CAPBIT(S390X_MSA4), S390X_CAPBIT(S390X_VX) | S390X_CAPBIT(S390X_VXD) | S390X_CAPBIT(S390X_VXE) | S390X_CAPBIT(S390X_MSA8) | S390X_CAPBIT(S390X_MSA9), 0ULL}, /*.kimd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512) | S390X_CAPBIT(S390X_SHA3_224) | S390X_CAPBIT(S390X_SHA3_256) | S390X_CAPBIT(S390X_SHA3_384) | S390X_CAPBIT(S390X_SHA3_512) | S390X_CAPBIT(S390X_SHAKE_128) | S390X_CAPBIT(S390X_SHAKE_256), S390X_CAPBIT(S390X_GHASH)}, /*.klmd = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_1) | S390X_CAPBIT(S390X_SHA_256) | S390X_CAPBIT(S390X_SHA_512) | S390X_CAPBIT(S390X_SHA3_224) | S390X_CAPBIT(S390X_SHA3_256) | S390X_CAPBIT(S390X_SHA3_384) | S390X_CAPBIT(S390X_SHA3_512) | S390X_CAPBIT(S390X_SHAKE_128) | S390X_CAPBIT(S390X_SHAKE_256), 0ULL}, /*.km = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256) | S390X_CAPBIT(S390X_XTS_AES_128) | S390X_CAPBIT(S390X_XTS_AES_256), 0ULL}, /*.kmc = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmac = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmctr = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmo = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.kmf = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.prno = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_SHA_512_DRNG), S390X_CAPBIT(S390X_TRNG)}, /*.kma = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_AES_128) | S390X_CAPBIT(S390X_AES_192) | S390X_CAPBIT(S390X_AES_256), 0ULL}, /*.pcc = */{S390X_CAPBIT(S390X_QUERY), S390X_CAPBIT(S390X_SCALAR_MULTIPLY_P256) | S390X_CAPBIT(S390X_SCALAR_MULTIPLY_P384) | S390X_CAPBIT(S390X_SCALAR_MULTIPLY_P521) | S390X_CAPBIT(S390X_SCALAR_MULTIPLY_ED25519) | S390X_CAPBIT(S390X_SCALAR_MULTIPLY_ED448) | S390X_CAPBIT(S390X_SCALAR_MULTIPLY_X25519) | S390X_CAPBIT(S390X_SCALAR_MULTIPLY_X448)}, /*.kdsa = */{S390X_CAPBIT(S390X_QUERY) | S390X_CAPBIT(S390X_ECDSA_VERIFY_P256) | S390X_CAPBIT(S390X_ECDSA_VERIFY_P384) | S390X_CAPBIT(S390X_ECDSA_VERIFY_P521) | S390X_CAPBIT(S390X_ECDSA_SIGN_P256) | S390X_CAPBIT(S390X_ECDSA_SIGN_P384) | S390X_CAPBIT(S390X_ECDSA_SIGN_P521) | S390X_CAPBIT(S390X_EDDSA_VERIFY_ED25519) | S390X_CAPBIT(S390X_EDDSA_VERIFY_ED448) | S390X_CAPBIT(S390X_EDDSA_SIGN_ED25519) | S390X_CAPBIT(S390X_EDDSA_SIGN_ED448), 0ULL}, }; /*- * z16 (2022) - z/Architecture POP * Implements MSA and MSA1-9 (same as z15, no need to repeat). */ char *tok_begin, *tok_end, *buff, tok[S390X_STFLE_MAX][LEN + 1]; int rc, off, i, n; buff = malloc(strlen(env) + 1); if (buff == NULL) return 0; rc = 0; memset(cap, ~0, sizeof(*cap)); strcpy(buff, env); tok_begin = buff + strspn(buff, ";"); strtok(tok_begin, ";"); tok_end = strtok(NULL, ";"); while (tok_begin != NULL) { /* stfle token */ if ((n = sscanf(tok_begin, " stfle : %" STR(LEN) "[^:] : " "%" STR(LEN) "[^:] : %" STR(LEN) "s ", tok[0], tok[1], tok[2]))) { for (i = 0; i < n; i++) { off = (tok[i][0] == '~') ? 1 : 0; if (sscanf(tok[i] + off, "%llx", &cap->stfle[i]) != 1) goto ret; if (off) cap->stfle[i] = ~cap->stfle[i]; } } /* query function tokens */ else if TOK_FUNC(kimd) else if TOK_FUNC(klmd) else if TOK_FUNC(km) else if TOK_FUNC(kmc) else if TOK_FUNC(kmac) else if TOK_FUNC(kmctr) else if TOK_FUNC(kmo) else if TOK_FUNC(kmf) else if TOK_FUNC(prno) else if TOK_FUNC(kma) else if TOK_FUNC(pcc) else if TOK_FUNC(kdsa) /* CPU model tokens */ else if TOK_CPU(z900) else if TOK_CPU(z990) else if TOK_CPU(z9) else if TOK_CPU(z10) else if TOK_CPU(z196) else if TOK_CPU(zEC12) else if TOK_CPU(z13) else if TOK_CPU(z14) else if TOK_CPU(z15) else if TOK_CPU_ALIAS(z16, z15) /* nocex to deactivate cex support */ else if (sscanf(tok_begin, " %" STR(LEN) "s %" STR(LEN) "s ", tok[0], tok[1]) == 1 && !strcmp(tok[0], "nocex")) { *cex = 0; } /* whitespace(ignored) or invalid tokens */ else { while (*tok_begin != '\0') { if (!ossl_isspace(*tok_begin)) goto ret; tok_begin++; } } tok_begin = tok_end; tok_end = strtok(NULL, ";"); } rc = 1; ret: free(buff); return rc; }
./openssl/crypto/quic_vlint.c
#include "internal/quic_vlint.h" #include "internal/e_os.h" #ifndef OPENSSL_NO_QUIC void ossl_quic_vlint_encode_n(uint8_t *buf, uint64_t v, int n) { if (n == 1) { buf[0] = (uint8_t)v; } else if (n == 2) { buf[0] = (uint8_t)(0x40 | ((v >> 8) & 0x3F)); buf[1] = (uint8_t)v; } else if (n == 4) { buf[0] = (uint8_t)(0x80 | ((v >> 24) & 0x3F)); buf[1] = (uint8_t)(v >> 16); buf[2] = (uint8_t)(v >> 8); buf[3] = (uint8_t)v; } else { buf[0] = (uint8_t)(0xC0 | ((v >> 56) & 0x3F)); buf[1] = (uint8_t)(v >> 48); buf[2] = (uint8_t)(v >> 40); buf[3] = (uint8_t)(v >> 32); buf[4] = (uint8_t)(v >> 24); buf[5] = (uint8_t)(v >> 16); buf[6] = (uint8_t)(v >> 8); buf[7] = (uint8_t)v; } } void ossl_quic_vlint_encode(uint8_t *buf, uint64_t v) { ossl_quic_vlint_encode_n(buf, v, ossl_quic_vlint_encode_len(v)); } uint64_t ossl_quic_vlint_decode_unchecked(const unsigned char *buf) { uint8_t first_byte = buf[0]; size_t sz = ossl_quic_vlint_decode_len(first_byte); if (sz == 1) return first_byte & 0x3F; if (sz == 2) return ((uint64_t)(first_byte & 0x3F) << 8) | buf[1]; if (sz == 4) return ((uint64_t)(first_byte & 0x3F) << 24) | ((uint64_t)buf[1] << 16) | ((uint64_t)buf[2] << 8) | buf[3]; return ((uint64_t)(first_byte & 0x3F) << 56) | ((uint64_t)buf[1] << 48) | ((uint64_t)buf[2] << 40) | ((uint64_t)buf[3] << 32) | ((uint64_t)buf[4] << 24) | ((uint64_t)buf[5] << 16) | ((uint64_t)buf[6] << 8) | buf[7]; } int ossl_quic_vlint_decode(const unsigned char *buf, size_t buf_len, uint64_t *v) { size_t dec_len; uint64_t x; if (buf_len < 1) return 0; dec_len = ossl_quic_vlint_decode_len(buf[0]); if (buf_len < dec_len) return 0; x = ossl_quic_vlint_decode_unchecked(buf); *v = x; return dec_len; } #endif
./openssl/crypto/time.c
/* * 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 <errno.h> #include <openssl/err.h> #include "internal/time.h" OSSL_TIME ossl_time_now(void) { OSSL_TIME r; #if defined(_WIN32) && !defined(OPENSSL_SYS_UEFI) SYSTEMTIME st; union { unsigned __int64 ul; FILETIME ft; } now; GetSystemTime(&st); SystemTimeToFileTime(&st, &now.ft); /* re-bias to 1/1/1970 */ # ifdef __MINGW32__ now.ul -= 116444736000000000ULL; # else now.ul -= 116444736000000000UI64; # endif r.t = ((uint64_t)now.ul) * (OSSL_TIME_SECOND / 10000000); #else /* defined(_WIN32) */ struct timeval t; if (gettimeofday(&t, NULL) < 0) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling gettimeofday()"); return ossl_time_zero(); } if (t.tv_sec <= 0) r.t = t.tv_usec <= 0 ? 0 : t.tv_usec * OSSL_TIME_US; else r.t = ((uint64_t)t.tv_sec * 1000000 + t.tv_usec) * OSSL_TIME_US; #endif /* defined(_WIN32) */ return r; }
./openssl/crypto/loongarchcap.c
/* * 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 <sys/auxv.h> #include "loongarch_arch.h" unsigned int OPENSSL_loongarch_hwcap_P = 0; void OPENSSL_cpuid_setup(void) { OPENSSL_loongarch_hwcap_P = getauxval(AT_HWCAP); }
./openssl/crypto/LPdir_vms.c
/* * Copyright 2004-2016 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 COPYRIGHT HOLDERS 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 COPYRIGHT * OWNER 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. */ #include <stddef.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <descrip.h> #include <namdef.h> #include <rmsdef.h> #include <libfildef.h> #include <lib$routines.h> #include <strdef.h> #include <str$routines.h> #include <stsdef.h> #ifndef LPDIR_H # include "LPdir.h" #endif #include "vms_rms.h" /* Some compiler options hide EVMSERR. */ #ifndef EVMSERR # define EVMSERR 65535 /* error for non-translatable VMS errors */ #endif struct LP_dir_context_st { unsigned long VMS_context; char filespec[NAMX_MAXRSS + 1]; char result[NAMX_MAXRSS + 1]; struct dsc$descriptor_d filespec_dsc; struct dsc$descriptor_d result_dsc; }; const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory) { int status; char *p, *r; size_t l; unsigned long flags = 0; /* Arrange 32-bit pointer to (copied) string storage, if needed. */ #if __INITIAL_POINTER_SIZE == 64 # pragma pointer_size save # pragma pointer_size 32 char *ctx_filespec_32p; # pragma pointer_size restore char ctx_filespec_32[NAMX_MAXRSS + 1]; #endif /* __INITIAL_POINTER_SIZE == 64 */ #ifdef NAML$C_MAXRSS flags |= LIB$M_FIL_LONG_NAMES; #endif if (ctx == NULL || directory == NULL) { errno = EINVAL; return 0; } errno = 0; if (*ctx == NULL) { size_t filespeclen = strlen(directory); char *filespec = NULL; if (filespeclen == 0) { errno = ENOENT; return 0; } /* MUST be a VMS directory specification! Let's estimate if it is. */ if (directory[filespeclen - 1] != ']' && directory[filespeclen - 1] != '>' && directory[filespeclen - 1] != ':') { errno = EINVAL; return 0; } filespeclen += 4; /* "*.*;" */ if (filespeclen > NAMX_MAXRSS) { errno = ENAMETOOLONG; return 0; } *ctx = malloc(sizeof(**ctx)); if (*ctx == NULL) { errno = ENOMEM; return 0; } memset(*ctx, 0, sizeof(**ctx)); strcpy((*ctx)->filespec, directory); strcat((*ctx)->filespec, "*.*;"); /* Arrange 32-bit pointer to (copied) string storage, if needed. */ #if __INITIAL_POINTER_SIZE == 64 # define CTX_FILESPEC ctx_filespec_32p /* Copy the file name to storage with a 32-bit pointer. */ ctx_filespec_32p = ctx_filespec_32; strcpy(ctx_filespec_32p, (*ctx)->filespec); #else /* __INITIAL_POINTER_SIZE == 64 */ # define CTX_FILESPEC (*ctx)->filespec #endif /* __INITIAL_POINTER_SIZE == 64 [else] */ (*ctx)->filespec_dsc.dsc$w_length = filespeclen; (*ctx)->filespec_dsc.dsc$b_dtype = DSC$K_DTYPE_T; (*ctx)->filespec_dsc.dsc$b_class = DSC$K_CLASS_S; (*ctx)->filespec_dsc.dsc$a_pointer = CTX_FILESPEC; } (*ctx)->result_dsc.dsc$w_length = 0; (*ctx)->result_dsc.dsc$b_dtype = DSC$K_DTYPE_T; (*ctx)->result_dsc.dsc$b_class = DSC$K_CLASS_D; (*ctx)->result_dsc.dsc$a_pointer = 0; status = lib$find_file(&(*ctx)->filespec_dsc, &(*ctx)->result_dsc, &(*ctx)->VMS_context, 0, 0, 0, &flags); if (status == RMS$_NMF) { errno = 0; vaxc$errno = status; return NULL; } if (!$VMS_STATUS_SUCCESS(status)) { errno = EVMSERR; vaxc$errno = status; return NULL; } /* * Quick, cheap and dirty way to discard any device and directory, since * we only want file names */ l = (*ctx)->result_dsc.dsc$w_length; p = (*ctx)->result_dsc.dsc$a_pointer; r = p; for (; *p; p++) { if (*p == '^' && p[1] != '\0') { /* Take care of ODS-5 escapes */ p++; } else if (*p == ':' || *p == '>' || *p == ']') { l -= p + 1 - r; r = p + 1; } else if (*p == ';') { l = p - r; break; } } strncpy((*ctx)->result, r, l); (*ctx)->result[l] = '\0'; str$free1_dx(&(*ctx)->result_dsc); return (*ctx)->result; } int LP_find_file_end(LP_DIR_CTX **ctx) { if (ctx != NULL && *ctx != NULL) { int status = lib$find_file_end(&(*ctx)->VMS_context); free(*ctx); if (!$VMS_STATUS_SUCCESS(status)) { errno = EVMSERR; vaxc$errno = status; return 0; } return 1; } errno = EINVAL; return 0; }
./openssl/crypto/cpuid.c
/* * Copyright 1998-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 "internal/e_os.h" #include "crypto/cryptlib.h" #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[4]; # if defined(OPENSSL_CPUID_OBJ) /* * Purpose of these minimalistic and character-type-agnostic subroutines * is to break dependency on MSVCRT (on Windows) and locale. This makes * OPENSSL_cpuid_setup safe to use as "constructor". "Character-type- * agnostic" means that they work with either wide or 8-bit characters, * exploiting the fact that first 127 characters can be simply casted * between the sets, while the rest would be simply rejected by ossl_is* * subroutines. */ # ifdef _WIN32 typedef WCHAR variant_char; static variant_char *ossl_getenv(const char *name) { /* * Since we pull only one environment variable, it's simpler to * just ignore |name| and use equivalent wide-char L-literal. * As well as to ignore excessively long values... */ static WCHAR value[48]; DWORD len = GetEnvironmentVariableW(L"OPENSSL_ia32cap", value, 48); return (len > 0 && len < 48) ? value : NULL; } # else typedef char variant_char; # define ossl_getenv getenv # endif # include "crypto/ctype.h" static int todigit(variant_char c) { if (ossl_isdigit(c)) return c - '0'; else if (ossl_isxdigit(c)) return ossl_tolower(c) - 'a' + 10; /* return largest base value to make caller terminate the loop */ return 16; } static uint64_t ossl_strtouint64(const variant_char *str) { uint64_t ret = 0; unsigned int digit, base = 10; if (*str == '0') { base = 8, str++; if (ossl_tolower(*str) == 'x') base = 16, str++; } while ((digit = todigit(*str++)) < base) ret = ret * base + digit; return ret; } static variant_char *ossl_strchr(const variant_char *str, char srch) { variant_char c; while ((c = *str)) { if (c == srch) return (variant_char *)str; str++; } return NULL; } # define OPENSSL_CPUID_SETUP typedef uint64_t IA32CAP; void OPENSSL_cpuid_setup(void) { static int trigger = 0; IA32CAP OPENSSL_ia32_cpuid(unsigned int *); IA32CAP vec; const variant_char *env; if (trigger) return; trigger = 1; if ((env = ossl_getenv("OPENSSL_ia32cap")) != NULL) { int off = (env[0] == '~') ? 1 : 0; vec = ossl_strtouint64(env + off); if (off) { IA32CAP mask = vec; vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~mask; if (mask & (1<<24)) { /* * User disables FXSR bit, mask even other capabilities * that operate exclusively on XMM, so we don't have to * double-check all the time. We mask PCLMULQDQ, AMD XOP, * AES-NI and AVX. Formally speaking we don't have to * do it in x86_64 case, but we can safely assume that * x86_64 users won't actually flip this flag. */ vec &= ~((IA32CAP)(1<<1|1<<11|1<<25|1<<28) << 32); } } else if (env[0] == ':') { vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P); } if ((env = ossl_strchr(env, ':')) != NULL) { IA32CAP vecx; env++; off = (env[0] == '~') ? 1 : 0; vecx = ossl_strtouint64(env + off); if (off) { OPENSSL_ia32cap_P[2] &= ~(unsigned int)vecx; OPENSSL_ia32cap_P[3] &= ~(unsigned int)(vecx >> 32); } else { OPENSSL_ia32cap_P[2] = (unsigned int)vecx; OPENSSL_ia32cap_P[3] = (unsigned int)(vecx >> 32); } } else { OPENSSL_ia32cap_P[2] = 0; OPENSSL_ia32cap_P[3] = 0; } } else { vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P); } /* * |(1<<10) sets a reserved bit to signal that variable * was initialized already... This is to avoid interference * with cpuid snippets in ELF .init segment. */ OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10); OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32); } # else unsigned int OPENSSL_ia32cap_P[4]; # endif #endif #ifndef OPENSSL_CPUID_OBJ # ifndef OPENSSL_CPUID_SETUP void OPENSSL_cpuid_setup(void) { } # endif /* * The rest are functions that are defined in the same assembler files as * the CPUID functionality. */ /* * The volatile is used to ensure that the compiler generates code that reads * all values from the array and doesn't try to optimize this away. The standard * doesn't actually require this behavior if the original data pointed to is * not volatile, but compilers do this in practice anyway. * * There are also assembler versions of this function. */ # undef CRYPTO_memcmp int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len) { size_t i; const volatile unsigned char *a = in_a; const volatile unsigned char *b = in_b; unsigned char x = 0; for (i = 0; i < len; i++) x |= a[i] ^ b[i]; return x; } /* * For systems that don't provide an instruction counter register or equivalent. */ uint32_t OPENSSL_rdtsc(void) { return 0; } size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt) { return 0; } size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max) { return 0; } #endif
./openssl/crypto/deterministic_nonce.c
/* * 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/bn.h> #include <openssl/evp.h> #include <openssl/core_names.h> #include <openssl/kdf.h> #include "internal/deterministic_nonce.h" /* * Convert a Bit String to an Integer (See RFC 6979 Section 2.3.2) * * Params: * out The returned Integer as a BIGNUM * qlen_bits The maximum size of the returned integer in bits. The returned * Integer is shifted right if inlen is larger than qlen_bits.. * in, inlen The input Bit String (in bytes). * Returns: 1 if successful, or 0 otherwise. */ static int bits2int(BIGNUM *out, int qlen_bits, const unsigned char *in, size_t inlen) { int blen_bits = inlen * 8; int shift; if (BN_bin2bn(in, (int)inlen, out) == NULL) return 0; shift = blen_bits - qlen_bits; if (shift > 0) return BN_rshift(out, out, shift); return 1; } /* * Convert an Integer to an Octet String (See RFC 6979 2.3.3). * The value is zero padded if required. * * Params: * out The returned Octet String * num The input Integer * rlen The required size of the returned Octet String in bytes * Returns: 1 if successful, or 0 otherwise. */ static int int2octets(unsigned char *out, const BIGNUM *num, int rlen) { return BN_bn2binpad(num, out, rlen) >= 0; } /* * Convert a Bit String to an Octet String (See RFC 6979 Section 2.3.4) * * Params: * out The returned octet string. * q The modulus * qlen_bits The length of q in bits * rlen The value of qlen_bits rounded up to the nearest 8 bits. * in, inlen The input bit string (in bytes) * Returns: 1 if successful, or 0 otherwise. */ static int bits2octets(unsigned char *out, const BIGNUM *q, int qlen_bits, int rlen, const unsigned char *in, size_t inlen) { int ret = 0; BIGNUM *z = BN_new(); if (z == NULL || !bits2int(z, qlen_bits, in, inlen)) goto err; /* z2 = z1 mod q (Do a simple subtract, since z1 < 2^qlen_bits) */ if (BN_cmp(z, q) >= 0 && !BN_usub(z, z, q)) goto err; ret = int2octets(out, z, rlen); err: BN_free(z); return ret; } /* * Setup a KDF HMAC_DRBG object using fixed entropy and nonce data. * * Params: * digestname The digest name for the HMAC * entropy, entropylen A fixed input entropy buffer * nonce, noncelen A fixed input nonce buffer * libctx, propq Are used for fetching algorithms * * Returns: The created KDF HMAC_DRBG object if successful, or NULL otherwise. */ static EVP_KDF_CTX *kdf_setup(const char *digestname, const unsigned char *entropy, size_t entropylen, const unsigned char *nonce, size_t noncelen, OSSL_LIB_CTX *libctx, const char *propq) { EVP_KDF_CTX *ctx = NULL; EVP_KDF *kdf = NULL; OSSL_PARAM params[5], *p; kdf = EVP_KDF_fetch(libctx, "HMAC-DRBG-KDF", propq); ctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (ctx == NULL) goto err; p = params; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)digestname, 0); if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_PROPERTIES, (char *)propq, 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_HMACDRBG_ENTROPY, (void *)entropy, entropylen); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_HMACDRBG_NONCE, (void *)nonce, noncelen); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_CTX_set_params(ctx, params) <= 0) goto err; return ctx; err: EVP_KDF_CTX_free(ctx); return NULL; } /* * Generate a Deterministic nonce 'k' for DSA/ECDSA as defined in * RFC 6979 Section 3.3. "Alternate Description of the Generation of k" * * Params: * out Returns the generated deterministic nonce 'k' * q A large prime number used for modulus operations for DSA and ECDSA. * priv The private key in the range [1, q-1] * hm, hmlen The digested message buffer in bytes * digestname The digest name used for signing. It is used as the HMAC digest. * libctx, propq Used for fetching algorithms * * Returns: 1 if successful, or 0 otherwise. */ int ossl_gen_deterministic_nonce_rfc6979(BIGNUM *out, const BIGNUM *q, const BIGNUM *priv, const unsigned char *hm, size_t hmlen, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { EVP_KDF_CTX *kdfctx = NULL; int ret = 0, rlen = 0, qlen_bits = 0; unsigned char *entropyx = NULL, *nonceh = NULL, *T = NULL; size_t allocsz = 0; if (out == NULL) return 0; qlen_bits = BN_num_bits(q); if (qlen_bits == 0) return 0; /* Note rlen used here is in bytes since the input values are byte arrays */ rlen = (qlen_bits + 7) / 8; allocsz = 3 * rlen; /* Use a single alloc for the buffers T, nonceh and entropyx */ T = (unsigned char *)OPENSSL_zalloc(allocsz); if (T == NULL) return 0; nonceh = T + rlen; entropyx = nonceh + rlen; if (!int2octets(entropyx, priv, rlen) || !bits2octets(nonceh, q, qlen_bits, rlen, hm, hmlen)) goto end; kdfctx = kdf_setup(digestname, entropyx, rlen, nonceh, rlen, libctx, propq); if (kdfctx == NULL) goto end; do { if (!EVP_KDF_derive(kdfctx, T, rlen, NULL) || !bits2int(out, qlen_bits, T, rlen)) goto end; } while (BN_is_zero(out) || BN_is_one(out) || BN_cmp(out, q) >= 0); ret = 1; end: EVP_KDF_CTX_free(kdfctx); OPENSSL_clear_free(T, allocsz); return ret; }
./openssl/crypto/o_init.c
/* * Copyright 2011-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/e_os.h" #include <openssl/err.h> /* * Perform any essential OpenSSL initialization operations. Currently does * nothing. */ void OPENSSL_init(void) { return; }
./openssl/crypto/bio/bss_core.c
/* * 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 */ #include <openssl/core_dispatch.h> #include "bio_local.h" #include "internal/cryptlib.h" #include "crypto/context.h" typedef struct { OSSL_FUNC_BIO_read_ex_fn *c_bio_read_ex; OSSL_FUNC_BIO_write_ex_fn *c_bio_write_ex; OSSL_FUNC_BIO_gets_fn *c_bio_gets; OSSL_FUNC_BIO_puts_fn *c_bio_puts; OSSL_FUNC_BIO_ctrl_fn *c_bio_ctrl; OSSL_FUNC_BIO_up_ref_fn *c_bio_up_ref; OSSL_FUNC_BIO_free_fn *c_bio_free; } BIO_CORE_GLOBALS; void ossl_bio_core_globals_free(void *vbcg) { OPENSSL_free(vbcg); } void *ossl_bio_core_globals_new(OSSL_LIB_CTX *ctx) { return OPENSSL_zalloc(sizeof(BIO_CORE_GLOBALS)); } static ossl_inline BIO_CORE_GLOBALS *get_globals(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_BIO_CORE_INDEX); } static int bio_core_read_ex(BIO *bio, char *data, size_t data_len, size_t *bytes_read) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_read_ex == NULL) return 0; return bcgbl->c_bio_read_ex(BIO_get_data(bio), data, data_len, bytes_read); } static int bio_core_write_ex(BIO *bio, const char *data, size_t data_len, size_t *written) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_write_ex == NULL) return 0; return bcgbl->c_bio_write_ex(BIO_get_data(bio), data, data_len, written); } static long bio_core_ctrl(BIO *bio, int cmd, long num, void *ptr) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_ctrl == NULL) return -1; return bcgbl->c_bio_ctrl(BIO_get_data(bio), cmd, num, ptr); } static int bio_core_gets(BIO *bio, char *buf, int size) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_gets == NULL) return -1; return bcgbl->c_bio_gets(BIO_get_data(bio), buf, size); } static int bio_core_puts(BIO *bio, const char *str) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_puts == NULL) return -1; return bcgbl->c_bio_puts(BIO_get_data(bio), str); } static int bio_core_new(BIO *bio) { BIO_set_init(bio, 1); return 1; } static int bio_core_free(BIO *bio) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL) return 0; BIO_set_init(bio, 0); bcgbl->c_bio_free(BIO_get_data(bio)); return 1; } static const BIO_METHOD corebiometh = { BIO_TYPE_CORE_TO_PROV, "BIO to Core filter", bio_core_write_ex, NULL, bio_core_read_ex, NULL, bio_core_puts, bio_core_gets, bio_core_ctrl, bio_core_new, bio_core_free, NULL, }; const BIO_METHOD *BIO_s_core(void) { return &corebiometh; } BIO *BIO_new_from_core_bio(OSSL_LIB_CTX *libctx, OSSL_CORE_BIO *corebio) { BIO *outbio; BIO_CORE_GLOBALS *bcgbl = get_globals(libctx); /* Check the library context has been initialised with the callbacks */ if (bcgbl == NULL || (bcgbl->c_bio_write_ex == NULL && bcgbl->c_bio_read_ex == NULL)) return NULL; if ((outbio = BIO_new_ex(libctx, BIO_s_core())) == NULL) return NULL; if (!bcgbl->c_bio_up_ref(corebio)) { BIO_free(outbio); return NULL; } BIO_set_data(outbio, corebio); return outbio; } int ossl_bio_init_core(OSSL_LIB_CTX *libctx, const OSSL_DISPATCH *fns) { BIO_CORE_GLOBALS *bcgbl = get_globals(libctx); if (bcgbl == NULL) return 0; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_BIO_READ_EX: if (bcgbl->c_bio_read_ex == NULL) bcgbl->c_bio_read_ex = OSSL_FUNC_BIO_read_ex(fns); break; case OSSL_FUNC_BIO_WRITE_EX: if (bcgbl->c_bio_write_ex == NULL) bcgbl->c_bio_write_ex = OSSL_FUNC_BIO_write_ex(fns); break; case OSSL_FUNC_BIO_GETS: if (bcgbl->c_bio_gets == NULL) bcgbl->c_bio_gets = OSSL_FUNC_BIO_gets(fns); break; case OSSL_FUNC_BIO_PUTS: if (bcgbl->c_bio_puts == NULL) bcgbl->c_bio_puts = OSSL_FUNC_BIO_puts(fns); break; case OSSL_FUNC_BIO_CTRL: if (bcgbl->c_bio_ctrl == NULL) bcgbl->c_bio_ctrl = OSSL_FUNC_BIO_ctrl(fns); break; case OSSL_FUNC_BIO_UP_REF: if (bcgbl->c_bio_up_ref == NULL) bcgbl->c_bio_up_ref = OSSL_FUNC_BIO_up_ref(fns); break; case OSSL_FUNC_BIO_FREE: if (bcgbl->c_bio_free == NULL) bcgbl->c_bio_free = OSSL_FUNC_BIO_free(fns); break; } } return 1; }
./openssl/crypto/bio/bf_nbio.c
/* * 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" #include <openssl/rand.h> /* * BIO_put and BIO_get both add to the digest, BIO_gets returns the digest */ static int nbiof_write(BIO *h, const char *buf, int num); static int nbiof_read(BIO *h, char *buf, int size); static int nbiof_puts(BIO *h, const char *str); static int nbiof_gets(BIO *h, char *str, int size); static long nbiof_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int nbiof_new(BIO *h); static int nbiof_free(BIO *data); static long nbiof_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); typedef struct nbio_test_st { /* only set if we sent a 'should retry' error */ int lrn; int lwn; } NBIO_TEST; static const BIO_METHOD methods_nbiof = { BIO_TYPE_NBIO_TEST, "non-blocking IO test filter", bwrite_conv, nbiof_write, bread_conv, nbiof_read, nbiof_puts, nbiof_gets, nbiof_ctrl, nbiof_new, nbiof_free, nbiof_callback_ctrl, }; const BIO_METHOD *BIO_f_nbio_test(void) { return &methods_nbiof; } static int nbiof_new(BIO *bi) { NBIO_TEST *nt; if ((nt = OPENSSL_zalloc(sizeof(*nt))) == NULL) return 0; nt->lrn = -1; nt->lwn = -1; bi->ptr = (char *)nt; bi->init = 1; return 1; } static int nbiof_free(BIO *a) { if (a == NULL) return 0; OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; return 1; } static int nbiof_read(BIO *b, char *out, int outl) { int ret = 0; int num; unsigned char n; if (out == NULL) return 0; if (b->next_bio == NULL) return 0; BIO_clear_retry_flags(b); if (RAND_priv_bytes(&n, 1) <= 0) return -1; num = (n & 0x07); if (outl > num) outl = num; if (num == 0) { ret = -1; BIO_set_retry_read(b); } else { ret = BIO_read(b->next_bio, out, outl); if (ret < 0) BIO_copy_next_retry(b); } return ret; } static int nbiof_write(BIO *b, const char *in, int inl) { NBIO_TEST *nt; int ret = 0; int num; unsigned char n; if ((in == NULL) || (inl <= 0)) return 0; if (b->next_bio == NULL) return 0; nt = (NBIO_TEST *)b->ptr; BIO_clear_retry_flags(b); if (nt->lwn > 0) { num = nt->lwn; nt->lwn = 0; } else { if (RAND_priv_bytes(&n, 1) <= 0) return -1; num = (n & 7); } if (inl > num) inl = num; if (num == 0) { ret = -1; BIO_set_retry_write(b); } else { ret = BIO_write(b->next_bio, in, inl); if (ret < 0) { BIO_copy_next_retry(b); nt->lwn = inl; } } return ret; } static long nbiof_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; if (b->next_bio == NULL) return 0; switch (cmd) { case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_DUP: ret = 0L; break; default: ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } return ret; } static long nbiof_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { if (b->next_bio == NULL) return 0; return BIO_callback_ctrl(b->next_bio, cmd, fp); } static int nbiof_gets(BIO *bp, char *buf, int size) { if (bp->next_bio == NULL) return 0; return BIO_gets(bp->next_bio, buf, size); } static int nbiof_puts(BIO *bp, const char *str) { if (bp->next_bio == NULL) return 0; return BIO_puts(bp->next_bio, str); }
./openssl/crypto/bio/bf_buff.c
/* * 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" static int buffer_write(BIO *h, const char *buf, int num); static int buffer_read(BIO *h, char *buf, int size); static int buffer_puts(BIO *h, const char *str); static int buffer_gets(BIO *h, char *str, int size); static long buffer_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int buffer_new(BIO *h); static int buffer_free(BIO *data); static long buffer_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); #define DEFAULT_BUFFER_SIZE 4096 static const BIO_METHOD methods_buffer = { BIO_TYPE_BUFFER, "buffer", bwrite_conv, buffer_write, bread_conv, buffer_read, buffer_puts, buffer_gets, buffer_ctrl, buffer_new, buffer_free, buffer_callback_ctrl, }; const BIO_METHOD *BIO_f_buffer(void) { return &methods_buffer; } static int buffer_new(BIO *bi) { BIO_F_BUFFER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; ctx->ibuf_size = DEFAULT_BUFFER_SIZE; ctx->ibuf = OPENSSL_malloc(DEFAULT_BUFFER_SIZE); if (ctx->ibuf == NULL) { OPENSSL_free(ctx); return 0; } ctx->obuf_size = DEFAULT_BUFFER_SIZE; ctx->obuf = OPENSSL_malloc(DEFAULT_BUFFER_SIZE); if (ctx->obuf == NULL) { OPENSSL_free(ctx->ibuf); OPENSSL_free(ctx); return 0; } bi->init = 1; bi->ptr = (char *)ctx; bi->flags = 0; return 1; } static int buffer_free(BIO *a) { BIO_F_BUFFER_CTX *b; if (a == NULL) return 0; b = (BIO_F_BUFFER_CTX *)a->ptr; OPENSSL_free(b->ibuf); OPENSSL_free(b->obuf); OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; return 1; } static int buffer_read(BIO *b, char *out, int outl) { int i, num = 0; BIO_F_BUFFER_CTX *ctx; if (out == NULL) return 0; ctx = (BIO_F_BUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) return 0; num = 0; BIO_clear_retry_flags(b); start: i = ctx->ibuf_len; /* If there is stuff left over, grab it */ if (i != 0) { if (i > outl) i = outl; memcpy(out, &(ctx->ibuf[ctx->ibuf_off]), i); ctx->ibuf_off += i; ctx->ibuf_len -= i; num += i; if (outl == i) return num; outl -= i; out += i; } /* * We may have done a partial read. try to do more. We have nothing in * the buffer. If we get an error and have read some data, just return it * and let them retry to get the error again. copy direct to parent * address space */ if (outl > ctx->ibuf_size) { for (;;) { i = BIO_read(b->next_bio, out, outl); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } num += i; if (outl == i) return num; out += i; outl -= i; } } /* else */ /* we are going to be doing some buffering */ i = BIO_read(b->next_bio, ctx->ibuf, ctx->ibuf_size); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } ctx->ibuf_off = 0; ctx->ibuf_len = i; /* Lets re-read using ourselves :-) */ goto start; } static int buffer_write(BIO *b, const char *in, int inl) { int i, num = 0; BIO_F_BUFFER_CTX *ctx; if ((in == NULL) || (inl <= 0)) return 0; ctx = (BIO_F_BUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) return 0; BIO_clear_retry_flags(b); start: i = ctx->obuf_size - (ctx->obuf_len + ctx->obuf_off); /* add to buffer and return */ if (i >= inl) { memcpy(&(ctx->obuf[ctx->obuf_off + ctx->obuf_len]), in, inl); ctx->obuf_len += inl; return (num + inl); } /* else */ /* stuff already in buffer, so add to it first, then flush */ if (ctx->obuf_len != 0) { if (i > 0) { /* lets fill it up if we can */ memcpy(&(ctx->obuf[ctx->obuf_off + ctx->obuf_len]), in, i); in += i; inl -= i; num += i; ctx->obuf_len += i; } /* we now have a full buffer needing flushing */ for (;;) { i = BIO_write(b->next_bio, &(ctx->obuf[ctx->obuf_off]), ctx->obuf_len); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } ctx->obuf_off += i; ctx->obuf_len -= i; if (ctx->obuf_len == 0) break; } } /* * we only get here if the buffer has been flushed and we still have * stuff to write */ ctx->obuf_off = 0; /* we now have inl bytes to write */ while (inl >= ctx->obuf_size) { i = BIO_write(b->next_bio, in, inl); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } num += i; in += i; inl -= i; if (inl == 0) return num; } /* * copy the rest into the buffer since we have only a small amount left */ goto start; } static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO *dbio; BIO_F_BUFFER_CTX *ctx; long ret = 1; char *p1, *p2; int r, i, *ip; int ibs, obs; ctx = (BIO_F_BUFFER_CTX *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: ctx->ibuf_off = 0; ctx->ibuf_len = 0; ctx->obuf_off = 0; ctx->obuf_len = 0; if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_EOF: if (ctx->ibuf_len > 0) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_INFO: ret = (long)ctx->obuf_len; break; case BIO_C_GET_BUFF_NUM_LINES: ret = 0; p1 = ctx->ibuf; for (i = 0; i < ctx->ibuf_len; i++) { if (p1[ctx->ibuf_off + i] == '\n') ret++; } break; case BIO_CTRL_WPENDING: ret = (long)ctx->obuf_len; if (ret == 0) { if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; case BIO_CTRL_PENDING: ret = (long)ctx->ibuf_len; if (ret == 0) { if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; case BIO_C_SET_BUFF_READ_DATA: if (num > ctx->ibuf_size) { if (num <= 0) return 0; p1 = OPENSSL_malloc((size_t)num); if (p1 == NULL) return 0; OPENSSL_free(ctx->ibuf); ctx->ibuf = p1; } ctx->ibuf_off = 0; ctx->ibuf_len = (int)num; memcpy(ctx->ibuf, ptr, (int)num); ret = 1; break; case BIO_C_SET_BUFF_SIZE: if (ptr != NULL) { ip = (int *)ptr; if (*ip == 0) { ibs = (int)num; obs = ctx->obuf_size; } else { /* if (*ip == 1) */ ibs = ctx->ibuf_size; obs = (int)num; } } else { ibs = (int)num; obs = (int)num; } p1 = ctx->ibuf; p2 = ctx->obuf; if ((ibs > DEFAULT_BUFFER_SIZE) && (ibs != ctx->ibuf_size)) { if (num <= 0) return 0; p1 = OPENSSL_malloc((size_t)num); if (p1 == NULL) return 0; } if ((obs > DEFAULT_BUFFER_SIZE) && (obs != ctx->obuf_size)) { p2 = OPENSSL_malloc((size_t)num); if (p2 == NULL) { if (p1 != ctx->ibuf) OPENSSL_free(p1); return 0; } } if (ctx->ibuf != p1) { OPENSSL_free(ctx->ibuf); ctx->ibuf = p1; ctx->ibuf_off = 0; ctx->ibuf_len = 0; ctx->ibuf_size = ibs; } if (ctx->obuf != p2) { OPENSSL_free(ctx->obuf); ctx->obuf = p2; ctx->obuf_off = 0; ctx->obuf_len = 0; ctx->obuf_size = obs; } break; case BIO_C_DO_STATE_MACHINE: if (b->next_bio == NULL) return 0; BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_FLUSH: if (b->next_bio == NULL) return 0; if (ctx->obuf_len <= 0) { ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; } for (;;) { BIO_clear_retry_flags(b); if (ctx->obuf_len > 0) { r = BIO_write(b->next_bio, &(ctx->obuf[ctx->obuf_off]), ctx->obuf_len); BIO_copy_next_retry(b); if (r <= 0) return (long)r; ctx->obuf_off += r; ctx->obuf_len -= r; } else { ctx->obuf_len = 0; ctx->obuf_off = 0; break; } } ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_DUP: dbio = (BIO *)ptr; if (BIO_set_read_buffer_size(dbio, ctx->ibuf_size) <= 0 || BIO_set_write_buffer_size(dbio, ctx->obuf_size) <= 0) ret = 0; break; case BIO_CTRL_PEEK: /* Ensure there's stuff in the input buffer */ { char fake_buf[1]; (void)buffer_read(b, fake_buf, 0); } if (num > ctx->ibuf_len) num = ctx->ibuf_len; memcpy(ptr, &(ctx->ibuf[ctx->ibuf_off]), num); ret = num; break; default: if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } return ret; } static long buffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { if (b->next_bio == NULL) return 0; return BIO_callback_ctrl(b->next_bio, cmd, fp); } static int buffer_gets(BIO *b, char *buf, int size) { BIO_F_BUFFER_CTX *ctx; int num = 0, i, flag; char *p; ctx = (BIO_F_BUFFER_CTX *)b->ptr; size--; /* reserve space for a '\0' */ BIO_clear_retry_flags(b); for (;;) { if (ctx->ibuf_len > 0) { p = &(ctx->ibuf[ctx->ibuf_off]); flag = 0; for (i = 0; (i < ctx->ibuf_len) && (i < size); i++) { *(buf++) = p[i]; if (p[i] == '\n') { flag = 1; i++; break; } } num += i; size -= i; ctx->ibuf_len -= i; ctx->ibuf_off += i; if (flag || size == 0) { *buf = '\0'; return num; } } else { /* read another chunk */ i = BIO_read(b->next_bio, ctx->ibuf, ctx->ibuf_size); if (i <= 0) { BIO_copy_next_retry(b); *buf = '\0'; if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } ctx->ibuf_len = i; ctx->ibuf_off = 0; } } } static int buffer_puts(BIO *b, const char *str) { return buffer_write(b, str, strlen(str)); }
./openssl/crypto/bio/bio_dump.c
/* * 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 */ /* * Stolen from tjh's ssl/ssl_trc.c stuff. */ #include <stdio.h> #include "bio_local.h" #define DUMP_WIDTH 16 #define DUMP_WIDTH_LESS_INDENT(i) (DUMP_WIDTH - ((i - (i > 6 ? 6 : i) + 3) / 4)) #define SPACE(buf, pos, n) (sizeof(buf) - (pos) > (n)) int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u), void *u, const void *s, int len) { return BIO_dump_indent_cb(cb, u, s, len, 0); } int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u), void *u, const void *v, int len, int indent) { const unsigned char *s = v; int res, ret = 0; char buf[288 + 1]; int i, j, rows, n; unsigned char ch; int dump_width; if (indent < 0) indent = 0; else if (indent > 64) indent = 64; dump_width = DUMP_WIDTH_LESS_INDENT(indent); rows = len / dump_width; if ((rows * dump_width) < len) rows++; for (i = 0; i < rows; i++) { n = BIO_snprintf(buf, sizeof(buf), "%*s%04x - ", indent, "", i * dump_width); for (j = 0; j < dump_width; j++) { if (SPACE(buf, n, 3)) { if (((i * dump_width) + j) >= len) { strcpy(buf + n, " "); } else { ch = *(s + i * dump_width + j) & 0xff; BIO_snprintf(buf + n, 4, "%02x%c", ch, j == 7 ? '-' : ' '); } n += 3; } } if (SPACE(buf, n, 2)) { strcpy(buf + n, " "); n += 2; } for (j = 0; j < dump_width; j++) { if (((i * dump_width) + j) >= len) break; if (SPACE(buf, n, 1)) { ch = *(s + i * dump_width + j) & 0xff; #ifndef CHARSET_EBCDIC buf[n++] = ((ch >= ' ') && (ch <= '~')) ? ch : '.'; #else buf[n++] = ((ch >= os_toascii[' ']) && (ch <= os_toascii['~'])) ? os_toebcdic[ch] : '.'; #endif buf[n] = '\0'; } } if (SPACE(buf, n, 1)) { buf[n++] = '\n'; buf[n] = '\0'; } /* * if this is the last call then update the ddt_dump thing so that we * will move the selection point in the debug window */ res = cb((void *)buf, n, u); if (res < 0) return res; ret += res; } return ret; } #ifndef OPENSSL_NO_STDIO static int write_fp(const void *data, size_t len, void *fp) { return UP_fwrite(data, len, 1, fp); } int BIO_dump_fp(FILE *fp, const void *s, int len) { return BIO_dump_cb(write_fp, fp, s, len); } int BIO_dump_indent_fp(FILE *fp, const void *s, int len, int indent) { return BIO_dump_indent_cb(write_fp, fp, s, len, indent); } #endif static int write_bio(const void *data, size_t len, void *bp) { return BIO_write((BIO *)bp, (const char *)data, len); } int BIO_dump(BIO *bp, const void *s, int len) { return BIO_dump_cb(write_bio, bp, s, len); } int BIO_dump_indent(BIO *bp, const void *s, int len, int indent) { return BIO_dump_indent_cb(write_bio, bp, s, len, indent); } int BIO_hex_string(BIO *out, int indent, int width, const void *data, int datalen) { const unsigned char *d = data; int i, j = 0; if (datalen < 1) return 1; for (i = 0; i < datalen - 1; i++) { if (i && !j) BIO_printf(out, "%*s", indent, ""); BIO_printf(out, "%02X:", d[i]); if (++j >= width) { j = 0; BIO_printf(out, "\n"); } } if (i && !j) BIO_printf(out, "%*s", indent, ""); BIO_printf(out, "%02X", d[datalen - 1]); return 1; }
./openssl/crypto/bio/bss_acpt.c
/* * 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 */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <errno.h> #include "bio_local.h" #ifndef OPENSSL_NO_SOCK typedef struct bio_accept_st { int state; int accept_family; int bind_mode; /* Socket mode for BIO_listen */ int accepted_mode; /* Socket mode for BIO_accept (set on accepted sock) */ char *param_addr; char *param_serv; int accept_sock; BIO_ADDRINFO *addr_first; const BIO_ADDRINFO *addr_iter; BIO_ADDR cache_accepting_addr; /* Useful if we asked for port 0 */ char *cache_accepting_name, *cache_accepting_serv; BIO_ADDR cache_peer_addr; char *cache_peer_name, *cache_peer_serv; BIO *bio_chain; } BIO_ACCEPT; static int acpt_write(BIO *h, const char *buf, int num); static int acpt_read(BIO *h, char *buf, int size); static int acpt_puts(BIO *h, const char *str); static long acpt_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int acpt_new(BIO *h); static int acpt_free(BIO *data); static int acpt_state(BIO *b, BIO_ACCEPT *c); static void acpt_close_socket(BIO *data); static BIO_ACCEPT *BIO_ACCEPT_new(void); static void BIO_ACCEPT_free(BIO_ACCEPT *a); # define ACPT_S_BEFORE 1 # define ACPT_S_GET_ADDR 2 # define ACPT_S_CREATE_SOCKET 3 # define ACPT_S_LISTEN 4 # define ACPT_S_ACCEPT 5 # define ACPT_S_OK 6 static const BIO_METHOD methods_acceptp = { BIO_TYPE_ACCEPT, "socket accept", bwrite_conv, acpt_write, bread_conv, acpt_read, acpt_puts, NULL, /* connect_gets, */ acpt_ctrl, acpt_new, acpt_free, NULL, /* connect_callback_ctrl */ }; const BIO_METHOD *BIO_s_accept(void) { return &methods_acceptp; } static int acpt_new(BIO *bi) { BIO_ACCEPT *ba; bi->init = 0; bi->num = (int)INVALID_SOCKET; bi->flags = 0; if ((ba = BIO_ACCEPT_new()) == NULL) return 0; bi->ptr = (char *)ba; ba->state = ACPT_S_BEFORE; bi->shutdown = 1; return 1; } static BIO_ACCEPT *BIO_ACCEPT_new(void) { BIO_ACCEPT *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->accept_family = BIO_FAMILY_IPANY; ret->accept_sock = (int)INVALID_SOCKET; return ret; } static void BIO_ACCEPT_free(BIO_ACCEPT *a) { if (a == NULL) return; OPENSSL_free(a->param_addr); OPENSSL_free(a->param_serv); BIO_ADDRINFO_free(a->addr_first); OPENSSL_free(a->cache_accepting_name); OPENSSL_free(a->cache_accepting_serv); OPENSSL_free(a->cache_peer_name); OPENSSL_free(a->cache_peer_serv); BIO_free(a->bio_chain); OPENSSL_free(a); } static void acpt_close_socket(BIO *bio) { BIO_ACCEPT *c; c = (BIO_ACCEPT *)bio->ptr; if (c->accept_sock != (int)INVALID_SOCKET) { shutdown(c->accept_sock, 2); closesocket(c->accept_sock); c->accept_sock = (int)INVALID_SOCKET; bio->num = (int)INVALID_SOCKET; } } static int acpt_free(BIO *a) { BIO_ACCEPT *data; if (a == NULL) return 0; data = (BIO_ACCEPT *)a->ptr; if (a->shutdown) { acpt_close_socket(a); BIO_ACCEPT_free(data); a->ptr = NULL; a->flags = 0; a->init = 0; } return 1; } static int acpt_state(BIO *b, BIO_ACCEPT *c) { BIO *bio = NULL, *dbio; int s = -1, ret = -1; for (;;) { switch (c->state) { case ACPT_S_BEFORE: if (c->param_addr == NULL && c->param_serv == NULL) { ERR_raise_data(ERR_LIB_BIO, BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED, "hostname=%s, service=%s", c->param_addr, c->param_serv); goto exit_loop; } /* Because we're starting a new bind, any cached name and serv * are now obsolete and need to be cleaned out. * QUESTION: should this be done in acpt_close_socket() instead? */ OPENSSL_free(c->cache_accepting_name); c->cache_accepting_name = NULL; OPENSSL_free(c->cache_accepting_serv); c->cache_accepting_serv = NULL; OPENSSL_free(c->cache_peer_name); c->cache_peer_name = NULL; OPENSSL_free(c->cache_peer_serv); c->cache_peer_serv = NULL; c->state = ACPT_S_GET_ADDR; break; case ACPT_S_GET_ADDR: { int family = AF_UNSPEC; switch (c->accept_family) { case BIO_FAMILY_IPV6: if (1) { /* This is a trick we use to avoid bit rot. * at least the "else" part will always be * compiled. */ #if OPENSSL_USE_IPV6 family = AF_INET6; } else { #endif ERR_raise(ERR_LIB_BIO, BIO_R_UNAVAILABLE_IP_FAMILY); goto exit_loop; } break; case BIO_FAMILY_IPV4: family = AF_INET; break; case BIO_FAMILY_IPANY: family = AF_UNSPEC; break; default: ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_IP_FAMILY); goto exit_loop; } if (BIO_lookup(c->param_addr, c->param_serv, BIO_LOOKUP_SERVER, family, SOCK_STREAM, &c->addr_first) == 0) goto exit_loop; } if (c->addr_first == NULL) { ERR_raise(ERR_LIB_BIO, BIO_R_LOOKUP_RETURNED_NOTHING); goto exit_loop; } c->addr_iter = c->addr_first; c->state = ACPT_S_CREATE_SOCKET; break; case ACPT_S_CREATE_SOCKET: ERR_set_mark(); s = BIO_socket(BIO_ADDRINFO_family(c->addr_iter), BIO_ADDRINFO_socktype(c->addr_iter), BIO_ADDRINFO_protocol(c->addr_iter), 0); if (s == (int)INVALID_SOCKET) { if ((c->addr_iter = BIO_ADDRINFO_next(c->addr_iter)) != NULL) { /* * if there are more addresses to try, do that first */ ERR_pop_to_mark(); break; } ERR_clear_last_mark(); ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling socket(%s, %s)", c->param_addr, c->param_serv); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_CREATE_SOCKET); goto exit_loop; } c->accept_sock = s; b->num = s; c->state = ACPT_S_LISTEN; s = -1; break; case ACPT_S_LISTEN: { if (!BIO_listen(c->accept_sock, BIO_ADDRINFO_address(c->addr_iter), c->bind_mode)) { BIO_closesocket(c->accept_sock); goto exit_loop; } } { union BIO_sock_info_u info; info.addr = &c->cache_accepting_addr; if (!BIO_sock_info(c->accept_sock, BIO_SOCK_INFO_ADDRESS, &info)) { BIO_closesocket(c->accept_sock); goto exit_loop; } } c->cache_accepting_name = BIO_ADDR_hostname_string(&c->cache_accepting_addr, 1); c->cache_accepting_serv = BIO_ADDR_service_string(&c->cache_accepting_addr, 1); c->state = ACPT_S_ACCEPT; s = -1; ret = 1; goto end; case ACPT_S_ACCEPT: if (b->next_bio != NULL) { c->state = ACPT_S_OK; break; } BIO_clear_retry_flags(b); b->retry_reason = 0; OPENSSL_free(c->cache_peer_name); c->cache_peer_name = NULL; OPENSSL_free(c->cache_peer_serv); c->cache_peer_serv = NULL; s = BIO_accept_ex(c->accept_sock, &c->cache_peer_addr, c->accepted_mode); /* If the returned socket is invalid, this might still be * retryable */ if (s < 0) { if (BIO_sock_should_retry(s)) { BIO_set_retry_special(b); b->retry_reason = BIO_RR_ACCEPT; goto end; } } /* If it wasn't retryable, we fail */ if (s < 0) { ret = s; goto exit_loop; } bio = BIO_new_socket(s, BIO_CLOSE); if (bio == NULL) goto exit_loop; BIO_set_callback_ex(bio, BIO_get_callback_ex(b)); #ifndef OPENSSL_NO_DEPRECATED_3_0 BIO_set_callback(bio, BIO_get_callback(b)); #endif BIO_set_callback_arg(bio, BIO_get_callback_arg(b)); /* * If the accept BIO has an bio_chain, we dup it and put the new * socket at the end. */ if (c->bio_chain != NULL) { if ((dbio = BIO_dup_chain(c->bio_chain)) == NULL) goto exit_loop; if (!BIO_push(dbio, bio)) goto exit_loop; bio = dbio; } if (BIO_push(b, bio) == NULL) goto exit_loop; c->cache_peer_name = BIO_ADDR_hostname_string(&c->cache_peer_addr, 1); c->cache_peer_serv = BIO_ADDR_service_string(&c->cache_peer_addr, 1); c->state = ACPT_S_OK; bio = NULL; ret = 1; goto end; case ACPT_S_OK: if (b->next_bio == NULL) { c->state = ACPT_S_ACCEPT; break; } ret = 1; goto end; default: ret = 0; goto end; } } exit_loop: if (bio != NULL) BIO_free(bio); else if (s >= 0) BIO_closesocket(s); end: return ret; } static int acpt_read(BIO *b, char *out, int outl) { int ret = 0; BIO_ACCEPT *data; BIO_clear_retry_flags(b); data = (BIO_ACCEPT *)b->ptr; while (b->next_bio == NULL) { ret = acpt_state(b, data); if (ret <= 0) return ret; } ret = BIO_read(b->next_bio, out, outl); BIO_copy_next_retry(b); return ret; } static int acpt_write(BIO *b, const char *in, int inl) { int ret; BIO_ACCEPT *data; BIO_clear_retry_flags(b); data = (BIO_ACCEPT *)b->ptr; while (b->next_bio == NULL) { ret = acpt_state(b, data); if (ret <= 0) return ret; } ret = BIO_write(b->next_bio, in, inl); BIO_copy_next_retry(b); return ret; } static long acpt_ctrl(BIO *b, int cmd, long num, void *ptr) { int *ip; long ret = 1; BIO_ACCEPT *data; char **pp; data = (BIO_ACCEPT *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: ret = 0; data->state = ACPT_S_BEFORE; acpt_close_socket(b); BIO_ADDRINFO_free(data->addr_first); data->addr_first = NULL; b->flags = 0; break; case BIO_C_DO_STATE_MACHINE: /* use this one to start the connection */ ret = (long)acpt_state(b, data); break; case BIO_C_SET_ACCEPT: if (ptr != NULL) { if (num == 0) { char *hold_serv = data->param_serv; /* We affect the hostname regardless. However, the input * string might contain a host:service spec, so we must * parse it, which might or might not affect the service */ OPENSSL_free(data->param_addr); data->param_addr = NULL; ret = BIO_parse_hostserv(ptr, &data->param_addr, &data->param_serv, BIO_PARSE_PRIO_SERV); if (hold_serv != data->param_serv) OPENSSL_free(hold_serv); b->init = 1; } else if (num == 1) { OPENSSL_free(data->param_serv); if ((data->param_serv = OPENSSL_strdup(ptr)) == NULL) ret = 0; else b->init = 1; } else if (num == 2) { data->bind_mode |= BIO_SOCK_NONBLOCK; } else if (num == 3) { BIO_free(data->bio_chain); data->bio_chain = (BIO *)ptr; } else if (num == 4) { data->accept_family = *(int *)ptr; } else if (num == 5) { data->bind_mode |= BIO_SOCK_TFO; } } else { if (num == 2) { data->bind_mode &= ~BIO_SOCK_NONBLOCK; } else if (num == 5) { data->bind_mode &= ~BIO_SOCK_TFO; } } break; case BIO_C_SET_NBIO: if (num != 0) data->accepted_mode |= BIO_SOCK_NONBLOCK; else data->accepted_mode &= ~BIO_SOCK_NONBLOCK; break; case BIO_C_SET_FD: b->num = *((int *)ptr); data->accept_sock = b->num; data->state = ACPT_S_ACCEPT; b->shutdown = (int)num; b->init = 1; break; case BIO_C_GET_FD: if (b->init) { ip = (int *)ptr; if (ip != NULL) *ip = data->accept_sock; ret = data->accept_sock; } else ret = -1; break; case BIO_C_GET_ACCEPT: if (b->init) { if (num == 0 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_accepting_name; } else if (num == 1 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_accepting_serv; } else if (num == 2 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_peer_name; } else if (num == 3 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_peer_serv; } else if (num == 4) { switch (BIO_ADDRINFO_family(data->addr_iter)) { #if OPENSSL_USE_IPV6 case AF_INET6: ret = BIO_FAMILY_IPV6; break; #endif case AF_INET: ret = BIO_FAMILY_IPV4; break; case 0: ret = data->accept_family; break; default: ret = -1; break; } } else ret = -1; } else ret = -1; break; case BIO_CTRL_GET_CLOSE: ret = b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown = (int)num; break; case BIO_CTRL_PENDING: case BIO_CTRL_WPENDING: ret = 0; break; case BIO_CTRL_FLUSH: break; case BIO_C_SET_BIND_MODE: data->bind_mode = (int)num; break; case BIO_C_GET_BIND_MODE: ret = (long)data->bind_mode; break; case BIO_CTRL_DUP: break; case BIO_CTRL_EOF: if (b->next_bio == NULL) ret = 0; else ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; default: ret = 0; break; } return ret; } static int acpt_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = acpt_write(bp, str, n); return ret; } BIO *BIO_new_accept(const char *str) { BIO *ret; ret = BIO_new(BIO_s_accept()); if (ret == NULL) return NULL; if (BIO_set_accept_name(ret, str) > 0) return ret; BIO_free(ret); return NULL; } #endif
./openssl/crypto/bio/bss_file.c
/* * 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 */ #if defined(__linux) || defined(__sun) || defined(__hpux) /* * Following definition aliases fopen to fopen64 on above mentioned * platforms. This makes it possible to open and sequentially access files * larger than 2GB from 32-bit application. It does not allow one to traverse * them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit * platform permits that, not with fseek/ftell. Not to mention that breaking * 2GB limit for seeking would require surgery to *our* API. But sequential * access suffices for practical cases when you can run into large files, * such as fingerprinting, so we can let API alone. For reference, the list * of 32-bit platforms which allow for sequential access of large files * without extra "magic" comprise *BSD, Darwin, IRIX... */ # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif #endif #include <stdio.h> #include <errno.h> #include "bio_local.h" #include <openssl/err.h> #if !defined(OPENSSL_NO_STDIO) static int file_write(BIO *h, const char *buf, int num); static int file_read(BIO *h, char *buf, int size); static int file_puts(BIO *h, const char *str); static int file_gets(BIO *h, char *str, int size); static long file_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int file_new(BIO *h); static int file_free(BIO *data); static const BIO_METHOD methods_filep = { BIO_TYPE_FILE, "FILE pointer", bwrite_conv, file_write, bread_conv, file_read, file_puts, file_gets, file_ctrl, file_new, file_free, NULL, /* file_callback_ctrl */ }; BIO *BIO_new_file(const char *filename, const char *mode) { BIO *ret; FILE *file = openssl_fopen(filename, mode); int fp_flags = BIO_CLOSE; if (strchr(mode, 'b') == NULL) fp_flags |= BIO_FP_TEXT; if (file == NULL) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fopen(%s, %s)", filename, mode); if (errno == ENOENT #ifdef ENXIO || errno == ENXIO #endif ) ERR_raise(ERR_LIB_BIO, BIO_R_NO_SUCH_FILE); else ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); return NULL; } if ((ret = BIO_new(BIO_s_file())) == NULL) { fclose(file); return NULL; } /* we did fopen -> we disengage UPLINK */ BIO_clear_flags(ret, BIO_FLAGS_UPLINK_INTERNAL); BIO_set_fp(ret, file, fp_flags); return ret; } BIO *BIO_new_fp(FILE *stream, int close_flag) { BIO *ret; if ((ret = BIO_new(BIO_s_file())) == NULL) return NULL; /* redundant flag, left for documentation purposes */ BIO_set_flags(ret, BIO_FLAGS_UPLINK_INTERNAL); BIO_set_fp(ret, stream, close_flag); return ret; } const BIO_METHOD *BIO_s_file(void) { return &methods_filep; } static int file_new(BIO *bi) { bi->init = 0; bi->num = 0; bi->ptr = NULL; bi->flags = BIO_FLAGS_UPLINK_INTERNAL; /* default to UPLINK */ return 1; } static int file_free(BIO *a) { if (a == NULL) return 0; if (a->shutdown) { if ((a->init) && (a->ptr != NULL)) { if (a->flags & BIO_FLAGS_UPLINK_INTERNAL) UP_fclose(a->ptr); else fclose(a->ptr); a->ptr = NULL; a->flags = BIO_FLAGS_UPLINK_INTERNAL; } a->init = 0; } return 1; } static int file_read(BIO *b, char *out, int outl) { int ret = 0; if (b->init && (out != NULL)) { if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = UP_fread(out, 1, (int)outl, b->ptr); else ret = fread(out, 1, (int)outl, (FILE *)b->ptr); if (ret == 0 && (b->flags & BIO_FLAGS_UPLINK_INTERNAL ? UP_ferror((FILE *)b->ptr) : ferror((FILE *)b->ptr))) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fread()"); ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); ret = -1; } } return ret; } static int file_write(BIO *b, const char *in, int inl) { int ret = 0; if (b->init && (in != NULL)) { if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = UP_fwrite(in, (int)inl, 1, b->ptr); else ret = fwrite(in, (int)inl, 1, (FILE *)b->ptr); if (ret) ret = inl; /* ret=fwrite(in,1,(int)inl,(FILE *)b->ptr); */ /* * according to Tim Hudson <tjh@openssl.org>, the commented out * version above can cause 'inl' write calls under some stupid stdio * implementations (VMS) */ } return ret; } static long file_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret = 1; FILE *fp = (FILE *)b->ptr; FILE **fpp; char p[4]; int st; switch (cmd) { case BIO_C_FILE_SEEK: case BIO_CTRL_RESET: if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = (long)UP_fseek(b->ptr, num, 0); else ret = (long)fseek(fp, num, 0); break; case BIO_CTRL_EOF: if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = (long)UP_feof(fp); else ret = (long)feof(fp); break; case BIO_C_FILE_TELL: case BIO_CTRL_INFO: if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) ret = UP_ftell(b->ptr); else ret = ftell(fp); break; case BIO_C_SET_FILE_PTR: file_free(b); b->shutdown = (int)num & BIO_CLOSE; b->ptr = ptr; b->init = 1; # if BIO_FLAGS_UPLINK_INTERNAL!=0 # if defined(__MINGW32__) && defined(__MSVCRT__) && !defined(_IOB_ENTRIES) # define _IOB_ENTRIES 20 # endif /* Safety net to catch purely internal BIO_set_fp calls */ # if (defined(_MSC_VER) && _MSC_VER>=1900) || defined(__BORLANDC__) if (ptr == stdin || ptr == stdout || ptr == stderr) BIO_clear_flags(b, BIO_FLAGS_UPLINK_INTERNAL); # elif defined(_IOB_ENTRIES) if ((size_t)ptr >= (size_t)stdin && (size_t)ptr < (size_t)(stdin + _IOB_ENTRIES)) BIO_clear_flags(b, BIO_FLAGS_UPLINK_INTERNAL); # endif # endif # ifdef UP_fsetmod if (b->flags & BIO_FLAGS_UPLINK_INTERNAL) UP_fsetmod(b->ptr, (char)((num & BIO_FP_TEXT) ? 't' : 'b')); else # endif { # if defined(OPENSSL_SYS_WINDOWS) int fd = _fileno((FILE *)ptr); if (num & BIO_FP_TEXT) _setmode(fd, _O_TEXT); else _setmode(fd, _O_BINARY); /* * Reports show that ftell() isn't trustable in text mode. * This has been confirmed as a bug in the Universal C RTL, see * https://developercommunity.visualstudio.com/content/problem/425878/fseek-ftell-fail-in-text-mode-for-unix-style-text.html * The suggested work-around from Microsoft engineering is to * turn off buffering until the bug is resolved. */ if ((num & BIO_FP_TEXT) != 0) setvbuf((FILE *)ptr, NULL, _IONBF, 0); # elif defined(OPENSSL_SYS_MSDOS) int fd = fileno((FILE *)ptr); /* Set correct text/binary mode */ if (num & BIO_FP_TEXT) _setmode(fd, _O_TEXT); /* Dangerous to set stdin/stdout to raw (unless redirected) */ else { if (fd == STDIN_FILENO || fd == STDOUT_FILENO) { if (isatty(fd) <= 0) _setmode(fd, _O_BINARY); } else _setmode(fd, _O_BINARY); } # elif defined(OPENSSL_SYS_WIN32_CYGWIN) int fd = fileno((FILE *)ptr); if (!(num & BIO_FP_TEXT)) setmode(fd, O_BINARY); # endif } break; case BIO_C_SET_FILENAME: file_free(b); b->shutdown = (int)num & BIO_CLOSE; if (num & BIO_FP_APPEND) { if (num & BIO_FP_READ) OPENSSL_strlcpy(p, "a+", sizeof(p)); else OPENSSL_strlcpy(p, "a", sizeof(p)); } else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE)) OPENSSL_strlcpy(p, "r+", sizeof(p)); else if (num & BIO_FP_WRITE) OPENSSL_strlcpy(p, "w", sizeof(p)); else if (num & BIO_FP_READ) OPENSSL_strlcpy(p, "r", sizeof(p)); else { ERR_raise(ERR_LIB_BIO, BIO_R_BAD_FOPEN_MODE); ret = 0; break; } # if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) if (!(num & BIO_FP_TEXT)) OPENSSL_strlcat(p, "b", sizeof(p)); else OPENSSL_strlcat(p, "t", sizeof(p)); # elif defined(OPENSSL_SYS_WIN32_CYGWIN) if (!(num & BIO_FP_TEXT)) OPENSSL_strlcat(p, "b", sizeof(p)); # endif fp = openssl_fopen(ptr, p); if (fp == NULL) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fopen(%s, %s)", ptr, p); ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); ret = 0; break; } b->ptr = fp; b->init = 1; /* we did fopen -> we disengage UPLINK */ BIO_clear_flags(b, BIO_FLAGS_UPLINK_INTERNAL); break; case BIO_C_GET_FILE_PTR: /* the ptr parameter is actually a FILE ** in this case. */ if (ptr != NULL) { fpp = (FILE **)ptr; *fpp = (FILE *)b->ptr; } break; case BIO_CTRL_GET_CLOSE: ret = (long)b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown = (int)num; break; case BIO_CTRL_FLUSH: st = b->flags & BIO_FLAGS_UPLINK_INTERNAL ? UP_fflush(b->ptr) : fflush((FILE *)b->ptr); if (st == EOF) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fflush()"); ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); ret = 0; } break; case BIO_CTRL_DUP: ret = 1; break; case BIO_CTRL_WPENDING: case BIO_CTRL_PENDING: case BIO_CTRL_PUSH: case BIO_CTRL_POP: default: ret = 0; break; } return ret; } static int file_gets(BIO *bp, char *buf, int size) { int ret = 0; buf[0] = '\0'; if (bp->flags & BIO_FLAGS_UPLINK_INTERNAL) { if (!UP_fgets(buf, size, bp->ptr)) goto err; } else { if (!fgets(buf, size, (FILE *)bp->ptr)) goto err; } if (buf[0] != '\0') ret = strlen(buf); err: return ret; } static int file_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = file_write(bp, str, n); return ret; } #else static int file_write(BIO *b, const char *in, int inl) { return -1; } static int file_read(BIO *b, char *out, int outl) { return -1; } static int file_puts(BIO *bp, const char *str) { return -1; } static int file_gets(BIO *bp, char *buf, int size) { return 0; } static long file_ctrl(BIO *b, int cmd, long num, void *ptr) { return 0; } static int file_new(BIO *bi) { return 0; } static int file_free(BIO *a) { return 0; } static const BIO_METHOD methods_filep = { BIO_TYPE_FILE, "FILE pointer", bwrite_conv, file_write, bread_conv, file_read, file_puts, file_gets, file_ctrl, file_new, file_free, NULL, /* file_callback_ctrl */ }; const BIO_METHOD *BIO_s_file(void) { return &methods_filep; } BIO *BIO_new_file(const char *filename, const char *mode) { return NULL; } #endif /* OPENSSL_NO_STDIO */
./openssl/crypto/bio/bio_addr.c
/* * 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 _GNU_SOURCE # define _GNU_SOURCE #endif /* * VC configurations may define UNICODE, to indicate to the C RTL that * WCHAR functions are preferred. * This affects functions like gai_strerror(), which is implemented as * an alias macro for gai_strerrorA() (which returns a const char *) or * gai_strerrorW() (which returns a const WCHAR *). This source file * assumes POSIX declarations, so prefer the non-UNICODE definitions. */ #undef UNICODE #include <assert.h> #include <string.h> #include "bio_local.h" #include <openssl/crypto.h> #ifndef OPENSSL_NO_SOCK #include <openssl/err.h> #include <openssl/buffer.h> #include "internal/thread_once.h" CRYPTO_RWLOCK *bio_lookup_lock; static CRYPTO_ONCE bio_lookup_init = CRYPTO_ONCE_STATIC_INIT; /* * Throughout this file and bio_local.h, the existence of the macro * AI_PASSIVE is used to detect the availability of struct addrinfo, * getnameinfo() and getaddrinfo(). If that macro doesn't exist, * we use our own implementation instead, using gethostbyname, * getservbyname and a few other. */ /********************************************************************** * * Address structure * */ BIO_ADDR *BIO_ADDR_new(void) { BIO_ADDR *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->sa.sa_family = AF_UNSPEC; return ret; } void BIO_ADDR_free(BIO_ADDR *ap) { OPENSSL_free(ap); } int BIO_ADDR_copy(BIO_ADDR *dst, const BIO_ADDR *src) { if (dst == NULL || src == NULL) return 0; if (src->sa.sa_family == AF_UNSPEC) { BIO_ADDR_clear(dst); return 1; } return BIO_ADDR_make(dst, &src->sa); } BIO_ADDR *BIO_ADDR_dup(const BIO_ADDR *ap) { BIO_ADDR *ret = NULL; if (ap != NULL) { ret = BIO_ADDR_new(); if (ret != NULL && !BIO_ADDR_copy(ret, ap)) { BIO_ADDR_free(ret); ret = NULL; } } return ret; } void BIO_ADDR_clear(BIO_ADDR *ap) { memset(ap, 0, sizeof(*ap)); ap->sa.sa_family = AF_UNSPEC; } /* * BIO_ADDR_make - non-public routine to fill a BIO_ADDR with the contents * of a struct sockaddr. */ int BIO_ADDR_make(BIO_ADDR *ap, const struct sockaddr *sa) { if (sa->sa_family == AF_INET) { memcpy(&(ap->s_in), sa, sizeof(struct sockaddr_in)); return 1; } #if OPENSSL_USE_IPV6 if (sa->sa_family == AF_INET6) { memcpy(&(ap->s_in6), sa, sizeof(struct sockaddr_in6)); return 1; } #endif #ifndef OPENSSL_NO_UNIX_SOCK if (sa->sa_family == AF_UNIX) { memcpy(&(ap->s_un), sa, sizeof(struct sockaddr_un)); return 1; } #endif return 0; } int BIO_ADDR_rawmake(BIO_ADDR *ap, int family, const void *where, size_t wherelen, unsigned short port) { #ifndef OPENSSL_NO_UNIX_SOCK if (family == AF_UNIX) { if (wherelen + 1 > sizeof(ap->s_un.sun_path)) return 0; memset(&ap->s_un, 0, sizeof(ap->s_un)); ap->s_un.sun_family = family; strncpy(ap->s_un.sun_path, where, sizeof(ap->s_un.sun_path) - 1); return 1; } #endif if (family == AF_INET) { if (wherelen != sizeof(struct in_addr)) return 0; memset(&ap->s_in, 0, sizeof(ap->s_in)); ap->s_in.sin_family = family; ap->s_in.sin_port = port; ap->s_in.sin_addr = *(struct in_addr *)where; return 1; } #if OPENSSL_USE_IPV6 if (family == AF_INET6) { if (wherelen != sizeof(struct in6_addr)) return 0; memset(&ap->s_in6, 0, sizeof(ap->s_in6)); ap->s_in6.sin6_family = family; ap->s_in6.sin6_port = port; ap->s_in6.sin6_addr = *(struct in6_addr *)where; return 1; } #endif return 0; } int BIO_ADDR_family(const BIO_ADDR *ap) { return ap->sa.sa_family; } int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l) { size_t len = 0; const void *addrptr = NULL; if (ap->sa.sa_family == AF_INET) { len = sizeof(ap->s_in.sin_addr); addrptr = &ap->s_in.sin_addr; } #if OPENSSL_USE_IPV6 else if (ap->sa.sa_family == AF_INET6) { len = sizeof(ap->s_in6.sin6_addr); addrptr = &ap->s_in6.sin6_addr; } #endif #ifndef OPENSSL_NO_UNIX_SOCK else if (ap->sa.sa_family == AF_UNIX) { len = strlen(ap->s_un.sun_path); addrptr = &ap->s_un.sun_path; } #endif if (addrptr == NULL) return 0; if (p != NULL) { memcpy(p, addrptr, len); } if (l != NULL) *l = len; return 1; } unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap) { if (ap->sa.sa_family == AF_INET) return ap->s_in.sin_port; #if OPENSSL_USE_IPV6 if (ap->sa.sa_family == AF_INET6) return ap->s_in6.sin6_port; #endif return 0; } /*- * addr_strings - helper function to get host and service names * @ap: the BIO_ADDR that has the input info * @numeric: 0 if actual names should be returned, 1 if the numeric * representation should be returned. * @hostname: a pointer to a pointer to a memory area to store the * hostname or numeric representation. Unused if NULL. * @service: a pointer to a pointer to a memory area to store the * service name or numeric representation. Unused if NULL. * * The return value is 0 on failure, with the error code in the error * stack, and 1 on success. */ static int addr_strings(const BIO_ADDR *ap, int numeric, char **hostname, char **service) { if (BIO_sock_init() != 1) return 0; if (1) { #ifdef AI_PASSIVE int ret = 0; char host[NI_MAXHOST] = "", serv[NI_MAXSERV] = ""; int flags = 0; if (numeric) flags |= NI_NUMERICHOST | NI_NUMERICSERV; if ((ret = getnameinfo(BIO_ADDR_sockaddr(ap), BIO_ADDR_sockaddr_size(ap), host, sizeof(host), serv, sizeof(serv), flags)) != 0) { # ifdef EAI_SYSTEM if (ret == EAI_SYSTEM) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling getnameinfo()"); } else # endif { ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB, gai_strerror(ret)); } return 0; } /* VMS getnameinfo() has a bug, it doesn't fill in serv, which * leaves it with whatever garbage that happens to be there. * However, we initialise serv with the empty string (serv[0] * is therefore NUL), so it gets real easy to detect when things * didn't go the way one might expect. */ if (serv[0] == '\0') { BIO_snprintf(serv, sizeof(serv), "%d", ntohs(BIO_ADDR_rawport(ap))); } if (hostname != NULL) *hostname = OPENSSL_strdup(host); if (service != NULL) *service = OPENSSL_strdup(serv); } else { #endif if (hostname != NULL) *hostname = OPENSSL_strdup(inet_ntoa(ap->s_in.sin_addr)); if (service != NULL) { char serv[6]; /* port is 16 bits => max 5 decimal digits */ BIO_snprintf(serv, sizeof(serv), "%d", ntohs(ap->s_in.sin_port)); *service = OPENSSL_strdup(serv); } } if ((hostname != NULL && *hostname == NULL) || (service != NULL && *service == NULL)) { if (hostname != NULL) { OPENSSL_free(*hostname); *hostname = NULL; } if (service != NULL) { OPENSSL_free(*service); *service = NULL; } return 0; } return 1; } char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric) { char *hostname = NULL; if (addr_strings(ap, numeric, &hostname, NULL)) return hostname; return NULL; } char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric) { char *service = NULL; if (addr_strings(ap, numeric, NULL, &service)) return service; return NULL; } char *BIO_ADDR_path_string(const BIO_ADDR *ap) { #ifndef OPENSSL_NO_UNIX_SOCK if (ap->sa.sa_family == AF_UNIX) return OPENSSL_strdup(ap->s_un.sun_path); #endif return NULL; } /* * BIO_ADDR_sockaddr - non-public routine to return the struct sockaddr * for a given BIO_ADDR. In reality, this is simply a type safe cast. * The returned struct sockaddr is const, so it can't be tampered with. */ const struct sockaddr *BIO_ADDR_sockaddr(const BIO_ADDR *ap) { return &(ap->sa); } /* * BIO_ADDR_sockaddr_noconst - non-public function that does the same * as BIO_ADDR_sockaddr, but returns a non-const. USE WITH CARE, as * it allows you to tamper with the data (and thereby the contents * of the input BIO_ADDR). */ struct sockaddr *BIO_ADDR_sockaddr_noconst(BIO_ADDR *ap) { return &(ap->sa); } /* * BIO_ADDR_sockaddr_size - non-public function that returns the size * of the struct sockaddr the BIO_ADDR is using. If the protocol family * isn't set or is something other than AF_INET, AF_INET6 or AF_UNIX, * the size of the BIO_ADDR type is returned. */ socklen_t BIO_ADDR_sockaddr_size(const BIO_ADDR *ap) { if (ap->sa.sa_family == AF_INET) return sizeof(ap->s_in); #if OPENSSL_USE_IPV6 if (ap->sa.sa_family == AF_INET6) return sizeof(ap->s_in6); #endif #ifndef OPENSSL_NO_UNIX_SOCK if (ap->sa.sa_family == AF_UNIX) return sizeof(ap->s_un); #endif return sizeof(*ap); } /********************************************************************** * * Address info database * */ const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai) { if (bai != NULL) return bai->bai_next; return NULL; } int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai) { if (bai != NULL) return bai->bai_family; return 0; } int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai) { if (bai != NULL) return bai->bai_socktype; return 0; } int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai) { if (bai != NULL) { if (bai->bai_protocol != 0) return bai->bai_protocol; #ifndef OPENSSL_NO_UNIX_SOCK if (bai->bai_family == AF_UNIX) return 0; #endif switch (bai->bai_socktype) { case SOCK_STREAM: return IPPROTO_TCP; case SOCK_DGRAM: return IPPROTO_UDP; default: break; } } return 0; } /* * BIO_ADDRINFO_sockaddr_size - non-public function that returns the size * of the struct sockaddr inside the BIO_ADDRINFO. */ socklen_t BIO_ADDRINFO_sockaddr_size(const BIO_ADDRINFO *bai) { if (bai != NULL) return bai->bai_addrlen; return 0; } /* * BIO_ADDRINFO_sockaddr - non-public function that returns bai_addr * as the struct sockaddr it is. */ const struct sockaddr *BIO_ADDRINFO_sockaddr(const BIO_ADDRINFO *bai) { if (bai != NULL) return bai->bai_addr; return NULL; } const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai) { if (bai != NULL) return (BIO_ADDR *)bai->bai_addr; return NULL; } void BIO_ADDRINFO_free(BIO_ADDRINFO *bai) { if (bai == NULL) return; #ifdef AI_PASSIVE # ifndef OPENSSL_NO_UNIX_SOCK # define _cond bai->bai_family != AF_UNIX # else # define _cond 1 # endif if (_cond) { freeaddrinfo(bai); return; } #endif /* Free manually when we know that addrinfo_wrap() was used. * See further comment above addrinfo_wrap() */ while (bai != NULL) { BIO_ADDRINFO *next = bai->bai_next; OPENSSL_free(bai->bai_addr); OPENSSL_free(bai); bai = next; } } /********************************************************************** * * Service functions * */ /*- * The specs in hostserv can take these forms: * * host:service => *host = "host", *service = "service" * host:* => *host = "host", *service = NULL * host: => *host = "host", *service = NULL * :service => *host = NULL, *service = "service" * *:service => *host = NULL, *service = "service" * * in case no : is present in the string, the result depends on * hostserv_prio, as follows: * * when hostserv_prio == BIO_PARSE_PRIO_HOST * host => *host = "host", *service untouched * * when hostserv_prio == BIO_PARSE_PRIO_SERV * service => *host untouched, *service = "service" * */ int BIO_parse_hostserv(const char *hostserv, char **host, char **service, enum BIO_hostserv_priorities hostserv_prio) { const char *h = NULL; size_t hl = 0; const char *p = NULL; size_t pl = 0; if (*hostserv == '[') { if ((p = strchr(hostserv, ']')) == NULL) goto spec_err; h = hostserv + 1; hl = p - h; p++; if (*p == '\0') p = NULL; else if (*p != ':') goto spec_err; else { p++; pl = strlen(p); } } else { const char *p2 = strrchr(hostserv, ':'); p = strchr(hostserv, ':'); /*- * Check for more than one colon. There are three possible * interpretations: * 1. IPv6 address with port number, last colon being separator. * 2. IPv6 address only. * 3. IPv6 address only if hostserv_prio == BIO_PARSE_PRIO_HOST, * IPv6 address and port number if hostserv_prio == BIO_PARSE_PRIO_SERV * Because of this ambiguity, we currently choose to make it an * error. */ if (p != p2) goto amb_err; if (p != NULL) { h = hostserv; hl = p - h; p++; pl = strlen(p); } else if (hostserv_prio == BIO_PARSE_PRIO_HOST) { h = hostserv; hl = strlen(h); } else { p = hostserv; pl = strlen(p); } } if (p != NULL && strchr(p, ':')) goto spec_err; if (h != NULL && host != NULL) { if (hl == 0 || (hl == 1 && h[0] == '*')) { *host = NULL; } else { *host = OPENSSL_strndup(h, hl); if (*host == NULL) return 0; } } if (p != NULL && service != NULL) { if (pl == 0 || (pl == 1 && p[0] == '*')) { *service = NULL; } else { *service = OPENSSL_strndup(p, pl); if (*service == NULL) return 0; } } return 1; amb_err: ERR_raise(ERR_LIB_BIO, BIO_R_AMBIGUOUS_HOST_OR_SERVICE); return 0; spec_err: ERR_raise(ERR_LIB_BIO, BIO_R_MALFORMED_HOST_OR_SERVICE); return 0; } /* addrinfo_wrap is used to build our own addrinfo "chain". * (it has only one entry, so calling it a chain may be a stretch) * It should ONLY be called when getaddrinfo() and friends * aren't available, OR when dealing with a non IP protocol * family, such as AF_UNIX * * the return value is 1 on success, or 0 on failure, which * only happens if a memory allocation error occurred. */ static int addrinfo_wrap(int family, int socktype, const void *where, size_t wherelen, unsigned short port, BIO_ADDRINFO **bai) { if ((*bai = OPENSSL_zalloc(sizeof(**bai))) == NULL) return 0; (*bai)->bai_family = family; (*bai)->bai_socktype = socktype; if (socktype == SOCK_STREAM) (*bai)->bai_protocol = IPPROTO_TCP; if (socktype == SOCK_DGRAM) (*bai)->bai_protocol = IPPROTO_UDP; #ifndef OPENSSL_NO_UNIX_SOCK if (family == AF_UNIX) (*bai)->bai_protocol = 0; #endif { /* Magic: We know that BIO_ADDR_sockaddr_noconst is really just an advanced cast of BIO_ADDR* to struct sockaddr * by the power of union, so while it may seem that we're creating a memory leak here, we are not. It will be all right. */ BIO_ADDR *addr = BIO_ADDR_new(); if (addr != NULL) { BIO_ADDR_rawmake(addr, family, where, wherelen, port); (*bai)->bai_addr = BIO_ADDR_sockaddr_noconst(addr); } } (*bai)->bai_next = NULL; if ((*bai)->bai_addr == NULL) { BIO_ADDRINFO_free(*bai); *bai = NULL; return 0; } return 1; } DEFINE_RUN_ONCE_STATIC(do_bio_lookup_init) { bio_lookup_lock = CRYPTO_THREAD_lock_new(); return bio_lookup_lock != NULL; } int BIO_lookup(const char *host, const char *service, enum BIO_lookup_type lookup_type, int family, int socktype, BIO_ADDRINFO **res) { return BIO_lookup_ex(host, service, lookup_type, family, socktype, 0, res); } /*- * BIO_lookup_ex - look up the host and service you want to connect to. * @host: the host (or node, in case family == AF_UNIX) you want to connect to. * @service: the service you want to connect to. * @lookup_type: declare intent with the result, client or server. * @family: the address family you want to use. Use AF_UNSPEC for any, or * AF_INET, AF_INET6 or AF_UNIX. * @socktype: The socket type you want to use. Can be SOCK_STREAM, SOCK_DGRAM * or 0 for all. * @protocol: The protocol to use, e.g. IPPROTO_TCP or IPPROTO_UDP or 0 for all. * Note that some platforms may not return IPPROTO_SCTP without * explicitly requesting it (i.e. IPPROTO_SCTP may not be returned * with 0 for the protocol) * @res: Storage place for the resulting list of returned addresses * * This will do a lookup of the host and service that you want to connect to. * It returns a linked list of different addresses you can try to connect to. * * When no longer needed you should call BIO_ADDRINFO_free() to free the result. * * The return value is 1 on success or 0 in case of error. */ int BIO_lookup_ex(const char *host, const char *service, int lookup_type, int family, int socktype, int protocol, BIO_ADDRINFO **res) { int ret = 0; /* Assume failure */ switch (family) { case AF_INET: #if OPENSSL_USE_IPV6 case AF_INET6: #endif #ifndef OPENSSL_NO_UNIX_SOCK case AF_UNIX: #endif #ifdef AF_UNSPEC case AF_UNSPEC: #endif break; default: ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY); return 0; } #ifndef OPENSSL_NO_UNIX_SOCK if (family == AF_UNIX) { if (addrinfo_wrap(family, socktype, host, strlen(host), 0, res)) return 1; else ERR_raise(ERR_LIB_BIO, ERR_R_BIO_LIB); return 0; } #endif if (BIO_sock_init() != 1) return 0; if (1) { #ifdef AI_PASSIVE int gai_ret = 0, old_ret = 0; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = socktype; hints.ai_protocol = protocol; # ifdef AI_ADDRCONFIG # ifdef AF_UNSPEC if (host != NULL && family == AF_UNSPEC) # endif hints.ai_flags |= AI_ADDRCONFIG; # endif if (lookup_type == BIO_LOOKUP_SERVER) hints.ai_flags |= AI_PASSIVE; /* Note that |res| SHOULD be a 'struct addrinfo **' thanks to * macro magic in bio_local.h */ # if defined(AI_ADDRCONFIG) && defined(AI_NUMERICHOST) retry: # endif switch ((gai_ret = getaddrinfo(host, service, &hints, res))) { # ifdef EAI_SYSTEM case EAI_SYSTEM: ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling getaddrinfo()"); ERR_raise(ERR_LIB_BIO, ERR_R_SYS_LIB); break; # endif # ifdef EAI_MEMORY case EAI_MEMORY: ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB, gai_strerror(old_ret ? old_ret : gai_ret)); break; # endif case 0: ret = 1; /* Success */ break; default: # if defined(AI_ADDRCONFIG) && defined(AI_NUMERICHOST) if (hints.ai_flags & AI_ADDRCONFIG) { hints.ai_flags &= ~AI_ADDRCONFIG; hints.ai_flags |= AI_NUMERICHOST; old_ret = gai_ret; goto retry; } # endif ERR_raise_data(ERR_LIB_BIO, ERR_R_SYS_LIB, gai_strerror(old_ret ? old_ret : gai_ret)); break; } } else { #endif const struct hostent *he; /* * Because struct hostent is defined for 32-bit pointers only with * VMS C, we need to make sure that '&he_fallback_address' and * '&he_fallback_addresses' are 32-bit pointers */ #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma pointer_size save # pragma pointer_size 32 #endif /* Windows doesn't seem to have in_addr_t */ #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) static uint32_t he_fallback_address; static const char *he_fallback_addresses[] = { (char *)&he_fallback_address, NULL }; #else static in_addr_t he_fallback_address; static const char *he_fallback_addresses[] = { (char *)&he_fallback_address, NULL }; #endif static const struct hostent he_fallback = { NULL, NULL, AF_INET, sizeof(he_fallback_address), (char **)&he_fallback_addresses }; #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma pointer_size restore #endif struct servent *se; /* Apparently, on WIN64, s_proto and s_port have traded places... */ #ifdef _WIN64 struct servent se_fallback = { NULL, NULL, NULL, 0 }; #else struct servent se_fallback = { NULL, NULL, 0, NULL }; #endif if (!RUN_ONCE(&bio_lookup_init, do_bio_lookup_init)) { /* Should this be raised inside do_bio_lookup_init()? */ ERR_raise(ERR_LIB_BIO, ERR_R_CRYPTO_LIB); ret = 0; goto err; } if (!CRYPTO_THREAD_write_lock(bio_lookup_lock)) { ret = 0; goto err; } he_fallback_address = INADDR_ANY; if (host == NULL) { he = &he_fallback; switch (lookup_type) { case BIO_LOOKUP_CLIENT: he_fallback_address = INADDR_LOOPBACK; break; case BIO_LOOKUP_SERVER: he_fallback_address = INADDR_ANY; break; default: /* We forgot to handle a lookup type! */ assert("We forgot to handle a lookup type!" == NULL); ERR_raise(ERR_LIB_BIO, ERR_R_INTERNAL_ERROR); ret = 0; goto err; } } else { he = gethostbyname(host); if (he == NULL) { #ifndef OPENSSL_SYS_WINDOWS /* * This might be misleading, because h_errno is used as if * it was errno. To minimize mixup add 1000. Underlying * reason for this is that hstrerror is declared obsolete, * not to mention that a) h_errno is not always guaranteed * to be meaningless; b) hstrerror can reside in yet another * library, linking for sake of hstrerror is an overkill; * c) this path is not executed on contemporary systems * anyway [above getaddrinfo/gai_strerror is]. We just let * system administrator figure this out... */ # if defined(OPENSSL_SYS_VXWORKS) /* h_errno doesn't exist on VxWorks */ ERR_raise_data(ERR_LIB_SYS, 1000, "calling gethostbyname()"); # else ERR_raise_data(ERR_LIB_SYS, 1000 + h_errno, "calling gethostbyname()"); # endif #else ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling gethostbyname()"); #endif ret = 0; goto err; } } if (service == NULL) { se_fallback.s_port = 0; se_fallback.s_proto = NULL; se = &se_fallback; } else { char *endp = NULL; long portnum = strtol(service, &endp, 10); /* * Because struct servent is defined for 32-bit pointers only with * VMS C, we need to make sure that 'proto' is a 32-bit pointer. */ #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma pointer_size save # pragma pointer_size 32 #endif char *proto = NULL; #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma pointer_size restore #endif switch (socktype) { case SOCK_STREAM: proto = "tcp"; break; case SOCK_DGRAM: proto = "udp"; break; } if (endp != service && *endp == '\0' && portnum > 0 && portnum < 65536) { se_fallback.s_port = htons((unsigned short)portnum); se_fallback.s_proto = proto; se = &se_fallback; } else if (endp == service) { se = getservbyname(service, proto); if (se == NULL) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling getservbyname()"); goto err; } } else { ERR_raise(ERR_LIB_BIO, BIO_R_MALFORMED_HOST_OR_SERVICE); goto err; } } *res = NULL; { /* * Because hostent::h_addr_list is an array of 32-bit pointers with VMS C, * we must make sure our iterator designates the same element type, hence * the pointer size dance. */ #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma pointer_size save # pragma pointer_size 32 #endif char **addrlistp; #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma pointer_size restore #endif size_t addresses; BIO_ADDRINFO *tmp_bai = NULL; /* The easiest way to create a linked list from an array is to start from the back */ for (addrlistp = he->h_addr_list; *addrlistp != NULL; addrlistp++) ; for (addresses = addrlistp - he->h_addr_list; addrlistp--, addresses-- > 0; ) { if (!addrinfo_wrap(he->h_addrtype, socktype, *addrlistp, he->h_length, se->s_port, &tmp_bai)) goto addrinfo_wrap_err; tmp_bai->bai_next = *res; *res = tmp_bai; continue; addrinfo_wrap_err: BIO_ADDRINFO_free(*res); *res = NULL; ERR_raise(ERR_LIB_BIO, ERR_R_BIO_LIB); ret = 0; goto err; } ret = 1; } err: CRYPTO_THREAD_unlock(bio_lookup_lock); } return ret; } #endif /* OPENSSL_NO_SOCK */
./openssl/crypto/bio/bio_sock2.c
/* * 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 */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "bio_local.h" #include "internal/ktls.h" #include "internal/bio_tfo.h" #include <openssl/err.h> #ifndef OPENSSL_NO_SOCK # ifdef SO_MAXCONN # define MAX_LISTEN SO_MAXCONN # elif defined(SOMAXCONN) # define MAX_LISTEN SOMAXCONN # else # define MAX_LISTEN 32 # endif /*- * BIO_socket - create a socket * @domain: the socket domain (AF_INET, AF_INET6, AF_UNIX, ...) * @socktype: the socket type (SOCK_STEAM, SOCK_DGRAM) * @protocol: the protocol to use (IPPROTO_TCP, IPPROTO_UDP) * @options: BIO socket options (currently unused) * * Creates a socket. This should be called before calling any * of BIO_connect and BIO_listen. * * Returns the file descriptor on success or INVALID_SOCKET on failure. On * failure errno is set, and a status is added to the OpenSSL error stack. */ int BIO_socket(int domain, int socktype, int protocol, int options) { int sock = -1; if (BIO_sock_init() != 1) return INVALID_SOCKET; sock = socket(domain, socktype, protocol); if (sock == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling socket()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_CREATE_SOCKET); return INVALID_SOCKET; } return sock; } /*- * BIO_connect - connect to an address * @sock: the socket to connect with * @addr: the address to connect to * @options: BIO socket options * * Connects to the address using the given socket and options. * * Options can be a combination of the following: * - BIO_SOCK_KEEPALIVE: enable regularly sending keep-alive messages. * - BIO_SOCK_NONBLOCK: Make the socket non-blocking. * - BIO_SOCK_NODELAY: don't delay small messages. * - BIO_SOCK_TFO: use TCP Fast Open * * options holds BIO socket options that can be used * You should call this for every address returned by BIO_lookup * until the connection is successful. * * Returns 1 on success or 0 on failure. On failure errno is set * and an error status is added to the OpenSSL error stack. */ int BIO_connect(int sock, const BIO_ADDR *addr, int options) { const int on = 1; if (sock == -1) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_SOCKET); return 0; } if (!BIO_socket_nbio(sock, (options & BIO_SOCK_NONBLOCK) != 0)) return 0; if (options & BIO_SOCK_KEEPALIVE) { if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_KEEPALIVE); return 0; } } if (options & BIO_SOCK_NODELAY) { if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_NODELAY); return 0; } } if (options & BIO_SOCK_TFO) { # if defined(OSSL_TFO_CLIENT_FLAG) # if defined(OSSL_TFO_SYSCTL_CLIENT) int enabled = 0; size_t enabledlen = sizeof(enabled); /* Later FreeBSD */ if (sysctlbyname(OSSL_TFO_SYSCTL_CLIENT, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for client flag */ if (!(enabled & OSSL_TFO_CLIENT_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # elif defined(OSSL_TFO_SYSCTL) int enabled = 0; size_t enabledlen = sizeof(enabled); /* macOS */ if (sysctlbyname(OSSL_TFO_SYSCTL, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for client flag */ if (!(enabled & OSSL_TFO_CLIENT_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # endif # endif # if defined(OSSL_TFO_CONNECTX) sa_endpoints_t sae; memset(&sae, 0, sizeof(sae)); sae.sae_dstaddr = BIO_ADDR_sockaddr(addr); sae.sae_dstaddrlen = BIO_ADDR_sockaddr_size(addr); if (connectx(sock, &sae, SAE_ASSOCID_ANY, CONNECT_DATA_IDEMPOTENT | CONNECT_RESUME_ON_READ_WRITE, NULL, 0, NULL, NULL) == -1) { if (!BIO_sock_should_retry(-1)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling connectx()"); ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR); } return 0; } # endif # if defined(OSSL_TFO_CLIENT_SOCKOPT) if (setsockopt(sock, IPPROTO_TCP, OSSL_TFO_CLIENT_SOCKOPT, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_TFO); return 0; } # endif # if defined(OSSL_TFO_DO_NOT_CONNECT) return 1; # endif } if (connect(sock, BIO_ADDR_sockaddr(addr), BIO_ADDR_sockaddr_size(addr)) == -1) { if (!BIO_sock_should_retry(-1)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling connect()"); ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR); } return 0; } # ifndef OPENSSL_NO_KTLS /* * The new socket is created successfully regardless of ktls_enable. * ktls_enable doesn't change any functionality of the socket, except * changing the setsockopt to enable the processing of ktls_start. * Thus, it is not a problem to call it for non-TLS sockets. */ ktls_enable(sock); # endif return 1; } /*- * BIO_bind - bind socket to address * @sock: the socket to set * @addr: local address to bind to * @options: BIO socket options * * Binds to the address using the given socket and options. * * Options can be a combination of the following: * - BIO_SOCK_REUSEADDR: Try to reuse the address and port combination * for a recently closed port. * * When restarting the program it could be that the port is still in use. If * you set to BIO_SOCK_REUSEADDR option it will try to reuse the port anyway. * It's recommended that you use this. */ int BIO_bind(int sock, const BIO_ADDR *addr, int options) { # ifndef OPENSSL_SYS_WINDOWS int on = 1; # endif if (sock == -1) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_SOCKET); return 0; } # ifndef OPENSSL_SYS_WINDOWS /* * SO_REUSEADDR has different behavior on Windows than on * other operating systems, don't set it there. */ if (options & BIO_SOCK_REUSEADDR) { if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_REUSEADDR); return 0; } } # endif if (bind(sock, BIO_ADDR_sockaddr(addr), BIO_ADDR_sockaddr_size(addr)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error() /* may be 0 */, "calling bind()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_BIND_SOCKET); return 0; } return 1; } /*- * BIO_listen - Creates a listen socket * @sock: the socket to listen with * @addr: local address to bind to * @options: BIO socket options * * Binds to the address using the given socket and options, then * starts listening for incoming connections. * * Options can be a combination of the following: * - BIO_SOCK_KEEPALIVE: enable regularly sending keep-alive messages. * - BIO_SOCK_NONBLOCK: Make the socket non-blocking. * - BIO_SOCK_NODELAY: don't delay small messages. * - BIO_SOCK_REUSEADDR: Try to reuse the address and port combination * for a recently closed port. * - BIO_SOCK_V6_ONLY: When creating an IPv6 socket, make it listen only * for IPv6 addresses and not IPv4 addresses mapped to IPv6. * - BIO_SOCK_TFO: accept TCP fast open (set TCP_FASTOPEN) * * It's recommended that you set up both an IPv6 and IPv4 listen socket, and * then check both for new clients that connect to it. You want to set up * the socket as non-blocking in that case since else it could hang. * * Not all operating systems support IPv4 addresses on an IPv6 socket, and for * others it's an option. If you pass the BIO_LISTEN_V6_ONLY it will try to * create the IPv6 sockets to only listen for IPv6 connection. * * It could be that the first BIO_listen() call will listen to all the IPv6 * and IPv4 addresses and that then trying to bind to the IPv4 address will * fail. We can't tell the difference between already listening ourself to * it and someone else listening to it when failing and errno is EADDRINUSE, so * it's recommended to not give an error in that case if the first call was * successful. * * When restarting the program it could be that the port is still in use. If * you set to BIO_SOCK_REUSEADDR option it will try to reuse the port anyway. * It's recommended that you use this. */ int BIO_listen(int sock, const BIO_ADDR *addr, int options) { int on = 1; int socktype; socklen_t socktype_len = sizeof(socktype); if (sock == -1) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_SOCKET); return 0; } if (getsockopt(sock, SOL_SOCKET, SO_TYPE, (void *)&socktype, &socktype_len) != 0 || socktype_len != sizeof(socktype)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling getsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_GETTING_SOCKTYPE); return 0; } if (!BIO_socket_nbio(sock, (options & BIO_SOCK_NONBLOCK) != 0)) return 0; if (options & BIO_SOCK_KEEPALIVE) { if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_KEEPALIVE); return 0; } } if (options & BIO_SOCK_NODELAY) { if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_NODELAY); return 0; } } /* On OpenBSD it is always IPv6 only with IPv6 sockets thus read-only */ # if defined(IPV6_V6ONLY) && !defined(__OpenBSD__) if (BIO_ADDR_family(addr) == AF_INET6) { /* * Note: Windows default of IPV6_V6ONLY is ON, and Linux is OFF. * Therefore we always have to use setsockopt here. */ on = options & BIO_SOCK_V6_ONLY ? 1 : 0; if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_LISTEN_V6_ONLY); return 0; } } # endif if (!BIO_bind(sock, addr, options)) return 0; if (socktype != SOCK_DGRAM && listen(sock, MAX_LISTEN) == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling listen()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_LISTEN_SOCKET); return 0; } # if defined(OSSL_TFO_SERVER_SOCKOPT) /* * Must do it explicitly after listen() for macOS, still * works fine on other OS's */ if ((options & BIO_SOCK_TFO) && socktype != SOCK_DGRAM) { int q = OSSL_TFO_SERVER_SOCKOPT_VALUE; # if defined(OSSL_TFO_CLIENT_FLAG) # if defined(OSSL_TFO_SYSCTL_SERVER) int enabled = 0; size_t enabledlen = sizeof(enabled); /* Later FreeBSD */ if (sysctlbyname(OSSL_TFO_SYSCTL_SERVER, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for server flag */ if (!(enabled & OSSL_TFO_SERVER_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # elif defined(OSSL_TFO_SYSCTL) int enabled = 0; size_t enabledlen = sizeof(enabled); /* Early FreeBSD, macOS */ if (sysctlbyname(OSSL_TFO_SYSCTL, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for server flag */ if (!(enabled & OSSL_TFO_SERVER_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # endif # endif if (setsockopt(sock, IPPROTO_TCP, OSSL_TFO_SERVER_SOCKOPT, (void *)&q, sizeof(q)) < 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_TFO); return 0; } } # endif return 1; } /*- * BIO_accept_ex - Accept new incoming connections * @sock: the listening socket * @addr: the BIO_ADDR to store the peer address in * @options: BIO socket options, applied on the accepted socket. * */ int BIO_accept_ex(int accept_sock, BIO_ADDR *addr_, int options) { socklen_t len; int accepted_sock; BIO_ADDR locaddr; BIO_ADDR *addr = addr_ == NULL ? &locaddr : addr_; len = sizeof(*addr); accepted_sock = accept(accept_sock, BIO_ADDR_sockaddr_noconst(addr), &len); if (accepted_sock == -1) { if (!BIO_sock_should_retry(accepted_sock)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling accept()"); ERR_raise(ERR_LIB_BIO, BIO_R_ACCEPT_ERROR); } return INVALID_SOCKET; } if (!BIO_socket_nbio(accepted_sock, (options & BIO_SOCK_NONBLOCK) != 0)) { closesocket(accepted_sock); return INVALID_SOCKET; } return accepted_sock; } /*- * BIO_closesocket - Close a socket * @sock: the socket to close */ int BIO_closesocket(int sock) { if (sock < 0 || closesocket(sock) < 0) return 0; return 1; } #endif