diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 5aea89e7..41ea58b2 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -21,9 +21,9 @@ of every version are on webcpp's index page. * Added ciphers::gcm, AES-GCM in place with an incremental seal, whose failed open zeroes the data. * Added the default backend, ciphers::aes128_gcm and aes256_gcm, and the refusals of backends that conflict. * Added backends::bearssl: AES-GCM on every target allocating nothing, the block cipher refused, and the Jamfile line a program lacks without it. -* Added backends::openssl and /webcpp/crypto//openssl on native and WASI; a message on it allocates nothing after make. +* Added backends::openssl, /webcpp/crypto//openssl on native and WASI, allocating nothing after make; WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE: OpenSSL's allocations in the program's resource, refused on WebAssembly (WASI included) and without OpenSSL: openssl_memory_resource, install_memory_functions, memory_functions_refused, memory_functions_not_installed. * Added backends::ctaes, the AES block cipher alone on every target; ciphers::gcm refuses it. * Added curves::secp256k1: key pairs, BIP340 and ECDSA signatures, ECDH, strict DER, low-S and the x-only tweak. * Added the link-time canaries of BearSSL, ctaes and libsecp256k1, and their own suites on webcpp's build. -* Added the page: a chapter per namespace and use case, tables generated from the tests, every Jamfile and message, and llms.txt. +* Added the page: a chapter per namespace and use case, the memory option's guide and example, tables generated from the tests, every Jamfile and message, and llms.txt. // end::unreleased[] diff --git a/doc/errors.adoc b/doc/errors.adoc index f88b69b1..d74d7c61 100644 --- a/doc/errors.adoc +++ b/doc/errors.adoc @@ -41,13 +41,20 @@ bytes) or 04 (65 bytes), or not a point of the curve. |11 |`invalid_signature` |A signature that does not verify, or is not a valid encoding: not strict DER, or an r or an s that is zero or not below the group order. |12 |`backend_failure` |A backend failed where its contract says it does not. +|13 |`memory_functions_refused` |OpenSSL's memory functions could not be installed: OpenSSL has +already allocated, or another party installed its own. From `backends::openssl::install_memory_functions`, +with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. +|14 |`memory_functions_not_installed` |OpenSSL's memory functions are not webcpp::crypto's. From +every `make` of the OpenSSL backend, with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. |=== -The values 13 and 14 are reserved for OpenSSL's memory option, which is not part -of this version, and are not declared. A value that `error` does not define +A value that `error` does not define has the message "unknown webcpp.crypto error". `random_device` also returns `errc::not_supported` where there is no generator at all, and OpenSSL's `make` `errc::not_enough_memory` when OpenSSL cannot allocate its context. +`memory_functions_refused` and `memory_functions_not_installed` come only with +OpenSSL's memory option, natively: <> says what each +means and what to do. include::generated/backends-error.adoc[] diff --git a/doc/generated/backend-facts.adoc b/doc/generated/backend-facts.adoc index e235abaf..e596ffac 100644 --- a/doc/generated/backend-facts.adoc +++ b/doc/generated/backend-facts.adoc @@ -48,7 +48,7 @@ The library behind each, and what it costs a program: |OpenSSL 3.5.9's libcrypto, built from source and static |Apache-2.0 |`++` -|`+make+` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource; a message allocates nothing after `+make+` +|`+make+` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+`, which sends every allocation of OpenSSL's in the process to `+openssl_memory_resource()+`; a message allocates nothing after `+make+` |ctaes |ctaes as Bitcoin Core v31.1 ships it (`+src/crypto/ctaes+`), built from source diff --git a/doc/generated/backends-memory_option.adoc b/doc/generated/backends-memory_option.adoc new file mode 100644 index 00000000..000037fa --- /dev/null +++ b/doc/generated/backends-memory_option.adoc @@ -0,0 +1,20 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, +// the message tests and the Jamfile fixtures: run it again, never edit this file. + +The backends of `+openssl_memory_resource+`, `+backends::openssl::install_memory_functions+`, from the test programs that run it: + +[cols="1,2,2,4",options="header"] +|=== +|Backend |Jamfile |Header |Targets + +|OpenSSL +|`+/webcpp/crypto//openssl+` +|`++` +|native (tested by `+adapter+`, `+everything+`, `+late+`, `+foreign+`, `+fresh_install+`, `+forgotten+`, `+replaced+`, `+second_install+`, `+fail_second+`, `+fail_init+`, `+fail_init_threads+`, `+neighbours+`, `+handshake+`); not on wasip2, wasip3, emscripten: `+config.hpp+` refuses the option on every WebAssembly target +|=== diff --git a/doc/generated/jamfiles.adoc b/doc/generated/jamfiles.adoc index 9fb36e0b..5e406cf8 100644 --- a/doc/generated/jamfiles.adoc +++ b/doc/generated/jamfiles.adoc @@ -55,6 +55,22 @@ It prints: include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/encrypt_and_sign/encrypt_and_sign.outcome[tag=output] ---- +`+memory_option+`:: OpenSSL's allocations in the program's own resource: the define and OpenSSL in the requirements of the program's project, the resource defined once, the install first in `+main+`. ++ +Its Jamfile, built and run on native: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_option/Jamfile[tag=jamfile] +---- ++ +It prints: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_option/memory_option.outcome[tag=output] +---- + `+openssl_linked+`:: OpenSSL, built from source, named in the type: natively and on WASI. + Its Jamfile, built and run on native, wasip2, wasip3: diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index e6a35e09..402d41e1 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -75,6 +75,11 @@ |libsecp256k1 |native, wasip2, wasip3, emscripten |`+secp256k1_xonly_tweak+` + +|`+openssl_memory_resource+`, `+backends::openssl::install_memory_functions+` +|OpenSSL +|native; not on wasip2, wasip3, emscripten: `+config.hpp+` refuses the option on every WebAssembly target +|`+adapter+`, `+everything+`, `+late+`, `+foreign+`, `+fresh_install+`, `+forgotten+`, `+replaced+`, `+second_install+`, `+fail_second+`, `+fail_init+`, `+fail_init_threads+`, `+neighbours+`, `+handshake+` |=== The same, by target: the backends each operation runs on. @@ -136,4 +141,10 @@ The same, by target: the backends each operation runs on. |libsecp256k1 |libsecp256k1 |libsecp256k1 + +|`+openssl_memory_resource+`, `+backends::openssl::install_memory_functions+` +|OpenSSL +|none +|none +|none |=== diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 9c6e7e15..61d1bcd8 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -49,6 +49,18 @@ The fix: Add `+/webcpp/crypto//openssl+` or `+/third_party//bearssl+` to the pro The fix: Add `+/third_party//bearssl+` to the program's sources. +|`+openssl_memory_not_linked+` +|native +|`+webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE routes OpenSSL's allocations, and OpenSSL is not linked. In the program's Jamfile, add /webcpp/crypto//openssl beside /webcpp/crypto//crypto, or remove that define. (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)+` + +The fix: A target has the define and not OpenSSL: put `+/webcpp/crypto//openssl+` in the same project requirements as the define, or remove the define. + +|`+openssl_memory_on_webassembly+` +|wasip2, wasip3 +|`+webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE is an option of native programs, and this program is built for WebAssembly. Remove that define from the program's Jamfile.+` + +The fix: Remove `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `+/third_party//bearssl+`. On WebAssembly the backend is BearSSL, which allocates nothing. + |`+openssl_not_linked+` |native, wasip2 |`+webcpp::crypto: the backend OpenSSL is used and not linked. In the program's Jamfile, add /webcpp/crypto//openssl beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)+` @@ -312,6 +324,40 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: OpenSSL is not built for Emscripten. In the program's Jamfile, replace /webcpp/crypto//openssl with /third_party//bearssl.+` +`+memory_missing_definition_install+`:: The memory option set in the program's project, the install called, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_missing_definition_install/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* native, macOS: +** `+Undefined symbols for architecture+` +** `+"webcpp::crypto::openssl_memory_resource()", referenced from:+` +* native, Linux: +** `pass:[undefined reference to `webcpp::crypto::openssl_memory_resource()']` + +`+memory_missing_definition_make+`:: The memory option set in the program's project, a `+make+` on OpenSSL, and `+openssl_memory_resource()+` not defined. The fix: Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_missing_definition_make/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* native, macOS: +** `+Undefined symbols for architecture+` +** `+"webcpp::crypto::openssl_memory_resource()", referenced from:+` +* native, Linux: +** `pass:[undefined reference to `webcpp::crypto::openssl_memory_resource()']` + `+no_backend_on_emscripten+`:: A program for Emscripten that uses the default backend and links none. The fix: Add `+/third_party//bearssl+` to the program's sources. + Its Jamfile: @@ -326,6 +372,20 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: no backend is linked. On WebAssembly the backend is BearSSL: in the program's Jamfile, add /third_party//bearssl beside /webcpp/crypto//crypto, as in: exe app : app.cpp /webcpp/crypto//crypto /third_party//bearssl ; (without b2: define WEBCPP_CRYPTO_HAS_BEARSSL=1 and link BearSSL built with webcpp's src/canary_bearssl.c)+` +`+openssl_memory_on_emscripten+`:: The memory option of the OpenSSL backend set in a build for Emscripten. The fix: Remove `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `+/third_party//bearssl+`. On WebAssembly the backend is BearSSL, which allocates nothing. ++ +Its Jamfile: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/openssl_memory_on_emscripten/Jamfile[tag=jamfile] +---- ++ +On each target, the build's output contains: ++ +* emscripten: +** `+webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE is an option of native programs, and this program is built for WebAssembly. Remove that define from the program's Jamfile.+` + `+openssl_on_emscripten+`:: `+/webcpp/crypto//openssl+` named in a build for Emscripten. The fix: Name `+/third_party//bearssl+` in its place for the Emscripten build. + Its Jamfile: @@ -398,10 +458,26 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Use `+aes256_gcm+` with BearSSL or OpenSSL linked. +|`+memory_missing_definition_install+` +|the link +|Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. + +|`+memory_missing_definition_make+` +|the link +|Define `+std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept+` once in the program, returning a resource that is never destroyed. + +|`+memory_two_files+` +|the link +|Give the define in the requirements of the program's project, with OpenSSL beside it, `+project app : requirements WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE /webcpp/crypto//openssl ;+`, so that every target of the program gets both. + |`+no_backend+` |the compile |As `+no_backend_native+`. +|`+openssl_memory_not_linked+` +|the compile +|A target has the define and not OpenSSL: put `+/webcpp/crypto//openssl+` in the same project requirements as the define, or remove the define. + |`+openssl_not_linked+` |the compile |Add `+/webcpp/crypto//openssl+`. @@ -422,3 +498,14 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Keep one of the two defines. |=== + +Elsewhere than MSVC these mistakes build, and nothing stops them; the fixtures record it: + +`+memory_two_files+`:: Two files of one program, one compiled with the memory option and one without. ++ +Its Jamfile, which builds on native: ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_two_files/Jamfile[tag=jamfile] +---- diff --git a/doc/generated/namespace-root.adoc b/doc/generated/namespace-root.adoc index 2c9ed8ee..c196e7c0 100644 --- a/doc/generated/namespace-root.adoc +++ b/doc/generated/namespace-root.adoc @@ -7,32 +7,37 @@ // Generated by doc/tables/generate.py from doc/tables/crypto.json, the test Jamfiles, // the message tests and the Jamfile fixtures: run it again, never edit this file. -[cols="2h,5,5,5",options="header"] +[cols="2h,5,5,5,5",options="header"] |=== -|Name |`random_device` |`equal` |`error` +|Name |`random_device` |`equal` |`error` |`openssl_memory_resource` |What it is for |Keys, IVs, tokens, nonces: every secret a program draws |Checking a tag, a MAC or a token |Telling failures apart +|Keeping every allocation of OpenSSL's in the program's own resource, natively |Header |`` |`` |`` +|`` |Errors |`entropy_unavailable`, `errc::not_supported` |none: it returns `bool` |its values are the errors +|`memory_functions_refused`, `memory_functions_not_installed` |Standards and sources |link:https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html[POSIX.1-2024, getentropy], link:https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom[Microsoft, BCryptGenRandom], link:https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues[W3C Web Cryptography API, getRandomValues], link:https://github.com/WebAssembly/wasi-random[WASI, wasi:random] |link:https://cwe.mitre.org/data/definitions/208.html[CWE-208, observable timing discrepancy] |none +|link:https://docs.openssl.org/3.5/man3/OPENSSL_malloc/[OpenSSL 3.5's OPENSSL_malloc(3), CRYPTO_set_mem_functions] |Choose it when |you need a random number an attacker must not predict; never `std::mt19937` or `rand` (link:https://cwe.mitre.org/data/definitions/338.html[CWE-338, a weak generator used for security]) |you compare anything secret; never `==` or `memcmp` on a MAC |you branch on a failure: forged data, a wrong size, no entropy +|a native program on OpenSSL must allocate only from its own arena; on WebAssembly, BearSSL allocates nothing |=== diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index 33e329a3..0878b2da 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -107,6 +107,12 @@ `+/third_party//secp256k1+` |<> +|Keep every allocation of OpenSSL's in the program's arena +|`+openssl_memory_resource+`, `+backends::openssl::install_memory_functions+` +|OpenSSL, natively +|`+/webcpp/crypto//crypto+` in the program; in the project requirements, `+WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE+` and `+/webcpp/crypto//openssl+` +|<> + |Seed BearSSL's own generator for code that calls BearSSL directly |`+random_device::fill+` |BearSSL's C API diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index 1639a9fd..31a2f83b 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -48,6 +48,32 @@ time, and there is no AES-NI. A program for which timing attacks matter there defines `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`, or names `ciphers::gcm>`. +[#crypto-jamfile-memory] +=== OpenSSL's memory option + +A native program that sends OpenSSL's allocations to its own resource +(<>) gives the define +`WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl` +together, in the requirements of its project, not of one target. Every target +of the program then gets both: its own libraries, and a tool that only calls +`random_device` or `equal`, which would otherwise have the define without +OpenSSL. The fixture `memory_option` builds and runs this Jamfile natively: + +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_option/Jamfile[tag=jamfile] +---- + +Each mistake stops the build, with the messages of +<>: the define on a target without OpenSSL, or in a +build for WebAssembly, is refused by `config.hpp`; `openssl_memory_resource()` +not defined is a link error; and on MSVC, files of one program compiled some +with the define and some without are refused by the linker (`LNK2038`). These +requirements cannot be built for WebAssembly, since the option is refused +there and `/webcpp/crypto//openssl` stops an Emscripten build: a WebAssembly +build of the same program is a project of its own, in a directory of its own, +with neither the define nor OpenSSL, and names `/third_party//bearssl`. + [#crypto-jamfile-cases] === Every Jamfile a user writes diff --git a/doc/llms.txt b/doc/llms.txt index 84dd937b..d9137d3b 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -18,6 +18,9 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - error_category: The category of every error. - make_error_code: Makes the `error_code` of an error, as its implicit conversion does. - message_of: The message of a value of error, or the unknown message for a value it does not define. +- [openssl_memory_resource, backends::openssl::install_memory_functions](https://webcpporg.github.io/libs/crypto/#crypto-memory-openssl): With `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, natively, every allocation of OpenSSL's in the process goes to a `std::pmr::memory_resource` the program defines. Header . Backends: OpenSSL (/webcpp/crypto//openssl) on native. + - openssl_memory_resource: The resource every allocation of OpenSSL's in the process goes to, from any thread: declared by `` under `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and defined once by the program. + - install_memory_functions: Installs webcpp's adapter as OpenSSL's memory functions, so that every allocation of OpenSSL's in the process goes to `openssl_memory_resource()`. ## webcpp::crypto::ciphers @@ -92,6 +95,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Sign a Bitcoin SegWit v0 input (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-der): `sign_ecdsa`, `to_der`, `normalize_ecdsa` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/ecdsa_der.cpp. - [Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly`, `keypair::tweak_xonly` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/taproot_tweak.cpp. - [Sign where allocation is restricted to the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory): `keypair::make(secret, resource)` (webcpp::crypto::curves::secp256k1); backend libsecp256k1; Jamfile /webcpp/crypto//crypto /third_party//secp256k1. Example: example/arena_signer.cpp. +- [Keep every allocation of OpenSSL's in the program's arena](https://webcpporg.github.io/libs/crypto/#crypto-memory-openssl): `openssl_memory_resource`, `backends::openssl::install_memory_functions` (webcpp::crypto); backend OpenSSL, natively; Jamfile `/webcpp/crypto//crypto` in the program; in the project requirements, `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl`. Example: example/openssl_memory.cpp. - [Seed BearSSL's own generator for code that calls BearSSL directly](https://webcpporg.github.io/libs/crypto/#crypto-entropy-bearssl): `random_device::fill` (webcpp::crypto); backend BearSSL's C API; Jamfile /webcpp/crypto//crypto /third_party//bearssl. Example: example/bearssl_prng.cpp. - [Hash, or compute an HMAC](https://webcpporg.github.io/libs/crypto/#crypto-overview-hash2): `boost::hash2::sha2_256`, `hmac_sha2_256` (Boost.Hash2, not this library); backend none; Jamfile `/webcpp/crypto//crypto` brings Boost's headers. Example: example/equal_hmac.cpp. - [Use P-256 (passkeys, JWT's ES256), Ed25519 or X25519](https://webcpporg.github.io/libs/crypto/#crypto-curves): secp256k1 keys and signatures do not interoperate with these curves (none in this version); backend none; Jamfile none. @@ -105,6 +109,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/ecdsa_der.cpp: Signs with ECDSA the way a domain library does: a sighash computed by the library, a 64-byte signature, its strict DER form for the wire, and the low-S rule. The same signature has a twin with S replaced by n - S; accepting both makes transaction ids malleable, so verifiers refuse the high-S twin. - example/equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::equal, the constant-time comparison. Comparing tags with == or memcmp stops at the first difference, and that timing lets an attacker guess a valid tag one byte at a time. - example/failure_reasons.cpp: Shows the three ways AES-GCM can refuse a message: a tampered ciphertext, an IV of the wrong size and a tag of the wrong size. A program must tell the first from the others: only authentication_failed means someone changed the data, and open then wipes the plaintext so that no unauthenticated bytes are ever used. +- example/openssl_memory.cpp: Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and threads (example/Jamfile). - example/order_reference.cpp: Turns a sequential order id into an opaque 16-byte reference with the raw AES block cipher, and back. Customers then cannot guess other orders' numbers. This is NOT authenticated encryption: a forged reference still decrypts, to garbage, so the program checks the padding. - example/reset_token.cpp: Draws a 32-byte password-reset token and a six-digit one-time code from the system's random generator. Tokens that can be guessed or repeated let an attacker take over accounts, so both come from random_device, never from rand() or the clock. - example/schnorr_sign.cpp: Signs BIP340's first test vector with secp256k1 and verifies it, then tweaks the key pair by a 32-byte tweak, as a domain library derives one, and signs and verifies under the tweaked key. Prints each key and signature in hex. diff --git a/doc/memory.adoc b/doc/memory.adoc index bdcc0184..9986b01d 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -24,7 +24,8 @@ allocator,* outside the program's resource; the first `make` of a process also initialises OpenSSL. The test `allocation_openssl` counts and prints these allocations on each target at every run, and fails if a message allocates; the count depends on the target and on OpenSSL's build, so the page does not copy -it. A program that needs every allocation in its arena uses BearSSL. +it. A program that needs every allocation in its arena uses BearSSL, or +OpenSSL with the memory option of <>, natively. * *Keys are wiped.* The key schedules that live inside crypto's objects (BearSSL's, ctaes's, libsecp256k1's key pair) are overwritten on destruction and on move by stores the optimiser cannot drop; OpenSSL wipes its own @@ -50,3 +51,142 @@ include::{examples}/arena_signer.cpp[tag=arena,indent=0] ---- include::{examples}/arena_signer.expected[] ---- + +[#crypto-memory-openssl] +=== OpenSSL's allocations in your own memory resource + +By default OpenSSL allocates with the C library's `malloc`, outside every +allocator of the program's. A native program that keeps its memory in its own +arena, such as an audio engine whose real-time thread may not touch the +system's heap, or an embedded server that gives each part a fixed budget, +finds OpenSSL bypassing that arena: its first `make` initialises OpenSSL, which +takes many blocks from the system's heap, and Beast's TLS and +libdatachannel's DTLS, which link the same OpenSSL, allocate there for every +connection. The arena's accounting is then wrong, a budget is exceeded with no +warning, and a real-time thread can wait on the system allocator's lock. The +memory option sends every allocation OpenSSL makes in the process to a +`std::pmr::memory_resource` the program defines. It is for native programs +only: on WebAssembly the backend is BearSSL, which allocates nothing. + +*How.* Three things, each needed: + +. *The define and OpenSSL, in the requirements of the program's project,* +so that every target of the program gets both, its own libraries and a tool +that only calls `random_device` included. `config.hpp` stops a target that has +the define without OpenSSL, and any build for WebAssembly, with an `#error` +(<>): ++ +[listing] +---- +include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/memory_option/Jamfile[tag=jamfile] +---- +. *`webcpp::crypto::openssl_memory_resource()`, defined once in the program.* +Without it the program does not link. It returns a resource that is +thread-safe and is never destroyed: create it with `new` and never delete it. +OpenSSL frees through it after `main` returns, so a static resource object, or +a local variable of `main`, would be used after its destruction: ++ +[source,cpp] +---- +include::{examples}/openssl_memory.cpp[tag=resource] +---- +. *`backends::openssl::install_memory_functions()`, the first statement of +`main`,* before any thread starts and before anything uses OpenSSL; the +program stops when it returns an error: ++ +[source,cpp] +---- +include::{examples}/openssl_memory.cpp[tag=install,indent=0] +---- + +*Example.* The whole program seals and opens one block on OpenSSL, every +allocation of OpenSSL's in the program's pool: + +[source,cpp] +---- +include::{examples}/openssl_memory.cpp[tag=program] +---- + +[listing] +---- +include::{examples}/openssl_memory.expected[] +---- + +*What to know.* + +* *The whole process.* The resource receives every allocation of the OpenSSL +the program links, not only crypto's: Beast's TLS and libdatachannel's DTLS +too. The test `neighbours` links Asio's TLS and libdatachannel beside the +option, with the objects of libdatachannel whose static initialisers name +OpenSSL, and the install still succeeds; the test `handshake` runs a TLS 1.3 +handshake through libssl, and counts no call of the C library's allocator over +the whole exchange: the key, the certificate, both contexts, the handshake, a +record each way and every free. +* *Nothing else may call `CRYPTO_set_mem_functions`.* If another library has +called it before, `install_memory_functions()` returns +`memory_functions_refused`; if it calls it after the install, the next `make` +returns `memory_functions_not_installed`, and only when that call has finished +before the `make`. The damage is done by then: OpenSSL accepts the replacement +after the install, and from then on frees the blocks it took from the resource +through the other party's `free`, which corrupts that party's heap; the +error that `make` then returns does not undo it. +* *`memory_functions_refused` although the install is the first statement of +`main`* means that something used OpenSSL before `main`: a static object of +another library. OpenSSL then keeps its own `malloc` for the rest of the +process. A libcrypto DLL, which webcpp never builds (a program built without +b2), is refused the same way. +* *`memory_functions_not_installed` from a `make`* means that the install was +not called, or that something replaced OpenSSL's functions after it. +* *One module.* The program's code that uses crypto's OpenSSL backend lives in +one module: a DLL, or a shared library of the program's that hides its +symbols, that includes the backend's header has its own copy of crypto's +functions, and its `make` returns `memory_functions_not_installed`. An ELF +shared library with default visibility usually binds to the executable's +copy instead, but nothing guarantees it. +* *Threads on Windows.* OpenSSL gives a thread's own blocks back when the +thread ends, except on Windows, where the static libcrypto that webcpp always +builds is never told that a thread ends. Every thread that used OpenSSL, a +`make`, Beast's TLS or libdatachannel's DTLS, leaves its error queue and its +list of handlers in the resource, never given back, not even at exit, unless +it calls `OPENSSL_thread_stop()` before it ends. A resource of a fixed size +under a thread pool that replaces its threads, or a thread per connection, +then runs out over time, and the failure lands in a later `make` or inside a +TLS handshake. The example's worker thread ends so, and so does the second +thread of the test `everything`, whose exit check fails on Windows without it: ++ +[source,cpp] +---- +include::{examples}/openssl_memory.cpp[tag=thread,indent=0] +---- +* *When the resource cannot allocate.* The resource must serve OpenSSL's +initialisation, which the first use of OpenSSL in the process runs, usually the +first `make`. On an OpenSSL built with threads, which is MSVC's only build and +b2's `threading=multi` elsewhere, a failure during OpenSSL's base initialisation +is not recoverable: OpenSSL reports it through its error queue, whose state +needs the initialisation that is running, so OpenSSL re-enters its own +initialisation and that call never returns. The process aborts on macOS, +deadlocks on Linux and spins on Windows. Only an OpenSSL built without threads, +b2's default on macOS and Linux, returns from that failure, and OpenSSL stays +unusable for the rest of the process: `make` gives `backend_failure` from then +on. When the failing allocation is OpenSSL's base initialisation (with OpenSSL +3.5.9, its first lock), OpenSSL never registers its cleanup, and +`OPENSSL_cleanup` frees nothing: the blocks it took meanwhile stay in the +resource until the process ends, and the thread's error queue takes no entry +from then on. The test `fail_init` pins this on an OpenSSL without threads and +prints how many blocks stay; with threads, as `fail_init_threads`, it prints how +many blocks the first `make` took instead. After the initialisation, `make` +gives `not_enough_memory` or `backend_failure`. `seal` and `open` allocate +nothing. A resource of a fixed size needs room for the first `make`, whose +allocations the test `allocation_openssl` prints on each run. Without +exceptions, a resource that throws ends the process; one that returns null +reports the failure. +* *Two allocations stay outside the resource,* because no hook of OpenSSL's +reaches them: the C library's `FILE` and its buffer while OpenSSL reads its +configuration file at initialisation (one or two blocks, by C library, freed +when the file closes), and OpenSSL's secure heap, if the program turns it on +with `CRYPTO_secure_malloc_init`. +* *Native only.* A WebAssembly build of the same program is a project of its +own, in a directory of its own, with neither the define nor OpenSSL, and names +`/third_party//bearssl`. + +include::generated/backends-memory_option.adoc[] diff --git a/doc/root.adoc b/doc/root.adoc index 126f55f7..af257303 100644 --- a/doc/root.adoc +++ b/doc/root.adoc @@ -9,6 +9,9 @@ The namespace `webcpp::crypto` holds what every other chapter relies on: where secrets come from (`random_device`), how a secret is checked (`equal`) and how -a failure is told apart (`error`). None needs a backend. +a failure is told apart (`error`). None needs a backend. It also declares, +for a native program on OpenSSL that turns the memory option on, the resource +every allocation of OpenSSL's goes to (`openssl_memory_resource`, +<>). include::generated/namespace-root.adoc[] diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 55366913..0708a798 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -59,7 +59,8 @@ "bitcoin-wiki-secp256k1": ["Bitcoin Wiki, secp256k1", "https://en.bitcoin.it/wiki/Secp256k1"], "secp256k1-configure": ["libsecp256k1's configure.ac, the precomputed tables' trade", "https://github.com/bitcoin-core/secp256k1/blob/master/configure.ac"], "nip44": ["Nostr NIP-44, encrypted payloads", "https://github.com/nostr-protocol/nips/blob/master/44.md"], - "bip32": ["BIP 32, hierarchical deterministic wallets", "https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki"] + "bip32": ["BIP 32, hierarchical deterministic wallets", "https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki"], + "openssl-mem": ["OpenSSL 3.5's OPENSSL_malloc(3), CRYPTO_set_mem_functions", "https://docs.openssl.org/3.5/man3/OPENSSL_malloc/"] }, "backends": { "bearssl": { @@ -80,7 +81,7 @@ "library": "OpenSSL 3.5.9's libcrypto, built from source and static", "licence": "Apache-2.0", "own_api": "``", - "allocation": "`make` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource; a message allocates nothing after `make`", + "allocation": "`make` allocates the cipher's context through OpenSSL's own allocator, outside the program's resource, unless a native program sets `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's in the process to `openssl_memory_resource()`; a message allocates nothing after `make`", "constant_time": "with assembly (native Clang and GCC), AES-NI and carry-less multiplication where the CPU has them; built no-asm (MSVC, wasip2, wasip3), table-based AES and 4-bit GHASH, neither constant time (`OPENSSL_AES_CONST_TIME` makes only the AES core constant time; GHASH stays table-based)", "constant_time_sources": ["openssl-install", "openssl-aes-core"] }, @@ -232,6 +233,16 @@ "what": "Tweaks an x-only public key by a 32-byte tweak a protocol computes.", "section": "crypto-secp256k1", "backends": {"secp256k1": {"tests": ["secp256k1_xonly_tweak"]}} + }, + { + "id": "memory_option", + "functions": ["openssl_memory_resource", "install_memory_functions"], + "namespace": "root", + "api": "openssl_memory_resource, backends::openssl::install_memory_functions", + "header": "", + "what": "With `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, natively, every allocation of OpenSSL's in the process goes to a `std::pmr::memory_resource` the program defines.", + "section": "crypto-memory-openssl", + "backends": {"openssl": {"tests": ["adapter", "everything", "late", "foreign", "fresh_install", "forgotten", "replaced", "second_install", "fail_second", "fail_init", "fail_init_threads", "neighbours", "handshake"], "elsewhere": "memory"}} } ], "rules": [ @@ -255,6 +266,7 @@ "emscripten": "emscripten" }, "elsewhere": { + "memory": "`config.hpp` refuses the option on every WebAssembly target", "openssl": "`/webcpp/crypto//openssl` stops the build there", "refused": "refused at compile time" }, @@ -274,7 +286,8 @@ "rows": [ ["`random_device`", "Keys, IVs, tokens, nonces: every secret a program draws", "``", "`entropy_unavailable`, `errc::not_supported`", "{getentropy}, {bcryptgenrandom}, {getrandomvalues}, {wasi-random}", "you need a random number an attacker must not predict; never `std::mt19937` or `rand` ({cwe338})"], ["`equal`", "Checking a tag, a MAC or a token", "``", "none: it returns `bool`", "{cwe208}", "you compare anything secret; never `==` or `memcmp` on a MAC"], - ["`error`", "Telling failures apart", "``", "its values are the errors", "none", "you branch on a failure: forged data, a wrong size, no entropy"] + ["`error`", "Telling failures apart", "``", "its values are the errors", "none", "you branch on a failure: forged data, a wrong size, no entropy"], + ["`openssl_memory_resource`", "Keeping every allocation of OpenSSL's in the program's own resource, natively", "``", "`memory_functions_refused`, `memory_functions_not_installed`", "{openssl-mem}", "a native program on OpenSSL must allocate only from its own arena; on WebAssembly, BearSSL allocates nothing"] ] }, "ciphers": { @@ -308,6 +321,7 @@ {"need": "Sign a Bitcoin SegWit v0 input (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`sign_ecdsa`, `to_der`, `normalize_ecdsa`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "ecdsa_der", "section": "crypto-wallets-der"}, {"need": "Derive a Bitcoin Taproot output key and spend by key path (a domain library's job)", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`tweak_xonly`, `keypair::tweak_xonly`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "taproot_tweak", "section": "crypto-wallets-taproot"}, {"need": "Sign where allocation is restricted to the program's arena", "namespace": "webcpp::crypto::curves::secp256k1", "api": "`keypair::make(secret, resource)`", "backend": "libsecp256k1", "jamfile": "/webcpp/crypto//crypto /third_party//secp256k1", "example": "arena_signer", "section": "crypto-memory"}, + {"need": "Keep every allocation of OpenSSL's in the program's arena", "namespace": "webcpp::crypto", "api": "`openssl_memory_resource`, `backends::openssl::install_memory_functions`", "backend": "OpenSSL, natively", "jamfile": "`/webcpp/crypto//crypto` in the program; in the project requirements, `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and `/webcpp/crypto//openssl`", "example": "openssl_memory", "section": "crypto-memory-openssl"}, {"need": "Seed BearSSL's own generator for code that calls BearSSL directly", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "BearSSL's C API", "jamfile": "/webcpp/crypto//crypto /third_party//bearssl", "example": "bearssl_prng", "section": "crypto-entropy-bearssl"}, {"need": "Hash, or compute an HMAC", "namespace": "Boost.Hash2, not this library", "api": "`boost::hash2::sha2_256`, `hmac_sha2_256`", "backend": "none", "jamfile": "`/webcpp/crypto//crypto` brings Boost's headers", "example": "equal_hmac", "section": "crypto-overview-hash2"}, {"need": "Use P-256 (passkeys, JWT's ES256), Ed25519 or X25519", "namespace": "none in this version", "api": "secp256k1 keys and signatures do not interoperate with these curves", "backend": "none", "jamfile": "none", "example": "", "section": "crypto-curves"} @@ -331,6 +345,11 @@ "default_openssl_on_emscripten": "OpenSSL selected as the default in a build for Emscripten.", "has_openssl_on_emscripten": "OpenSSL declared linked, without b2, in a build for Emscripten.", "openssl_on_emscripten": "`/webcpp/crypto//openssl` named in a build for Emscripten.", + "openssl_memory_on_emscripten": "The memory option of the OpenSSL backend set in a build for Emscripten.", + "memory_missing_definition_install": "The memory option set in the program's project, the install called, and `openssl_memory_resource()` not defined.", + "memory_missing_definition_make": "The memory option set in the program's project, a `make` on OpenSSL, and `openssl_memory_resource()` not defined.", + "memory_two_files": "Two files of one program, one compiled with the memory option and one without.", + "memory_option": "OpenSSL's allocations in the program's own resource: the define and OpenSSL in the requirements of the program's project, the resource defined once, the install first in `main`.", "no_backend_on_emscripten": "A program for Emscripten that uses the default backend and links none." }, "fixes": { @@ -349,6 +368,12 @@ "default_openssl_on_emscripten": "Remove the define, or make it `WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL`.", "has_openssl_on_emscripten": "Replace `/webcpp/crypto//openssl` with `/third_party//bearssl`.", "openssl_on_emscripten": "Name `/third_party//bearssl` in its place for the Emscripten build.", + "openssl_memory_on_emscripten": "Remove `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `/third_party//bearssl`. On WebAssembly the backend is BearSSL, which allocates nothing.", + "openssl_memory_on_webassembly": "Remove `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` from the WebAssembly build: give that build a project of its own, without the define and OpenSSL, naming `/third_party//bearssl`. On WebAssembly the backend is BearSSL, which allocates nothing.", + "memory_missing_definition_install": "Define `std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept` once in the program, returning a resource that is never destroyed.", + "memory_missing_definition_make": "Define `std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept` once in the program, returning a resource that is never destroyed.", + "memory_two_files": "Give the define in the requirements of the program's project, with OpenSSL beside it, `project app : requirements WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE /webcpp/crypto//openssl ;`, so that every target of the program gets both.", + "openssl_memory_not_linked": "A target has the define and not OpenSSL: put `/webcpp/crypto//openssl` in the same project requirements as the define, or remove the define.", "canary_missing": "Link the library through b2, `/third_party//bearssl`; built by other means, it must be the pinned commit, with webcpp's `src/canary_bearssl.c`.", "canary_other_commit": "Build the library at the commit of webcpp's submodule, or link it through b2.", "canary_other_configuration": "Build BearSSL in webcpp's configuration (`getentropy`), or link it through b2.", diff --git a/doc/tables/generate.py b/doc/tables/generate.py index c2378051..2a24e7a9 100644 --- a/doc/tables/generate.py +++ b/doc/tables/generate.py @@ -48,8 +48,9 @@ BACKEND_ORDER = ('bearssl', 'openssl', 'ctaes', 'secp256k1', 'system', 'none') NAMESPACE_TITLES = {'root': 'webcpp::crypto', 'ciphers': 'webcpp::crypto::ciphers', 'curves': 'webcpp::crypto::curves'} -RUN_RULES = ('crypto-run', 'webcpp.run', 'webcpp.compile', 'webcpp.compile-diagnostic', - 'webcpp.compile-fail', 'webcpp.link-fail', 'webcpp.example') +RUN_RULES = ('crypto-run', 'memory-run', 'webcpp.run', 'webcpp.compile', + 'webcpp.compile-diagnostic', 'webcpp.compile-fail', 'webcpp.link-fail', + 'webcpp.example') EXPECTED_ERROR = re.compile(r'expected-error@\S+ \{\{(.*)\}\}') SOURCE = re.compile(r'\{([a-z0-9-]+)\}') NOT_MEASURED = 'not measured yet' @@ -112,10 +113,19 @@ def programs(jamfile: Path, inherited: Optional[List[str]] = None) -> Dict[str, def tests(library: Path) -> Dict[str, List[str]]: - """Every program of the test Jamfile and of each message test, with its targets.""" - found = programs(library / 'test' / 'Jamfile') - for jamfile in sorted((library / 'test' / 'messages').glob('*/Jamfile')): - found.update(programs(jamfile)) + """Every program of the test Jamfile, of each message test and of the OpenSSL memory + option's tests (test/openssl_memory), with its targets. A name two Jamfiles declare is a + fault: a table that cites it would name one of two programs.""" + found: Dict[str, List[str]] = {} + test = library / 'test' + jamfiles = [test / 'Jamfile', *sorted((test / 'messages').glob('*/Jamfile'))] + if (test / 'openssl_memory' / 'Jamfile').is_file(): + jamfiles.append(test / 'openssl_memory' / 'Jamfile') + for jamfile in jamfiles: + for name, targets in programs(jamfile).items(): + if name in found: + raise Fault(f'{jamfile}: the test {name} is declared twice') + found[name] = targets return found @@ -146,11 +156,14 @@ def msvc_cases(library: Path) -> Dict[str, str]: class Outcome: - """A fixture's .outcome: its targets, whether it builds, what it prints or contains.""" + """A fixture's .outcome: its targets, whether it builds, whether its program runs, what it + prints or contains. A fixture that builds and runs nothing is a record: a misuse that only + MSVC's linker stops, which links elsewhere.""" def __init__(self, path: Path) -> None: self.targets: List[str] = [] self.succeeds = False + self.runs = False self.output: List[str] = [] self.contains: List[Tuple[str, str]] = [] self.absent: List[Tuple[str, str]] = [] @@ -167,7 +180,7 @@ def __init__(self, path: Path) -> None: elif line.startswith('build:'): self.succeeds = line.split()[1] == 'succeeds' elif line.startswith('run:'): - printing = True + self.runs = printing = True elif line.startswith('contains:'): self.contains.append((section, line[len('contains:'):].strip())) elif line.startswith('not-contains:'): @@ -188,7 +201,7 @@ def fixtures(root: Path) -> Dict[str, Tuple[List[str], Outcome]]: continue outcome = Outcome(case / f'{case.name}.outcome') regions = [('Jamfile', 'jamfile')] - if outcome.succeeds: + if outcome.succeeds and outcome.runs: regions.append((f'{case.name}.outcome', 'output')) for file, wanted in regions: text = (case / file).read_text(encoding='utf-8') @@ -279,6 +292,9 @@ def __init__(self, data: Data, declared: Dict[str, List[str]], self.supported: Dict[Tuple[str, str], List[str]] = {} self.proofs: Dict[Tuple[str, str], List[str]] = {} self.refused: Dict[Tuple[str, str], str] = {} + # Why an operation is missing on the targets its tests leave out, when it is not the + # backend's own reason: a key of crypto.json's elsewhere. + self.elsewhere: Dict[Tuple[str, str], str] = {} for operation in data['operations']: for backend, entry in operation['backends'].items(): key = (operation['id'], backend) @@ -292,6 +308,18 @@ def __init__(self, data: Data, declared: Dict[str, List[str]], self.supported[key] = [target for target in data['targets'] if target in targets] self.proofs[key] = list(entry['tests']) + if 'elsewhere' in entry: + # Only OpenSSL's cells name what stops an operation elsewhere + # (targets()); another backend's reason would never be shown. + if backend != 'openssl': + raise Fault(f'crypto.json: {operation["id"]} on {backend} names ' + f'the reason {entry["elsewhere"]}, which only ' + 'OpenSSL\'s entries may give') + if entry['elsewhere'] not in data['elsewhere']: + raise Fault(f'crypto.json: {operation["id"]} on {backend} names ' + f'the reason {entry["elsewhere"]}, which elsewhere ' + 'does not hold') + self.elsewhere[key] = entry['elsewhere'] else: if entry['refused'] not in refusals: raise Fault(f'crypto.json: {operation["id"]} on {backend} is refused by ' @@ -318,7 +346,8 @@ def targets(self, operation: str, backend: str) -> str: missing = [target for target in self.data['targets'] if target not in self.supported[key]] if missing and backend == 'openssl': - text += f'; not on {", ".join(missing)}: {marked(self.data["elsewhere"]["openssl"])}' + reason = self.elsewhere.get(key, 'openssl') + text += f'; not on {", ".join(missing)}: {marked(self.data["elsewhere"][reason])}' return text def tests(self, operation: str, backend: str) -> str: @@ -514,10 +543,10 @@ def case_list(entries: List[Tuple[str, str, List[Tuple[str, str]]]]) -> str: def jamfiles_page(data: Data, cases: Dict[str, Tuple[List[str], Outcome]]) -> str: - """Every fixture that builds: its Jamfile, its targets and what it prints.""" + """Every fixture that builds and runs: its Jamfile, its targets and what it prints.""" entries: List[Tuple[str, str, List[Tuple[str, str]]]] = [] for name, (_, outcome) in cases.items(): - if not outcome.succeeds: + if not outcome.succeeds or not outcome.runs: continue entries.append((code(name), marked(cite(data, data['fixtures'][name])), [ (f'Its Jamfile, built and run on {", ".join(outcome.targets)}:', @@ -569,6 +598,14 @@ def messages_page(data: Data, refusals: Dict[str, Tuple[str, List[str]]], 'at link time; its text is MSVC\'s own, the same instruction in MSVC\'s words, and ' 'two files compiled with different settings stop the link with LNK2038.\n\n') text += table(['Case', 'Stops', 'Fix'], windows, 'cols="1,1,4",') + records = [(code(name), marked(cite(data, data['fixtures'][name])), + [('Its Jamfile, which builds on ' + ', '.join(outcome.targets) + ':', + included(name, 'Jamfile', 'jamfile'))]) + for name, (_, outcome) in cases.items() if outcome.succeeds and not outcome.runs] + if records: + text += ('\nElsewhere than MSVC these mistakes build, and nothing stops them; the fixtures ' + 'record it:\n\n') + text += case_list(records) return text diff --git a/doc/tables/generate_test.py b/doc/tables/generate_test.py index 8f0a0329..9990c895 100644 --- a/doc/tables/generate_test.py +++ b/doc/tables/generate_test.py @@ -6,12 +6,14 @@ # https://www.boost.org/LICENSE_1_0.txt) """Checks generate.py's readers and writers on small fixtures of their own: the Jamfile reader (a -program inside an `if`, a rule's body, the targets a program inherits), the outcome reader (each -directive and section), the Doc Comment reader (a line reference left out), and the writers whose -output a reader of the page sees (inline code that holds a `+` or a backtick, a failing fixture's -output per target, a comparison table's names of code, the decision table's Jamfile column). -generate.py --check proves only that the committed tables are what generate.py writes now: a reader -that regresses and is regenerated in the same change would pass it, and fails here. +program inside an `if`, a rule's body, the targets a program inherits, the memory option's tests, a +name declared twice), a backend's reason for the targets an operation misses (OpenSSL's alone), the +outcome reader (each directive and section), the Doc Comment reader (a line reference left out), +and the writers whose output a reader of the page sees (inline code that holds a `+` or a backtick, +a failing fixture's output per target, a comparison table's names of code, the decision table's +Jamfile column). generate.py --check proves only that the committed tables are what generate.py +writes now: a reader that regresses and is regenerated in the same change would pass it, and fails +here. Usage: generate_test.py [...]. The doc build runs it before generate.py --check (doc/Jamfile). Exit 0, or 1 at the first failing case. @@ -60,6 +62,58 @@ def test_a_program_inside_an_if_is_a_fault(scratch: Path) -> None: raise AssertionError('a program inside an if was read as declared everywhere') +def test_the_memory_option_s_tests_are_declared(scratch: Path) -> None: + # The OpenSSL memory option's programs live in test/openssl_memory, each through its own + # rule; a name that two Jamfiles declare is a fault, since a table would cite one of them. + written(scratch, 'test/Jamfile', 'webcpp.targets native wasip2 ;\ncrypto-run a : a.cpp ;\n') + written(scratch, 'test/openssl_memory/Jamfile', ( + 'webcpp.targets native ;\n' + 'rule memory-run ( name : sources + : requirements * )\n{\n' + ' webcpp.run $(name) : $(sources) : $(requirements) ;\n}\n' + 'memory-run late : late_test.cpp : multi ;\n')) + found = generate.tests(scratch) + assert found == {'a': ['native', 'wasip2'], 'late': ['native']}, found + written(scratch, 'test/openssl_memory/Jamfile', 'memory-run a : a_test.cpp ;\n') + try: + generate.tests(scratch) + except generate.Fault as fault: + assert 'a' in str(fault) and 'twice' in str(fault), fault + else: + raise AssertionError('a test declared twice was read as one') + + +def test_a_backend_says_why_it_is_missing_elsewhere(_: Path) -> None: + # OpenSSL's operations are missing where /webcpp/crypto//openssl stops the build, unless + # the operation names its own reason: the memory option is refused on every WebAssembly + # target, wasip2 and wasip3 included, where OpenSSL itself builds. + data = {'targets': ['native', 'wasip2', 'emscripten'], + 'elsewhere': {'openssl': 'the build stops', 'memory': 'config.hpp refuses it'}, + 'operations': [ + {'id': 'gcm', 'backends': {'openssl': {'tests': ['g']}}}, + {'id': 'memory', 'backends': {'openssl': {'tests': ['m'], + 'elsewhere': 'memory'}}}]} + matrix = generate.Matrix(data, {'g': ['native', 'wasip2'], 'm': ['native']}, {}) + assert matrix.targets('gcm', 'openssl') == 'native, wasip2; not on emscripten: the build stops' + assert matrix.targets('memory', 'openssl') == ( + 'native; not on wasip2, emscripten: config.hpp refuses it'), matrix.targets('memory', + 'openssl') + + +def test_a_reason_elsewhere_is_openssl_s_alone(_: Path) -> None: + # Only OpenSSL's cells say why an operation is missing on a target; a reason on another + # backend's entry would be read and never shown, so it is a fault. + data = {'targets': ['native', 'wasip2'], + 'elsewhere': {'openssl': 'the build stops', 'memory': 'config.hpp refuses it'}, + 'operations': [{'id': 'gcm', 'backends': {'bearssl': {'tests': ['g'], + 'elsewhere': 'memory'}}}]} + try: + generate.Matrix(data, {'g': ['native']}, {}) + except generate.Fault as fault: + assert 'gcm on bearssl' in str(fault) and 'memory' in str(fault), fault + else: + raise AssertionError('a reason elsewhere on bearssl was read and never shown') + + def test_an_outcome_reads_each_directive(scratch: Path) -> None: outcome = generate.Outcome(written(scratch, 'case.outcome', ( '# A comment\n[all]\ntargets: native wasip2\nbuild: fails\n' @@ -127,6 +181,25 @@ def test_a_failing_fixture_lists_its_texts_per_target(scratch: Path) -> None: raise AssertionError('a section with no label was printed') +def test_a_fixture_that_builds_and_runs_nothing_is_a_record(scratch: Path) -> None: + # A misuse that only MSVC's linker stops builds elsewhere: its fixture says build: succeeds + # with no run:. It is no program of the Jamfiles page; the messages page lists it after + # MSVC's cases, its Jamfile included, and needs no output region. + data = {'outcome_sections': {'all': 'every target'}, 'sources': {}, 'fixes': {}, + 'fixtures': {'program': 'A program.', 'record': 'Two files, one with an option.'}} + program = generate.Outcome(written(scratch, 'program.outcome', ( + 'targets: native\nbuild: succeeds\nrun: app\nhello\n'))) + record = generate.Outcome(written(scratch, 'record.outcome', ( + 'targets: native\nbuild: succeeds\n'))) + assert program.runs and not record.runs, (program.runs, record.runs) + cases = {'program': ([], program), 'record': ([], record)} + programs = generate.jamfiles_page(data, cases) + assert '`+program+`' in programs and 'record' not in programs, programs + messages = generate.messages_page(data, {}, cases, {}) + assert '`+record+`:: Two files, one with an option.' in messages, messages + assert 'record/Jamfile[tag=jamfile]' in messages and 'program' not in messages, messages + + def test_a_comparison_column_is_headed_by_its_plain_name(_: Path) -> None: data = {'sources': {}, 'namespaces': {'ciphers': { 'columns': ['Algorithm', 'AEAD'], @@ -159,10 +232,14 @@ def test_the_decision_table_writes_no_jamfile_as_prose(scratch: Path) -> None: CASES: list[Callable[[Path], None]] = [ test_a_rule_body_declares_nothing, test_a_program_inside_an_if_is_a_fault, + test_the_memory_option_s_tests_are_declared, + test_a_backend_says_why_it_is_missing_elsewhere, + test_a_reason_elsewhere_is_openssl_s_alone, test_an_outcome_reads_each_directive, test_a_brief_leaves_out_a_line_reference, test_code_that_holds_a_plus_is_one_span, test_a_failing_fixture_lists_its_texts_per_target, + test_a_fixture_that_builds_and_runs_nothing_is_a_record, test_a_comparison_column_is_headed_by_its_plain_name, test_the_decision_table_writes_no_jamfile_as_prose, ] diff --git a/example/Jamfile b/example/Jamfile index 10c2c6a4..d124518c 100644 --- a/example/Jamfile +++ b/example/Jamfile @@ -60,3 +60,13 @@ webcpp.example taproot_tweak.cpp : /third_party//secp256k1 ; # The key pair's one allocation counted in the program's own arena. webcpp.example arena_signer.cpp : /third_party//secp256k1 ; + +# OpenSSL's allocations sent to the program's own resource, natively only: the +# define and OpenSSL given together, as a program's project requirements give +# them (doc/jamfile.adoc); its work runs on a thread of its own. +# tag::openssl_memory[] +webcpp.example openssl_memory.cpp + : WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE /webcpp/crypto//openssl + multi + : native ; +# end::openssl_memory[] diff --git a/example/openssl_memory.cpp b/example/openssl_memory.cpp new file mode 100644 index 00000000..e8ae4cd9 --- /dev/null +++ b/example/openssl_memory.cpp @@ -0,0 +1,82 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Sends every allocation of OpenSSL's to the program's own memory resource, natively, then seals +// and opens one block with AES-256-GCM on OpenSSL, on a worker thread as an audio engine's or a +// server's would. Built with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, /webcpp/crypto//openssl and +// threads (example/Jamfile). +// tag::program[] +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace crypto = webcpp::crypto; + +// tag::resource[] +// Declared by crypto under WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE, defined once by the program. +// Never destroyed: OpenSSL frees through it after main returns. The synchronized pool serves +// OpenSSL on any thread. +std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept { + // Never deleted, on purpose; a new that fails this early ends the program, which has no + // resource for OpenSSL. + // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,bugprone-unhandled-exception-at-new) + static auto* const resource = new std::pmr::synchronized_pool_resource; + return *resource; +} + +// end::resource[] +int main() { + // tag::install[] + // The first statement of main: before any thread starts and before anything uses OpenSSL. + auto const installed = crypto::backends::openssl::install_memory_functions(); + if (!installed) { + std::string const message = installed.error().message(); + std::printf("install: %s\n", message.c_str()); + return 1; + } + // end::install[] + + bool ok = false; + std::thread worker([&ok] { + // A zero key and IV keep the output stable: a real program draws its key from + // random_device and never reuses an IV under it. + std::array const key{}; + std::array const iv{}; + std::array data{}; + { + auto aead = crypto::ciphers::aes256_gcm::make(key); + if (aead) { + auto const tag = aead->seal(iv, {}, data); + ok = + tag && aead->open(iv, {}, data, *tag) && data == std::array{}; + } else { + std::string const message = aead.error().message(); + std::printf("make: %s\n", message.c_str()); + } + } + // tag::thread[] + // The thread's last call into OpenSSL, on every path: it gives the thread's own blocks back + // to the resource now. On Windows, whose static libcrypto is never told that a thread ends, + // they would otherwise stay in the resource until the process ends. + OPENSSL_thread_stop(); + // end::thread[] + }); + worker.join(); + auto const name = crypto::ciphers::aes256_gcm::backend_type::name; + std::printf("aes256_gcm %s backend=%.*s\n", ok ? "ok" : "FAILED", static_cast(name.size()), + name.data()); + return ok ? 0 : 1; +} + +// end::program[] diff --git a/example/openssl_memory.expected b/example/openssl_memory.expected new file mode 100644 index 00000000..f02f682d --- /dev/null +++ b/example/openssl_memory.expected @@ -0,0 +1 @@ +aes256_gcm ok backend=openssl diff --git a/include/webcpp/crypto/backends/openssl.hpp b/include/webcpp/crypto/backends/openssl.hpp index 1bf7f7ee..efa857d9 100644 --- a/include/webcpp/crypto/backends/openssl.hpp +++ b/include/webcpp/crypto/backends/openssl.hpp @@ -8,7 +8,9 @@ The backend OpenSSL: OpenSSL 3.5.9 built from `third_party/libs/openssl` by `/webcpp/crypto//openssl`, static, on native, wasip2 and wasip3; never on Emscripten. It serves `ciphers::aes128/192/256` and `ciphers::gcm<...>`. Its - `make` allocates through OpenSSL's own functions. On MSVC, wasip2 and wasip3 OpenSSL is compiled + `make` allocates through OpenSSL's own functions, unless a native program sets + `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, which sends every allocation of OpenSSL's to + `openssl_memory_resource()`. On MSVC, wasip2 and wasip3 OpenSSL is compiled without assembly: table-driven AES and 4-bit GHASH, no AES-NI, not constant time. OpenSSL's default initialisation reads the configuration file of the directory it was configured with (`/etc/ssl/openssl.cnf`, when the machine has one), as any program of @@ -50,6 +52,7 @@ #include #include +#include #include #include @@ -58,16 +61,234 @@ #include #include #include +#include +#include +#include #include #include #include +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + +namespace webcpp::crypto { + +/** + * The resource every allocation of OpenSSL's in the process goes to, from any thread: + * declared by `` under + * `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE` and defined once by the program. It returns a + * resource that is never destroyed and is thread-safe whenever OpenSSL may run on two threads + * at once: OpenSSL frees through it after `main` returns. + * + * It must serve OpenSSL's initialisation, which the first use of OpenSSL in the process runs, + * usually the first `make`: on an OpenSSL built with threads, which MSVC always builds, a + * resource that fails during OpenSSL's base initialisation makes OpenSSL re-enter it, and that + * call never returns: the process aborts on macOS, deadlocks on Linux and spins on Windows. Only on + * an OpenSSL built without threads does it return, and every `make` then gives `backend_failure`. + * On Windows a thread that used OpenSSL keeps its blocks in the resource until the process ends + * unless it calls `OPENSSL_thread_stop()` before it ends. + * + * @return The program's resource. + * @see "OpenSSL's allocations in your own memory resource", in the guide. + */ +std::pmr::memory_resource& openssl_memory_resource() noexcept; + +} // namespace webcpp::crypto + +namespace webcpp::crypto::detail { + +/** + * The alignment of the adapter's blocks, and the size of the header before each that + * holds its size: at least what the system's `malloc` gives OpenSSL without the option + * (16 on x86-64 and arm64; on macOS arm64 `alignof(std::max_align_t)` is only 8). + */ +inline constexpr std::size_t openssl_block_alignment = + (std::max)(alignof(std::max_align_t), std::size_t{__STDCPP_DEFAULT_NEW_ALIGNMENT__}); + +} // namespace webcpp::crypto::detail + +// The adapter: three C functions given to OpenSSL, with C linkage since OpenSSL calls +// them as C, inline with external linkage so that every file of the program sees one +// function, which the install and make recognise by its address. +extern "C" { + +/** + * OpenSSL's `malloc` under the option: a block of the program's resource, after a header + * that holds its size. + * + * @param size The bytes OpenSSL asks for; 0, or a size whose header overflows, gives null. + * @return The block, or null, which OpenSSL takes as a failure. + */ +inline void* webcpp_crypto_openssl_malloc(std::size_t size, char const* /*file*/, + int /*line*/) noexcept { + constexpr std::size_t header = webcpp::crypto::detail::openssl_block_alignment; + // NOLINTNEXTLINE(readability-redundant-parentheses) + if (size == 0 || size > (std::numeric_limits::max)() - header) { + return nullptr; + } +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + try { +#endif + void* const block = + webcpp::crypto::openssl_memory_resource().allocate(header + size, header); + if (block == nullptr) { + return nullptr; + } + std::memcpy(block, &size, sizeof size); + return static_cast(block) + header; +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + } catch (...) { // OpenSSL is C: no exception may cross it + return nullptr; + } +#endif +} + +/** + * OpenSSL's `free` under the option: the block back to the program's resource. + * + * @param address A block of the adapter's, or null. + */ +inline void webcpp_crypto_openssl_free(void* address, char const* /*file*/, int /*line*/) noexcept { + if (address == nullptr) { + return; + } + constexpr std::size_t header = webcpp::crypto::detail::openssl_block_alignment; + auto* const block = static_cast(address) - header; + std::size_t size = 0; + std::memcpy(&size, block, sizeof size); +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + try { +#endif + webcpp::crypto::openssl_memory_resource().deallocate(block, header + size, header); +#ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + // NOLINTNEXTLINE(bugprone-empty-catch): no exception may cross OpenSSL + } catch (...) { + } +#endif +} + +/** + * OpenSSL's `realloc` under the option, as C's: null is `malloc`, 0 frees and gives null, + * and a failure gives null and leaves the old block valid. + * + * @param address The block, or null. + * @param size The new size. + * @return The new block, or null. + */ +inline void* webcpp_crypto_openssl_realloc(void* address, std::size_t size, char const* file, + int line) noexcept { + if (address == nullptr) { + return webcpp_crypto_openssl_malloc(size, file, line); + } + if (size == 0) { + webcpp_crypto_openssl_free(address, file, line); + return nullptr; + } + void* const moved = webcpp_crypto_openssl_malloc(size, file, line); + if (moved == nullptr) { + return nullptr; + } + constexpr std::size_t header = webcpp::crypto::detail::openssl_block_alignment; + std::size_t old = 0; + std::memcpy(&old, static_cast(address) - header, sizeof old); + std::memcpy(moved, address, (std::min)(old, size)); + webcpp_crypto_openssl_free(address, file, line); + return moved; +} + +} // extern "C" + +namespace webcpp::crypto::detail { + +/** Whether OpenSSL's functions are the adapter's: three loads, no call into OpenSSL's heap. */ +inline bool openssl_adapter_installed() noexcept { + CRYPTO_malloc_fn m = nullptr; + CRYPTO_realloc_fn r = nullptr; + CRYPTO_free_fn f = nullptr; + CRYPTO_get_mem_functions(&m, &r, &f); + return m == &webcpp_crypto_openssl_malloc && r == &webcpp_crypto_openssl_realloc && + f == &webcpp_crypto_openssl_free; +} + +/** + * Whether OpenSSL's functions are its own defaults (`mem.c:23-25`): the three addresses + * are those of `CRYPTO_malloc`, `CRYPTO_realloc` and `CRYPTO_free`. A libcrypto DLL, which + * webcpp never builds, is refused by this comparison. + */ +inline bool openssl_defaults_installed() noexcept { + CRYPTO_malloc_fn m = nullptr; + CRYPTO_realloc_fn r = nullptr; + CRYPTO_free_fn f = nullptr; + CRYPTO_get_mem_functions(&m, &r, &f); + return m == &CRYPTO_malloc && r == &CRYPTO_realloc && f == &CRYPTO_free; +} + +} // namespace webcpp::crypto::detail + +#ifdef _MSC_VER +#pragma detect_mismatch("webcpp_crypto_openssl_memory", "resource") +#endif + +#elif defined(_MSC_VER) +#pragma detect_mismatch("webcpp_crypto_openssl_memory", "openssl") +#endif // WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + +namespace webcpp::crypto::detail { + +/** + * The check every OpenSSL `make` runs first, before any call into OpenSSL that allocates: + * with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`, `memory_functions_not_installed` unless the + * adapter is installed; without it, nothing. + * + * @return Nothing, or `memory_functions_not_installed`. + */ +[[nodiscard]] inline boost::system::result openssl_memory_guard() noexcept { +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + if (!openssl_adapter_installed()) { + return error::memory_functions_not_installed; + } +#endif + return {}; +} + +} // namespace webcpp::crypto::detail + namespace webcpp::crypto::backends { // The backend OpenSSL, declared and documented in config.hpp. struct openssl { /** The backend's name, which the examples print. */ static constexpr std::string_view name = "openssl"; + +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + /** + * Installs webcpp's adapter as OpenSSL's memory functions, so that every allocation of + * OpenSSL's in the process goes to `openssl_memory_resource()`. Called as the first + * statement of `main`, before any thread starts and anything uses OpenSSL. The first use + * of OpenSSL after it, usually the first `make`, runs OpenSSL's initialisation through the + * resource: on an OpenSSL built with threads (MSVC's only build) a failure during its + * base initialisation makes that call never return; on one built without threads every + * `make` then gives `backend_failure`. + * + * @return Nothing, also when the adapter is installed already; + * `memory_functions_refused` when another party installed its own functions, or OpenSSL + * has allocated with its own and refuses the change. + */ + [[nodiscard]] static boost::system::result install_memory_functions() noexcept { + if (detail::openssl_adapter_installed()) { + return {}; + } + if (!detail::openssl_defaults_installed()) { + return error::memory_functions_refused; + } + // The resource is constructed here, outside OpenSSL's allocation path. + static_cast(openssl_memory_resource()); + if (CRYPTO_set_mem_functions(&webcpp_crypto_openssl_malloc, &webcpp_crypto_openssl_realloc, + &webcpp_crypto_openssl_free) != 1) { + return error::memory_functions_refused; + } + return {}; + } +#endif }; } // namespace webcpp::crypto::backends @@ -120,6 +341,9 @@ inline boost::system::error_code openssl_context(EVP_CIPHER_CTX*& made_context, char const* cipher_name, std::span key_bytes, bool is_encrypting, bool use_padding) noexcept { + if (auto const guard = openssl_memory_guard(); !guard) { + return guard.error(); + } ERR_set_mark(); EVP_CIPHER* const fetched_cipher = EVP_CIPHER_fetch(nullptr, cipher_name, nullptr); if (fetched_cipher == nullptr) { diff --git a/include/webcpp/crypto/config.hpp b/include/webcpp/crypto/config.hpp index 8bfc20d3..558e0a3d 100644 --- a/include/webcpp/crypto/config.hpp +++ b/include/webcpp/crypto/config.hpp @@ -19,7 +19,9 @@ // MrDocs parses crypto natively, as a build with exceptions does, where neither // macro is defined: these definitions, each undone at once, are the ones the // reference lists. WEBCPP_CRYPTO_HAS_OPENSSL stays when the reference's build -// defines it, linking OpenSSL to read the backend headers (doc/Jamfile). +// defines it, linking OpenSSL to read the backend headers (doc/Jamfile), and +// WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE stays, so that the reference lists the +// declarations of the memory option too. #ifdef __MRDOCS__ /** Defined when webcpp::crypto is built without exceptions: when webcpp has none (the @@ -118,6 +120,16 @@ */ #define WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL #undef WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL +/** + Defined by a native program, in its project's requirements beside `/webcpp/crypto//openssl`, to + send every allocation of OpenSSL's in the process to a resource of the program's: the program + then defines `openssl_memory_resource()` once and calls + `backends::openssl::install_memory_functions()` as the first statement of `main`. Refused on + every WebAssembly target, and natively without OpenSSL linked. + + @see "OpenSSL's allocations in your own memory resource", in the guide. +*/ +#define WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE #endif #if !defined(WEBCPP_HAS_EXCEPTIONS) && !defined(WEBCPP_CRYPTO_NO_EXCEPTIONS) @@ -143,6 +155,13 @@ #if defined(WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL) && defined(WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL) #error "webcpp::crypto: both WEBCPP_CRYPTO_DEFAULT_BACKEND_OPENSSL and WEBCPP_CRYPTO_DEFAULT_BACKEND_BEARSSL are defined. Keep one." #endif +#if defined(WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE) && defined(WEBCPP_CRYPTO_WEBASSEMBLY) +#error "webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE is an option of native programs, and this program is built for WebAssembly. Remove that define from the program's Jamfile." +#endif +#if defined(WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE) && !defined(WEBCPP_CRYPTO_WEBASSEMBLY) && \ + !defined(WEBCPP_CRYPTO_HAS_OPENSSL) +#error "webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE routes OpenSSL's allocations, and OpenSSL is not linked. In the program's Jamfile, add /webcpp/crypto//openssl beside /webcpp/crypto//crypto, or remove that define. (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)" +#endif // clang-format on // The default backend of the AEADs: the one the program selects; else diff --git a/include/webcpp/crypto/error.hpp b/include/webcpp/crypto/error.hpp index 25188f11..408997f7 100644 --- a/include/webcpp/crypto/error.hpp +++ b/include/webcpp/crypto/error.hpp @@ -66,8 +66,19 @@ enum class error : int { invalid_signature = 11, /** A backend failed where its contract says it does not. */ backend_failure = 12, - // 13 and 14 are reserved for OpenSSL's memory option (memory_functions_refused and - // memory_functions_not_installed), which declares them; never reused. + /** + * OpenSSL's memory functions could not be installed: OpenSSL has already allocated, or another + * party installed its own. + * + * Returned by `backends::openssl::install_memory_functions`, with + * `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. + */ + memory_functions_refused = 13, + /** + * OpenSSL's memory functions are not webcpp::crypto's, so a `make` of the OpenSSL backend + * refuses to run, with `WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE`. + */ + memory_functions_not_installed = 14, }; namespace detail { @@ -89,6 +100,15 @@ inline const char* message_of(int error_value) noexcept { case error::invalid_signature: return "the signature does not verify or is not a valid encoding"; case error::backend_failure: return "the backend failed where it should not"; + case error::memory_functions_refused: + return "OpenSSL's memory functions cannot be installed: OpenSSL has already " + "allocated, or another party installed its own. Call " + "backends::openssl::install_memory_functions() as the first statement of " + "main, before anything uses OpenSSL."; + case error::memory_functions_not_installed: + return "OpenSSL's memory functions are not webcpp::crypto's. Call " + "backends::openssl::install_memory_functions() as the first statement of " + "main, and let nothing else call CRYPTO_set_mem_functions."; } return "unknown webcpp.crypto error"; } diff --git a/test/Jamfile b/test/Jamfile index a921e26c..37fd1037 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -103,6 +103,7 @@ webcpp.compile-fail openssl_named_c_on_emscripten : openssl_named_c_test.c : /webcpp/crypto//openssl : emscripten ; build-project msvc ; +build-project openssl_memory ; # The default backend (spec section 5), one combination of linked and selected # backends per program, each on the targets where its answer holds. diff --git a/test/error_test.cpp b/test/error_test.cpp index 8c9ce52a..b56beef1 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -35,6 +35,8 @@ int main() { BOOST_TEST_EQ(static_cast(error::invalid_public_key), 10); BOOST_TEST_EQ(static_cast(error::invalid_signature), 11); BOOST_TEST_EQ(static_cast(error::backend_failure), 12); + BOOST_TEST_EQ(static_cast(error::memory_functions_refused), 13); + BOOST_TEST_EQ(static_cast(error::memory_functions_not_installed), 14); boost::system::error_code const code = error::authentication_failed; BOOST_TEST_EQ(std::string_view(code.category().name()), "webcpp.crypto"); @@ -46,9 +48,17 @@ int main() { BOOST_TEST_EQ(crypto::make_error_code(error::authentication_failed).message(), "the authentication tag does not match"); - // 13 and 14 are reserved, not declared: their messages are the unknown one. - BOOST_TEST_EQ(crypto::make_error_code(static_cast(13)).message(), - "unknown webcpp.crypto error"); + // The memory option's two errors carry spec section 3.7's texts. + BOOST_TEST_EQ( + crypto::make_error_code(error::memory_functions_refused).message(), + "OpenSSL's memory functions cannot be installed: OpenSSL has already allocated, or " + "another party installed its own. Call backends::openssl::install_memory_functions() as " + "the first statement of main, before anything uses OpenSSL."); + BOOST_TEST_EQ( + crypto::make_error_code(error::memory_functions_not_installed).message(), + "OpenSSL's memory functions are not webcpp::crypto's. Call " + "backends::openssl::install_memory_functions() as the first statement of main, and let " + "nothing else call CRYPTO_set_mem_functions."); BOOST_TEST_EQ(crypto::make_error_code(static_cast(99)).message(), "unknown webcpp.crypto error"); // The form that allocates nothing returns the whole message, and copies into the buffer @@ -61,13 +71,13 @@ int main() { // Every defined value has its own message, never the unknown one. std::set messages; - for (int value = 1; value <= 12; ++value) { + for (int value = 1; value <= 14; ++value) { std::string const text = crypto::error_category().message(value); BOOST_TEST(!text.empty()); BOOST_TEST_NE(text, "unknown webcpp.crypto error"); messages.insert(text); } - BOOST_TEST_EQ(messages.size(), 12u); + BOOST_TEST_EQ(messages.size(), 14u); // The guards of the buffer form: a null buffer or a size of 0 writes nothing, a size of 1 // writes the terminating zero alone, and a message longer than the buffer is cut with one. diff --git a/test/messages/Jamfile b/test/messages/Jamfile index f58bc893..16690c6a 100644 --- a/test/messages/Jamfile +++ b/test/messages/Jamfile @@ -21,3 +21,5 @@ build-project bearssl_not_linked ; build-project openssl_only_on_wasi ; build-project aes_on_bearssl ; build-project secp256k1_other_backend ; +build-project openssl_memory_on_webassembly ; +build-project openssl_memory_not_linked ; diff --git a/test/messages/openssl_memory_not_linked/Jamfile b/test/messages/openssl_memory_not_linked/Jamfile new file mode 100644 index 00000000..f397d821 --- /dev/null +++ b/test/messages/openssl_memory_not_linked/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +webcpp.compile-diagnostic openssl_memory_not_linked : openssl_memory_not_linked.cpp + : WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE : native ; diff --git a/test/messages/openssl_memory_not_linked/openssl_memory_not_linked.cpp b/test/messages/openssl_memory_not_linked/openssl_memory_not_linked.cpp new file mode 100644 index 00000000..7b49ca6a --- /dev/null +++ b/test/messages/openssl_memory_not_linked/openssl_memory_not_linked.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A native program that sets the memory option of the OpenSSL backend and does not link OpenSSL +// stops with the instruction to add /webcpp/crypto//openssl (spec section 3.7). + +// clang-format off +// expected-error@webcpp/crypto/config.hpp:* {{webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE routes OpenSSL's allocations, and OpenSSL is not linked. In the program's Jamfile, add /webcpp/crypto//openssl beside /webcpp/crypto//crypto, or remove that define. (without b2: define WEBCPP_CRYPTO_HAS_OPENSSL=1 and link libcrypto)}} +// clang-format on +#include + +int main() { + return 0; +} diff --git a/test/messages/openssl_memory_on_webassembly/Jamfile b/test/messages/openssl_memory_on_webassembly/Jamfile new file mode 100644 index 00000000..b0b27fc7 --- /dev/null +++ b/test/messages/openssl_memory_on_webassembly/Jamfile @@ -0,0 +1,15 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/crypto//crypto ; + +import webcpp ; + +# OpenSSL is linked, as on a WASI program that names it: what is refused is +# the option. +webcpp.compile-diagnostic openssl_memory_on_webassembly : openssl_memory_on_webassembly.cpp + : WEBCPP_CRYPTO_HAS_OPENSSL=1 WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + : wasip2 wasip3 ; diff --git a/test/messages/openssl_memory_on_webassembly/openssl_memory_on_webassembly.cpp b/test/messages/openssl_memory_on_webassembly/openssl_memory_on_webassembly.cpp new file mode 100644 index 00000000..74acf6bc --- /dev/null +++ b/test/messages/openssl_memory_on_webassembly/openssl_memory_on_webassembly.cpp @@ -0,0 +1,17 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program for wasip2 or wasip3 that sets the memory option of the OpenSSL backend stops with +// the instruction to remove the define: the option is native (spec section 3.7). + +// clang-format off +// expected-error@webcpp/crypto/config.hpp:* {{webcpp::crypto: WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE is an option of native programs, and this program is built for WebAssembly. Remove that define from the program's Jamfile.}} +// clang-format on +#include + +int main() { + return 0; +} diff --git a/test/msvc/Jamfile b/test/msvc/Jamfile index e4699354..1521c91d 100644 --- a/test/msvc/Jamfile +++ b/test/msvc/Jamfile @@ -38,3 +38,7 @@ build-project ctaes_not_linked ; build-project secp256k1_not_linked ; build-project openssl_old ; build-project secp256k1_other_backend ; +build-project openssl_memory_not_linked ; +build-project memory_missing_definition_install ; +build-project memory_missing_definition_make ; +build-project memory_two_files ; diff --git a/test/msvc/memory_missing_definition_install/Jamfile b/test/msvc/memory_missing_definition_install/Jamfile new file mode 100644 index 00000000..617fe743 --- /dev/null +++ b/test/msvc/memory_missing_definition_install/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.link-fail memory_missing_definition_install : app.cpp + : /webcpp/crypto//crypto /webcpp/crypto//openssl + WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + : native ; diff --git a/test/msvc/memory_missing_definition_install/app.cpp b/test/msvc/memory_missing_definition_install/app.cpp new file mode 100644 index 00000000..fb7332a9 --- /dev/null +++ b/test/msvc/memory_missing_definition_install/app.cpp @@ -0,0 +1,15 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// MSVC's case of the fixture memory_missing_definition_install (spec section 8.6): a program that +// sets the memory option, calls install_memory_functions() and defines no +// webcpp::crypto::openssl_memory_resource() fails to link on that name, LNK2019 and LNK1120. +// The texts of ld64 and GNU ld are checked by tools/test/crypto_jamfiles_test.py. +#include + +int main() { + return webcpp::crypto::backends::openssl::install_memory_functions() ? 0 : 1; +} diff --git a/test/msvc/memory_missing_definition_make/Jamfile b/test/msvc/memory_missing_definition_make/Jamfile new file mode 100644 index 00000000..ac5d82a1 --- /dev/null +++ b/test/msvc/memory_missing_definition_make/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.link-fail memory_missing_definition_make : app.cpp + : /webcpp/crypto//crypto /webcpp/crypto//openssl + WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + : native ; diff --git a/test/msvc/memory_missing_definition_make/app.cpp b/test/msvc/memory_missing_definition_make/app.cpp new file mode 100644 index 00000000..fc243b77 --- /dev/null +++ b/test/msvc/memory_missing_definition_make/app.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// MSVC's case of the fixture memory_missing_definition_make (spec section 8.6): a program that +// sets the memory option, makes AES-256-GCM on OpenSSL and defines no +// webcpp::crypto::openssl_memory_resource() fails to link on that name, LNK2019 and LNK1120. +// The texts of ld64 and GNU ld are checked by tools/test/crypto_jamfiles_test.py. +#include +#include +#include + +#include +#include + +int main() { + std::array const key{}; + auto const aead = webcpp::crypto::ciphers::gcm< + webcpp::crypto::ciphers::aes256>::make(key); + return aead ? 0 : 1; +} diff --git a/test/msvc/memory_two_files/Jamfile b/test/msvc/memory_two_files/Jamfile new file mode 100644 index 00000000..4d6f3874 --- /dev/null +++ b/test/msvc/memory_two_files/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.link-fail memory_two_files : main.cpp with.cpp + : /webcpp/crypto//crypto /webcpp/crypto//openssl + : native ; diff --git a/test/msvc/memory_two_files/main.cpp b/test/msvc/memory_two_files/main.cpp new file mode 100644 index 00000000..5e329bb4 --- /dev/null +++ b/test/msvc/memory_two_files/main.cpp @@ -0,0 +1,25 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Two translation units, one compiled with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE (with.cpp) and +// one without (this file), whose OpenSSL make functions differ. MSVC's linker compares the values +// of backends/openssl.hpp's #pragma detect_mismatch and fails with LNK2038 (spec section 3.7). +// Elsewhere the program links (the fixture memory_two_files records it); it is MSVC's case alone. +#include +#include +#include + +#include +#include + +bool make_with_the_option(); + +int main() { + std::array const key{}; + auto const aead = webcpp::crypto::ciphers::gcm< + webcpp::crypto::ciphers::aes256>::make(key); + return aead && make_with_the_option() ? 0 : 1; +} diff --git a/test/msvc/memory_two_files/with.cpp b/test/msvc/memory_two_files/with.cpp new file mode 100644 index 00000000..95adedfa --- /dev/null +++ b/test/msvc/memory_two_files/with.cpp @@ -0,0 +1,29 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The second translation unit of memory_two_files: it sets the memory option before its +// includes, defines the program's resource and makes AES-256-GCM on OpenSSL under the option, +// so its detect_mismatch value of webcpp_crypto_openssl_memory differs from main.cpp's. +#define WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE + +#include +#include +#include + +#include +#include +#include + +std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept { + return *std::pmr::new_delete_resource(); +} + +bool make_with_the_option() { + std::array const key{}; + return webcpp::crypto::ciphers::gcm< + webcpp::crypto::ciphers::aes256>::make(key) + .has_value(); +} diff --git a/test/msvc/openssl_memory_not_linked/Jamfile b/test/msvc/openssl_memory_not_linked/Jamfile new file mode 100644 index 00000000..107c68a7 --- /dev/null +++ b/test/msvc/openssl_memory_not_linked/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.compile-fail openssl_memory_not_linked : app.cpp + : WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE /webcpp/crypto//crypto + : native ; diff --git a/test/msvc/openssl_memory_not_linked/app.cpp b/test/msvc/openssl_memory_not_linked/app.cpp new file mode 100644 index 00000000..c35741c3 --- /dev/null +++ b/test/msvc/openssl_memory_not_linked/app.cpp @@ -0,0 +1,14 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A native program that sets the memory option of the OpenSSL backend and does not link OpenSSL +// stops at config.hpp's instruction to add /webcpp/crypto//openssl (spec section 3.7): on MSVC +// the compile fails. The text is checked on clang, in test/messages/openssl_memory_not_linked. +#include + +int main() { + return 0; +} diff --git a/test/openssl_memory/Jamfile b/test/openssl_memory/Jamfile new file mode 100644 index 00000000..cf35b25a --- /dev/null +++ b/test/openssl_memory/Jamfile @@ -0,0 +1,74 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# OpenSSL's memory functions under WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE (spec +# sections 3.7 and 8.5): each test is a program of its own, since OpenSSL's +# functions are the process's and cannot be put back once allocated through; +# each runs with exceptions on and off, on native programs only. +project : requirements /webcpp/crypto//openssl ; + +import webcpp ; + +webcpp.targets native ; + +rule memory-run ( name : sources + : requirements * ) +{ + webcpp.run $(name) : $(sources) + : $(requirements) WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE ; + webcpp.run $(name)_no_exceptions : $(sources) + : $(requirements) WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE off ; +} + +memory-run adapter : adapter_test.cpp ; + +# The C library's allocator, counted while a test says so: through +# malloc_logger on macOS, by the program's own malloc on Linux, not at all on +# Windows (spec section 8.5). +.counter = darwin:interpose_darwin.cpp + linux:interpose_linux.cpp + windows:interpose_windows.cpp ; + +# A second thread uses OpenSSL: the provider is built with threads. +memory-run everything : everything_test.cpp : $(.counter) multi ; + +# The late, foreign, fresh, forgotten, replaced and second installs, and a +# failing resource (spec section 8.5). +memory-run late : late_test.cpp : $(.counter) ; +memory-run foreign : foreign_test.cpp : $(.counter) ; +memory-run fresh_install : fresh_install_test.cpp : $(.counter) ; +memory-run forgotten : forgotten_test.cpp : $(.counter) ; +memory-run replaced : replaced_test.cpp : $(.counter) ; +memory-run second_install : second_install_test.cpp : $(.counter) ; +memory-run fail_second : fail_second_test.cpp : $(.counter) ; +memory-run fail_init : fail_init_test.cpp : $(.counter) ; +# The same program on an OpenSSL built with threads (MSVC's only build): the +# failure is not run there, since OpenSSL re-enters its own initialisation. +memory-run fail_init_threads : fail_init_test.cpp : $(.counter) multi ; + +# The header alone, with the option: its branch compiles with nothing before it. +webcpp.compile header_alone : header_alone_test.cpp + : WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE ; + +# before and after every public header with the option on (spec +# sections 2.2 and 8.6), so that backends/openssl.hpp's branch of the option is +# compiled beside a bare on MSVC; elsewhere the headers alone. +.every-backend = /third_party//bearssl /third_party//ctaes + /third_party//secp256k1 WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE ; +webcpp.compile windows_h_before_memory : ../windows_h_before_test.cpp : $(.every-backend) ; +webcpp.compile windows_h_after_memory : ../windows_h_after_test.cpp : $(.every-backend) ; + +# Its neighbours in the process (spec section 8.5): Asio's TLS and +# libdatachannel linked beside the option, as webcpp::beast's tls and +# webcpp::webrtc link them natively, and the install still succeeds. Test-only +# dependencies, never in /webcpp/crypto//crypto's usage requirements; +# libdatachannel needs threads. +memory-run neighbours : neighbours_test.cpp + : /webcpp/asio//asio /webcpp/asio//openssl + /third_party//libdatachannel multi ; + +# A TLS 1.3 handshake through libssl over a pair of memory BIOs, with the C +# library's allocator counted from the key to the last free. +memory-run handshake : handshake_test.cpp : $(.counter) ; diff --git a/test/openssl_memory/adapter_test.cpp b/test/openssl_memory/adapter_test.cpp new file mode 100644 index 00000000..b84a56c0 --- /dev/null +++ b/test/openssl_memory/adapter_test.cpp @@ -0,0 +1,141 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The adapter's C functions, called directly (spec section 3.7): 0 bytes and a size whose +// header overflows give null without asking the resource; a block is aligned as malloc's; +// realloc grows, shrinks, frees at 0 and, when the resource fails, returns null and +// leaves the old block valid; a resource that throws (with exceptions) or returns null +// (without) is a null for OpenSSL. + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +class test_resource final : public std::pmr::memory_resource { +public: + std::size_t allocations = 0; + std::size_t live = 0; + bool failing = false; + // Every deallocate whose (pointer, size, alignment) is not what do_allocate gave out. + std::size_t mismatches = 0; + // The size and alignment of the latest successful allocate. + std::size_t last_size = 0; + std::size_t last_alignment = 0; + +private: + struct record { + void* pointer; + std::size_t size; + std::size_t alignment; + }; + + std::vector records_; + + void* do_allocate(std::size_t size, std::size_t alignment) override { + if (failing) { +#ifdef WEBCPP_CRYPTO_NO_EXCEPTIONS + return nullptr; +#else + boost::throw_exception(std::bad_alloc()); +#endif + } + ++allocations; + ++live; + last_size = size; + last_alignment = alignment; + void* const pointer = std::pmr::new_delete_resource()->allocate(size, alignment); + records_.push_back({.pointer = pointer, .size = size, .alignment = alignment}); + return pointer; + } + + void do_deallocate(void* p, std::size_t size, std::size_t alignment) override { + --live; + bool matched = false; + for (auto it = records_.begin(); it != records_.end(); ++it) { + if (it->pointer == p) { + matched = it->size == size && it->alignment == alignment; + records_.erase(it); + break; + } + } + if (!matched) { + ++mismatches; + } + std::pmr::new_delete_resource()->deallocate(p, size, alignment); + } + + [[nodiscard]] bool do_is_equal(memory_resource const& other) const noexcept override { + return this == &other; + } +}; + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): never destroyed, by design +alignas(test_resource) std::array storage; + +test_resource& the_resource() noexcept { + static auto* const resource = new (storage.data()) test_resource; + return *resource; +} + +} // namespace + +std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept { + return the_resource(); +} + +int main() { + namespace detail = webcpp::crypto::detail; + auto& resource = the_resource(); + BOOST_TEST(webcpp_crypto_openssl_malloc(0, __FILE__, __LINE__) == nullptr); + BOOST_TEST(webcpp_crypto_openssl_malloc((std::numeric_limits::max)() - 3, __FILE__, + __LINE__) == nullptr); + BOOST_TEST_EQ(resource.allocations, 0U); + + void* const block = webcpp_crypto_openssl_malloc(10, __FILE__, __LINE__); + BOOST_TEST(block != nullptr); + BOOST_TEST_EQ(reinterpret_cast(block) % detail::openssl_block_alignment, 0U); + BOOST_TEST_EQ(resource.last_size, detail::openssl_block_alignment + 10); + BOOST_TEST_EQ(resource.last_alignment, detail::openssl_block_alignment); + std::memcpy(block, "0123456789", 10); + + void* const grown = webcpp_crypto_openssl_realloc(block, 1000, __FILE__, __LINE__); + BOOST_TEST(grown != nullptr && std::memcmp(grown, "0123456789", 10) == 0); + BOOST_TEST_EQ(resource.last_size, detail::openssl_block_alignment + 1000); + BOOST_TEST_EQ(resource.mismatches, 0U); // the 10-byte block went back with its size + void* const shrunk = webcpp_crypto_openssl_realloc(grown, 4, __FILE__, __LINE__); + BOOST_TEST(shrunk != nullptr && std::memcmp(shrunk, "0123", 4) == 0); + BOOST_TEST_EQ(resource.last_size, detail::openssl_block_alignment + 4); + BOOST_TEST_EQ(resource.mismatches, 0U); // the 1000-byte block went back with its size + + resource.failing = true; + BOOST_TEST(webcpp_crypto_openssl_malloc(8, __FILE__, __LINE__) == nullptr); + BOOST_TEST(webcpp_crypto_openssl_realloc(shrunk, 64, __FILE__, __LINE__) == nullptr); + BOOST_TEST(std::memcmp(shrunk, "0123", 4) == 0); // the old block is still valid + resource.failing = false; + + BOOST_TEST(webcpp_crypto_openssl_realloc(shrunk, 0, __FILE__, __LINE__) == nullptr); + BOOST_TEST_EQ(resource.live, 0U); + void* const fresh = webcpp_crypto_openssl_realloc(nullptr, 16, __FILE__, __LINE__); + BOOST_TEST(fresh != nullptr); + webcpp_crypto_openssl_free(fresh, __FILE__, __LINE__); + webcpp_crypto_openssl_free(nullptr, __FILE__, __LINE__); + BOOST_TEST_EQ(resource.live, 0U); + BOOST_TEST_EQ(resource.mismatches, 0U); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/openssl_memory/everything_test.cpp b/test/openssl_memory/everything_test.cpp new file mode 100644 index 00000000..d4d28907 --- /dev/null +++ b/test/openssl_memory/everything_test.cpp @@ -0,0 +1,103 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Everything in the resource, refused otherwise (spec section 8.5): installed first, the +// configuration file not read, make, the one-shot and incremental seals, good and failed +// opens and the destructors, for gcm and aes256 on OpenSSL, make no call of the C +// library's allocator from any caller; seal, open and the incremental seal allocate +// nothing anywhere; a second thread does the same (Review Focus 5); no foreign block is +// freed; and after main OpenSSL's cleanup gives every block back (support.hpp's exit). +// Built multi, so that the provider has threads. + +#include "support.hpp" + +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using aead = crypto::ciphers::gcm>; + +void messages(aead& made) { + std::array const iv{}; + std::array data{}; + auto const& resource = webcpp::test::the_counting_resource(); + std::size_t const before = resource.allocations(); + auto const tag = made.seal(iv, {}, data); + BOOST_TEST(tag.has_value()); + BOOST_TEST(made.open(iv, {}, data, *tag).has_value()); + std::array const bad{}; + BOOST_TEST(made.open(iv, {}, data, bad).error() == crypto::error::authentication_failed); + BOOST_TEST(made.begin_seal(iv, {}).has_value()); + BOOST_TEST(made.update(data).has_value()); + BOOST_TEST(made.result().has_value()); + BOOST_TEST_EQ(resource.allocations(), before); +} + +} // namespace + +int main() { + webcpp::test::say_whether_c_is_counted(); + if (!BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + // The configuration file makes the C library allocate its FILE and buffer, which no + // hook of OpenSSL's reaches (spec section 3.7). + BOOST_TEST_EQ(OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, nullptr), 1); + webcpp_test_count_c_allocations(1); + { + std::array const key{}; + auto made = aead::make(key); + BOOST_TEST(made.has_value()); + messages(*made); + auto block = crypto::ciphers::aes256::make(key); + BOOST_TEST(block.has_value()); + std::array blocks{}; + auto const& resource = webcpp::test::the_counting_resource(); + std::size_t const before = resource.allocations(); + BOOST_TEST(block->encrypt(blocks).has_value()); + BOOST_TEST(block->decrypt(blocks).has_value()); + BOOST_TEST_EQ(resource.allocations(), before); + // Starting and joining a thread allocates in the C library, which is not OpenSSL's: + // the counter is off around both, and the thread turns it on for its own work. + webcpp_test_count_c_allocations(0); + std::thread other([&key] { + webcpp_test_count_c_allocations(1); + { + auto made_there = aead::make(key); + BOOST_TEST(made_there.has_value()); + messages(*made_there); + } + // The static libcrypto on Windows is never told that a thread ends (OpenSSL's + // OPENSSL_init_crypto(3), NOTES): the thread gives its own blocks back itself, or + // they stay in the resource and the exit check fails. Elsewhere it frees them now + // rather than when the thread ends. + OPENSSL_thread_stop(); + webcpp_test_count_c_allocations(0); + }); + other.join(); + webcpp_test_count_c_allocations(1); + } + webcpp_test_count_c_allocations(0); + BOOST_TEST_EQ(webcpp_test_c_allocations(), 0U); + BOOST_TEST(!webcpp::test::the_counting_resource().foreign_free()); + if (int const errors = boost::report_errors(); errors != 0) { + return webcpp::test::exit_status(errors); + } + webcpp::test::the_counting_resource().main_returned(); + return 3; // the resource ends the process with 0 once OpenSSL has freed everything +} diff --git a/test/openssl_memory/fail_init_test.cpp b/test/openssl_memory/fail_init_test.cpp new file mode 100644 index 00000000..d9811679 --- /dev/null +++ b/test/openssl_memory/fail_init_test.cpp @@ -0,0 +1,97 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A failure inside OpenSSL's first initialisation (spec sections 3.7 and 8.5, +// crypto-r3-review mode failinit), on an OpenSSL built without threads: the first allocation +// after the install fails, make gives backend_failure, and a make after the resource has +// stopped failing gives backend_failure again. No entry is raised before the first make, since +// raising one would run OpenSSL's initialisation first. +// +// What follows is OpenSSL 3.5.9's, measured on macOS and Linux (2026-11-17), and pinned so +// that a pin move that changes it fails here. The failing allocation is the base +// initialisation's first lock (crypto/init.c:66, reached from make's ERR_set_mark), so the +// base is never initialised: +// - the error queue's state cannot be made, so no entry can be raised afterwards and the +// queue stays empty whatever make does; +// - OpenSSL never registers its cleanup with atexit, and OPENSSL_cleanup returns at once +// (init.c:384), so the blocks the default library context took meanwhile stay live in +// the resource until the process ends. The exit check cannot hold here: main returns the +// tests' status, and prints the count of those blocks. +// +// On an OpenSSL built with threads (OPENSSL_THREADS: MSVC's only build, and b2's +// threading=multi elsewhere, which the Jamfile's fail_init_threads asks for) the failure is +// not recoverable and is not run. There the lock is allocated with a file and a line +// (crypto/threads_pthread.c, threads_win.c), so CRYPTO_malloc's failure path raises an error, +// whose state needs the base initialisation that is running: OpenSSL re-enters its own +// run-once, which aborts on macOS, deadlocks on Linux and spins on Windows. Without threads +// the lock is allocated with neither (threads_none.c), nothing is raised, and the failure +// returns. The threaded program pins the documented boundary instead: the first make, with a +// resource that does not fail, runs OpenSSL's initialisation through the resource, which must +// therefore serve it; the count is printed. It ends through the exit check. + +#include "support.hpp" + +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using aead = crypto::ciphers::gcm>; + webcpp::test::say_whether_c_is_counted(); + BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value()); + auto& resource = webcpp::test::the_counting_resource(); + std::array const key{}; + BOOST_TEST_EQ(resource.allocations(), 0U); +#ifdef OPENSSL_THREADS + { + auto const first = aead::make(key); + BOOST_TEST(first.has_value()); + } + std::size_t const taken = resource.allocations(); + BOOST_TEST_NE(taken, 0U); + webcpp::test::write_out( + "OpenSSL is built with threads: the resource is not made to fail; the first make took " + + std::to_string(taken) + " blocks of it, OpenSSL's initialisation among them\n"); + BOOST_TEST(!resource.foreign_free()); + if (int const errors = boost::report_errors(); errors != 0) { + return webcpp::test::exit_status(errors); + } + resource.main_returned(); + return 3; // the resource ends the process with 0 once OpenSSL has freed everything +#else + // The makes live in this scope so that their objects are destroyed before the explicit + // OPENSSL_cleanup() below: should a pin move let OpenSSL initialise, no context is then + // freed after the cleanup, and the live count compared across it is the library's alone. + { + resource.arm(0); + auto const first = aead::make(key); + BOOST_TEST(first.has_error() && first.error() == crypto::error::backend_failure); + BOOST_TEST_EQ(webcpp::test::raise_entry(), 0UL); + auto const second = aead::make(key); + BOOST_TEST(second.has_error() && second.error() == crypto::error::backend_failure); + } + + std::size_t const live = resource.live(); + BOOST_TEST_NE(live, 0U); + OPENSSL_cleanup(); + BOOST_TEST_EQ(resource.live(), live); + webcpp::test::write_out("blocks left live by the failed initialisation, never given back: " + + std::to_string(live) + "\n"); + + BOOST_TEST(!resource.foreign_free()); + return webcpp::test::exit_status(boost::report_errors()); +#endif +} diff --git a/test/openssl_memory/fail_second_test.cpp b/test/openssl_memory/fail_second_test.cpp new file mode 100644 index 00000000..71b65a96 --- /dev/null +++ b/test/openssl_memory/fail_second_test.cpp @@ -0,0 +1,79 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A failing resource after a good make (spec sections 3.7 and 8.5, crypto-r3-review mode +// failsecond): the next make's allocation in EVP_CIPHER_CTX_new fails and gives +// errc::not_enough_memory, a make after it succeeds, and a failing allocation in +// EVP_EncryptInit_ex gives backend_failure. Before each make the test raises an entry of its +// own, and after it the thread's queue holds that entry alone. The program ends through the +// exit check. + +#include "support.hpp" + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace { + +namespace crypto = webcpp::crypto; +using aead = crypto::ciphers::gcm>; + +// A make after the first takes two blocks on OpenSSL 3.5.9 (measured on macOS and Linux, +// 2026-11-17): EVP_CIPHER_fetch finds the cipher in its cache and allocates nothing, then +// EVP_CIPHER_CTX_new takes the first block and EVP_EncryptInit_ex the second. +constexpr std::size_t context_new = 0; +constexpr std::size_t encrypt_init = 1; + +// Raises the test's entry, makes with the resource armed to fail after `failing_after` +// allocations (or not armed), and checks that the queue holds the test's entry alone +// afterwards. +boost::system::result make_between_entries(std::array const& key, + std::optional failing_after) { + unsigned long const ours = webcpp::test::raise_entry(); + BOOST_TEST_NE(ours, 0UL); + if (failing_after) { + webcpp::test::the_counting_resource().arm(*failing_after); + } + auto made = aead::make(key); + unsigned long first = 0; + BOOST_TEST_EQ(webcpp::test::drain(first), 1U); + BOOST_TEST_EQ(first, ours); + return made; +} + +} // namespace + +int main() { + webcpp::test::say_whether_c_is_counted(); + BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value()); + std::array const key{}; + BOOST_TEST(make_between_entries(key, std::nullopt).has_value()); + + auto const no_context = make_between_entries(key, context_new); + BOOST_TEST(no_context.has_error() && + no_context.error() == boost::system::errc::not_enough_memory); + BOOST_TEST(make_between_entries(key, std::nullopt).has_value()); + auto const no_init = make_between_entries(key, encrypt_init); + BOOST_TEST(no_init.has_error() && no_init.error() == crypto::error::backend_failure); + BOOST_TEST(make_between_entries(key, std::nullopt).has_value()); + + auto& resource = webcpp::test::the_counting_resource(); + BOOST_TEST(!resource.foreign_free()); + if (int const errors = boost::report_errors(); errors != 0) { + return webcpp::test::exit_status(errors); + } + resource.main_returned(); + return 3; // the resource ends the process with 0 once OpenSSL has freed everything +} diff --git a/test/openssl_memory/foreign_test.cpp b/test/openssl_memory/foreign_test.cpp new file mode 100644 index 00000000..8cfa8244 --- /dev/null +++ b/test/openssl_memory/foreign_test.cpp @@ -0,0 +1,33 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A foreign install is an error value (spec section 8.5, PROBE-R3 mode foreign): another +// party's functions installed with CRYPTO_set_mem_functions, and one allocation made through +// them, make install_memory_functions() give memory_functions_refused and leave that party's +// functions in place. The resource never receives a block, so the exit check does not apply. + +#include "support.hpp" + +#include + +#include + +#include + +int main() { + namespace crypto = webcpp::crypto; + using webcpp::test::other_party; + webcpp::test::say_whether_c_is_counted(); + BOOST_TEST_EQ(other_party::install(), 1); + OPENSSL_free(OPENSSL_malloc(1)); + BOOST_TEST_EQ(other_party::calls(), 2U); + auto const installed = crypto::backends::openssl::install_memory_functions(); + BOOST_TEST(installed.has_error() && + installed.error() == crypto::error::memory_functions_refused); + BOOST_TEST(other_party::installed()); + BOOST_TEST_EQ(webcpp::test::the_counting_resource().allocations(), 0U); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/openssl_memory/forgotten_test.cpp b/test/openssl_memory/forgotten_test.cpp new file mode 100644 index 00000000..7a3a4834 --- /dev/null +++ b/test/openssl_memory/forgotten_test.cpp @@ -0,0 +1,58 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A forgotten install is an error value (spec section 8.5): built with the option and +// without the install, make gives memory_functions_not_installed with section 3.7's +// message, and OpenSSL has allocated nothing, since the guard comes before the error queue's +// mark: its defaults are still replaceable, CRYPTO_set_mem_functions returning 1. The +// program then makes and seals through the adapter, and ends through the exit check. + +#include "support.hpp" + +#include +#include +#include + +#include + +#include + +#include +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using aead = crypto::ciphers::gcm>; + webcpp::test::say_whether_c_is_counted(); + auto& resource = webcpp::test::the_counting_resource(); + std::array const key{}; + auto const forgotten = aead::make(key); + // On success error() is the empty code, which fails both checks below. + BOOST_TEST(forgotten.error() == crypto::error::memory_functions_not_installed); + BOOST_TEST_EQ(forgotten.error().message(), + std::string("OpenSSL's memory functions are not webcpp::crypto's. Call " + "backends::openssl::install_memory_functions() as the first " + "statement of main, and let nothing else call " + "CRYPTO_set_mem_functions.")); + BOOST_TEST_EQ( + CRYPTO_set_mem_functions(&webcpp_crypto_openssl_malloc, &webcpp_crypto_openssl_realloc, + &webcpp_crypto_openssl_free), + 1); + { + auto made = aead::make(key); + BOOST_TEST(made.has_value()); + std::array const iv{}; + std::array data{}; + BOOST_TEST(made.has_value() && made->seal(iv, {}, data).has_value()); + } + BOOST_TEST(!resource.foreign_free()); + if (int const errors = boost::report_errors(); errors != 0) { + return webcpp::test::exit_status(errors); + } + resource.main_returned(); + return 3; // the resource ends the process with 0 once OpenSSL has freed everything +} diff --git a/test/openssl_memory/fresh_install_test.cpp b/test/openssl_memory/fresh_install_test.cpp new file mode 100644 index 00000000..1bf0731e --- /dev/null +++ b/test/openssl_memory/fresh_install_test.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The install in a program that has not used OpenSSL succeeds (spec section 8.5): the check +// that refuses a late install recognises OpenSSL's own functions. Nothing allocates, so the +// exit check does not apply. + +#include "support.hpp" + +#include + +#include + +int main() { + namespace crypto = webcpp::crypto; + webcpp::test::say_whether_c_is_counted(); + BOOST_TEST(crypto::detail::openssl_defaults_installed()); + BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value()); + BOOST_TEST(crypto::detail::openssl_adapter_installed()); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/openssl_memory/handshake_test.cpp b/test/openssl_memory/handshake_test.cpp new file mode 100644 index 00000000..97705e7f --- /dev/null +++ b/test/openssl_memory/handshake_test.cpp @@ -0,0 +1,217 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A TLS 1.3 handshake through libssl under the option (spec section 8.5): installed first, the +// configuration file not read, libssl and the C library's gmtime started; a server whose P-256 key +// and self-signed certificate are made at run time and a client that does not verify, in one +// process over a pair of memory BIOs, which stand for the spec's loopback socket (libssl allocates +// the same, and no socket is needed); both stepped with SSL_do_handshake until both finish, one +// application record each way, then everything freed. From the key to the last free the C library's +// allocator is never called (the interposer); no foreign block is freed through the adapter; and +// after main OpenSSL's cleanup gives every block back (support.hpp's exit). + +#include "support.hpp" + +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +// OpenSSL's objects, each freed by its own function. +struct free_key { + void operator()(EVP_PKEY* key) const noexcept { EVP_PKEY_free(key); } +}; + +struct free_certificate { + void operator()(X509* certificate) const noexcept { X509_free(certificate); } +}; + +struct free_context { + void operator()(SSL_CTX* context) const noexcept { SSL_CTX_free(context); } +}; + +struct free_connection { + void operator()(SSL* connection) const noexcept { SSL_free(connection); } +}; + +using key_ptr = std::unique_ptr; +using certificate_ptr = std::unique_ptr; +using context_ptr = std::unique_ptr; +using connection_ptr = std::unique_ptr; + +// A P-256 key, made at run time. +key_ptr make_key() { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg): the curve's name is a variadic argument. + return key_ptr(EVP_PKEY_Q_keygen(nullptr, nullptr, "EC", "P-256")); +} + +// A certificate for key, signed by key itself, valid for an hour from now. +certificate_ptr make_certificate(EVP_PKEY* key) { + certificate_ptr certificate(X509_new()); + if (!certificate) { + return certificate; + } + X509* const raw = certificate.get(); + X509_NAME* const name = X509_get_subject_name(raw); + constexpr std::array common_name{'l', 'o', 'c', 'a', 'l', 'h', 'o', 's', 't'}; + // NOLINTNEXTLINE(bugprone-signed-bitwise): OpenSSL's macro ORs signed flags + constexpr int ascii = MBSTRING_ASC; + bool const made = + X509_set_version(raw, X509_VERSION_3) == 1 && + ASN1_INTEGER_set(X509_get_serialNumber(raw), 1) == 1 && + X509_gmtime_adj(X509_getm_notBefore(raw), 0) != nullptr && + X509_gmtime_adj(X509_getm_notAfter(raw), 3600) != nullptr && + X509_NAME_add_entry_by_txt(name, "CN", ascii, common_name.data(), + static_cast(common_name.size()), -1, 0) == 1 && + X509_set_issuer_name(raw, name) == 1 && X509_set_pubkey(raw, key) == 1 && + X509_sign(raw, key, EVP_sha256()) > 0; + if (!made) { + certificate.reset(); + } + return certificate; +} + +// A TLS 1.3-only context: the server's with key and certificate, the client's not verifying. +context_ptr make_context(bool is_server, EVP_PKEY* key, X509* certificate) { + context_ptr context(SSL_CTX_new(is_server ? TLS_server_method() : TLS_client_method())); + if (!context) { + return context; + } + bool made = SSL_CTX_set_min_proto_version(context.get(), TLS1_3_VERSION) == 1; + if (is_server) { + made = made && SSL_CTX_use_certificate(context.get(), certificate) == 1 && + SSL_CTX_use_PrivateKey(context.get(), key) == 1; + } else { + SSL_CTX_set_verify(context.get(), SSL_VERIFY_NONE, nullptr); + } + if (!made) { + context.reset(); + } + return context; +} + +// Whether a step of connection may go on: it finished, or it waits for the other side. +bool goes_on(SSL const* connection, int result) { + if (result == 1) { + return true; + } + int const reason = SSL_get_error(connection, result); + return reason == SSL_ERROR_WANT_READ || reason == SSL_ERROR_WANT_WRITE; +} + +// Steps both sides until both finished; false when either fails or neither finishes. +bool handshake(SSL* client, SSL* server) { + constexpr int most_steps = 16; + for (int step = 0; step != most_steps; ++step) { + int const by_client = SSL_do_handshake(client); + if (!goes_on(client, by_client)) { + return false; + } + int const by_server = SSL_do_handshake(server); + if (!goes_on(server, by_server)) { + return false; + } + if (by_client == 1 && by_server == 1) { + return true; + } + } + return false; +} + +// Sends one application record from one side and reads it on the other. +bool record(SSL* from, SSL* to, std::string_view text) { + if (!std::cmp_equal(SSL_write(from, text.data(), static_cast(text.size())), text.size())) { + return false; + } + std::array received{}; + int const read = SSL_read(to, received.data(), static_cast(received.size())); + return std::cmp_equal(read, text.size()) && + std::string_view(received.data(), text.size()) == text; +} + +// The whole exchange: key, certificate, contexts, connections over a pair of memory BIOs, the +// handshake and a record each way; everything is freed on return. +void exchange() { + key_ptr const key = make_key(); + if (!BOOST_TEST(key != nullptr)) { + return; + } + certificate_ptr const certificate = make_certificate(key.get()); + context_ptr const server_context = make_context(true, key.get(), certificate.get()); + context_ptr const client_context = make_context(false, nullptr, nullptr); + if (!BOOST_TEST(certificate != nullptr) || !BOOST_TEST(server_context != nullptr) || + !BOOST_TEST(client_context != nullptr)) { + return; + } + connection_ptr const server(SSL_new(server_context.get())); + connection_ptr const client(SSL_new(client_context.get())); + if (!BOOST_TEST(server != nullptr) || !BOOST_TEST(client != nullptr)) { + return; + } + BIO* client_end = nullptr; + BIO* server_end = nullptr; + if (!BOOST_TEST_EQ(BIO_new_bio_pair(&client_end, 0, &server_end, 0), 1)) { + return; + } + // Each connection owns its end of the pair from here on, and frees it. + SSL_set_bio(client.get(), client_end, client_end); + SSL_set_bio(server.get(), server_end, server_end); + SSL_set_connect_state(client.get()); + SSL_set_accept_state(server.get()); + if (!BOOST_TEST(handshake(client.get(), server.get()))) { + return; + } + BOOST_TEST_EQ(SSL_version(client.get()), TLS1_3_VERSION); + BOOST_TEST_EQ(SSL_version(server.get()), TLS1_3_VERSION); + BOOST_TEST(record(client.get(), server.get(), "from the client")); + BOOST_TEST(record(server.get(), client.get(), "from the server")); +} + +} // namespace + +int main() { + if (!BOOST_TEST(webcpp::crypto::backends::openssl::install_memory_functions().has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + webcpp::test::say_whether_c_is_counted(); + // Three things make the C library allocate once per process, outside every hook of + // OpenSSL's, so they are done here, before counting. The configuration file: its FILE and + // buffer (spec section 3.7); it is not read. + BOOST_TEST_EQ(OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, nullptr), 1); + // libssl's start-up, which sorts its cipher table with the C library's qsort; glibc's takes + // its scratch block from malloc (measured on Debian 13: one malloc and one free). + BOOST_TEST_EQ(OPENSSL_init_ssl(OPENSSL_INIT_NO_LOAD_CONFIG, nullptr), 1); + // The C library's gmtime, which OpenSSL calls for a certificate's dates: its first call + // loads the time zone data, and on macOS its thread's buffer (measured on macOS: 80 calls + // of the C library's allocator). + std::time_t const now = std::time(nullptr); + std::tm calendar{}; + BOOST_TEST(OPENSSL_gmtime(&now, &calendar) != nullptr); + webcpp_test_count_c_allocations(1); + exchange(); + webcpp_test_count_c_allocations(0); + BOOST_TEST_EQ(webcpp_test_c_allocations(), 0U); + BOOST_TEST_NE(webcpp::test::the_counting_resource().allocations(), 0U); + BOOST_TEST(!webcpp::test::the_counting_resource().foreign_free()); + if (int const errors = boost::report_errors(); errors != 0) { + return webcpp::test::exit_status(errors); + } + webcpp::test::the_counting_resource().main_returned(); + return 3; // the resource ends the process with 0 once OpenSSL has freed everything +} diff --git a/test/openssl_memory/header_alone_test.cpp b/test/openssl_memory/header_alone_test.cpp new file mode 100644 index 00000000..e202f9b4 --- /dev/null +++ b/test/openssl_memory/header_alone_test.cpp @@ -0,0 +1,11 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The backend OpenSSL's header alone with the memory option: the option's branch compiles +// with nothing before it (webcpp.headers-alone takes a header once, and the header's call +// in test/Jamfile is for the build without the option). + +#include diff --git a/test/openssl_memory/interpose_darwin.cpp b/test/openssl_memory/interpose_darwin.cpp new file mode 100644 index 00000000..1f59970f --- /dev/null +++ b/test/openssl_memory/interpose_darwin.cpp @@ -0,0 +1,54 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Counts the C library's allocations and releases on macOS, from any caller, while the test +// says so (spec section 8.5): through malloc_logger, the hook libsystem_malloc calls on every +// allocation and release of the process, installed at static initialisation as +// test/support/counting.hpp installs it. Nothing here reads a thread_local: the first read of +// one on a thread allocates through dyld, inside the hook (counting.hpp's N1). The hook relies +// on the private malloc_logger symbol of libsystem_malloc and overwrites any hook already +// there (MallocStackLogging's, a sanitizer's). + +#include + +#include +#include +#include + +// libsystem_malloc's hook, called on every allocation and release of the process. +using webcpp_test_malloc_logger = void(std::uint32_t, std::uintptr_t, std::uintptr_t, + std::uintptr_t, std::uintptr_t, std::uint32_t); +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): libsystem_malloc's hook +extern "C" webcpp_test_malloc_logger* malloc_logger; + +namespace { +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the interposer's count +std::atomic counted{0}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the interposer's switch +std::atomic counting{false}; + +void count_c_call(std::uint32_t type, std::uintptr_t /*zone*/, std::uintptr_t /*first*/, + std::uintptr_t /*second*/, std::uintptr_t /*result*/, std::uint32_t /*skip*/) { + constexpr std::uint32_t allocate = 2; // MALLOC_LOG_TYPE_ALLOCATE + constexpr std::uint32_t deallocate = 4; // MALLOC_LOG_TYPE_DEALLOCATE + if ((type & (allocate | deallocate)) != 0 && counting.load(std::memory_order_relaxed)) { + counted.fetch_add(1, std::memory_order_relaxed); + } +} + +// Installs the hook at static initialisation, before main. +[[maybe_unused]] bool const installed = (malloc_logger = &count_c_call, true); +} // namespace + +extern "C" { +std::size_t webcpp_test_c_allocations(void) { + return counted.load(); +} + +void webcpp_test_count_c_allocations(int on) { + counting.store(on != 0); +} +} diff --git a/test/openssl_memory/interpose_linux.cpp b/test/openssl_memory/interpose_linux.cpp new file mode 100644 index 00000000..9e7b49d9 --- /dev/null +++ b/test/openssl_memory/interpose_linux.cpp @@ -0,0 +1,88 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Counts the C library's allocations and releases on Linux, from any caller, while the test +// says so (spec section 8.5): the program's own malloc and its kin replace glibc's in the +// whole process, OpenSSL's calls included, and forward to glibc's __libc_* functions, never +// through dlsym, which itself allocates. A free of a non-null block counts too. + +#include +#include +#include + +// glibc's own entry points, which the replacements forward to: their names are glibc's. +// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) +// NOLINTBEGIN(readability-identifier-naming) +extern "C" { +void* __libc_malloc(std::size_t); +void* __libc_calloc(std::size_t, std::size_t); +void* __libc_realloc(void*, std::size_t); +void* __libc_memalign(std::size_t, std::size_t); +void __libc_free(void*); +} +// NOLINTEND(readability-identifier-naming) +// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp) + +namespace { +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the interposer's count +std::atomic counted{0}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the interposer's switch +std::atomic counting{false}; + +void count() noexcept { + if (counting.load(std::memory_order_relaxed)) { + counted.fetch_add(1, std::memory_order_relaxed); + } +} +} // namespace + +// The replacements: glibc's declarations name their parameters otherwise, and cert-dcl58-cpp +// takes a replacement of what declares for a change to namespace std. +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) +extern "C" { +std::size_t webcpp_test_c_allocations(void) { + return counted.load(); +} + +void webcpp_test_count_c_allocations(int on) { + counting.store(on != 0); +} + +// glibc declares these with __THROW, noexcept in C++11 and later: a replacement must match. +void* malloc(std::size_t size) noexcept { + count(); + return __libc_malloc(size); +} + +void* calloc(std::size_t count_of, std::size_t size) noexcept { + count(); + return __libc_calloc(count_of, size); +} + +void* realloc(void* block, std::size_t size) noexcept { + count(); + return __libc_realloc(block, size); +} + +void free(void* block) noexcept { + if (block != nullptr) { + count(); + } + __libc_free(block); +} + +void* aligned_alloc(std::size_t alignment, std::size_t size) noexcept { + count(); + return __libc_memalign(alignment, size); +} + +int posix_memalign(void** block, std::size_t alignment, std::size_t size) noexcept { + count(); + *block = __libc_memalign(alignment, size); + return *block == nullptr ? ENOMEM : 0; +} +} +// NOLINTEND(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) diff --git a/test/openssl_memory/interpose_windows.cpp b/test/openssl_memory/interpose_windows.cpp new file mode 100644 index 00000000..0bef3e04 --- /dev/null +++ b/test/openssl_memory/interpose_windows.cpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Windows has no interposition of the C library's allocator (spec section 8.5): the count +// stays 0, the switch does nothing, and the programs say in their output that the C +// library is not counted; their other checks run. + +#include + +extern "C" { +std::size_t webcpp_test_c_allocations(void) { + return 0; +} + +void webcpp_test_count_c_allocations(int /*on*/) {} +} diff --git a/test/openssl_memory/late_test.cpp b/test/openssl_memory/late_test.cpp new file mode 100644 index 00000000..b17b6d8f --- /dev/null +++ b/test/openssl_memory/late_test.cpp @@ -0,0 +1,37 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A late install is an error value (spec section 8.5, PROBE-R3 mode late): once OpenSSL has +// allocated through its own functions, install_memory_functions() gives +// memory_functions_refused with section 3.7's message, and OpenSSL's own functions stay in +// place. The resource never receives a block, so the exit check does not apply. + +#include "support.hpp" + +#include + +#include + +#include + +#include + +int main() { + namespace crypto = webcpp::crypto; + webcpp::test::say_whether_c_is_counted(); + EVP_CIPHER_free(EVP_CIPHER_fetch(nullptr, "AES-256-GCM", nullptr)); + auto const installed = crypto::backends::openssl::install_memory_functions(); + // On success error() is the empty code, which fails both checks below. + BOOST_TEST(installed.error() == crypto::error::memory_functions_refused); + BOOST_TEST_EQ(installed.error().message(), + std::string("OpenSSL's memory functions cannot be installed: OpenSSL has " + "already allocated, or another party installed its own. Call " + "backends::openssl::install_memory_functions() as the first " + "statement of main, before anything uses OpenSSL.")); + BOOST_TEST(crypto::detail::openssl_defaults_installed()); + BOOST_TEST_EQ(webcpp::test::the_counting_resource().allocations(), 0U); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/openssl_memory/neighbours_test.cpp b/test/openssl_memory/neighbours_test.cpp new file mode 100644 index 00000000..b8cf48ef --- /dev/null +++ b/test/openssl_memory/neighbours_test.cpp @@ -0,0 +1,84 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The option beside its neighbours in the process (spec section 8.5): Boost.Asio's TLS, as +// webcpp::beast's tls uses it, and libdatachannel, as webcpp::webrtc uses it, are linked into +// the program, and the install, main's first statement, succeeds: neither used OpenSSL during +// static initialisation. One symbol of each is kept in a volatile pointer, so that the linker +// keeps their objects and static initialisers; neither is called. Asio's context is never +// constructed, but the function that would construct one is kept too, so that Asio's +// openssl_init instance, which every program that makes a context has, is initialised before +// main. Then one gcm is made and sealed, so that blocks exist, and after main OpenSSL's +// cleanup gives every block back (support.hpp's exit). +// rtcInitLogger alone brings in libdatachannel's static initialisers: its object, the C +// API's, names the rest of the library, so the linker takes 37 objects of libdatachannel.a, +// among them 21 of the 28 that have static initialisers, every one that names an OpenSSL +// function (certificate, dtlstransport, dtlssrtptransport) included; the 7 left out +// (the RTP depacketizers, the pacing handler, and the TLS and WebSocket transports, empty +// without WebSocket) name none. libjuice and usrsctp have none. Measured with the linker's +// map on macOS and on Linux (libdatachannel 0.24.6, 2026-11-17), so R15's fallback, +// rtc::InitLogger's address, is not needed. + +#include "support.hpp" + +#include +#include +#include +#include + +#include + +#include + +#include +#include + +namespace { + +namespace ssl = webcpp::asio::ssl; + +// Makes the context Beast's TLS would make; never called, only kept. +SSL_CTX* make_context() { + ssl::context context(ssl::context::tls_client); + return context.native_handle(); +} + +// The kept symbols: the linker keeps what they name, and nothing calls them. +// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables): kept for the linker +auto volatile asio_symbol = &ssl::context::native_handle; +auto volatile asio_constructor = &make_context; +auto volatile libdatachannel_symbol = &rtcInitLogger; +// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables) + +} // namespace + +int main() { + namespace crypto = webcpp::crypto; + if (!BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value())) { + return webcpp::test::exit_status(boost::report_errors()); + } + BOOST_TEST(asio_symbol != nullptr); + BOOST_TEST(asio_constructor != nullptr); + BOOST_TEST(libdatachannel_symbol != nullptr); + { + using aead = crypto::ciphers::gcm>; + std::array const key{}; + auto made = aead::make(key); + BOOST_TEST(made.has_value()); + if (made.has_value()) { + std::array const iv{}; + std::array data{}; + BOOST_TEST(made->seal(iv, {}, data).has_value()); + } + } + BOOST_TEST_NE(webcpp::test::the_counting_resource().allocations(), 0U); + BOOST_TEST(!webcpp::test::the_counting_resource().foreign_free()); + if (int const errors = boost::report_errors(); errors != 0) { + return webcpp::test::exit_status(errors); + } + webcpp::test::the_counting_resource().main_returned(); + return 3; // the resource ends the process with 0 once OpenSSL has freed everything +} diff --git a/test/openssl_memory/replaced_test.cpp b/test/openssl_memory/replaced_test.cpp new file mode 100644 index 00000000..a53434c5 --- /dev/null +++ b/test/openssl_memory/replaced_test.cpp @@ -0,0 +1,52 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Replaced functions are an error value (spec section 8.5, PROBE-R3 mode on): after an +// install and a make, a second party installs its own functions, which OpenSSL accepts; the +// next make gives memory_functions_not_installed and calls nothing of OpenSSL's, so that the +// second party's functions are never called. The adapter is put back before main returns, +// so that OpenSSL's cleanup frees through it, and the program ends through the exit check. + +#include "support.hpp" + +#include +#include +#include + +#include + +#include + +#include +#include + +int main() { + namespace crypto = webcpp::crypto; + using aead = crypto::ciphers::gcm>; + using webcpp::test::other_party; + webcpp::test::say_whether_c_is_counted(); + BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value()); + std::array const key{}; + // Destroyed before the replacement: its free goes to the resource that gave its blocks. + BOOST_TEST(aead::make(key).has_value()); + BOOST_TEST_EQ(other_party::install(), 1); + auto const replaced = aead::make(key); + BOOST_TEST(replaced.has_error() && + replaced.error() == crypto::error::memory_functions_not_installed); + BOOST_TEST_EQ(other_party::calls(), 0U); + BOOST_TEST_EQ( + CRYPTO_set_mem_functions(&webcpp_crypto_openssl_malloc, &webcpp_crypto_openssl_realloc, + &webcpp_crypto_openssl_free), + 1); + BOOST_TEST(aead::make(key).has_value()); + auto& resource = webcpp::test::the_counting_resource(); + BOOST_TEST(!resource.foreign_free()); + if (int const errors = boost::report_errors(); errors != 0) { + return webcpp::test::exit_status(errors); + } + resource.main_returned(); + return 3; // the resource ends the process with 0 once OpenSSL has freed everything +} diff --git a/test/openssl_memory/second_install_test.cpp b/test/openssl_memory/second_install_test.cpp new file mode 100644 index 00000000..e9e2c6eb --- /dev/null +++ b/test/openssl_memory/second_install_test.cpp @@ -0,0 +1,23 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A second install returns success and changes nothing (spec section 8.5). Nothing +// allocates, so the exit check does not apply. + +#include "support.hpp" + +#include + +#include + +int main() { + namespace crypto = webcpp::crypto; + webcpp::test::say_whether_c_is_counted(); + BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value()); + BOOST_TEST(crypto::backends::openssl::install_memory_functions().has_value()); + BOOST_TEST(crypto::detail::openssl_adapter_installed()); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/openssl_memory/support.hpp b/test/openssl_memory/support.hpp new file mode 100644 index 00000000..7755d4e3 --- /dev/null +++ b/test/openssl_memory/support.hpp @@ -0,0 +1,331 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// What every program of the memory option shares: a counting resource that is never +// destroyed (spec section 3.7), on a fixed buffer through a synchronized pool whose +// upstream is null_memory_resource(), so that the resource itself never calls the C +// library; its table of the blocks it gave, which finds a free of another's block; and the +// exit check: main returns 3, and when OpenSSL's cleanup has given every block back after +// main, the resource writes its line and ends the process with 0. Its destructor, which +// must never run, writes a line and ends it with 4 (C7); a table with no free slot left +// writes a line and ends it with 6. The C library's counter is the interposer's +// (interpose_*.cpp, picked by the Jamfile per target-os). Beside them: OpenSSL's error +// queue drained and an entry of the test's raised in it, and another party's memory +// functions, which a test installs as a library other than webcpp would. +// Each program includes this header once: it defines openssl_memory_resource(). + +#ifndef WEBCPP_TEST_CRYPTO_OPENSSL_MEMORY_SUPPORT_HPP +#define WEBCPP_TEST_CRYPTO_OPENSSL_MEMORY_SUPPORT_HPP + +#include + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +/** The C library's allocations and non-null releases counted while counting is on. */ +extern "C" std::size_t webcpp_test_c_allocations(void); +/** Turns the counting of the C library's allocations on (non-zero) or off (0). */ +extern "C" void webcpp_test_count_c_allocations(int on); + +namespace webcpp::test { + +/** + * Writes text to standard output unbuffered: after main the C library's streams may be gone + * (spec section 8.5). + */ +inline void write_out(std::string_view text) noexcept { +#ifdef _WIN32 + static_cast(_write(1, text.data(), static_cast(text.size()))); +#else + static_cast(::write(1, text.data(), text.size())); +#endif +} + +/** Says, on a target where the interposer counts nothing, that the C library is not counted. */ +inline void say_whether_c_is_counted() noexcept { +#ifdef _WIN32 + write_out("the C library's allocator is not counted on Windows\n"); +#endif +} + +/** + * The memory option's resource for the tests: counts the blocks it gives and keeps a table of + * them, so that a free of a block it did not give is found; fails on demand (`arm`); and, once + * `main_returned()` was called, ends the process with 0 when the last block comes back. It never + * calls the C library: its blocks come from a fixed buffer in the object itself. + */ +class counting_resource final : public std::pmr::memory_resource { +public: + /** An empty resource over its own buffer; made once, by `the_counting_resource()`. */ + counting_resource() : pool_(&monotonic_) {} + + counting_resource(counting_resource const&) = delete; + counting_resource& operator=(counting_resource const&) = delete; + counting_resource(counting_resource&&) = delete; + counting_resource& operator=(counting_resource&&) = delete; + + /** + * Never runs: the resource lives in static storage and is never destroyed. If it ran, it + * writes its line and ends the process with 4, which fails the test. + */ + ~counting_resource() override { + write_out("the resource was destroyed\n"); + end(4); + } + + /** + * Ends the process with status, now. OpenSSL is linked static (R5): its cleanup runs from + * the program's own exit handlers, never under a DLL's loader lock. + */ + [[noreturn]] static void end(int status) noexcept { std::_Exit(status); } + + /** The blocks given so far. */ + std::size_t allocations() const { return allocations_.load(); } + + /** The blocks given and not yet given back. */ + std::size_t live() const { return live_.load(); } + + /** Whether a block the resource did not give was given back to it. */ + bool foreign_free() const { return foreign_.load(); } + + /** + * Makes an allocation fail, as Task 15's resource fails: by throwing `std::bad_alloc`, or by + * returning null without exceptions. + * + * @param after The allocations that still succeed before the one that fails. + */ + void arm(std::size_t after) { fail_after_.store(after + 1); } + + /** + * Says that main is returning: from now on, the last block given back ends the process with + * 0 (the exit check), or with 5 after a foreign free. + */ + void main_returned() noexcept { main_returned_.store(true); } + +private: + // An open-addressing table of the blocks given (linear probing): one slot always stays + // free, so that a search for a block not in it ends. 65,536 slots: the most blocks live at + // once in everything_test on OpenSSL 3.5.9 is 4,452 (measured on macOS, 2026-11-17). + static constexpr std::size_t slots = std::size_t{1} << 16U; + static_assert(std::has_single_bit(slots), "the table's index is the hash's top bits"); + // The hash's top bits that index the table. + static constexpr unsigned shift = 64U - static_cast(std::bit_width(slots - 1)); + + static std::size_t home(void const* block) noexcept { + auto const bits = static_cast(reinterpret_cast(block)); + return static_cast(((bits >> 4U) * 0x9E3779B97F4A7C15ULL) >> shift); + } + + static std::size_t next(std::size_t slot) noexcept { return (slot + 1) & (slots - 1); } + + void remember(void* block) { + if (used_ + 1 == slots) { + write_out("the resource's table is full\n"); + end(6); + } + std::size_t slot = home(block); + while (given_[slot] != nullptr) { + slot = next(slot); + } + given_[slot] = block; + ++used_; + } + + // Removes block from the table, shifting back the entries after it; false if it is absent. + bool forget(void* block) { + std::size_t slot = home(block); + while (given_[slot] != block) { + if (given_[slot] == nullptr) { + return false; + } + slot = next(slot); + } + std::size_t hole = slot; + for (std::size_t probe = next(hole); given_[probe] != nullptr; probe = next(probe)) { + std::size_t const wanted = home(given_[probe]); + // The entry at probe stays unless its home is cyclically outside (hole, probe]. + bool const stays = hole <= probe ? (hole < wanted && wanted <= probe) + : (hole < wanted || wanted <= probe); + if (!stays) { + given_[hole] = given_[probe]; + hole = probe; + } + } + given_[hole] = nullptr; + --used_; + return true; + } + + void* do_allocate(std::size_t size, std::size_t alignment) override { + if (fail_after_.load() != 0 && fail_after_.fetch_sub(1) == 1) { +#ifdef WEBCPP_CRYPTO_NO_EXCEPTIONS + return nullptr; +#else + boost::throw_exception(std::bad_alloc()); +#endif + } + std::scoped_lock const lock(mutex_); + void* const block = pool_.allocate(size, alignment); + remember(block); + ++allocations_; + ++live_; + return block; + } + + void do_deallocate(void* block, std::size_t size, std::size_t alignment) override { + { + std::scoped_lock const lock(mutex_); + if (!forget(block)) { + foreign_.store(true); + return; + } + pool_.deallocate(block, size, alignment); + } + if (--live_ == 0 && main_returned_.load()) { + if (foreign_.load()) { + write_out("a foreign block was freed through the adapter\n"); + end(5); + } + write_out("OpenSSL gave every block back after main\n"); + end(0); + } + } + + bool do_is_equal(memory_resource const& other) const noexcept override { + return this == &other; + } + + // 16 MiB. On OpenSSL 3.5.9 (measured on macOS, 2026-11-17) everything_test's first make + // takes 5,027 blocks, 4,441 still live after it; the whole test asks for 5,042 blocks and + // 388,040 bytes, at most 349,350 of them live at once. A buffer that runs out makes + // null_memory_resource() throw std::bad_alloc. With exceptions, the adapter catches it + // and gives OpenSSL null, so the OpenSSL call fails and so does the test's check of it. + // Without exceptions (the program is built so, the C++ library is not) nothing catches + // it, and std::terminate ends the process with SIGABRT. + alignas(std::max_align_t) std::array buffer_{}; + std::pmr::monotonic_buffer_resource monotonic_{buffer_.data(), buffer_.size(), + std::pmr::null_memory_resource()}; + std::pmr::synchronized_pool_resource pool_; + std::mutex mutex_; + std::array given_{}; + std::size_t used_ = 0; + std::atomic allocations_{0}; + std::atomic live_{0}; + std::atomic fail_after_{0}; + std::atomic foreign_{false}; + std::atomic main_returned_{false}; +}; + +/** The one resource, in static storage, constructed by placement and never destroyed. */ +inline counting_resource& the_counting_resource() noexcept { + alignas(counting_resource) static std::array storage; + static auto* const resource = new (storage.data()) counting_resource; + return *resource; +} + +/** + * Empties the calling thread's OpenSSL error queue. + * + * @param first Set to the oldest entry's code, or 0 when the queue was empty. + * @return The number of entries the queue held. + */ +inline std::size_t drain(unsigned long& first) { + std::size_t count = 0; + first = ERR_peek_error(); + while (ERR_get_error() != 0) { + ++count; + } + return count; +} + +/** + * Another party's memory functions for OpenSSL: the C library's, each call counted. A test + * installs them with `CRYPTO_set_mem_functions`, as a library other than webcpp would. + */ +struct other_party { + /** The calls of the three functions so far. */ + static std::size_t& calls() noexcept { + static std::size_t count = 0; + return count; + } + + /** `malloc`, counted. */ + static void* allocate(std::size_t size, char const* /*file*/, int /*line*/) noexcept { + ++calls(); + return std::malloc(size); + } + + /** `realloc`, counted. */ + static void* reallocate(void* address, std::size_t size, char const* /*file*/, + int /*line*/) noexcept { + ++calls(); + return std::realloc(address, size); + } + + /** `free`, counted. */ + static void release(void* address, char const* /*file*/, int /*line*/) noexcept { + ++calls(); + std::free(address); + } + + /** + * Installs the three as OpenSSL's memory functions. + * + * @return `CRYPTO_set_mem_functions`'s answer: 1 when OpenSSL took them. + */ + static int install() noexcept { + return CRYPTO_set_mem_functions(&allocate, &reallocate, &release); + } + + /** Whether OpenSSL's memory functions are the three. */ + static bool installed() noexcept { + CRYPTO_malloc_fn m = nullptr; + CRYPTO_realloc_fn r = nullptr; + CRYPTO_free_fn f = nullptr; + CRYPTO_get_mem_functions(&m, &r, &f); + return m == &allocate && r == &reallocate && f == &release; + } +}; + +/** + * Raises an entry of the test's own in the thread's OpenSSL error queue. + * + * @return The entry's code, or 0 when OpenSSL could not raise it. + */ +inline unsigned long raise_entry() { + // NOLINTNEXTLINE(bugprone-signed-bitwise): OpenSSL's reason macro ORs signed flags + ERR_raise(ERR_LIB_USER, ERR_R_PASSED_INVALID_ARGUMENT); + return ERR_peek_last_error(); +} + +} // namespace webcpp::test + +// The program's one definition: each program includes this header once. +// NOLINTNEXTLINE(misc-definitions-in-headers) +std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept { + return webcpp::test::the_counting_resource(); +} + +#endif diff --git a/test/windows_h_after_test.cpp b/test/windows_h_after_test.cpp index a1d9886c..d0393255 100644 --- a/test/windows_h_after_test.cpp +++ b/test/windows_h_after_test.cpp @@ -39,6 +39,16 @@ #include #include +#include + +// With WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE (test/openssl_memory's twins, spec section 8.6), the +// option's branch of backends/openssl.hpp is compiled too, and the program defines the resource +// the option needs. +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE +std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept { + return *std::pmr::new_delete_resource(); +} +#endif int main() { BOOST_TEST_EQ(std::max(1, 2), 2); diff --git a/test/windows_h_before_test.cpp b/test/windows_h_before_test.cpp index 160e177c..1c88eca9 100644 --- a/test/windows_h_before_test.cpp +++ b/test/windows_h_before_test.cpp @@ -45,6 +45,7 @@ #include #include +#include // webcpp left defined none of the macros it defines for its own include of , // which the program's include made add nothing. @@ -52,6 +53,15 @@ #error "webcpp's headers left NOMINMAX or WIN32_LEAN_AND_MEAN defined" #endif +// With WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE (test/openssl_memory's twins, spec section 8.6), the +// option's branch of backends/openssl.hpp is compiled too, and the program defines the resource +// the option needs. +#ifdef WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE +std::pmr::memory_resource& webcpp::crypto::openssl_memory_resource() noexcept { + return *std::pmr::new_delete_resource(); +} +#endif + int main() { BOOST_TEST_EQ((std::max)(1, 2), 2); BOOST_TEST_EQ((webcpp::crypto::random_device::max)(),