diff --git a/AGENTS.md b/AGENTS.md index 5b8bddf4..7f729c4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,9 @@ specific to crypto. - **webcpp's own library** (`"port-of": null`) over C backends: BearSSL, OpenSSL, ctaes, libsecp256k1 and libsodium (the superproject's `/third_party//sodium`, shared with webcpp::hash). The algorithms are the backends'; crypto is the interface shaped as Boost.Hash2's. + crypto depends on config, hash and secure: the timing guard, `erase_secret`, + `constant_time_equal`, `secret` and `declassify` are webcpp::secure's, with no copy and no + alias in crypto. - **No oracle.** No original runs beside crypto: the evidence is the published vectors (the GCM specification's cases, Wycheproof, FIPS 197, RFC 8439 and RFC 8032, BIP340 and BIP341), the backends' own suites in the lane `c-suites`, and the agreement tests, which compare two backends @@ -43,11 +46,20 @@ specific to crypto. `aead_engine`, `secretbox_state`, `secretbox_engine`), the two of `detail/p_curves.hpp` per P-curve (`p_curve_state`, `p_curve_engine`) and, for the other curves, `public_key_encryption` and `key_exchange`, the functions of its own header. -- A new public function that calls a backend holds `detail::timing_guard` as its - first statement (it sets arm64's DIT for the call, `detail/timing.hpp`) and joins the coverage +- A new public function that calls a backend holds `secure::timing_guard` as its first statement + (`secure::timing_guard const timing_scope;`, webcpp::secure's, + ``, which sets arm64's DIT for the call) and joins the coverage test of its backend, `test/timing_coverage__test.cpp`, which checks through the seam - that each call entered its own guard. A function that only copies or encodes bytes, with no - backend call, holds none. + that each call entered its own guard. The seam support (`test/support/timing_seam.hpp`) counts + crypto's own guards by their file, under `include/webcpp/crypto/`, in `timing_entries`, and + every guard, hash's and secure's included, in `timing_all_entries`. A function that only copies + or encodes bytes, with no backend call, holds none. +- Every wipe of a key, a state or a failed output is `secure::erase_secret` over a span + (``; an object that is not an array as + `std::span(&object, 1)`); a verdict webcpp branches on is marked with `secure::declassify(x)`, + which the constant-time lane's `WEBCPP_SECURE_CT_VALGRIND` and `WEBCPP_SECURE_CT_MSAN` turn into + the checker's mark; a returned secret is a `secure::secret`, a comparison of secrets + `secure::constant_time_equal`, each always written qualified. - The constant-time lane's P-256 paths (`test/constant_time/paths.hpp`): BearSSL's ECDSA signing branches on its own verdicts, listed for memcheck in `bearssl_verdicts.supp`, which a later P-curve's signing joins; MemorySanitizer counts BearSSL's window selections public (masks of the diff --git a/README.md b/README.md index c19d32ed..9bc1a652 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,10 @@ target [webcpp](https://github.com/webcpporg/webcpp) has: native (Linux, macOS, MSVC), wasip2, wasip3 and Emscripten. - `webcpp::crypto`: a `random_device` that reads the operating system's or the browser's - generator, `constant_time_equal` for tags and MACs, `erase_secret`, which zeroes a buffer of - the program's with stores the optimiser keeps, and `error`, every failure's value. + generator, and `error`, every failure's value. The constant-time comparison + (`constant_time_equal`), the erasure of a buffer (`erase_secret`) and the self-wiping + `secret` crypto returns are [webcpp::secure](https://github.com/webcpporg/secure)'s, which + crypto depends on. - `webcpp::crypto::ciphers`: AES-GCM (`gcm`, `aes128_gcm`, `aes256_gcm`) with keys of 16, 24 and 32 bytes, the AES block cipher (`aes128`, `aes192`, `aes256`) and the ChaCha20-Poly1305 AEADs. - `webcpp::crypto::secret_key_encryption`: NaCl's and libsodium's secret boxes (`secretbox`, diff --git a/bench/Jamfile b/bench/Jamfile index 89452daa..979065c7 100644 --- a/bench/Jamfile +++ b/bench/Jamfile @@ -40,7 +40,7 @@ webcpp.run throughput_check : throughput.cpp : $(.requirements) ; exe throughput : throughput.cpp : $(.requirements) release ; explicit throughput ; -# The guard's cost needs no backend: detail/timing.hpp alone. +# The guard's cost needs no backend: alone. webcpp.run timing_check : timing.cpp ; # The same program at variant=release, the one collect.py --timing measures, diff --git a/bench/collect.py b/bench/collect.py index acf1ef40..37783741 100755 --- a/bench/collect.py +++ b/bench/collect.py @@ -47,13 +47,14 @@ script reads (an older bench/timing.cpp's, without the fastest and slowest runs, among them), are refused with a message naming what is wrong, before the page is written. -The timing guard's cost (detail::timing_guard, which every public operation holds and which sets -64-bit ARM's DIT where the CPU has it) is `timing --measure`'s one line: whether the guard sets DIT -on this machine, and the nanoseconds a guard adds to a call entered from a thread whose DIT is -clear and from one where it is already set, each the median of five runs of 10^7 guards minus an -empty loop's, with the fastest and slowest run. The data keeps it under "timing_guard" with the -date, the machine and the load; the page renders it as a paragraph and a two-row table under the -throughput. Every date is UTC's, as the constant-time lane's are. +The timing guard's cost (webcpp::secure::timing_guard, secure's guard, which every public +operation holds and which sets 64-bit ARM's DIT where the CPU has it) is `timing --measure`'s one +line: whether the guard sets DIT on this machine, and the nanoseconds a guard adds to a call +entered from a thread whose DIT is clear and from one where it is already set, each the median of +five runs of 10^7 guards minus an empty loop's, with the fastest and slowest run. The data keeps +it under "timing_guard" with the date, the machine and the load; the page renders it as a +paragraph and a two-row table under the throughput. Every date is UTC's, as the constant-time +lane's are. libsodium's x86-64 assembly (HAVE_AMD64_ASM, design D7) is recorded beside the table as not measured yet, with its reason, until an x86-64 machine runs a scratch build of it by hand. @@ -350,7 +351,8 @@ def measure_timing(exe): loads.append(os.getloadavg()) result = program_line("native", [exe, "--measure"], output, TIMING_LINE_SHAPE) return { - "measurement": "the nanoseconds detail::timing_guard adds to a call, bench/timing.cpp", + "measurement": "the nanoseconds webcpp::secure::timing_guard adds to a call, " + "bench/timing.cpp", "date": utc_today(), "machine": machine(), "load_average_before_after": [list(loads[0]), list(loads[1])], @@ -417,12 +419,13 @@ def render_timing(data, timing, titles, backends): "[#crypto-performance-timing]", "==== The timing guard's cost", "", - "Every public operation runs inside `detail::timing_guard`, which on 64-bit ARM under", - "macOS, iOS, Linux and Android, where the CPU has FEAT_DIT, sets DIT (data-independent", - "timing) for the call and restores the thread's state after it", - "(<>): one `mrs`, and where DIT was clear, two `msr`", - "each followed by an `isb`. Elsewhere (x86, WebAssembly, Windows on ARM64) it executes", - "no instruction.", + "Every public operation runs inside `webcpp::secure::timing_guard`, webcpp::secure's", + "guard, which on 64-bit ARM under macOS, iOS, Linux, Android and Windows, where the", + "CPU has FEAT_DIT, sets DIT (data-independent timing) for the call and restores the", + "thread's state after it (<>): one `mrs`; where DIT was clear, two", + "`msr` each followed by an `isb`; where it was set, a second `mrs` on the way out", + "(and an `msr` if something inside cleared it). Elsewhere (x86, WebAssembly, ARM64EC) it", + "executes no instruction.", "", ] if timing is None: @@ -464,7 +467,7 @@ def render_timing(data, timing, titles, backends): f"| {fmt_ns(timing.get('clear_slowest_ns'))}", "", "| already set, by the program or by an outer guard", - "| reads DIT and leaves it set", + "| reads DIT, and reads it again on the way out", f"| {fmt_ns(timing['set_ns'])}", f"| {fmt_ns(timing.get('set_fastest_ns'))}", f"| {fmt_ns(timing.get('set_slowest_ns'))}", diff --git a/bench/timing.cpp b/bench/timing.cpp index a5ae1368..b371b9ec 100644 --- a/bench/timing.cpp +++ b/bench/timing.cpp @@ -4,26 +4,26 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// The cost of detail::timing_guard, the scope every public operation of crypto runs in, which sets -// 64-bit ARM's DIT (data-independent timing) bit where the CPU has it and restores the thread's -// state after it. +// The cost of webcpp::secure::timing_guard, secure's guard, the scope every public operation of +// crypto runs in, which sets 64-bit ARM's DIT (data-independent timing) bit where the CPU has it +// and restores the thread's state after it. // // Run as `timing --measure`, it times, in one process, 10^7 iterations each of an empty loop body, // of a guard entered from a thread whose DIT is clear (it sets DIT and clears it again), and of a -// guard entered with DIT already set (it reads DIT and leaves it; the program sets DIT for that -// part with the same `msr` as the guard, and clears it after), five runs of each, interleaved, and -// prints one JSON line: `{"dit": true|false, "clear": , "set": , ...}`, each cost the -// median of its runs minus the empty loop's median, in nanoseconds per guard, then each part's -// fastest and slowest run (minus the same median), the iterations, the runs, the target and the -// compiler. "dit" says whether the guard sets DIT here (a target it covers, on a CPU that has it); -// where it does not, the guard executes no instruction and both costs are the loop's noise. Both -// modes fail when the process starts with DIT set, or when the thread's DIT is not as the guard -// must leave it after a part. Run with no argument, it is the correctness test: the same +// guard entered with DIT already set (it reads DIT, and again at its end; the program sets DIT +// for that part with the same `msr` as the guard, and clears it after), five runs of each, +// interleaved, and prints one JSON line: `{"dit": true|false, "clear": , "set": , ...}`, +// each cost the median of its runs minus the empty loop's median, in nanoseconds per guard, then +// each part's fastest and slowest run (minus the same median), the iterations, the runs, the +// target and the compiler. "dit" says whether the guard sets DIT here (a target it covers, on a CPU +// that has it); where it does not, the guard executes no instruction and both costs are the loop's +// noise. Both modes fail when the process starts with DIT set, or when the thread's DIT is not as +// the guard must leave it after a part. Run with no argument, it is the correctness test: the same // measurement at 10^3 iterations, whose line must also have that form, and whose "dit" must be // what the library reads. A measurement never fails on its time; bench/collect.py --timing runs // it and writes doc/performance.adoc. -#include +#include #include #include @@ -36,7 +36,7 @@ #include #include -namespace detail = webcpp::crypto::detail; +namespace secure = webcpp::secure; namespace { @@ -70,8 +70,8 @@ constexpr std::size_t runs = 5; // Whether the guard sets DIT on this target and CPU. bool guard_sets_dit() noexcept { -#ifdef WEBCPP_CRYPTO_DETAIL_TIMING_COVERED - return detail::cpu_has_dit(); +#ifdef WEBCPP_SECURE_TIMING_COVERED + return secure::cpu_has_dit(); #else return false; #endif @@ -79,9 +79,9 @@ bool guard_sets_dit() noexcept { // Sets or clears this thread's DIT where the guard would, as a program that asks for it does. void force_dit([[maybe_unused]] bool set) noexcept { -#ifdef WEBCPP_CRYPTO_DETAIL_TIMING_COVERED - if (detail::cpu_has_dit()) { - detail::write_dit(set ? detail::dit_bit : 0); +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (secure::cpu_has_dit()) { + secure::detail::write_dit(set ? secure::detail::dit_bit : 0); } #endif } @@ -127,24 +127,24 @@ result measure(std::uint64_t iterations) { std::array clear{}; std::array set{}; // A process that starts with DIT set would measure the set part twice. - bool restored = !detail::dit_is_set(); + bool restored = !secure::dit_is_set(); // Written by every iteration of every part, so that no loop is removed or merged. std::uint64_t volatile sink = 0; for (std::size_t run = 0; run < runs; ++run) { empty[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { sink = i; }); clear[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { - detail::timing_guard const guard; + secure::timing_guard const guard; sink = i; }); - restored = restored && !detail::dit_is_set(); + restored = restored && !secure::dit_is_set(); force_dit(true); set[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { - detail::timing_guard const guard; + secure::timing_guard const guard; sink = i; }); - restored = restored && detail::dit_is_set() == guard_sets_dit(); + restored = restored && secure::dit_is_set() == guard_sets_dit(); force_dit(false); - restored = restored && !detail::dit_is_set(); + restored = restored && !secure::dit_is_set(); } double const loop = summarise(empty, 0).median; return {.clear = summarise(clear, loop), .set = summarise(set, loop), .restored = restored}; diff --git a/build.jam b/build.jam index 50899505..cc0f05d1 100644 --- a/build.jam +++ b/build.jam @@ -19,11 +19,14 @@ project /webcpp/crypto ; # Header-only, on webcpp's configuration, with webcpp::hash's header-only # alias, whose algorithms name a signature's prehash (Ed25519ph's SHA-512; -# design D1). random_device reads Windows' generator through bcrypt +# design D1), and webcpp::secure's, whose timing guard, erase_secret, +# constant_time_equal, secret and declassify crypto's code holds and +# returns. random_device reads Windows' generator through bcrypt # (BCryptGenRandom), a system library. # tag::crypto[] alias crypto : : : : include /boost//headers /webcpp/config//config /webcpp/hash//hash + /webcpp/secure//secure windows:bcrypt ; # end::crypto[] diff --git a/doc/async.adoc b/doc/async.adoc index 380ddcc2..0cbbc843 100644 --- a/doc/async.adoc +++ b/doc/async.adoc @@ -57,11 +57,11 @@ its own, and the handler would run off the program's loop. | X25519 (<>) | `async_from_secret(executor, secret_key, token)`, `async_generate(executor, token)`, `async_agree(executor, key_pair, peer_public_key, token)`, the peer's key a `curves::x25519::public_key` -| `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, secret<32>)` for `async_agree` +| `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, secure::secret<32>)` for `async_agree` | P-256 (<>) | `async_from_secret(executor, scalar, token)`, `async_generate(executor, token)`, `async_sign(executor, key_pair, crypto::ecdsa_sha256, input, token)`, `async_verify(executor, crypto::ecdsa_sha256, signature, input, public_key, token)`, `async_agree(executor, key_pair, peer_public_key, token)` -| `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify`, `void(error_code, secret<32>)` for `async_agree` +| `void(error_code, Keypair)` for `async_from_secret` and `async_generate`, `void(error_code, signature)` for `async_sign`, `void(error_code)` for `async_verify`, `void(error_code, secure::secret<32>)` for `async_agree` |=== Each function has its member form, which the free function calls, with the @@ -178,7 +178,7 @@ include::{examples}/async_sign.expected[] *The completion's value on an error.* A value that is a keyed object or a secret has no meaning when the call failed, and the completion gives the -empty object a move leaves: a `gcm` or a key pair without a key, a `secret<32>` +empty object a move leaves: a `gcm` or a key pair without a key, a `secure::secret<32>` or a signature of zeros, a tag of zeros. A program that reads the object by mistake gets `invalid_state` from every member of a `gcm` or a key pair, and zeros from a secret, never a key. Check the error code first. An operation @@ -279,7 +279,7 @@ executor: a handler not bound to the loop's completes on the pool, and so waits for one of its threads. * After the work starts, it is not interrupted. A `terminal` or `partial` cancellation lets it run to its end, destroys its value (which wipes a -`secret` or a key pair) and completes with `operation_aborted`. A `total` +`secure::secret` or a key pair) and completes with `operation_aborted`. A `total` one is then ignored, since the value's destruction is a side effect already under way. * The signal is emitted on the handler's executor, as Asio's slots require: diff --git a/doc/backends.adoc b/doc/backends.adoc index cdef7007..83d7f5f4 100644 --- a/doc/backends.adoc +++ b/doc/backends.adoc @@ -45,7 +45,7 @@ scalar, the nonce and the HMAC-DRBG state that derives the nonce in its own stack frame and returns without clearing them (link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_i31_sign_raw.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l45[ecdsa_i31_sign_raw.c, lines 45 to 51 and 115 to 135]). webcpp wipes what it owns, a key pair's state -and every `secret`, and cannot reach a callee's frame, which the program's +and every `secure::secret`, and cannot reach a callee's frame, which the program's next calls overwrite. BearSSL's P-256 code differs by target. Natively webcpp takes `br_ec_p256_m62`, @@ -120,8 +120,8 @@ tag secret under Valgrind's memcheck, as link:https://github.com/agl/ctgrind[ctgrind] does, and, in a clang build, under MemorySanitizer, which only clang has (a gcc build runs memcheck alone): any branch or memory index that depends on them fails the run. The lane covers -`constant_time_equal`, `is_all_zero`, `erase_secret` and the wipe of -`secret`; BearSSL's AES-GCM and ChaCha20-Poly1305 `from_key`, `seal` and +`secure::constant_time_equal`, `is_all_zero`, `secure::erase_secret` and the wipe of +`secure::secret`; BearSSL's AES-GCM and ChaCha20-Poly1305 `from_key`, `seal` and `open`; OpenSSL's `from_key` and `seal` of both; ctaes's AES; libsodium's Ed25519 key pair and signature, X25519's public key, agreement and the key pair's wipe by a move, a @@ -151,7 +151,7 @@ selects a window's points with masks of that form) and the bytes a destructor wiped are checked by memcheck alone. dudect's statistics (link:https://eprint.iacr.org/2016/1123[Reparaz, Balasch and Verbauwhede]) time BearSSL's two AEADs' seal and open, BearSSL's P-256 `sign` of a digest and -`agree` against the key pair's scalar, ctaes, `constant_time_equal`, libsodium's +`agree` against the key pair's scalar, ctaes, `secure::constant_time_equal`, libsodium's X25519 agreement and Ed25519 signing, and libsecp256k1's `agree` natively, on Linux and macOS, and under wasmtime. dudect's programs set nothing themselves: they measure what a program gets, @@ -242,14 +242,21 @@ instructions Arm lists take a time independent of their data, and Apple requires it of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, enable DIT for constant-time cryptographic operations]). None of the C libraries sets it, so webcpp does: every public function that -runs a backend's cryptographic code, and `constant_time_equal`, runs its whole -body with DIT set on 64-bit ARM under macOS, iOS, Linux and Android where the -CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's systems, `HWCAP_DIT` on -Linux), and returns with the thread's DIT as it found it: clear when it was -clear, set when the program set it itself (Apple's -`timingsafe_enable_if_supported`, from macOS 15.2) or an outer call did. An -error and an exception leave it as found too, and DIT is a thread's own -state, so a call never changes another thread's. A program does nothing. +runs a backend's cryptographic code, and `secure::constant_time_equal`, runs its +whole body with DIT set on 64-bit ARM under macOS, iOS, Linux, Android and +Windows where the CPU has FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's +systems, `HWCAP_DIT` on Linux, one read of the register under structured +exception handling on Windows), through webcpp::secure's guard, +`webcpp::secure::timing_guard`, which webcpp's libraries share, and returns +with the thread's DIT as it found it: clear when it was clear, set when the +program set it itself (Apple's `timingsafe_enable_if_supported`, from macOS +15.2) or an outer call did, a call of webcpp::hash's among them. An error +leaves it as found too, and so does an exception, while it unwinds the call. +After the catch, Windows on ARM64 clears DIT when it resumes the thread: a +program there that set DIT itself and catches an exception from a call sets it +again after the catch (webcpp::secure's guide, "Exceptions" of its guard). +DIT is a thread's own state, so a call never changes another thread's. +Otherwise a program does nothing. Elsewhere webcpp sets nothing: @@ -258,9 +265,6 @@ mode), a model-specific register that only the kernel writes: it is the system's choice, out of webcpp's reach. * On WebAssembly, the engine that compiles the code decides, and the WebAssembly cannot set DIT: X25519 on wasip2 is the open finding above. -* On Windows on ARM64, no documented way to ask Windows whether the CPU has -FEAT_DIT was found, and DIT's instructions trap on a CPU without it: the -guard is empty there, and untested. What the guard adds to a call, measured from a release build beside the shortest operation's time, is in <>. diff --git a/doc/changelog.adoc b/doc/changelog.adoc index 327bc145..6e007898 100644 --- a/doc/changelog.adoc +++ b/doc/changelog.adoc @@ -16,8 +16,8 @@ of every version are on webcpp's index page. === Unreleased // tag::unreleased[] -* Added crypto, C-backed primitives setting DIT on arm64 macOS, iOS, Linux and Android: ciphers, curves, randomness, self-wiping secret, errors 1 to 20, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, asynchronous functions on Asio. -* Added constant_time_equal, random_device, pem on libsodium, the AES block cipher ciphers::aes128, aes192 and aes256 with a per-target default, and ciphers::gcm, aes128_gcm and aes256_gcm: incremental seal, two-pass open, failures zeroing data. +* Added crypto, C-backed primitives on webcpp::secure's guard, DIT on arm64 Apple, Linux and Windows: ciphers, curves, randomness, errors 1 to 20, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS, asynchronous functions on Asio. +* Added random_device, pem on libsodium, the AES block cipher ciphers::aes128, aes192 and aes256 with a per-target default, and ciphers::gcm, aes128_gcm and aes256_gcm: incremental seal, two-pass open, failures zeroing data. * Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line. * Added backends::bearssl (AES-GCM, ChaCha20-Poly1305, curves::p256: keys, low-S ECDSA, agree, SPKI/PKCS#8; allocating nothing), backends::openssl natively and on WASI (allocating at from_key only, or in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes. * Added curves::secp256k1: key pairs signing with crypto::ecdsa_sha256 (hedged too), ecdsa_sha256_recoverable, ecdsa_keccak256_recoverable (Ethereum's recoverable ECDSA) and schnorr, agree's three forms, strict DER, low-S, tweaks, SPKI, PKCS#8, PEM, ElligatorSwift, MuSig2, silent payments. @@ -25,5 +25,5 @@ of every version are on webcpp's index page. * Added backends::sodium on /third_party//sodium, shared with webcpp::hash, every backend's link-time canary and C suite, and ciphers::basic_chacha20_poly1305: chacha20_poly1305 (also BearSSL, OpenSSL), the original form, xchacha20_poly1305, failed seals and opens zeroing data. * Added secret_key_encryption's secretbox and secretbox_xchacha20poly1305 without associated data, public_key_encryption's box, box_xchacha20poly1305 and sealed_box, key_exchange::kx_keypair on libsodium, on typed X25519 keys. * Added the page: chapters per namespace and use case, the memory option's guide, generated tables, Jamfiles, messages, llms.txt, release-built sizes and throughput, X25519 timing findings (wasip2, DIT). -* Added signing.hpp, keypair.hpp, factories.hpp, secret_key_encryption/aead.hpp, erase_secret.hpp: typed signatures, sign(scheme, input), verify; keypair, signing_keypair, agreement_keypair; aead::cipher, authenticated_box; from_secret, from_bytes, from_key. +* Added signing.hpp, keypair.hpp, factories.hpp, secret_key_encryption/aead.hpp: typed signatures, sign(scheme, input), verify; keypair, signing_keypair, agreement_keypair; aead::cipher, authenticated_box; from_secret, from_bytes, from_key; secret, constant_time_equal, erase_secret are webcpp::secure's, no alias. // end::unreleased[] diff --git a/doc/constant_time_equal.adoc b/doc/constant_time_equal.adoc index cd20e8af..bacfedf7 100644 --- a/doc/constant_time_equal.adoc +++ b/doc/constant_time_equal.adoc @@ -17,19 +17,20 @@ bytes of a forged MAC are right; with enough requests the attacker builds a valid one byte by byte (link:https://cwe.mitre.org/data/definitions/208.html[CWE-208]). -`constant_time_equal`, in ``, compares in -constant time: it reads every byte, combines the differences without a branch, -and its running time depends only on the length. It takes two Hash2 digests of -one size, or two spans; spans of different sizes compare unequal without reading -their contents, since a size is public. HMAC itself -(link:https://www.rfc-editor.org/rfc/rfc2104[RFC 2104]) is Boost.Hash2's; crypto -adds the comparison that makes it safe to check. - -include::generated/backends-constant_time_equal.adoc[] +`secure::constant_time_equal`, webcpp::secure's, in +``, compares in constant time: it reads +every byte, combines the differences without a branch, and its running time +depends only on the length. It takes any two byte sequences: two Hash2 digests, +two spans, a `std::array`, a `std::string_view` or a `secure::secret`; +sequences of different sizes compare unequal without reading their contents, +since a size is public. It needs no backend. HMAC itself +(link:https://www.rfc-editor.org/rfc/rfc2104[RFC 2104]) is Boost.Hash2's; +webcpp::secure adds the comparison that makes it safe to check, and crypto, +which depends on it, compares its own tags and encodings with it. *Example.* A payment provider signs each webhook call with HMAC-SHA-256 under a shared secret. The program recomputes the MAC over the body and compares it with -`constant_time_equal`; here the key, the body and the MAC are RFC 4231's test +`secure::constant_time_equal`; here the key, the body and the MAC are RFC 4231's test case 2 (link:https://www.rfc-editor.org/rfc/rfc4231[RFC 4231]): [source,cpp] diff --git a/doc/curves.adoc b/doc/curves.adoc index bf913647..6f071dd6 100644 --- a/doc/curves.adoc +++ b/doc/curves.adoc @@ -394,15 +394,15 @@ one from `random_device`, each giving `result` key: `curves::ed25519::public_key`, `curves::x25519::public_key`, `curves::p256::public_key` or `curves::secp256k1::public_key`, whose value goes straight into `crypto::verify` or a peer's `agree`; -* `secret()` gives `result>`, the bytes `from_secret` takes, in a -`secret` that wipes itself (<>): Ed25519's seed, X25519's +* `secret()` gives `result>`, the bytes `from_secret` takes, in a +`secure::secret` that wipes itself (<>): Ed25519's seed, X25519's secret key, P-256's scalar, secp256k1's secret key. It is the export a PKCS#8 file or a backup takes. `crypto::signing_keypair` adds `sign(scheme, input)`, with every scheme its curve has, at least one, each giving the scheme's signature type (<>). `crypto::agreement_keypair` adds -`agree(peer)`, the peer a `K::public_key_type`, giving a `secret`. Each +`agree(peer)`, the peer a `K::public_key_type`, giving a `secure::secret`. Each curve's header checks its row of the table with a `static_assert` each: .The key pairs and the concepts they meet @@ -448,7 +448,7 @@ Ed25519's checks the size alone, whether the point is canonical and not of small order being its verification policy's judgment. ECDH is `agree(peer)` on every curve that has it, the peer a typed public key, -and gives a `secret<32>`: X25519's gives RFC 7748's shared secret +and gives a `secure::secret<32>`: X25519's gives RFC 7748's shared secret (<>), and the others the shared point's raw x coordinate, as WebCrypto's `deriveBits` does: P-256's (<>) and secp256k1's, whose two other forms keep names of their own, `agree_hashed` and diff --git a/doc/ed25519.adoc b/doc/ed25519.adoc index 61d86184..8a734e86 100644 --- a/doc/ed25519.adoc +++ b/doc/ed25519.adoc @@ -24,7 +24,7 @@ Ethereum and Nostr sign on secp256k1 instead (<>). A `keypair` is made from a seed with `from_secret(seed)`, or drawn from `random_device` with `generate()`; it gives its public key (`public_key()`), -its seed back (`secret()`, a `secret<32>`), signs +its seed back (`secret()`, a `secure::secret<32>`), signs (`sign(crypto::eddsa, message)`), and converts itself to an X25519 key pair (`to_x25519()`, <>), so that one seed serves for signatures and for key agreement. The key pair wipes its secret key when it is moved from and diff --git a/doc/erase_secret.adoc b/doc/erase_secret.adoc index ed7ea38d..8b9b2684 100644 --- a/doc/erase_secret.adoc +++ b/doc/erase_secret.adoc @@ -17,14 +17,12 @@ freed memory would find it. again is a dead store, and an optimising compiler removes it: the zeroes are never written and the secret stays (link:https://cwe.mitre.org/data/definitions/14.html[CWE-14]). -`erase_secret`, in ``, writes through a -volatile pointer and then a signal fence, as `secret` does when it is -destroyed, so the stores are kept: - -[source,cpp] ----- -include::{library-root}/test/erase_secret_test.cpp[tag=erase,indent=0] ----- +`secure::erase_secret`, webcpp::secure's, in ``, +writes through a volatile pointer and then a signal fence, as `secure::secret` +does when it is destroyed, so the stores are kept; crypto wipes its own copies +of keys with it. A password read into a `std::string` reserved beforehand, then +checked or hashed, is erased with `webcpp::secure::erase_secret(password)`; +webcpp::secure's guide shows the whole program. It takes any contiguous sized range of elements the program may write and that are trivially copyable: a `std::vector`, a `std::string`, a @@ -32,10 +30,8 @@ are trivially copyable: a `std::vector`, a `std::string`, a `size() * sizeof(element)` bytes from the first element: a string's size, not its capacity. A const range, or one of elements that are not trivially copyable, stops the build with a message naming the ranges it takes; a range -that is not contiguous, such as a `std::list`, has no `erase_secret`. It calls -no backend and never fails. - -include::generated/backends-erase_secret.adoc[] +that is not contiguous, such as a `std::list`, has no `secure::erase_secret`. It +calls no backend and never fails. *What it is not.* @@ -46,5 +42,5 @@ include::generated/backends-erase_secret.adoc[] * It does not lock the memory: the page may still be swapped to disk before the call. Locking it (`mlock`, `VirtualLock`) is the program's, and has no equivalent on WebAssembly. -* A secret that crypto returns is already a `secret`, which erases itself: - `erase_secret` is for the buffers the program fills itself. +* A secret that crypto returns is already a `secure::secret`, which erases itself: + `secure::erase_secret` is for the buffers the program fills itself. diff --git a/doc/everyday.adoc b/doc/everyday.adoc index 00570f92..7e5bac94 100644 --- a/doc/everyday.adoc +++ b/doc/everyday.adoc @@ -83,7 +83,7 @@ when the token comes back, so that a leaked database hands out no live session or reset link (OWASP asks that reset tokens be stored securely, link:https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html[Forgot Password Cheat Sheet]); a random token of 32 bytes needs no slow password hash. -`constant_time_equal` is for a token or a MAC checked against one value the +`secure::constant_time_equal` is for a token or a MAC checked against one value the program already knows. <> shows the program, `reset_token`. A password itself is never encrypted: it is hashed with a slow password hash, Argon2id or scrypt, which @@ -95,7 +95,7 @@ crypto. A payment provider or a source-code host signs each call to a program's webhook with an HMAC under a shared secret. The program recomputes it with -Boost.Hash2 and compares with `constant_time_equal`, never `==`: +Boost.Hash2 and compares with `secure::constant_time_equal`, never `==`: <>. [#crypto-everyday-storage] diff --git a/doc/formats.adoc b/doc/formats.adoc index e3bb9d9e..36282f69 100644 --- a/doc/formats.adoc +++ b/doc/formats.adoc @@ -56,7 +56,7 @@ WebCrypto's `exportKey("pkcs8")`, are refused; `pem` armours both `decode_spki(spki)`, `encode_pkcs8(keypair, out)` and `decode_pkcs8(pkcs8)`, which makes the key pair at once; `` gives the same four in `webcpp::crypto::curves::x25519`, where a PKCS#8 -holds a 32-byte secret key and `decode_pkcs8` gives it as a `secret<32>`, which +holds a 32-byte secret key and `decode_pkcs8` gives it as a `secure::secret<32>`, which wipes itself. `max_spki_size` and `max_pkcs8_size`, 44 and 48, size the caller's buffers. `` gives, in `webcpp::crypto::pem`, `armour(label, der, out)` and `unarmour(label, text, out)`, with the labels @@ -104,7 +104,7 @@ include::{examples}/key_formats.expected[] *Pitfalls.* -* A PKCS#8, as DER or as PEM, is the secret key: kept in a `secret`, as the +* A PKCS#8, as DER or as PEM, is the secret key: kept in a `secure::secret`, as the example does, it is wiped when it goes; written to a file or a database, it is sealed first, as any secret at rest (<>). * `decode_spki` checks the form, not the key: `crypto::verify` with diff --git a/doc/generated/backend-facts.adoc b/doc/generated/backend-facts.adoc index 37d8dd65..628802a2 100644 --- a/doc/generated/backend-facts.adoc +++ b/doc/generated/backend-facts.adoc @@ -43,7 +43,7 @@ |no backend |`+/webcpp/crypto//crypto+` -|`++`, `++`, `++` +|`++` |native, wasip2, wasip3, emscripten |=== diff --git a/doc/generated/backends-constant_time_equal.adoc b/doc/generated/backends-constant_time_equal.adoc deleted file mode 100644 index 4ce07b37..00000000 --- a/doc/generated/backends-constant_time_equal.adoc +++ /dev/null @@ -1,20 +0,0 @@ -// 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 `+constant_time_equal+`, from the test programs that run it: - -[cols="1,2,2,4",options="header"] -|=== -|Backend |Jamfile |Header |Targets - -|no backend -|`+/webcpp/crypto//crypto+` -|`++`, `++`, `++` -|native, wasip2, wasip3, emscripten (tested by `+constant_time_equal+`) -|=== diff --git a/doc/generated/backends-erase_secret.adoc b/doc/generated/backends-erase_secret.adoc deleted file mode 100644 index 22872a0d..00000000 --- a/doc/generated/backends-erase_secret.adoc +++ /dev/null @@ -1,20 +0,0 @@ -// 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 `+erase_secret+`, from the test programs that run it: - -[cols="1,2,2,4",options="header"] -|=== -|Backend |Jamfile |Header |Targets - -|no backend -|`+/webcpp/crypto//crypto+` -|`++`, `++`, `++` -|native, wasip2, wasip3, emscripten (tested by `+erase_secret+`) -|=== diff --git a/doc/generated/backends-error.adoc b/doc/generated/backends-error.adoc index 6f8c9b6c..b8d18d6c 100644 --- a/doc/generated/backends-error.adoc +++ b/doc/generated/backends-error.adoc @@ -15,6 +15,6 @@ The backends of `+error+`, from the test programs that run it: |no backend |`+/webcpp/crypto//crypto+` -|`++`, `++`, `++` +|`++` |native, wasip2, wasip3, emscripten (tested by `+error+`) |=== diff --git a/doc/generated/constant-time.adoc b/doc/generated/constant-time.adoc index 2f2179ff..7725ce01 100644 --- a/doc/generated/constant-time.adoc +++ b/doc/generated/constant-time.adoc @@ -54,14 +54,14 @@ |not measured yet |no backend -|`+constant_time_equal+` is constant time in the contents: every byte is read, no branch and no index depends on one -|Valgrind's memcheck (Linux): `+constant_time_equal+`, `+is_all_zero+` and the wipe of `+secret+`; MemorySanitizer (Linux, clang): `+constant_time_equal+`, `+is_all_zero+` and the wipe of `+secret+`; dudect (judged; on a runner GitHub hosts, by two of three runs): `+constant_time_equal+` -|dudect (judged; on a runner GitHub hosts, by two of three runs): `+constant_time_equal+` +|webcpp::secure's `+secure::constant_time_equal+`, which crypto's code calls, is constant time in the contents: every byte is read, no branch and no index depends on one +|Valgrind's memcheck (Linux): `+secure::constant_time_equal+`, `+is_all_zero+` and the wipe of `+secure::secret+`; MemorySanitizer (Linux, clang): `+secure::constant_time_equal+`, `+is_all_zero+` and the wipe of `+secure::secret+`; dudect (judged; on a runner GitHub hosts, by two of three runs): `+secure::constant_time_equal+` +|dudect (judged; on a runner GitHub hosts, by two of three runs): `+secure::constant_time_equal+` |not measured yet |not measured yet |=== Measured where a family differs from its backend's design: -* X25519 on libsodium, native: nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux and Android where the CPU has it, as Apple requires of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: |t| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `+dudect_planted+`, an early-exit scan of the secret key run inside the same guard, reads |t| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `+agree+` with an all-zero secret key against random ones at |t| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86, WebAssembly or Windows on ARM64 +* X25519 on libsodium, native: nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: |t| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `+dudect_planted+`, an early-exit scan of the secret key run inside the same guard, reads |t| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `+agree+` with an all-zero secret key against random ones at |t| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly * X25519 on libsodium, wasip2: an open finding, its cause measured: dudect times `+agree+` with an all-zero secret key against random ones at |t| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads |t| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next diff --git a/doc/generated/matrix.adoc b/doc/generated/matrix.adoc index fbeea4fe..0d59f2c1 100644 --- a/doc/generated/matrix.adoc +++ b/doc/generated/matrix.adoc @@ -46,16 +46,6 @@ |native, wasip2, wasip3, emscripten |`+async_p256+` -|`+constant_time_equal+` -|no backend -|native, wasip2, wasip3, emscripten -|`+constant_time_equal+` - -|`+erase_secret+` -|no backend -|native, wasip2, wasip3, emscripten -|`+erase_secret+` - |`+error+` |no backend |native, wasip2, wasip3, emscripten @@ -358,18 +348,6 @@ The same, by target: the backends each operation runs on. |BearSSL |BearSSL -|`+constant_time_equal+` -|no backend -|no backend -|no backend -|no backend - -|`+erase_secret+` -|no backend -|no backend -|no backend -|no backend - |`+error+` |no backend |no backend diff --git a/doc/generated/messages.adoc b/doc/generated/messages.adoc index 4828d0ef..16a097ff 100644 --- a/doc/generated/messages.adoc +++ b/doc/generated/messages.adoc @@ -275,6 +275,12 @@ The fix: Name a backend that has ChaCha20-Poly1305, as in `+chacha20_poly1305+`. +|`+constant_time_equal_moved+` +|native, wasip2, wasip3 +|`+no member named 'constant_time_equal' in namespace 'webcpp::crypto'+` + +The fix: Call `+webcpp::secure::constant_time_equal+`, from `++`, the same comparison in constant time; `+crypto::constant_time_equal+` moved to webcpp::secure, with no alias. + |`+ctaes_not_linked+` |native, wasip2, wasip3 |`+webcpp::crypto: the backend ctaes is used and not linked. In the program's Jamfile, add /third_party//ctaes beside /webcpp/crypto//crypto. (without b2: define WEBCPP_CRYPTO_HAS_CTAES=1 and link ctaes.c with webcpp's src/canary_ctaes.c)+` @@ -327,19 +333,19 @@ The fix: Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp2 |native, wasip2, wasip3 |`+'webcpp/crypto/equal.hpp' file not found+` -The fix: Include `++`, the header of `+constant_time_equal+`; `+equal.hpp+` is gone, with no header left at its path. +The fix: Include `++`, the header of `+secure::constant_time_equal+`; `+equal.hpp+` is gone, with no header left at its path. |`+equal_removed+` |native, wasip2, wasip3 |`+no member named 'equal' in namespace 'webcpp::crypto'+` -The fix: Call `+crypto::constant_time_equal+`, the same comparison of two spans or two digests in constant time; `+crypto::equal+` is gone, with no alias. +The fix: Call `+webcpp::secure::constant_time_equal+`, the same comparison of two byte sequences in constant time; `+crypto::equal+` is gone, with no alias. -|`+erase_secret_const_range+` +|`+erase_secret_moved+` |native, wasip2, wasip3 -|`+webcpp::crypto: erase_secret zeroes a buffer the program may write, of trivially copyable elements: a std::vector, a std::string, a std::array, a std::span; this range's elements are const or not trivially copyable.+` +|`+no type named 'erase_secret' in namespace 'webcpp::crypto'+` -The fix: Erase the buffer the secret was written to, through a non-const reference to it (`+std::string&+`, `+std::span+`): a const view cannot be erased. Its elements must be trivially copyable, bytes or integers; a range of `+std::string+` or of another type with its own storage cannot be erased as bytes, so erase each element's buffer instead. +The fix: Call `+webcpp::secure::erase_secret+`, from `++`, the same erasure; `+crypto::erase_secret+` moved to webcpp::secure, with no alias. |`+gcm_default_openssl_not_linked+` |native @@ -617,11 +623,11 @@ The fix: Call public_key_tweak_add, public_key_tweak_mul, public_key_negate, pub The fix: As `+secp256k1_tweak_names_removed+`. -|`+secret_of_no_bytes+` +|`+secret_moved+` |native, wasip2, wasip3 -|`+webcpp::crypto: a secret of no bytes holds nothing.+` +|`+no template named 'secret' in namespace 'webcpp::crypto'+` -The fix: Give `+secret+` the number of bytes it holds, at least one, as in `+secret<32>+`. +The fix: Name `+webcpp::secure::secret+`, from `++`, the type every secret crypto returns; `+crypto::secret+` moved to webcpp::secure, with no alias. |`+secretbox_header_removed+` |native, wasip2, wasip3 @@ -871,7 +877,7 @@ The fix: Verify a BIP340 signature with `+crypto::schnorr+`, its scheme; `+crypt |native, wasip2, wasip3 |`+no type named 'wipe' in namespace 'webcpp::crypto'+` -The fix: Call `+crypto::erase_secret+`, which zeroes a contiguous range the program owns (a `+std::string&+`, a `+std::span+`) with stores the optimiser keeps; `+crypto::wipe+` is gone, with no alias. +The fix: Call `+webcpp::secure::erase_secret+`, which zeroes a contiguous range the program owns (a `+std::string&+`, a `+std::span+`) with stores the optimiser keeps; `+crypto::wipe+` is gone, with no alias. |`+x25519_asynchronous_backend+` |native, wasip2, wasip3 @@ -1510,20 +1516,6 @@ On each target, the build's output contains: * emscripten: ** `+webcpp::crypto: PEM's default backend on this target is libsodium, which is not linked, and the one backend that has it there. Add /webcpp/crypto//pem-default, the default's library on every target, to the program's Jamfile, as in: exe app : app.cpp /webcpp/crypto//crypto /webcpp/crypto//pem-default ; (without b2: define WEBCPP_CRYPTO_HAS_SODIUM=1 and link libsodium built with webcpp's src/canary_sodium.c)+` -`+secret_of_no_bytes_on_emscripten+`:: A program for Emscripten that names `+secret<0>+`. The fix: As `+secret_of_no_bytes+`. -+ -Its Jamfile: -+ -[listing] ----- -include::{webcpp-root}/tools/test/fixtures/crypto_jamfiles/secret_of_no_bytes_on_emscripten/Jamfile[tag=jamfile] ----- -+ -On each target, the build's output contains: -+ -* emscripten: -** `+webcpp::crypto: a secret of no bytes holds nothing.+` - `+sodium_not_linked_on_emscripten+`:: A program for Emscripten that names libsodium and links none. The fix: Add `+/third_party//sodium+` to the program's sources. + Its Jamfile: @@ -1758,10 +1750,6 @@ On MSVC, each case of `test/msvc` is proven to stop the build, at compile or at |the compile |Name `+backends::secp256k1+`, or leave the backend out: `+curves::secp256k1::keypair+`. -|`+secret_of_no_bytes+` -|the compile -|Give `+secret+` the number of bytes it holds, at least one, as in `+secret<32>+`. - |`+sign_eddsa_prehashed_message+` |the compile |Give `+crypto::eddsa_prehashed+` the message's SHA-512 marked as a digest, `+crypto::prehashed{digest}+` of a `+std::array+`; sign the message itself with `+crypto::eddsa+`, or give it in pieces to `+curves::ed25519::prehashed_signer+`. diff --git a/doc/generated/namespace-curves.adoc b/doc/generated/namespace-curves.adoc index 3b8e3bb0..30fc16e0 100644 --- a/doc/generated/namespace-curves.adoc +++ b/doc/generated/namespace-curves.adoc @@ -44,7 +44,7 @@ |Constant time, measured |libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `+ctime_tests.c+`, and webcpp's code around it: the key pair's making and `+secret()+`, its signatures and x-only tweak, ECDH in three forms (`+agree+`, `+agree_hashed+` and `+agree_point+`), the secret key's tweaks and negation, and PKCS#8), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `+agree+`), nothing found; not measured yet on wasip3, emscripten (<>) |libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten (<>) -|libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux and Android where the CPU has it, as Apple requires of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: \|t\| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads \|t\| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at \|t\| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86, WebAssembly or Windows on ARM64; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at \|t\| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads \|t\| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten (<>) +|libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires of constant-time code (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]); the lane's dudect sets nothing itself and measures what a program gets: \|t\| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads \|t\| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at \|t\| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at \|t\| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set (link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations]): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads \|t\| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten (<>) |BearSSL: native, Valgrind's memcheck (Linux; the key pair's making, `+sign+` of a digest (`+crypto::prehashed+`), which makes its signature low S without a branch, then `+normalize_low_s+` and `+is_low_s+` on it, `+agree+` and `+decode_pkcs8+`; BearSSL's own branches on its signing's verdicts listed in `+bearssl_verdicts.supp+`; nothing found with webcpp's fix to BearSSL's decoding of the nonce, whose leak of the nonce's bit length this checker found on 2026-11-21, including `+sign+` with its low-S step (Valgrind 3.22, arm64 Linux container, 2026-11-22)), MemorySanitizer (Linux, clang; the same paths as memcheck's; for the previous signing, found the same leak, nothing after the fix, including `+sign+` with its low-S step (clang 18, arm64 Linux container, 2026-11-22)) and dudect (judged; on a runner GitHub hosts, by two of three runs; `+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `+sign+` of a digest and `+agree+`, each against the key pair's scalar; `+sign+` with its low-S step judged constant time, \|t\| 1.70 on Linux and 1.63 natively on an Apple M5 Max (release, one run each, 2026-11-22; provisional, measured again in the final quiet pass)), nothing found; not measured yet on wasip3, emscripten (<>) |Standards diff --git a/doc/generated/namespace-key_exchange.adoc b/doc/generated/namespace-key_exchange.adoc index 1ab77ffb..695b27b2 100644 --- a/doc/generated/namespace-key_exchange.adoc +++ b/doc/generated/namespace-key_exchange.adoc @@ -21,7 +21,7 @@ |a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed or drawn, and the peer's X25519 public key |Output -|two 32-byte `secret<32>` per side, the client's `transmit` the server's `receive` +|two 32-byte `secure::secret<32>` per side, the client's `transmit` the server's `receive` |Standards and sources |link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange] diff --git a/doc/generated/namespace-root.adoc b/doc/generated/namespace-root.adoc index f5f09200..15013edd 100644 --- a/doc/generated/namespace-root.adoc +++ b/doc/generated/namespace-root.adoc @@ -9,7 +9,7 @@ [cols="2h,5,5,5,5,5,5,5,5,5,5",options="header"] |=== -|Name |`random_device` |`constant_time_equal` |`erase_secret` |`secret` |`error` |`pem` |`openssl_memory_resource` |Signatures |The key pair concepts |Making by type +|Name |`random_device` |`secure::constant_time_equal` |`secure::erase_secret` |`secure::secret` |`error` |`pem` |`openssl_memory_resource` |Signatures |The key pair concepts |Making by type |Names | @@ -37,9 +37,9 @@ |Header |`` -|`` -|`` -|`` +|`` +|`` +|`` |`` |`` |`` diff --git a/doc/generated/use-cases.adoc b/doc/generated/use-cases.adoc index a11e11ab..58617e49 100644 --- a/doc/generated/use-cases.adoc +++ b/doc/generated/use-cases.adoc @@ -40,7 +40,7 @@ |<> |Check a webhook's or an API's HMAC signature -|`+constant_time_equal+`, with Boost.Hash2's `+hmac+` +|`+secure::constant_time_equal+`, with Boost.Hash2's `+hmac+` |none |`+/webcpp/crypto//crypto+` |<> diff --git a/doc/jamfile.adoc b/doc/jamfile.adoc index fc64cf31..cf2b6296 100644 --- a/doc/jamfile.adoc +++ b/doc/jamfile.adoc @@ -80,7 +80,7 @@ A native program that sends OpenSSL's allocations to its own resource `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 `constant_time_equal`, which would otherwise have the define +`random_device` or `secure::constant_time_equal`, which would otherwise have the define without OpenSSL. The fixture `memory_option` builds and runs this Jamfile natively: diff --git a/doc/kx.adoc b/doc/kx.adoc index b5fa665a..718e4e57 100644 --- a/doc/kx.adoc +++ b/doc/kx.adoc @@ -30,7 +30,7 @@ given back by `keypair()`); they send each other their public keys, each an the 32 bytes received); the client calls `client_session_keys(server_public_key)` and the server `server_session_keys(client_public_key)`. Each gets a `session_keys`, a -`receive` and a `transmit` key, both `secret<32>` that wipe themselves; the +`receive` and a `transmit` key, both `secure::secret<32>` that wipe themselves; the client's `transmit` is the server's `receive` and the reverse, so that a message each side sends has a key of its own (link:https://doc.libsodium.org/key_exchange[libsodium's documentation, key exchange]). diff --git a/doc/llms.txt b/doc/llms.txt index 413acc60..41f947a2 100644 --- a/doc/llms.txt +++ b/doc/llms.txt @@ -1,6 +1,6 @@ # webcpp::crypto -> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, a constant_time_equal and an erase_secret whose stores the optimiser keeps, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. +> Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's; the constant-time comparison, the erasure of a buffer and secret are webcpp::secure's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives. Generated by doc/tables/generate.py with the page's tables. Page: https://webcpporg.github.io/libs/crypto/ @@ -31,10 +31,6 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - async_sign: Signs with an Ed25519 or a P-256 key pair, asynchronously: `key_pair.sign(signing_scheme, signing_input)` run when the operation is initiated, its result posted to `completion_executor`. - async_verify: Verifies a P-256 ECDSA signature over SHA-256, asynchronously: `crypto::verify(crypto::ecdsa_sha256, signature_value, signing_input, public_key)` run when the operation is initiated, its result posted to `completion_executor`; the message is hashed with SHA-256, as WebCrypto's ECDSA with SHA-256 verifies, or `crypto::prehashed{digest}` gives its digest. - async_agree: Agrees a shared secret, asynchronously: `key_pair.agree(peer_public_key)` run when the operation is initiated, its result posted to `completion_executor`: X25519's (RFC 7748), or P-256's ECDH raw x coordinate, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. -- [constant_time_equal](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): Compares two tags or MACs in constant time. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: check a webhook's or an API's HMAC signature. - - constant_time_equal: Whether two byte sequences are equal, in a time that does not depend on their contents. -- [erase_secret](https://webcpporg.github.io/libs/crypto/#crypto-erase-secret): Zeroes a buffer the program owns, a password, a key or a plaintext, with stores the optimiser keeps. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. - - erase_secret: Zeroes every byte of a buffer the program owns, with stores the optimiser keeps. - [error](https://webcpporg.github.io/libs/crypto/#crypto-errors): Every failure's value, fixed and never reused, in the category webcpp.crypto. Header . Backends: no backend (/webcpp/crypto//crypto) on native, wasip2, wasip3, emscripten. Use it to: tell a forged message from a malformed one. - error_category: The category of every error. - make_error_code: Makes the `error_code` of an error, as its implicit conversion does. @@ -154,7 +150,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - verify: Verifies a signature of the message given, which it ends, strictly (design D31). - [crypto::to_x25519](https://webcpporg.github.io/libs/crypto/#crypto-x25519): Converts an Ed25519 key pair to an X25519 key pair of its backend, and an Ed25519 public key to an X25519 public key (the birational map), refusing a key of small order or not canonical with `invalid_public_key`: the free form of both members, `to_x25519()`, synchronous on every backend. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. - to_x25519: Converts an Ed25519 key pair or public key to X25519's, `converted_value.to_x25519()`: the free form of the member, which it calls, with its results and its errors. -- [curves::x25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-x25519): An X25519 key pair (RFC 7748): made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::x25519::public_key`, computed once; and `agree(peer)`, the 32-byte shared secret with a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. +- [curves::x25519::keypair](https://webcpporg.github.io/libs/crypto/#crypto-x25519): An X25519 key pair (RFC 7748): made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::x25519::public_key`, computed once; and `agree(peer)`, the 32-byte shared secret with a peer's public key, a `secure::secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order). Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: agree a shared secret with a peer's public key (X25519, RFC 7748), or with the X25519 form of an Ed25519 key. - from_secret: Makes a key pair from its secret key; its public key is computed here, once. - generate: Makes a key pair from a fresh secret key, drawn from the system's generator. - async_from_secret: Makes a key pair from its secret key, asynchronously: `from_secret` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_from_secret`, with the same arguments, which calls it. @@ -171,7 +167,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - decode_spki: The public key of an SPKI, refused unless it is exactly RFC 8410's form: the 12 bytes of Ed25519's prefix, then the key, and nothing after. - encode_pkcs8: Writes a key pair's PKCS#8 (RFC 8410, version 1: the seed, without the public key) into `output_bytes`, which then holds the secret key: a program wipes it, or seals it, when it is done. - decode_pkcs8: The key pair of a PKCS#8, refused unless it is exactly RFC 8410's version 1 form: the 16 bytes of Ed25519's prefix, then the seed, and nothing after. -- [curves::x25519::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): RFC 8410's SPKI of an X25519 public key (44 bytes) and PKCS#8 of a secret key (version 1, 48 bytes), the forms OpenSSL and WebCrypto write, decoded strictly into a `secret<32>`: any other bytes are `invalid_encoding`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text. +- [curves::x25519::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-key-formats): RFC 8410's SPKI of an X25519 public key (44 bytes) and PKCS#8 of a secret key (version 1, 48 bytes), the forms OpenSSL and WebCrypto write, decoded strictly into a `secure::secret<32>`: any other bytes are `invalid_encoding`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: export or import an Ed25519 or X25519 key in the standard forms OpenSSL and WebCrypto use: SPKI and PKCS#8 (RFC 8410), as DER or PEM text. - encode_spki: Writes a public key's SPKI (RFC 8410) into `output_bytes`. - decode_spki: The public key of an SPKI, refused unless it is exactly RFC 8410's form: the 12 bytes of X25519's prefix, then the key, and nothing after. - encode_pkcs8: Writes a secret key's PKCS#8 (RFC 8410, version 1: the secret key, without the public key) into `output_bytes`, which then holds the secret key: a program wipes it, or seals it, when it is done. @@ -230,7 +226,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - create_labeled_spend_key: The spend key of a labelled address (`..._create_labeled_spend_pubkey`). - make_previous_outputs_summary: The previous outputs' summary (`secp256k1_silentpayments_recipient_prevouts_summary_create`) from the eligible inputs' public keys. - scan_outputs: Scans a transaction's x-only outputs (`..._recipient_scan_outputs`) with the scan key pair and the unlabelled spend key; `label_lookup` is called with a candidate label's 33 bytes and returns a span over its tweak, in bytes the lookup owns, or `std::nullopt`, noexcept (no labels: the default). -- [curves::p256::keypair](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A P-256 key pair: made from its 32-byte scalar, refused unless 0 < d < n, or drawn from `random_device`; its validated public key and its scalar, `secret()`, a `secret<32>`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. +- [curves::p256::keypair](https://webcpporg.github.io/libs/crypto/#crypto-p256-keys): A P-256 key pair: made from its 32-byte scalar, refused unless 0 < d < n, or drawn from `random_device`; its validated public key and its scalar, `secret()`, a `secure::secret<32>`. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: make and keep a P-256 key pair, and import a browser's public key (WebCrypto's raw form), as webcpp::trystero's peers do. - from_secret: Makes a key pair from its secret scalar, as a program that kept `secret()` loads it again. - generate: Makes a key pair from a fresh scalar, drawn from the system's generator until it is below the group order (a draw is refused about once in 2^32). - async_from_secret: Makes a key pair from its secret scalar, asynchronously: `from_secret` run when the operation is initiated, its result posted to `completion_executor`; the member form of the free `crypto::async_from_secret`, with the same arguments, which calls it. @@ -251,7 +247,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - from_der: Decodes a strict DER signature to its raw form: only the encoding `to_der` writes is accepted. - normalize_low_s: The low-S form of a signature: s replaced by n - s when s is above (n - 1) / 2, returned unchanged otherwise. - is_low_s: Whether a signature is in its low-S form, as a protocol that requires low S checks what it receives before `crypto::verify`, which accepts both forms; `sign` gives the low form. -- [curves::p256::keypair::agree](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as Trystero 0.27.0's pairwise keys are derived. +- [curves::p256::keypair::agree](https://webcpporg.github.io/libs/crypto/#crypto-p256-ecdh): ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secure::secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: agree on a key with a browser's WebCrypto (ECDH on P-256, deriveBits), then derive the session's keys with HKDF, as Trystero 0.27.0's pairwise keys are derived. - agree: ECDH with a peer's public key: the x coordinate of the shared point d * Q, raw, as WebCrypto's `deriveBits` with ECDH on P-256 gives its 256 bits. - async_agree: ECDH with a peer's public key, asynchronously: `agree` run when the operation is initiated, its result posted to `completion_executor`; the member form of `crypto::async_agree(completion_executor, key_pair, peer_key, completion_token)`, which calls it. - [curves::p256::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8](https://webcpporg.github.io/libs/crypto/#crypto-p256-formats): A public key's SPKI (RFC 5480, the uncompressed point, 91 bytes) and a key pair's PKCS#8 (RFC 5915's ECPrivateKey with its public key and no parameters, 138 bytes), by fixed layouts, decoded strictly: any other bytes are `invalid_encoding`; `pem::armour` makes either PEM text. Header . Backends: BearSSL (/third_party//bearssl) on native, wasip2, wasip3, emscripten. Default: BearSSL on native, wasip2, wasip3, emscripten. Use it to: export or import a P-256 key in the forms OpenSSL and WebCrypto's spki and pkcs8 use (SPKI, PKCS#8), as DER or PEM text. @@ -280,7 +276,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp ## webcpp::crypto::key_exchange -- [key_exchange::kx_keypair](https://webcpporg.github.io/libs/crypto/#crypto-kx): libsodium's `crypto_kx` on X25519's typed keys: a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed as libsodium does (BLAKE2b-256 of the seed) or drawn from `random_device`, and the two session keys of a client or a server, each a `secret<32>`, from the peer's X25519 public key; a peer key of low order is refused with `weak_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: give a client and a server a key for each direction from each other's public key, as libsodium's `crypto_kx` does. +- [key_exchange::kx_keypair](https://webcpporg.github.io/libs/crypto/#crypto-kx): libsodium's `crypto_kx` on X25519's typed keys: a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed as libsodium does (BLAKE2b-256 of the seed) or drawn from `random_device`, and the two session keys of a client or a server, each a `secure::secret<32>`, from the peer's X25519 public key; a peer key of low order is refused with `weak_public_key`. Header . Backends: libsodium (/third_party//sodium) on native, wasip2, wasip3, emscripten. Default: libsodium on native, wasip2, wasip3, emscripten. Use it to: give a client and a server a key for each direction from each other's public key, as libsodium's `crypto_kx` does. - from_keypair: Takes an X25519 key pair as it is: its secret key is the key pair's, as `crypto_kx` uses it, with no hash (`derive_from_seed` hashes its seed). - derive_from_seed: Derives a key pair from a seed, `crypto_kx_seed_keypair`: the same seed gives the same key pair, its secret key BLAKE2b-256 of the seed, not the seed itself. - generate: Makes a key pair from a fresh seed, drawn from the system's generator. @@ -322,7 +318,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - AES block cipher: OpenSSL: not measured yet. ctaes: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. - secp256k1: libsecp256k1: native, Valgrind's memcheck (Linux; libsecp256k1's own `ctime_tests.c`, and webcpp's code around it: the key pair's making and `secret()`, its signatures and x-only tweak, ECDH in three forms (`agree`, `agree_hashed` and `agree_point`), the secret key's tweaks and negation, and PKCS#8), MemorySanitizer (Linux, clang; the same paths as memcheck's) and dudect (judged; on a runner GitHub hosts, by two of three runs; `agree`), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs; `agree`), nothing found; not measured yet on wasip3, emscripten. - Ed25519: libsodium: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. -- X25519: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux and Android where the CPU has it, as Apple requires of constant-time code ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)); the lane's dudect sets nothing itself and measures what a program gets: |t| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads |t| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at |t| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86, WebAssembly or Windows on ARM64; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at |t| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads |t| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten. +- X25519: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found, and dudect (judged; on a runner GitHub hosts, by two of three runs): nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires of constant-time code ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)); the lane's dudect sets nothing itself and measures what a program gets: |t| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads |t| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at |t| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs): an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at |t| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set ([Apple, Writing ARM64 code for Apple platforms: enable DIT for constant-time cryptographic operations](https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations)): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads |t| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next; not measured yet on wasip3, emscripten. - crypto_kx: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. - PEM: libsodium: not measured yet. - ChaCha20-Poly1305: libsodium: native, Valgrind's memcheck (Linux) and MemorySanitizer (Linux, clang), nothing found; not measured yet on wasip2, wasip3, emscripten. BearSSL: native, Valgrind's memcheck (Linux), MemorySanitizer (Linux, clang) and dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; wasip2, dudect (judged; on a runner GitHub hosts, by two of three runs), nothing found; not measured yet on wasip3, emscripten. OpenSSL (seal alone: its open branches on the verdict inside OpenSSL): native, Valgrind's memcheck (Linux), nothing found; not measured yet on wasip2, wasip3. @@ -347,7 +343,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [ECDH's form](https://webcpporg.github.io/libs/crypto/#crypto-secp256k1-ecdh): `keypair::agree` returns the raw x coordinate of the shared point, which protocols such as Nostr's NIP-44 ([Nostr NIP-44, encrypted payloads](https://github.com/nostr-protocol/nips/blob/master/44.md)) take; `keypair::agree_hashed` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly. - [The x-only tweak is not BIP 32](https://webcpporg.github.io/libs/crypto/#crypto-wallets-taproot): `tweak_xonly` is BIP 341's even-y arithmetic ([BIP 341, Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki)); BIP 32's child derivation tweaks the full key, with `secret_key_tweak_add` and `public_key_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ([BIP 32, hierarchical deterministic wallets](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)). - [Ethereum](https://webcpporg.github.io/libs/crypto/#crypto-curves): this version signs Ethereum's recoverable ECDSA over Keccak-256 (`keypair::sign(crypto::ecdsa_keccak256_recoverable, input)`, a message hashed inside or the 32-byte digest a program builds), recovers a signer's public key from a signature and the same input (`recover`), and writes the uncompressed key ([The Ethereum yellow paper, appendix F: ECDSA on secp256k1](https://ethereum.github.io/yellowpaper/paper.pdf)); the recovery id's `v` encoding, the digests Ethereum signs (EIP-191, EIP-712, a transaction's), transactions and addresses are a domain library's, which the guide shows over webcpp::hash. -- [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): compare a tag, a MAC or a token with `constant_time_equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). +- [Compare secrets in constant time](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): compare a tag, a MAC or a token with `secure::constant_time_equal`, never `==` or `memcmp` ([CWE-208, observable timing discrepancy](https://cwe.mitre.org/data/definitions/208.html)). - [Secrets come from random_device](https://webcpporg.github.io/libs/crypto/#crypto-entropy): keys, nonces and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ([CWE-338, a weak generator used for security](https://cwe.mitre.org/data/definitions/338.html)). - [Never reuse a nonce under one ChaCha20-Poly1305 key](https://webcpporg.github.io/libs/crypto/#crypto-chacha): two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ([RFC 8439, section 4: a nonce is never repeated under one key](https://www.rfc-editor.org/rfc/rfc8439#section-4)). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte nonces ([NIST SP 800-38D, GCM and GMAC](https://csrc.nist.gov/pubs/sp/800/38/d/final)). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw. - [A shared secret is not a key](https://webcpporg.github.io/libs/crypto/#crypto-x25519): derive keys from X25519's shared secret and both public keys with a KDF such as webcpp::hash's HKDF, never use its bytes as a cipher's key ([RFC 7748, section 6.1: a KDF over the shared secret and both public keys](https://www.rfc-editor.org/rfc/rfc7748#section-6.1)); `kx_keypair` and the boxes do this themselves. @@ -359,7 +355,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - [Sign and verify with Ed25519 in a coroutine](https://webcpporg.github.io/libs/crypto/#crypto-async): `async_sign`, `async_verify` (webcpp::crypto); backend the default of Ed25519; Jamfile /webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio. Example: example/async_sign.cpp. - [Generate a session token, a password-reset link or an API key](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device::fill` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. - [Draw an unbiased number in a range, such as a six-digit code](https://webcpporg.github.io/libs/crypto/#crypto-entropy): `random_device` with `std::uniform_int_distribution` (webcpp::crypto); backend the system's generator; Jamfile /webcpp/crypto//crypto. Example: example/reset_token.cpp. -- [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): `constant_time_equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/constant_time_equal_hmac.cpp. +- [Check a webhook's or an API's HMAC signature](https://webcpporg.github.io/libs/crypto/#crypto-constant-time-equal): `secure::constant_time_equal`, with Boost.Hash2's `hmac` (webcpp::crypto); backend none; Jamfile /webcpp/crypto//crypto. Example: example/constant_time_equal_hmac.cpp. - [Encrypt a database field, a cookie or a token at rest](https://webcpporg.github.io/libs/crypto/#crypto-gcm): `aes256_gcm` (webcpp::crypto::ciphers); backend the default: OpenSSL natively, BearSSL on WebAssembly; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default. Example: example/store_token.cpp. - [Encrypt a large file or a stream](https://webcpporg.github.io/libs/crypto/#crypto-gcm-incremental): `aes256_gcm`: records, or `begin_seal`, `update` and `result` (webcpp::crypto::ciphers); backend the default; Jamfile /webcpp/crypto//crypto /webcpp/crypto//gcm-default. Example: example/sealed_records.cpp. - [Tell a forged message from a malformed one](https://webcpporg.github.io/libs/crypto/#crypto-errors): `error` (webcpp::crypto); backend any; Jamfile /webcpp/crypto//crypto. Example: example/failure_reasons.cpp. @@ -405,7 +401,7 @@ Generated by doc/tables/generate.py with the page's tables. Page: https://webcpp - example/bearssl_prng.cpp: Seeds BearSSL's own HMAC-DRBG from webcpp::crypto::random_device and draws bytes from it. A generator is only as good as its seed: the seed must come from the system's entropy, never from the clock or a counter. - example/bitcoin_sighash.cpp: Signs a Bitcoin legacy or segwit v0 input's sighash: SHA-256d of the transaction's serialization, computed by the program with webcpp::hash, signed as a digest with ECDSA over SHA-256, verified, and written as strict DER for the witness. Crypto computes no sighash: the serialization and its hash are the protocol's, a domain library's work; the sighash is the SHA-256 of a SHA-256, so the second hash is the scheme's own and the digest is honest under crypto::ecdsa_sha256. A taproot sighash, BIP341's tagged hash, is the message of crypto::schnorr instead (musig_taproot.cpp, taproot_tweak.cpp). - example/box_messages.cpp: Two people who know each other's X25519 public keys exchange messages in libsodium's box: each makes a box from the own key pair and the other's public key, agreeing one key for the pair, then seals each message with a nonce drawn at random. What one seals the other opens; a stranger's box, from another key pair, does not. Prints what each reads. -- example/constant_time_equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::constant_time_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/constant_time_equal_hmac.cpp: Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::secure::constant_time_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/ecdh_session.cpp: Two peers agree on a shared secret with ECDH, derive a session key from it with HKDF-SHA-256 and talk over AES-256-GCM. The raw ECDH output is not a key: HKDF turns it into one and ties it to this application with a context string. - example/ecdh_x_coordinate.cpp: Two key pairs agree on the shared point's raw x coordinate with agree, the form Nostr's encrypted messages (NIP-44) take, then derive from it what a NIP-44 library would: the conversation key, HKDF-extract with the salt "nip44-v2". The x coordinate is not a key; the derivation that makes one is the protocol's, and belongs to a domain library. - 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. diff --git a/doc/memory.adoc b/doc/memory.adoc index 7901d0b3..98a85e36 100644 --- a/doc/memory.adoc +++ b/doc/memory.adoc @@ -196,7 +196,14 @@ into OpenSSL's null. It never returns null: the standard libraries of LLVM and GCC declare `allocate` never to return null, so the optimiser removes any check of its result, and a null is written through in a release build. Without exceptions, a resource that cannot allocate ends the process, as the resources -of `std::pmr` do, and the failures above are not reached. +of `std::pmr` do, and the failures above are not reached. With exceptions, a +`deallocate` that throws is swallowed, since OpenSSL's `free` returns nothing, +and OpenSSL goes on after either catch, inside the guarded call that reached +it. Windows on ARM64 clears DIT when it resumes a thread after a catch +(webcpp::secure's guide, "Exceptions" of its guard), so each adapter function +holds a guard engaged only when DIT is set, which sets it again after its catch: +OpenSSL continues with DIT as the call's guard wants, and DIT clear stays clear. +The test `timing_adapter` checks it. * *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 diff --git a/doc/overview.adoc b/doc/overview.adoc index d66eb697..98bf8189 100644 --- a/doc/overview.adoc +++ b/doc/overview.adoc @@ -33,9 +33,10 @@ the scheme named at every call and a digest given only as has the member and its free form, and, where WebCrypto has the algorithm, their asynchronous forms, with one implementation (<>). -* *`constant_time_equal`* for tags and MACs, Boost.Hash2's included, and -*`erase_secret`*, which zeroes a buffer of the program's with stores the -optimiser keeps. +* *`secure::constant_time_equal`* for tags and MACs, Boost.Hash2's included, and +*`secure::erase_secret`*, which zeroes a buffer of the program's with stores the +optimiser keeps: webcpp::secure's, which crypto depends on, as is the +self-wiping `secure::secret` every secret crypto returns is. * *The AES block cipher,* a building block for the rare case that needs one. The algorithms are not webcpp's. Each runs on a backend, a C library that @@ -70,8 +71,9 @@ Nostr rule) belongs to a domain library, which <> shows how to build. Its names are grouped by kind, one chapter each, and the headers mirror the namespaces as `/.hpp>`: -* `webcpp::crypto`: `random_device`, `constant_time_equal`, `erase_secret`, -`secret`, `error` and the configuration (<>); the +* `webcpp::crypto`: `random_device`, `error` and the configuration +(<>, which also shows webcpp::secure's +`secure::constant_time_equal`, `secure::erase_secret` and `secure::secret`); the signatures' schemes, `prehashed` and `verify` (``), the key pair concepts, `sign` and `agree` (``), the factories `from_secret`, `from_bytes`, `from_key` and `generate` @@ -109,7 +111,7 @@ Hashing and HMAC are Boost.Hash2's: SHA-1, SHA-2, SHA-3, RIPEMD, BLAKE2 and `boost::hash2::hmac`. crypto offers no second interface for them, and its examples use Hash2 wherever a hash is needed: a key derived with HKDF (link:https://www.rfc-editor.org/rfc/rfc5869[RFC 5869]) is written on Hash2's -`hmac` in a few lines (<>). What crypto adds for Hash2's -users is `constant_time_equal`: the `operator==` of Hash2's digests is `memcmp`, -which is not constant time, so a MAC is never checked with it -(<>). +`hmac` in a few lines (<>). What Hash2's users need beside +it is webcpp::secure's `secure::constant_time_equal`, which crypto depends on: +the `operator==` of Hash2's digests is `memcmp`, which is not constant time, so +a MAC is never checked with it (<>). diff --git a/doc/p256.adoc b/doc/p256.adoc index 8a4636f7..1c5461fe 100644 --- a/doc/p256.adoc +++ b/doc/p256.adoc @@ -65,7 +65,7 @@ and refuses a scalar of another size with `invalid_key_size` and a scalar 0, n or above with `invalid_secret_key`: that check runs in webcpp, in time independent of the scalar, before BearSSL sees it. `keypair::generate()` draws the scalar from `random_device`. `secret()` gives the scalar back as a -`secret<32>`, which wipes itself, and `from_secret` of it gives the same key pair: the +`secure::secret<32>`, which wipes itself, and `from_secret` of it gives the same key pair: the way a program stores a key pair and loads it again. The key pair computes its public point once, when it is made, wipes the scalar when it is moved from and destroyed, and answers `invalid_state` moved from. It is a @@ -148,14 +148,14 @@ include::{examples}/p256_keys.expected[] *Pitfalls.* -* A scalar stored outside a `secret<32>` outlives the key pair: the key pair -and the `secret<32>` that `secret()` returns wipe their bytes, but a copy in a string, a log or +* A scalar stored outside a `secure::secret<32>` outlives the key pair: the key pair +and the `secure::secret<32>` that `secret()` returns wipe their bytes, but a copy in a string, a log or a file stays where it was written. What webcpp wipes is what it owns: BearSSL's own signing keeps the scalar, the nonce and the state that derives the nonce in its stack frame and returns without zeroing them (link:https://www.bearssl.org/gitweb/?p=BearSSL;a=blob;f=src/ec/ecdsa_i31_sign_raw.c;hb=7bea48e5e850ab4cafbe68d3765cdaba13a86d6f#l45[BearSSL's ecdsa_i31_sign_raw.c, lines 45 to 51 and 115 to 135]), where a later call -overwrites them; nothing in webcpp can reach that frame. Keep the scalar in the `secret<32>` until it +overwrites them; nothing in webcpp can reach that frame. Keep the scalar in the `secure::secret<32>` until it is encrypted or written to the key store, and never print it. * A peer's key is made into a `public_key` once, where it arrives, and kept: made again for every message, it costs a point check each time, and code that @@ -293,7 +293,7 @@ Diffie-Hellman, ECDH (link:https://www.secg.org/sec1-v2.pdf[SEC 1, section 3.3.1]). Each side multiplies the other's public point by its own scalar, and both arrive at the same point, d~A~ times d~B~ times the generator. `keypair::agree(peer)` returns that point's x coordinate, 32 bytes big-endian, -as a `secret<32>`, which wipes itself: +as a `secure::secret<32>`, which wipes itself: [source,cpp] ---- @@ -317,7 +317,7 @@ its scale manager generates an ECDH P-256 key pair (link:https://github.com/dmotz/trystero/blob/8d3f57ef42c3d622840eec479784c99deeeb2d05/packages/core/src/scale/manager.ts#L306[packages/core/src/scale/manager.ts, line 306]). The peer's key is a `public_key`, validated when it was made, so `agree` never sees a point off the curve; it refuses a moved-from key pair -with `invalid_state`. The `secret<32>` and webcpp's own copy of the point are +with `invalid_state`. The `secure::secret<32>` and webcpp's own copy of the point are wiped, but BearSSL's multiplication leaves the values it computes from the scalar in its stack frame, as its signing does (<>, its pitfalls; @@ -441,7 +441,7 @@ program that writes or reads PEM links `/webcpp/crypto//pem-default` beside include::generated/backends-p256_formats.adoc[] *Example.* RFC 6979's key: its public key written as PEM SPKI, printed and read -back; its key pair written as PEM PKCS#8, kept in a `secret` and never +back; its key pair written as PEM PKCS#8, kept in a `secure::secret` and never printed, and read back: [source,cpp] @@ -481,5 +481,5 @@ that is not its scalar's, and a program that shows or checks that key, rather than the one the scalar gives, trusts the wrong key. `decode_pkcs8` refuses such a file. * The PKCS#8, as DER or as PEM, is the secret key in clear: base64 is an -encoding, not encryption. Keep it in a `secret`, as the example does, and +encoding, not encryption. Keep it in a `secure::secret`, as the example does, and seal it before it is written anywhere (<>). diff --git a/doc/p2p.adoc b/doc/p2p.adoc index 59d621e9..df34a9de 100644 --- a/doc/p2p.adoc +++ b/doc/p2p.adoc @@ -152,7 +152,7 @@ keys, while fresh pairs wiped after the session give *forward secrecy* (link:https://en.wikipedia.org/wiki/Forward_secrecy[Wikipedia]); a long-lived key signs the fresh public keys instead. `agree_hashed` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point, as a -`secret<32>` that wipes itself: both sides must use the same form, and a +`secure::secret<32>` that wipes itself: both sides must use the same form, and a protocol that takes the raw x coordinate, such as Nostr's NIP-44, needs `agree` (<>). @@ -169,7 +169,7 @@ ECDH, and both find the same shared point. Nostr's encrypted payloads take its x coordinate unhashed, and derive from it a conversation key, HKDF-extract with the salt `nip44-v2`, then a key for each message (link:https://github.com/nostr-protocol/nips/blob/master/44.md[NIP-44]). -`agree` gives the x coordinate as a `secret<32>` +`agree` gives the x coordinate as a `secure::secret<32>` (<>); the conversation key and everything after it, the message keys, the padding and the payload's format, are NIP-44's, which a domain library built on crypto and hash, such as a future webcpp::nostr, diff --git a/doc/performance.adoc b/doc/performance.adoc index 29d08f37..08c7e356 100644 --- a/doc/performance.adoc +++ b/doc/performance.adoc @@ -503,25 +503,22 @@ libsodium's x86-64 assembly (design D7): Ed25519 signature, libsodium with HAVE_ [#crypto-performance-timing] ==== The timing guard's cost -Every public operation runs inside `detail::timing_guard`, which on 64-bit ARM under -macOS, iOS, Linux and Android, where the CPU has FEAT_DIT, sets DIT (data-independent -timing) for the call and restores the thread's state after it -(<>): one `mrs`, and where DIT was clear, two `msr` -each followed by an `isb`. Elsewhere (x86, WebAssembly, Windows on ARM64) it executes -no instruction. - -Measured natively on 2026-11-21 on Apple M5 Max +Every public operation runs inside `webcpp::secure::timing_guard`, webcpp::secure's +guard, which on 64-bit ARM under macOS, iOS, Linux, Android and Windows, where the +CPU has FEAT_DIT, sets DIT (data-independent timing) for the call and restores the +thread's state after it (<>): one `mrs`; where DIT was clear, two +`msr` each followed by an `isb`; where it was set, a second `mrs` on the way out +(and an `msr` if something inside cleared it). Elsewhere (x86, WebAssembly, ARM64EC) it +executes no instruction. + +Measured natively on 2026-11-26 on Apple M5 Max (arm64), Darwin 27.0.0, built with variant=release by Apple LLVM 21.0.0 (clang-2100.4.1.1) (bench/timing.cpp): each row is the median of 5 runs of 10,000,000 guards around a store, with the fastest and slowest run beside it, each minus the median of the same loop without the guard, in nanoseconds per call. The guard sets DIT on this machine. -The machine's 1, 5 and 15 minute load averages were 83/55/129 before and -87/56/129 after, on 18 cores. - -NOTE: these figures are provisional. They were measured on a shared machine under load (the load averages above), and are measured again in a final measurement pass on a quiet machine, once the work in progress has merged; read them as an upper bound. - -WARNING: the machine was shared and loaded while this was measured (rule: the larger of the two 1-minute load averages exceeds half the core count). +The machine's 1, 5 and 15 minute load averages were 2/3/3 before and +2/3/3 after, on 18 cores. [cols="2,4,1,1,1",options="header"] |=== @@ -529,15 +526,15 @@ WARNING: the machine was shared and loaded while this was measured (rule: the la | clear, as a program that sets nothing has it | reads DIT, sets it, and clears it on the way out -| 77.6 -| 64.4 -| 88.1 +| 37.0 +| 37.0 +| 38.5 | already set, by the program or by an outer guard -| reads DIT and leaves it set -| 1.8 -| 0.8 -| 3.2 +| reads DIT, and reads it again on the way out +| 1.2 +| 1.2 +| 1.2 |=== For scale, the shortest operation of the table above natively, diff --git a/doc/performance.json b/doc/performance.json index e5295cd3..db154360 100644 --- a/doc/performance.json +++ b/doc/performance.json @@ -1517,8 +1517,8 @@ }, "provisional": true, "timing_guard": { - "measurement": "the nanoseconds detail::timing_guard adds to a call, bench/timing.cpp", - "date": "2026-11-21", + "measurement": "the nanoseconds webcpp::secure::timing_guard adds to a call, bench/timing.cpp", + "date": "2026-11-26", "machine": { "cpu": "Apple M5 Max", "architecture": "arm64", @@ -1530,14 +1530,14 @@ }, "load_average_before_after": [ [ - 83.2802734375, - 54.90771484375, - 128.51513671875 + 1.9169921875, + 2.66796875, + 3.16845703125 ], [ - 87.021484375, - 56.154296875, - 128.5234375 + 1.9169921875, + 2.66796875, + 3.16845703125 ] ], "build": "variant=release", @@ -1546,12 +1546,11 @@ "iterations": 10000000, "runs": 5, "dit": true, - "clear_ns": 77.594, - "clear_fastest_ns": 64.399, - "clear_slowest_ns": 88.056, - "set_ns": 1.798, - "set_fastest_ns": 0.771, - "set_slowest_ns": 3.25, - "provisional": true + "clear_ns": 37.031, + "clear_fastest_ns": 36.984, + "clear_slowest_ns": 38.492, + "set_ns": 1.193, + "set_fastest_ns": 1.192, + "set_slowest_ns": 1.212 } } diff --git a/doc/protecting_secrets.adoc b/doc/protecting_secrets.adoc index 8497c415..e114712c 100644 --- a/doc/protecting_secrets.adoc +++ b/doc/protecting_secrets.adoc @@ -11,39 +11,40 @@ A cipher or a curve keeps its own secrets: it compares its tags in constant time, wipes its keys when it is destroyed and draws what it needs from the system's generator. A program also handles secrets of its own around them: it checks a MAC a request carries, holds a key or a password in a buffer, and -draws a token. Four utilities serve that, each named by what it does. They are -at the top of `webcpp::crypto`, beside the rest of the root, with no namespace -of their own, and need no backend: `random_device` reads the system's -generator, and the other three are code of crypto's. +draws a token. Four utilities serve that, each named by what it does, and none +needs a backend: `random_device`, at the top of `webcpp::crypto`, reads the +system's generator; the other three are webcpp::secure's, which crypto depends +on and whose `secure::secret` every secret crypto returns is +(`` holds all three). .What each utility guards against [cols="2,2,5,3",options="header"] |=== | Utility | Hygiene | What it guards against | Header -| `constant_time_equal` +| `secure::constant_time_equal` | timing | a comparison whose time tells how many bytes of a forged MAC or token are right (link:https://cwe.mitre.org/data/definitions/208.html[CWE-208]; <>) -| `` +| `` -| `erase_secret` +| `secure::erase_secret` | memory | a secret left in a buffer the program owns, a string, a vector or an array, after its use, where a `memset` the optimiser removed did not erase it (link:https://cwe.mitre.org/data/definitions/14.html[CWE-14]; <>) -| `` +| `` -| `secret` +| `secure::secret` | memory | a secret crypto returns outliving its use: it wipes itself when it is destroyed or moved from (link:https://cwe.mitre.org/data/definitions/14.html[CWE-14]; <>) -| `` +| `` | `random_device` | drawing @@ -58,30 +59,30 @@ include::constant_time_equal.adoc[] include::erase_secret.adoc[] [#crypto-secret] -==== Secrets that wipe themselves: `secret` +==== Secrets that wipe themselves: `secure::secret` -Every secret crypto gives back is a `secret`, `N` its size in bytes: a key +Every secret crypto gives back is a `secure::secret`, `N` its size in bytes: a key pair's `secret()`, the shared secret of `agree`, the session keys of `crypto_kx`, a tweaked secret key, the secret key read from a PKCS#8 file. It holds its bytes in an array of its own and wipes them, with the volatile stores -and the fence of `erase_secret`, when it is destroyed and when it is moved +and the fence of `secure::erase_secret`, when it is destroyed and when it is moved from, so that the secret lives in one object and leaves memory with it. It is not copyable: a copy is asked for by name, `clone()`, and the caller owns it. `bytes()` gives a `std::span` to read, which a cipher's `from_key`, a key pair's `from_secret` or an HKDF takes as its input -without a copy (`from_key(session_keys.transmit.bytes())`), and a `secret` +without a copy (`from_key(session_keys.transmit.bytes())`), and a `secure::secret` converts to that span where a function takes it. Neither is offered on a -temporary `secret`, whose bytes would be wiped before the span is read: the +temporary `secure::secret`, whose bytes would be wiped before the span is read: the program keeps the secret in a variable first. *What it is not.* * It wipes its own storage, and only that. A copy of `bytes()` into a string, - a vector or a log is the program's, to erase with `erase_secret`, and a move + a vector or a log is the program's, to erase with `secure::erase_secret`, and a move or a `clone` may leave copies in registers or temporaries that no library reaches. -* It does not lock the memory, as `erase_secret` does not: the page may be +* It does not lock the memory, as `secure::erase_secret` does not: the page may be swapped to disk while the secret is in it. include::entropy.adoc[] diff --git a/doc/root.adoc b/doc/root.adoc index dab5ae58..4a4e2bf0 100644 --- a/doc/root.adoc +++ b/doc/root.adoc @@ -8,10 +8,11 @@ == The root utilities: `webcpp::crypto` The namespace `webcpp::crypto` holds what every other chapter relies on: where -secrets come from (`random_device`), how a secret is checked -(`constant_time_equal`), erased from a buffer of the program's -(`erase_secret`) and held so that it wipes itself (`secret`), the four -utilities of <>, and how a failure is told apart +secrets come from (`random_device`), one of the four utilities of +<>, whose other three, how a secret is checked +(`secure::constant_time_equal`), erased from a buffer of the program's +(`secure::erase_secret`) and held so that it wipes itself (`secure::secret`), +are webcpp::secure's, which crypto depends on; and how a failure is told apart (`error`), none of which needs a backend; and how a key's standard form becomes text and back (`pem`, on libsodium; <>). It also declares, for a native program on OpenSSL that turns the memory option on, the diff --git a/doc/secp256k1.adoc b/doc/secp256k1.adoc index 304183de..0ebcb12c 100644 --- a/doc/secp256k1.adoc +++ b/doc/secp256k1.adoc @@ -200,7 +200,7 @@ way. (0x04, x, y; link:https://www.secg.org/sec1-v2.pdf[SEC 1, sections 2.3.3 and 2.3.4]): both coordinates, of which the other two forms keep x alone. -Each is returned as a `secret`, which wipes its bytes when it is destroyed +Each is returned as a `secure::secret`, which wipes its bytes when it is destroyed or moved from: a program reads it with `bytes()` and makes no copy of its own to forget. Each takes the peer's `public_key`, a point the type guarantees (<>), and refuses a moved-from key pair with @@ -470,7 +470,7 @@ key pair without the server ever holding a secret. keys, each function a call of libsecp256k1: * `secret_key_tweak_add` and `secret_key_tweak_mul`: a secret key plus or times -a 32-byte tweak, modulo the group order, returned as a `secret<32>`; +a 32-byte tweak, modulo the group order, returned as a `secure::secret<32>`; `public_key_tweak_add` and `public_key_tweak_mul`: P + tG and tP, the public keys of those two secrets; * `secret_key_negate` and `public_key_negate`: the negation of either, n - d and @@ -514,7 +514,7 @@ links every derived key to the wallet: anyone who sees the public key computes the same tweaks and recognises each payment. Mix in a value only the two sides hold, as BIP 32's chain code is (link:https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki[BIP 32]). -* A tweaked secret is a secret, which is why it is returned as a `secret<32>`: +* A tweaked secret is a secret, which is why it is returned as a `secure::secret<32>`: whoever knows the tweak and the tweaked secret key computes the original. With BIP 32's public derivation, one leaked child secret key and the parent's extended public key give away the parent's secret key, and with it every key @@ -615,7 +615,7 @@ it. * The PKCS#8 these functions write holds the secret key in clear, and so does its PEM text: base64 is an encoding, not encryption. Keep both where only the program reads them, out of source control, or seal them at rest -(<>), and wipe the buffers when done, as `secret` does. +(<>), and wipe the buffers when done, as `secure::secret` does. [#crypto-secp256k1-ellswift] ==== ElligatorSwift: keys that look like noise @@ -645,7 +645,7 @@ apart; `ellswift_encode` encodes any `public_key`; * `ellswift_decode` returns the `public_key` of any 64 bytes: it never fails; * `ellswift_xdh` is the key exchange: the x coordinate of the shared point, hashed with both encodings as BIP 324 hashes it, a tagged SHA-256, into a -`secret<32>`. It takes the initiator's encoding, then the responder's, and +`secure::secret<32>`. It takes the initiator's encoding, then the responder's, and which of the two the key pair is (`ellswift_party`). A moved-from key pair is refused with `invalid_state`. The tests check BIP @@ -846,7 +846,7 @@ the smallest outpoint's 36 bytes; * `make_previous_outputs_summary` sums the eligible inputs' public keys for the recipient, into a `previous_outputs_summary`, and `scan_outputs` scans a transaction's x-only outputs with the scan key pair and the spend key: each -`found_output` holds the output's key, its `spend_tweak` (a `secret<32>`, which +`found_output` holds the output's key, its `spend_tweak` (a `secure::secret<32>`, which `secret_key_tweak_add` adds to the spend secret key to spend the output, <>) and the label it was sent to; * `create_label` makes the scan key's `m`-th label, 0 being BIP 352's change diff --git a/doc/secret_key_encryption.adoc b/doc/secret_key_encryption.adoc index 2fd6d74e..eb066676 100644 --- a/doc/secret_key_encryption.adoc +++ b/doc/secret_key_encryption.adoc @@ -28,8 +28,8 @@ forms are the box forms. | Namespace | Holds | `webcpp::crypto` -| the root: `random_device`, `constant_time_equal`, `erase_secret`, -`secret`, `error`, the signing vocabulary, the key pair concepts and the +| the root: `random_device`, `secure::constant_time_equal`, `secure::erase_secret`, +`secure::secret`, `error`, the signing vocabulary, the key pair concepts and the free factories (<>) | `crypto::ciphers` diff --git a/doc/tables/crypto.json b/doc/tables/crypto.json index 411a4b6e..27c12293 100644 --- a/doc/tables/crypto.json +++ b/doc/tables/crypto.json @@ -1,7 +1,7 @@ { "comment": "The data of crypto's generated tables and of llms.txt; doc/tables/generate.py reads it with the test Jamfiles, the message tests and the superproject's Jamfile fixtures, and writes doc/generated/, doc/llms.txt, include/webcpp/crypto/detail/capabilities.hpp, include/webcpp/crypto/detail/defaults.hpp and test/capabilities_test.cpp. The capability table is `families`: per family its algorithms, the targets on which each backend has it (each claimed only where a test of the family's operations on that backend runs), constant time per target where it differs from the backend's own `constant_time` (X25519 on wasip2, an open finding, and natively without arm64's DIT, the cause of both), with `constant_time_checker` naming the checker that measured it where that is not every checker of the target, and the default per target, one whatever the program links (design D32), with its reason and the tests that fix it (a row of some of `compilers` restates its target's default for them, with a reason of their own, and each compiler of a target has one row), from which come include/webcpp/crypto/detail/defaults.hpp and the refusal that says what a program whose default is not linked needs; a backend with `targets`, where it is built, is a tag of `backends`. A name in a text is written between backticks, as Markdown writes code: the tables show it as code and llms.txt keeps the backticks. A comparison table's cell {speed:} or {constant_time:} is written from doc/performance.json or from the family's `constant_time`, and each cell of a column a namespace lists in `cited` cites a source or begins with \"none\". Edit this file, then run python3 libs/crypto/doc/tables/generate.py; the doc build runs it with --check.", "page": "https://webcpporg.github.io/libs/crypto/", - "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, a constant_time_equal and an erase_secret whose stores the optimiser keeps, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", + "llms": "Cryptographic primitives for C++20 on native, wasip2, wasip3 and Emscripten: AES-GCM, the AES block cipher, secp256k1 (BIP 340 Schnorr, ECDSA and recoverable signatures, ECDH, tweaks, ElligatorSwift, MuSig2, silent payments), Ed25519 and Ed25519ph (RFC 8032), X25519 (RFC 7748), their keys in SPKI, PKCS#8 (RFC 8410) and PEM, P-256 key pairs, ECDSA and ECDH on BearSSL, libsodium's crypto_kx, the ChaCha20-Poly1305 AEADs, libsodium's secret boxes, boxes and sealed boxes, a random_device on the system's generator, each over a widely used, reviewed C library (BearSSL, OpenSSL, ctaes, libsecp256k1, libsodium) that the program names in its Jamfile. Hashing and HMAC are Boost.Hash2's; HKDF and password hashing are webcpp::hash's; the constant-time comparison, the erasure of a buffer and secret are webcpp::secure's. Every failure is a boost::system::result value. Protocols (Bitcoin, Ethereum, Nostr) belong to domain libraries built on these primitives.", "targets": ["native", "wasip2", "wasip3", "emscripten"], "compilers": {"clang": "Clang", "gcc": "GCC", "msvc": "MSVC"}, "checkers": {"memcheck": "Valgrind's memcheck (Linux)", "msan": "MemorySanitizer (Linux, clang)", "dudect": "dudect (judged; on a runner GitHub hosts, by two of three runs)"}, @@ -224,16 +224,16 @@ "none": { "title": "no backend", "jamfile": "/webcpp/crypto//crypto", - "header": ", , ", + "header": "", "library": "webcpp's own header-only code", "licence": "BSL-1.0", "own_api": "none", "allocation": "none", - "constant_time": "`constant_time_equal` is constant time in the contents: every byte is read, no branch and no index depends on one", + "constant_time": "webcpp::secure's `secure::constant_time_equal`, which crypto's code calls, is constant time in the contents: every byte is read, no branch and no index depends on one", "constant_time_sources": [], "lane_paths": [ - {"what": "`constant_time_equal`", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}}, - {"what": "`is_all_zero` and the wipe of `secret`", "lane": {"native": ["memcheck", "msan"]}} + {"what": "`secure::constant_time_equal`", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}}, + {"what": "`is_all_zero` and the wipe of `secure::secret`", "lane": {"native": ["memcheck", "msan"]}} ] } }, @@ -304,26 +304,6 @@ "bearssl": {"tests": ["async_p256"]} } }, - { - "id": "constant_time_equal", - "functions": ["constant_time_equal"], - "namespace": "root", - "api": "constant_time_equal", - "header": "", - "what": "Compares two tags or MACs in constant time.", - "section": "crypto-constant-time-equal", - "backends": {"none": {"tests": ["constant_time_equal"]}} - }, - { - "id": "erase_secret", - "functions": ["erase_secret"], - "namespace": "root", - "api": "erase_secret", - "header": "", - "what": "Zeroes a buffer the program owns, a password, a key or a plaintext, with stores the optimiser keeps.", - "section": "crypto-erase-secret", - "backends": {"none": {"tests": ["erase_secret"]}} - }, { "id": "error", "functions": ["error_category", "make_error_code", "message_of"], @@ -502,7 +482,7 @@ "namespace": "curves", "api": "curves::x25519::keypair", "header": "", - "what": "An X25519 key pair (RFC 7748): made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::x25519::public_key`, computed once; and `agree(peer)`, the 32-byte shared secret with a peer's public key, a `secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order).", + "what": "An X25519 key pair (RFC 7748): made from its 32-byte secret key, which `secret()` gives back, or drawn from `random_device`; its public key, a `curves::x25519::public_key`, computed once; and `agree(peer)`, the 32-byte shared secret with a peer's public key, a `secure::secret<32>`, refused with `weak_public_key` when it is all zero (a peer key of low order).", "section": "crypto-x25519", "backends": {"sodium": {"tests": ["x25519_sodium", "x25519_wycheproof_sodium", "oracle_25519"]}} }, @@ -537,7 +517,7 @@ "namespace": "curves", "api": "curves::x25519::encode_spki, decode_spki, encode_pkcs8, decode_pkcs8", "header": "", - "what": "RFC 8410's SPKI of an X25519 public key (44 bytes) and PKCS#8 of a secret key (version 1, 48 bytes), the forms OpenSSL and WebCrypto write, decoded strictly into a `secret<32>`: any other bytes are `invalid_encoding`.", + "what": "RFC 8410's SPKI of an X25519 public key (44 bytes) and PKCS#8 of a secret key (version 1, 48 bytes), the forms OpenSSL and WebCrypto write, decoded strictly into a `secure::secret<32>`: any other bytes are `invalid_encoding`.", "section": "crypto-key-formats", "backends": {"sodium": {"tests": ["formats_25519_sodium", "formats_25519_openssl_oracle", "formats_25519_webcrypto_oracle", "allocation_sodium"]}} }, @@ -560,7 +540,7 @@ "namespace": "key_exchange", "api": "key_exchange::kx_keypair", "header": "", - "what": "libsodium's `crypto_kx` on X25519's typed keys: a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed as libsodium does (BLAKE2b-256 of the seed) or drawn from `random_device`, and the two session keys of a client or a server, each a `secret<32>`, from the peer's X25519 public key; a peer key of low order is refused with `weak_public_key`.", + "what": "libsodium's `crypto_kx` on X25519's typed keys: a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed as libsodium does (BLAKE2b-256 of the seed) or drawn from `random_device`, and the two session keys of a client or a server, each a `secure::secret<32>`, from the peer's X25519 public key; a peer key of low order is refused with `weak_public_key`.", "section": "crypto-kx", "backends": {"sodium": {"tests": ["kx_sodium", "kx_wipe_sodium", "allocation_sodium"]}} }, @@ -767,7 +747,7 @@ "namespace": "curves", "api": "curves::p256::keypair", "header": "", - "what": "A P-256 key pair: made from its 32-byte scalar, refused unless 0 < d < n, or drawn from `random_device`; its validated public key and its scalar, `secret()`, a `secret<32>`.", + "what": "A P-256 key pair: made from its 32-byte scalar, refused unless 0 < d < n, or drawn from `random_device`; its validated public key and its scalar, `secret()`, a `secure::secret<32>`.", "section": "crypto-p256-keys", "backends": { "bearssl": {"tests": ["p256_keys_bearssl", "p256_openssl_oracle", "p256_webcrypto_oracle", "allocation_bearssl"]}, @@ -813,7 +793,7 @@ "namespace": "curves", "api": "curves::p256::keypair::agree", "header": "", - "what": "ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys.", + "what": "ECDH with a validated public key: the shared point's raw x coordinate, 32 bytes in a `secure::secret<32>`, as WebCrypto's `deriveBits` gives it; a protocol hashes it into its keys.", "section": "crypto-p256-ecdh", "backends": { "bearssl": {"tests": ["p256_ecdh_bearssl", "p256_openssl_oracle", "p256_webcrypto_oracle", "allocation_bearssl"]}, @@ -934,7 +914,7 @@ {"targets": ["native", "wasip2", "wasip3", "emscripten"], "backend": "sodium", "tests": ["x25519_sodium", "default_backend_none_linked"], "why": "the only backend in this version, on every target; it refuses an all-zero shared secret itself ({rfc7748})"} ], "backends": { - "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "constant_time_checker": {"native": "dudect"}, "constant_time": {"native": "nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux and Android where the CPU has it, as Apple requires of constant-time code ({apple-dit}); the lane's dudect sets nothing itself and measures what a program gets: |t| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads |t| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at |t| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86, WebAssembly or Windows on ARM64", "wasip2": "an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at |t| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set ({apple-dit}): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads |t| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next"}} + "sodium": {"targets": "all", "lane": {"native": ["memcheck", "msan", "dudect"], "wasip2": ["dudect"]}, "constant_time_checker": {"native": "dudect"}, "constant_time": {"native": "nothing found with arm64's DIT (data-independent timing) bit set, which webcpp sets around every call on 64-bit ARM under macOS, iOS, Linux, Android and Windows where the CPU has it, as Apple requires of constant-time code ({apple-dit}); the lane's dudect sets nothing itself and measures what a program gets: |t| 1.8 to 2.8 against the threshold 10 (2026-11-21, five runs), while its `dudect_planted`, an early-exit scan of the secret key run inside the same guard, reads |t| 66.72 and 65.53 (2026-11-21): DIT does not hide a leak. Without DIT, dudect times `agree` with an all-zero secret key against random ones at |t| 6.7 to 14.5 (2026-11-19) and 4.3 to 7.8 (2026-11-21, three runs): about one nanosecond in 15 µs. Each on an Apple M5 Max, from a release build. libsodium does not set DIT, and webcpp sets nothing on x86 or WebAssembly", "wasip2": "an open finding, its cause measured: dudect times `agree` with an all-zero secret key against random ones at |t| 13 to 32 (2026-11-18; a fixed key against another fixed key: 22.9) and 107 to 260 (2026-11-19), and 25.25 in the lane on 2026-11-21, against the threshold 10, under wasmtime 47 on an Apple M5 Max, from a release build. The cause is Apple silicon's DIT (data-independent timing), which wasmtime does not set ({apple-dit}): with DIT set in wasmtime's main thread, an experiment and not the lane, the same case reads |t| 1.5 to 2.1; no branch on a secret was found in the WebAssembly or in wasmtime's compiled code. The lane cannot set DIT from inside the WebAssembly, so it prints this value on wasip2 without judging it; the CI's x86-64 run measures it next"}} } }, { @@ -1190,7 +1170,7 @@ {"title": "ECDH's form", "section": "crypto-secp256k1-ecdh", "text": "`keypair::agree` returns the raw x coordinate of the shared point, which protocols such as Nostr's NIP-44 ({nip44}) take; `keypair::agree_hashed` returns libsecp256k1's hashed form, the SHA-256 of the compressed shared point. Both sides must use the same form, or they derive different keys. Derive keys with a KDF, never use a shared secret directly."}, {"title": "The x-only tweak is not BIP 32", "section": "crypto-wallets-taproot", "text": "`tweak_xonly` is BIP 341's even-y arithmetic ({bip341}); BIP 32's child derivation tweaks the full key, with `secret_key_tweak_add` and `public_key_tweak_add`, and computes the tweak with HMAC-SHA-512, a domain library's ({bip32})."}, {"title": "Ethereum", "section": "crypto-curves", "text": "this version signs Ethereum's recoverable ECDSA over Keccak-256 (`keypair::sign(crypto::ecdsa_keccak256_recoverable, input)`, a message hashed inside or the 32-byte digest a program builds), recovers a signer's public key from a signature and the same input (`recover`), and writes the uncompressed key ({ethereum}); the recovery id's `v` encoding, the digests Ethereum signs (EIP-191, EIP-712, a transaction's), transactions and addresses are a domain library's, which the guide shows over webcpp::hash."}, - {"title": "Compare secrets in constant time", "section": "crypto-constant-time-equal", "text": "compare a tag, a MAC or a token with `constant_time_equal`, never `==` or `memcmp` ({cwe208})."}, + {"title": "Compare secrets in constant time", "section": "crypto-constant-time-equal", "text": "compare a tag, a MAC or a token with `secure::constant_time_equal`, never `==` or `memcmp` ({cwe208})."}, {"title": "Secrets come from random_device", "section": "crypto-entropy", "text": "keys, nonces and tokens are drawn from `random_device`, never `std::mt19937` or `rand` ({cwe338})."}, {"title": "Never reuse a nonce under one ChaCha20-Poly1305 key", "section": "crypto-chacha", "text": "two messages under one key and one nonce reveal the XOR of their plaintexts and let an attacker forge tags ({rfc8439-nonce}). `xchacha20_poly1305` and the secret boxes: draw 24 bytes at random per message. `chacha20_poly1305`: number the 12-byte nonces with a counter that never repeats, a restart included, or draw them at random for at most 2^32 messages per key, AES-GCM's bound for random 12-byte nonces ({sp800-38d}). `chacha20_poly1305_original`: a counter only, its 8 bytes are too short to draw."}, {"title": "A shared secret is not a key", "section": "crypto-x25519", "text": "derive keys from X25519's shared secret and both public keys with a KDF such as webcpp::hash's HKDF, never use its bytes as a cipher's key ({rfc7748-kdf}); `kx_keypair` and the boxes do this themselves."}, @@ -1215,9 +1195,9 @@ "columns": ["Name", "What it is for", "Header", "Errors", "Standards and sources", "Choose it when"], "rows": [ ["`random_device`", "Keys, nonces, tokens: 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}); <>"], - ["`constant_time_equal`", "Checking a tag, a MAC or a token", "``", "none: it returns `bool`", "{cwe208}", "you compare anything secret; never `==` or `memcmp` on a MAC; <>"], - ["`erase_secret`", "Erasing a password, a key or a plaintext from a buffer the program owns", "``", "none", "{cwe14}", "a secret sits in a `std::string`, a `std::vector` or an array of the program's and must not outlive its use; never `memset`, which the optimiser may drop; <>"], - ["`secret`", "Holding a secret crypto gives back: a key pair's `secret()`, a shared secret, a session key", "``", "none", "{cwe14}", "crypto returns a secret: it wipes itself when destroyed or moved from, is copied only by `clone()`, and gives its bytes with `bytes()`; keep it in one variable; <>"], + ["`secure::constant_time_equal`", "Checking a tag, a MAC or a token", "``", "none: it returns `bool`", "{cwe208}", "you compare anything secret; never `==` or `memcmp` on a MAC; <>"], + ["`secure::erase_secret`", "Erasing a password, a key or a plaintext from a buffer the program owns", "``", "none", "{cwe14}", "a secret sits in a `std::string`, a `std::vector` or an array of the program's and must not outlive its use; never `memset`, which the optimiser may drop; <>"], + ["`secure::secret`", "Holding a secret crypto gives back: a key pair's `secret()`, a shared secret, a session key", "``", "none", "{cwe14}", "crypto returns a secret: it wipes itself when destroyed or moved from, is copied only by `clone()`, and gives its bytes with `bytes()`; keep it in one variable; <>"], ["`error`", "Telling failures apart", "``", "its values are the errors", "none", "you branch on a failure: forged data, a wrong size, no entropy"], ["`pem`", "A key's SPKI or PKCS#8 as text, to paste, store or exchange with OpenSSL", "``", "`invalid_encoding`, `invalid_input_size`", "{rfc7468}, {libsodium-base64}", "a key goes to or comes from a file, a form or a tool as `-----BEGIN PUBLIC KEY-----` text; with the `encode_spki` and `encode_pkcs8` of `curves::ed25519`, `curves::x25519`, `curves::secp256k1` or `curves::p256`"], ["`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"], @@ -1283,7 +1263,7 @@ "columns": ["Construction", "What it does", "Keys", "Output", "Standards and sources", "Choose it when"], "cited": ["Standards and sources"], "rows": [ - ["`kx_keypair`: crypto_kx", "Session keys for a client and a server: X25519 agrees a secret, and BLAKE2b-512 of it and both public keys gives each side a key to receive with and one to transmit with", "a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed or drawn, and the peer's X25519 public key", "two 32-byte `secret<32>` per side, the client's `transmit` the server's `receive`", "{libsodium-kx}", "a client and a server that swapped public keys need a key for each direction, as libsodium's `crypto_kx` gives them; a peer key of low order is refused; a protocol with a KDF of its own uses X25519's `agree` instead"] + ["`kx_keypair`: crypto_kx", "Session keys for a client and a server: X25519 agrees a secret, and BLAKE2b-512 of it and both public keys gives each side a key to receive with and one to transmit with", "a key pair that holds an X25519 key pair, taken as is, derived from a 32-byte seed or drawn, and the peer's X25519 public key", "two 32-byte `secure::secret<32>` per side, the client's `transmit` the server's `receive`", "{libsodium-kx}", "a client and a server that swapped public keys need a key for each direction, as libsodium's `crypto_kx` gives them; a peer key of low order is refused; a protocol with a KDF of its own uses X25519's `agree` instead"] ] } }, @@ -1292,7 +1272,7 @@ {"need": "Sign and verify with Ed25519 in a coroutine", "namespace": "webcpp::crypto", "api": "`async_sign`, `async_verify`", "backend": "the default of Ed25519", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//ed25519-default /webcpp/asio//asio", "example": "async_sign", "section": "crypto-async", "operations": ["async_ed25519"]}, {"need": "Generate a session token, a password-reset link or an API key", "namespace": "webcpp::crypto", "api": "`random_device::fill`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, {"need": "Draw an unbiased number in a range, such as a six-digit code", "namespace": "webcpp::crypto", "api": "`random_device` with `std::uniform_int_distribution`", "backend": "the system's generator", "jamfile": "/webcpp/crypto//crypto", "example": "reset_token", "section": "crypto-entropy"}, - {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`constant_time_equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "constant_time_equal_hmac", "section": "crypto-constant-time-equal"}, + {"need": "Check a webhook's or an API's HMAC signature", "namespace": "webcpp::crypto", "api": "`secure::constant_time_equal`, with Boost.Hash2's `hmac`", "backend": "none", "jamfile": "/webcpp/crypto//crypto", "example": "constant_time_equal_hmac", "section": "crypto-constant-time-equal"}, {"need": "Encrypt a database field, a cookie or a token at rest", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`", "backend": "the default: OpenSSL natively, BearSSL on WebAssembly", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default", "example": "store_token", "section": "crypto-gcm"}, {"need": "Encrypt a large file or a stream", "namespace": "webcpp::crypto::ciphers", "api": "`aes256_gcm`: records, or `begin_seal`, `update` and `result`", "backend": "the default", "jamfile": "/webcpp/crypto//crypto /webcpp/crypto//gcm-default", "example": "sealed_records", "section": "crypto-gcm-incremental"}, {"need": "Tell a forged message from a malformed one", "namespace": "webcpp::crypto", "api": "`error`", "backend": "any", "jamfile": "/webcpp/crypto//crypto", "example": "failure_reasons", "section": "crypto-errors"}, @@ -1395,8 +1375,7 @@ "chacha_header_not_included_on_emscripten": "A program for Emscripten that names BearSSL in ChaCha20-Poly1305's type without including BearSSL's header.", "chacha_unknown_backend_on_emscripten": "A program for Emscripten that names a type of its own as ChaCha20-Poly1305's backend.", "chacha_openssl_on_emscripten": "A program for Emscripten that names OpenSSL, which is not built there, in ChaCha20-Poly1305's type.", - "ed25519_unknown_policy_on_emscripten": "A program for Emscripten that names a policy of its own in Ed25519's `crypto::verify`.", - "secret_of_no_bytes_on_emscripten": "A program for Emscripten that names `secret<0>`." + "ed25519_unknown_policy_on_emscripten": "A program for Emscripten that names a policy of its own in Ed25519's `crypto::verify`." }, "fixes": { "gcm_default_openssl_not_linked": "Natively the default is OpenSSL: add `/webcpp/crypto//gcm-default`, which links `/webcpp/crypto//openssl` there, or name BearSSL in the type, as in `gcm>`.", @@ -1536,10 +1515,12 @@ "chacha_header_not_included": "Include the backend's header the message names, as ``, and add its library, as `/third_party//bearssl`.", "chacha_unknown_backend": "Name a backend of `webcpp::crypto::backends` that has the family, as `backends::bearssl`, or leave the backend out for the family's default: `chacha20_poly1305<>`.", "ed25519_unknown_policy": "Leave the policy out, as in `crypto::verify(crypto::eddsa, signature, message, public_key)`, or name `curves::ed25519::strict`.", - "secret_of_no_bytes": "Give `secret` the number of bytes it holds, at least one, as in `secret<32>`.", - "equal_header_removed": "Include ``, the header of `constant_time_equal`; `equal.hpp` is gone, with no header left at its path.", - "equal_removed": "Call `crypto::constant_time_equal`, the same comparison of two spans or two digests in constant time; `crypto::equal` is gone, with no alias.", - "wipe_removed": "Call `crypto::erase_secret`, which zeroes a contiguous range the program owns (a `std::string&`, a `std::span`) with stores the optimiser keeps; `crypto::wipe` is gone, with no alias.", + "equal_header_removed": "Include ``, the header of `secure::constant_time_equal`; `equal.hpp` is gone, with no header left at its path.", + "equal_removed": "Call `webcpp::secure::constant_time_equal`, the same comparison of two byte sequences in constant time; `crypto::equal` is gone, with no alias.", + "wipe_removed": "Call `webcpp::secure::erase_secret`, which zeroes a contiguous range the program owns (a `std::string&`, a `std::span`) with stores the optimiser keeps; `crypto::wipe` is gone, with no alias.", + "constant_time_equal_moved": "Call `webcpp::secure::constant_time_equal`, from ``, the same comparison in constant time; `crypto::constant_time_equal` moved to webcpp::secure, with no alias.", + "erase_secret_moved": "Call `webcpp::secure::erase_secret`, from ``, the same erasure; `crypto::erase_secret` moved to webcpp::secure, with no alias.", + "secret_moved": "Name `webcpp::secure::secret`, from ``, the type every secret crypto returns; `crypto::secret` moved to webcpp::secure, with no alias.", "x25519_free_functions_removed": "Make the key pair with `curves::x25519::keypair::from_secret(secret)`, then call its `public_key()`, and its `agree` with the peer's `curves::x25519::public_key` from `from_bytes`; the free functions over bytes are gone, with no alias. The `x25519::public_key(secret)` half pins clang's generic \"no matching conversion for functional-style cast\", since `public_key` now names the type.", "iv_size_removed": "Name nonce_size, max_nonce_size and error::invalid_nonce_size: crypto spells its names out.", "aead_template_removed": "Name `ciphers::basic_chacha20_poly1305`, or its aliases `chacha20_poly1305`, `chacha20_poly1305_original` and `xchacha20_poly1305`: the template is named for its algorithm, with no alias.", @@ -1566,7 +1547,6 @@ "seal_box_asynchronous_backend": "Name a native backend, such as `backends::sodium`, for the crypto_box: WebCrypto has no crypto_box, so neither its `seal` nor its `async_seal` completes on the browser's backend.", "async_seal_box_associated_data": "Call the box form, `secret_key_encryption::async_seal(executor, box, nonce, data, token)`, or the box's own `async_seal(executor, nonce, data, token)`: a secret box or a crypto_box takes no associated data.", "seal_removed_call_wasi": "As `seal_removed_call`: call crypto::secret_key_encryption::aead::seal and open; clang's offer of the C library's fopen is not the AEAD's open.", - "erase_secret_const_range": "Erase the buffer the secret was written to, through a non-const reference to it (`std::string&`, `std::span`): a const view cannot be erased. Its elements must be trivially copyable, bytes or integers; a range of `std::string` or of another type with its own storage cannot be erased as bytes, so erase each element's buffer instead.", "chacha_default_not_linked_on_emscripten": "As `chacha_default_not_linked`.", "box_default_not_linked_on_emscripten": "As `box_default_not_linked`.", "kx_default_not_linked_on_emscripten": "As `kx_default_not_linked`.", @@ -1576,7 +1556,6 @@ "chacha_header_not_included_on_emscripten": "As `chacha_header_not_included`.", "chacha_unknown_backend_on_emscripten": "As `chacha_unknown_backend`.", "chacha_openssl_on_emscripten": "Name a backend that has ChaCha20-Poly1305 on Emscripten, as in `chacha20_poly1305`, or its default, `chacha20_poly1305<>`, and link its library.", - "ed25519_unknown_policy_on_emscripten": "As `ed25519_unknown_policy`.", - "secret_of_no_bytes_on_emscripten": "As `secret_of_no_bytes`." + "ed25519_unknown_policy_on_emscripten": "As `ed25519_unknown_policy`." } } diff --git a/doc/x25519.adoc b/doc/x25519.adoc index 67451bb0..74c34439 100644 --- a/doc/x25519.adoc +++ b/doc/x25519.adoc @@ -29,7 +29,7 @@ is made, is `public_key()`, a `curves::x25519::public_key`, whose `bytes()` a program sends, and `secret()` gives the secret key back, to keep. A peer's key arrives as bytes and is made by `public_key::from_bytes(bytes)`, which checks their size alone. `key_pair.agree(peer_key)` gives the shared secret, a -`secret<32>` that wipes itself. A moved-from key pair refuses every call with +`secure::secret<32>` that wipes itself. A moved-from key pair refuses every call with `invalid_state`. A peer's public key of low order makes the shared secret all zero, whatever the secret key: `agree` refuses it with `weak_public_key`, so that an attacker who sends such a key cannot make both sides use a secret it @@ -102,10 +102,9 @@ a secret of its own choosing. timing), libsodium's `agree` takes a time that depends on the secret key when DIT is clear: about one nanosecond less for the all-zero key, enough for dudect to tell it apart (<>). libsodium does not set -DIT; webcpp sets it around every call on 64-bit ARM under macOS, iOS, Linux and -Android where the CPU has it, and restores the thread's state after it, so a -program does nothing there; on Windows on ARM64 it sets nothing -(<>). +DIT; webcpp sets it around every call on 64-bit ARM under macOS, iOS, Linux, +Android and Windows where the CPU has it, and restores the thread's state after +it, so a program does nothing there (<>). * On WebAssembly, timing is an open finding: under wasmtime, on wasip2, dudect times `agree` against its secret key above the lane's threshold, where every native build passes (with the DIT webcpp sets on 64-bit ARM). The cause is diff --git a/example/aes256_gcm_bearssl.cpp b/example/aes256_gcm_bearssl.cpp index 6d215cc3..ece8ac31 100644 --- a/example/aes256_gcm_bearssl.cpp +++ b/example/aes256_gcm_bearssl.cpp @@ -11,13 +11,14 @@ #include #include #include -#include +#include #include #include #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; // The backend is part of the type: no default, no surprise. using aead_type = crypto::ciphers::gcm>; @@ -43,7 +44,7 @@ int main() { } // Seal encrypts in place and returns the tag. auto const tag = aead->seal(nonce, {}, data); - if (!tag || data != expected_cipher || !crypto::constant_time_equal(*tag, expected_tag)) { + if (!tag || data != expected_cipher || !secure::constant_time_equal(*tag, expected_tag)) { return 1; } // Open decrypts in place and checks the tag; on a mismatch it zeroes data and returns diff --git a/example/arena_signer.cpp b/example/arena_signer.cpp index 8f1a5b65..acb968d3 100644 --- a/example/arena_signer.cpp +++ b/example/arena_signer.cpp @@ -10,28 +10,20 @@ // tag::program[] #include #include +#include #include #include #include #include #include -#include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // tag::counting[] // Counts allocations and forwards them to the arena. class counting_resource : public std::pmr::memory_resource { @@ -75,7 +67,7 @@ int main() { std::array secret{}; secret.fill(0x42); auto key = secp256k1::keypair::from_secret(secret, &counting); - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); if (!key) { return 1; } diff --git a/example/bearssl_prng.cpp b/example/bearssl_prng.cpp index b6d4405e..cb68e23f 100644 --- a/example/bearssl_prng.cpp +++ b/example/bearssl_prng.cpp @@ -9,28 +9,15 @@ // from the clock or a counter. // tag::program[] #include +#include #include #include -#include #include #include #include -namespace { - -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - -} // namespace - int main() { std::array seed{}; webcpp::crypto::random_device device; @@ -41,14 +28,14 @@ int main() { br_hmac_drbg_context drbg; br_hmac_drbg_init(&drbg, &br_sha256_vtable, seed.data(), seed.size()); // The generator holds what it needs: the seed goes now. - wipe(std::as_writable_bytes(std::span(seed))); + webcpp::secure::erase_secret(seed); std::array bytes{}; br_hmac_drbg_generate(&drbg, bytes.data(), bytes.size()); // The bytes are random, so the program never prints them. // The generator's state predicts its next outputs: wipe it, and what it gave, after use. - wipe(std::as_writable_bytes(std::span(&drbg, 1))); - wipe(std::as_writable_bytes(std::span(bytes))); + webcpp::secure::erase_secret(std::span(&drbg, 1)); + webcpp::secure::erase_secret(bytes); std::printf("seeded\n"); return 0; } diff --git a/example/bitcoin_sighash.cpp b/example/bitcoin_sighash.cpp index fa5e1ac5..807cfc9c 100644 --- a/example/bitcoin_sighash.cpp +++ b/example/bitcoin_sighash.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -24,19 +25,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // Prints bytes in hex after a name, 32 bytes (64 digits) to a line, the lines after the first // indented under the first, so that a long value stays readable on a narrow page. void print(char const* name, std::span bytes) { @@ -58,7 +51,7 @@ int main() { std::array secret{}; secret.fill(0x11); auto key = secp256k1::keypair::from_secret(secret); - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); if (!key) { return 1; } diff --git a/example/constant_time_equal_hmac.cpp b/example/constant_time_equal_hmac.cpp index 51ff9af7..226ce97c 100644 --- a/example/constant_time_equal_hmac.cpp +++ b/example/constant_time_equal_hmac.cpp @@ -4,11 +4,11 @@ // accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) -// Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::crypto::constant_time_equal, the +// Checks an HMAC-SHA-256 tag from Boost.Hash2 with webcpp::secure::constant_time_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. // tag::program[] -#include +#include #include #include @@ -19,7 +19,7 @@ #include #include -namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace hash2 = boost::hash2; int main() { @@ -37,7 +37,7 @@ int main() { hash2::hmac_sha2_256 mac(key.data(), key.size()); mac.update(data.data(), data.size()); auto const computed = mac.result(); - bool const valid = crypto::constant_time_equal( + bool const valid = secure::constant_time_equal( std::span(computed.data(), computed.size()), sent_tag); // end::check[] if (!valid) { @@ -48,7 +48,7 @@ int main() { // A tag with one changed byte must be refused. auto altered = sent_tag; altered[31] ^= 1U; - if (crypto::constant_time_equal(std::span(computed.data(), computed.size()), + if (secure::constant_time_equal(std::span(computed.data(), computed.size()), altered)) { return 1; } diff --git a/example/ecdh_session.cpp b/example/ecdh_session.cpp index 5a1345d0..077bdea2 100644 --- a/example/ecdh_session.cpp +++ b/example/ecdh_session.cpp @@ -9,11 +9,12 @@ // it to this application with a context string. // tag::program[] #include -#include #include #include #include -#include +#include +#include +#include #include #include @@ -26,32 +27,15 @@ #include #include #include -#include #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace hash2 = boost::hash2; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - -// Wipes an object of key-derived state, such as an HMAC whose inner and outer states hold the -// key: its bytes are all it is, so overwriting them leaves nothing of the key. -template -void wipe_object(T& object) { - static_assert(std::is_trivially_copyable_v); - wipe(std::as_writable_bytes(std::span(&object, 1))); -} - std::span bytes_of(std::string_view text) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return {reinterpret_cast(text.data()), text.size()}; @@ -83,7 +67,7 @@ std::array hkdf_sha256(std::span input hash2::hmac_sha2_256 extract(salt.data(), salt.size()); extract.update(input.data(), input.size()); auto prk = extract.result(); - wipe_object(extract); + secure::erase_secret(std::span(&extract, 1)); std::array out{}; std::array previous{}; @@ -95,9 +79,9 @@ std::array hkdf_sha256(std::span input expand.update(info.data(), info.size()); expand.update(&counter, 1); auto block = expand.result(); - wipe_object(expand); + secure::erase_secret(std::span(&expand, 1)); std::copy_n(block.data(), block.size(), previous.begin()); - wipe(std::as_writable_bytes(std::span(block))); + secure::erase_secret(block); previous_size = previous.size(); std::size_t const taken = std::min(previous.size(), Length - offset); std::copy_n(previous.begin(), taken, out.begin() + static_cast(offset)); @@ -105,8 +89,8 @@ std::array hkdf_sha256(std::span input } // The pseudorandom key and the last block are as secret as the input, and so are the HMACs // keyed with them, wiped above: wipe them. - wipe(std::as_writable_bytes(std::span(prk))); - wipe(std::as_writable_bytes(std::span(previous))); + secure::erase_secret(prk); + secure::erase_secret(previous); return out; } @@ -123,7 +107,7 @@ boost::system::result generate_key() { auto key = secp256k1::keypair::from_secret(secret); if (key || key.error() != crypto::error::invalid_secret_key) { // The key pair keeps its own copy, which it wipes; this one goes now. - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); return key; } } @@ -132,11 +116,11 @@ boost::system::result generate_key() { // Both sides derive their session key the same way. The shared secret wipes itself when it // goes out of scope; the key derived from it is the program's to wipe. boost::system::result session_cipher( - crypto::secret<32> const& shared) { + secure::secret<32> const& shared) { auto key = hkdf_sha256<32>(shared.bytes(), {}, bytes_of("example chat v1 session key")); auto cipher = crypto::ciphers::aes256_gcm::from_key(key); // The cipher keeps its own copy of the key, which it wipes; this one goes now. - wipe(std::as_writable_bytes(std::span(key))); + secure::erase_secret(key); return cipher; } @@ -148,7 +132,7 @@ bool hkdf_is_correct() { auto const info = from_hex<10>("f0f1f2f3f4f5f6f7f8f9"); auto const expected = from_hex<42>( "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"); - return crypto::constant_time_equal(hkdf_sha256<42>(input, salt, info), expected); + return secure::constant_time_equal(hkdf_sha256<42>(input, salt, info), expected); } } // namespace @@ -179,7 +163,7 @@ int main() { auto const alice_shared = alice->agree_hashed(*bob_public); auto const bob_shared = bob->agree_hashed(*alice_public); if (!alice_shared || !bob_shared || - !crypto::constant_time_equal(alice_shared->bytes(), bob_shared->bytes())) { + !secure::constant_time_equal(alice_shared->bytes(), bob_shared->bytes())) { return 1; } std::printf("shared secrets match\n"); diff --git a/example/ecdh_x_coordinate.cpp b/example/ecdh_x_coordinate.cpp index 5bfe52c3..2b6cae60 100644 --- a/example/ecdh_x_coordinate.cpp +++ b/example/ecdh_x_coordinate.cpp @@ -9,45 +9,27 @@ // conversation key, HKDF-extract with the salt "nip44-v2". The x coordinate is not a key; the // derivation that makes one is the protocol's, and belongs to a domain library. // tag::program[] -#include #include -#include +#include +#include +#include #include #include #include #include -#include #include #include #include #include -#include -namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace hash2 = boost::hash2; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - -// Wipes an object of key-derived state, such as an HMAC whose inner and outer states hold the -// key: its bytes are all it is, so overwriting them leaves nothing of the key. -template -void wipe_object(T& object) { - static_assert(std::is_trivially_copyable_v); - wipe(std::as_writable_bytes(std::span(&object, 1))); -} - std::span bytes_of(std::string_view text) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return {reinterpret_cast(text.data()), text.size()}; @@ -64,16 +46,16 @@ void print_hex(char const* label, std::span bytes) { // NIP-44's conversation key: HKDF-extract (RFC 5869), an HMAC-SHA-256 keyed with the salt // "nip44-v2" over the shared x coordinate. A NIP-44 library computes it; the message keys, // the padding and the payload's format that follow are the protocol's too. -std::array conversation_key(crypto::secret<32> const& shared_x) { +std::array conversation_key(secure::secret<32> const& shared_x) { auto const salt = bytes_of("nip44-v2"); hash2::hmac_sha2_256 extract(salt.data(), salt.size()); - extract.update(shared_x.bytes().data(), crypto::secret<32>::size()); + extract.update(shared_x.bytes().data(), secure::secret<32>::size()); auto digest = extract.result(); - wipe_object(extract); + secure::erase_secret(std::span(&extract, 1)); std::array key{}; std::span const digest_bytes(digest.data(), digest.size()); std::ranges::copy(digest_bytes, key.begin()); - wipe(std::as_writable_bytes(std::span(digest.data(), digest.size()))); + secure::erase_secret(std::span(digest.data(), digest.size())); return key; } @@ -82,7 +64,7 @@ boost::system::result from_secret(std::uint8_t fill) { secret.fill(fill); auto made = secp256k1::keypair::from_secret(secret); // The key pair keeps its own copy, which it wipes; this one goes now. - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); return made; } @@ -105,7 +87,7 @@ int main() { // a secret<32> that wipes itself. auto const alice_x = alice->agree(*bob_public); auto const bob_x = bob->agree(*alice_public); - if (!alice_x || !bob_x || !crypto::constant_time_equal(alice_x->bytes(), bob_x->bytes())) { + if (!alice_x || !bob_x || !secure::constant_time_equal(alice_x->bytes(), bob_x->bytes())) { return 1; } std::printf("shared x coordinates match\n"); @@ -114,7 +96,7 @@ int main() { print_hex("x: ", alice_x->bytes()); auto key = conversation_key(*alice_x); print_hex("conversation key (what a NIP-44 library derives): ", key); - wipe(std::as_writable_bytes(std::span(key))); + secure::erase_secret(key); return 0; } diff --git a/example/ecdsa_der.cpp b/example/ecdsa_der.cpp index d053bf48..0ac6fc44 100644 --- a/example/ecdsa_der.cpp +++ b/example/ecdsa_der.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include @@ -24,19 +25,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // Prints bytes in hex after a name, 32 bytes (64 digits) to a line, the lines after the first // indented under the first, so that a long value stays readable on a narrow page. void print(char const* name, std::span bytes) { @@ -85,7 +78,7 @@ int main() { std::array secret{}; secret.fill(0x11); auto key = secp256k1::keypair::from_secret(secret); - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); if (!key) { return 1; } diff --git a/example/ellswift_handshake.cpp b/example/ellswift_handshake.cpp index b441ebd4..aef5fc3f 100644 --- a/example/ellswift_handshake.cpp +++ b/example/ellswift_handshake.cpp @@ -10,16 +10,16 @@ // encodings. The secrets and the randomness are fixed here, so that the program runs the same // each time; a real program draws all four from random_device. Nothing random is printed. // tag::program[] -#include #include #include #include +#include #include #include #include -namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { @@ -64,7 +64,7 @@ int main() { auto const responder_secret = secp256k1::ellswift_xdh( *responder, *initiator_message, *responder_message, secp256k1::ellswift_party::responder); if (!initiator_secret || !responder_secret || - !crypto::constant_time_equal(initiator_secret->bytes(), responder_secret->bytes())) { + !secure::constant_time_equal(initiator_secret->bytes(), responder_secret->bytes())) { return 1; } std::printf("initiator and responder agree\n"); diff --git a/example/failure_reasons.cpp b/example/failure_reasons.cpp index 45e7119f..051d0092 100644 --- a/example/failure_reasons.cpp +++ b/example/failure_reasons.cpp @@ -11,10 +11,10 @@ // tag::program[] #include #include +#include #include #include -#include #include #include #include @@ -22,19 +22,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; using aead_type = crypto::ciphers::aes256_gcm; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - bool all_zero(std::span bytes) { return std::ranges::all_of(bytes, [](std::uint8_t b) { return b == 0; }); } @@ -53,7 +45,7 @@ int main() { std::ranges::copy(text, sealed.begin()); auto aead = aead_type::from_key(key); - wipe(std::as_writable_bytes(std::span(key))); + secure::erase_secret(key); if (!aead) { return 1; } diff --git a/example/file_share.cpp b/example/file_share.cpp index abbb9975..d93a32e8 100644 --- a/example/file_share.cpp +++ b/example/file_share.cpp @@ -15,8 +15,8 @@ #include #include #include -#include #include +#include #include #include @@ -27,6 +27,7 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; using crypto::public_key_encryption::sealed_box; using crypto::secret_key_encryption::secretbox; @@ -46,7 +47,7 @@ struct upload { bool share(crypto::random_device& device, crypto::curves::x25519::public_key const& recipient_public_key, std::string_view contents, upload& out) { - crypto::secret<32> file_key; + secure::secret<32> file_key; if (!device.fill(file_key.writable()) || !device.fill(out.nonce)) { return false; } @@ -68,7 +69,7 @@ bool share(crypto::random_device& device, // tag::receive[] // The recipient: the file key out of the sealed box, then the file out of the secret box. void receive(char const* who, crypto::curves::x25519::keypair const& key_pair, upload received) { - crypto::secret<32> file_key; + secure::secret<32> file_key; auto const key_opened = sealed_box::open(key_pair, received.sealed_key, file_key.writable()); if (!key_opened) { std::string const reason = key_opened.error().message(); diff --git a/example/key_formats.cpp b/example/key_formats.cpp index dc64e84e..d4f92865 100644 --- a/example/key_formats.cpp +++ b/example/key_formats.cpp @@ -15,8 +15,8 @@ #include #include #include -#include #include +#include #include #include @@ -25,6 +25,7 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace ed25519 = webcpp::crypto::curves::ed25519; namespace x25519 = webcpp::crypto::curves::x25519; namespace pem = webcpp::crypto::pem; @@ -59,7 +60,7 @@ bool print_public_pem(std::array const& spki) { // An Ed25519 key pair from PEM, its public key back to PEM, and a signature. bool ed25519_from_pem() { // The PKCS#8 holds the seed: a secret, which wipes itself. - crypto::secret pkcs8; + secure::secret pkcs8; auto const read = pem::unarmour(pem::private_key_label, private_pem, pkcs8.writable()); if (!read) { return false; @@ -96,7 +97,7 @@ bool x25519_to_pem() { // Version 2 decodes from PEM, then the PKCS#8 is refused: strict decoding takes one form. bool version2_refused() { - crypto::secret<128> der; + secure::secret<128> der; auto const read = pem::unarmour(pem::private_key_label, version2_pem, der.writable()); if (!read) { return false; diff --git a/example/key_tweak.cpp b/example/key_tweak.cpp index 56df582a..76299c49 100644 --- a/example/key_tweak.cpp +++ b/example/key_tweak.cpp @@ -17,34 +17,23 @@ #include #include #include +#include #include #include #include -#include #include #include #include -#include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace hash2 = boost::hash2; namespace { -// Overwrites an object's bytes through a volatile pointer, which the optimiser cannot drop as a -// dead store: crypto wipes its own copies of keys this way, and the program wipes its own. -template -void wipe(T& object) { - static_assert(std::is_trivially_destructible_v, "an object whose bytes are all its state"); - auto* const data = reinterpret_cast(&object); - for (std::size_t i = 0; i < sizeof(T); ++i) { - data[i] = 0; - } -} - // 32 secret bytes the program holds, wiped when the scope ends, on every path, an early return's // included. struct wiped_bytes { @@ -54,7 +43,7 @@ struct wiped_bytes { wiped_bytes(wiped_bytes const&) = delete; wiped_bytes& operator=(wiped_bytes const&) = delete; - ~wiped_bytes() { wipe(bytes); } + ~wiped_bytes() { secure::erase_secret(bytes); } }; // The tweak of payment `number`: HMAC-SHA-256 under the chain code of the compressed public key @@ -75,8 +64,8 @@ void payment_tweak(std::span chain_code, mac.update(index.data(), index.size()); auto digest = mac.result(); std::copy_n(digest.data(), tweak.bytes.size(), tweak.bytes.begin()); - wipe(digest); - wipe(mac); + secure::erase_secret(digest); + secure::erase_secret(std::span(&mac, 1)); } } // namespace diff --git a/example/kx_session.cpp b/example/kx_session.cpp index e256b9a7..c116e84a 100644 --- a/example/kx_session.cpp +++ b/example/kx_session.cpp @@ -10,10 +10,10 @@ // of low order is refused. Prints the public keys and the client's session keys in hex. // tag::program[] #include -#include #include #include #include +#include #include #include @@ -22,6 +22,7 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace key_exchange = webcpp::crypto::key_exchange; namespace { @@ -89,9 +90,9 @@ bool client_and_server() { // Printed here only because libsodium's test publishes them; a program never prints a key. print("client rx ", client_keys->receive.bytes()); print("client tx ", client_keys->transmit.bytes()); - return crypto::constant_time_equal(client_keys->transmit.bytes(), + return secure::constant_time_equal(client_keys->transmit.bytes(), server_keys->receive.bytes()) && - crypto::constant_time_equal(client_keys->receive.bytes(), + secure::constant_time_equal(client_keys->receive.bytes(), server_keys->transmit.bytes()) && message(*client_keys, *server_keys); } diff --git a/example/opened_in_two_passes.cpp b/example/opened_in_two_passes.cpp index 662e08f5..22501ea6 100644 --- a/example/opened_in_two_passes.cpp +++ b/example/opened_in_two_passes.cpp @@ -12,6 +12,7 @@ // tag::program[] #include #include +#include #include @@ -27,6 +28,7 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; using aead_type = crypto::ciphers::aes256_gcm; namespace { @@ -34,15 +36,6 @@ namespace { constexpr std::size_t file_size = std::size_t{1} << 20U; // 1 MiB constexpr std::size_t file_piece_size = std::size_t{1} << 16U; // 64 KiB -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // Reads the next piece of the file into `piece`: the bytes read, 0 at its end. std::span read_piece(std::istream& file, std::vector& piece) { file.read(reinterpret_cast(piece.data()), static_cast(piece.size())); @@ -123,7 +116,7 @@ int main() { return 1; } auto aead = aead_type::from_key(key); - wipe(std::as_writable_bytes(std::span(key))); + secure::erase_secret(key); if (!aead) { return 1; } diff --git a/example/order_reference.cpp b/example/order_reference.cpp index e84b8c5f..ff8fe40d 100644 --- a/example/order_reference.cpp +++ b/example/order_reference.cpp @@ -10,6 +10,7 @@ // tag::program[] #include #include +#include #include #include @@ -19,19 +20,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; using cipher_type = crypto::ciphers::aes256; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - bool padding_is_zero(std::span block) { return std::ranges::all_of(block.last<8>(), [](std::uint8_t b) { return b == 0; }); } @@ -46,7 +39,7 @@ int main() { key[i] = static_cast(i); } auto cipher = cipher_type::from_key(key); - wipe(std::as_writable_bytes(std::span(key))); + secure::erase_secret(key); if (!cipher) { return 1; } diff --git a/example/p256_ecdh.cpp b/example/p256_ecdh.cpp index 63a4261e..748e9581 100644 --- a/example/p256_ecdh.cpp +++ b/example/p256_ecdh.cpp @@ -19,9 +19,9 @@ // -kdfopt salt:"example salt" -kdfopt info:"example chat v1 key" HKDF (one line) // which print the x and the key of p256_ecdh.expected. // tag::program[] -#include #include -#include +#include +#include #include @@ -34,7 +34,7 @@ #include #include -namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace p256 = webcpp::crypto::curves::p256; namespace { @@ -84,7 +84,7 @@ int main() { auto const alice_x = alice->agree(*bob_public); auto const bob_x = bob->agree(*alice_public); // end::agree[] - if (!alice_x || !bob_x || !crypto::constant_time_equal(alice_x->bytes(), bob_x->bytes())) { + if (!alice_x || !bob_x || !secure::constant_time_equal(alice_x->bytes(), bob_x->bytes())) { std::printf("failed\n"); return 1; } @@ -94,7 +94,7 @@ int main() { // tag::derive[] // The x is hashed into the key: HKDF-SHA-256 (RFC 5869) with the protocol's salt and info. - crypto::secret<32> key; + secure::secret<32> key; auto const derived = webcpp::hash::hkdf( key.writable(), bytes_of("example salt"), alice_x->bytes(), bytes_of("example chat v1 key")); diff --git a/example/p256_handshake.cpp b/example/p256_handshake.cpp index 0fac9b3f..2dffab2d 100644 --- a/example/p256_handshake.cpp +++ b/example/p256_handshake.cpp @@ -13,10 +13,10 @@ // a real program draws its key pairs with keypair::generate(). What is signed, when, and the // low-S rule are a protocol's: this one is an example, not webcpp::trystero's. // tag::program[] -#include #include -#include #include +#include +#include #include #include @@ -33,6 +33,7 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace p256 = webcpp::crypto::curves::p256; namespace { @@ -191,7 +192,7 @@ struct peer { // tag::session[] // The session key: ECDH's x of the two session key pairs, through HKDF-SHA-256 with the // transcript's digest as the salt, so that the key is bound to this handshake. - [[nodiscard]] boost::system::result> session_key( + [[nodiscard]] boost::system::result> session_key( hello const& other, std::span digest) const { auto const other_key = p256::public_key::from_bytes(other.session); if (!other_key) { @@ -201,7 +202,7 @@ struct peer { if (!x) { return x.error(); } - crypto::secret<32> key; + secure::secret<32> key; auto const derived = webcpp::hash::hkdf( key.writable(), digest, x->bytes(), bytes_of("example handshake v1 session key")); if (!derived) { @@ -284,7 +285,7 @@ int main() { auto const alice_key = alice->session_key(*bob_hello, *digest); auto const bob_key = bob->session_key(*alice_hello, *digest); if (!alice_key || !bob_key || - !crypto::constant_time_equal(alice_key->bytes(), bob_key->bytes())) { + !secure::constant_time_equal(alice_key->bytes(), bob_key->bytes())) { std::printf("failed\n"); return 1; } diff --git a/example/p256_key_formats.cpp b/example/p256_key_formats.cpp index 96a7fa48..da44d9a3 100644 --- a/example/p256_key_formats.cpp +++ b/example/p256_key_formats.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include #include #include @@ -22,7 +22,7 @@ #include #include -namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace pem = webcpp::crypto::pem; namespace p256 = webcpp::crypto::curves::p256; @@ -57,14 +57,14 @@ bool public_key_to_pem(p256::public_key const& key) { // secret, which wipes itself, the text as its bytes' characters. Read back, it is a key pair // of the same public key. bool key_pair_to_pem(p256::keypair const& key_pair) { - crypto::secret pkcs8; + secure::secret pkcs8; auto const size = p256::encode_pkcs8(key_pair, pkcs8.writable()); if (!size) { return false; } constexpr std::size_t file_size = pem::armoured_size(pem::private_key_label.size(), p256::max_pkcs8_size); - crypto::secret file; + secure::secret file; std::span const text(reinterpret_cast(file.writable().data()), file_size); auto const written = pem::armour(pem::private_key_label, pkcs8.bytes().first(*size), text); if (!written) { @@ -72,7 +72,7 @@ bool key_pair_to_pem(p256::keypair const& key_pair) { } std::printf("PKCS#8: %zu bytes, %zu characters of PEM, kept secret\n", *size, *written); - crypto::secret read; + secure::secret read; auto const read_size = pem::unarmour(pem::private_key_label, std::string_view(text.data(), *written), read.writable()); if (!read_size) { diff --git a/example/recover_signer.cpp b/example/recover_signer.cpp index 5d106797..8470f4c3 100644 --- a/example/recover_signer.cpp +++ b/example/recover_signer.cpp @@ -14,11 +14,11 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -26,19 +26,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // A text's bytes, the message. crypto::ecdsa_sha256_recoverable hashes it with SHA-256 inside; // Ethereum's own message hash is EIP-191's (a prefix, then Keccak-256), which a domain library // computes and gives as crypto::prehashed{digest}. @@ -58,7 +50,7 @@ boost::system::result generate_key() { auto key = secp256k1::keypair::from_secret(secret); if (key || key.error() != crypto::error::invalid_secret_key) { // The key pair keeps its own copy, which it wipes; this one goes now. - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); return key; } } diff --git a/example/schnorr_sign.cpp b/example/schnorr_sign.cpp index 0d09b80d..9b7d1c8a 100644 --- a/example/schnorr_sign.cpp +++ b/example/schnorr_sign.cpp @@ -10,6 +10,7 @@ // tag::program[] #include #include +#include #include #include @@ -18,19 +19,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // Prints bytes in hex after a name, 32 bytes (64 digits) to a line, the lines after the first // indented under the first, so that a long value stays readable on a narrow page. void print(char const* name, std::span bytes) { @@ -68,7 +61,7 @@ int main() { secret.back() = 3; std::array const message{}; auto key = secp256k1::keypair::from_secret(secret); - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); if (!key || !sign_and_verify(*key, message)) { return 1; } diff --git a/example/sealed_records.cpp b/example/sealed_records.cpp index f2b9aec1..728261d5 100644 --- a/example/sealed_records.cpp +++ b/example/sealed_records.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -28,19 +29,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; using aead_type = crypto::ciphers::aes256_gcm; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // A record sealed alone: its bytes and its tag. struct record { std::vector data; @@ -97,7 +90,7 @@ bool incremental() { return false; } auto aead = aead_type::from_key(key); - wipe(std::as_writable_bytes(std::span(key))); + secure::erase_secret(key); if (!aead) { return false; } @@ -144,7 +137,7 @@ bool records() { return false; } auto aead = aead_type::from_key(key); - wipe(std::as_writable_bytes(std::span(key))); + secure::erase_secret(key); if (!aead) { return false; } diff --git a/example/secp256k1_key_formats.cpp b/example/secp256k1_key_formats.cpp index 3f465df9..6106ce45 100644 --- a/example/secp256k1_key_formats.cpp +++ b/example/secp256k1_key_formats.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include @@ -20,7 +20,7 @@ #include #include -namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace pem = webcpp::crypto::pem; namespace secp256k1 = webcpp::crypto::curves::secp256k1; @@ -56,21 +56,21 @@ bool public_key_to_pem(secp256k1::public_key const& key) { // secret, which wipes itself, the text as its bytes' characters. Read back, it is a key pair // of the same public key. bool key_pair_to_pem(secp256k1::keypair const& key_pair) { - crypto::secret pkcs8; + secure::secret pkcs8; auto const size = secp256k1::encode_pkcs8(key_pair, pkcs8.writable()); if (!size) { return false; } constexpr std::size_t file_size = pem::armoured_size(pem::private_key_label.size(), secp256k1::max_pkcs8_size); - crypto::secret file; + secure::secret file; std::span const text(reinterpret_cast(file.writable().data()), file_size); auto const written = pem::armour(pem::private_key_label, pkcs8.bytes().first(*size), text); if (!written) { return false; } - crypto::secret read; + secure::secret read; auto const read_size = pem::unarmour(pem::private_key_label, std::string_view(text.data(), *written), read.writable()); if (!read_size) { diff --git a/example/signed_message.cpp b/example/signed_message.cpp index 0dbb54bc..434e1d71 100644 --- a/example/signed_message.cpp +++ b/example/signed_message.cpp @@ -12,18 +12,18 @@ #include #include #include +#include #include #include #include -#include #include #include -#include #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { @@ -39,15 +39,6 @@ std::array id_of(std::string_view text) { } // tag::keygen[] -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - boost::system::result generate_key() { crypto::random_device device; std::array secret{}; @@ -61,7 +52,7 @@ boost::system::result generate_key() { // draw again. Any other error is real. if (key || key.error() != crypto::error::invalid_secret_key) { // The key pair keeps its own copy, which it wipes; this one goes now. - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); return key; } } diff --git a/example/signed_update.cpp b/example/signed_update.cpp index 36ebbe9c..48f6b41b 100644 --- a/example/signed_update.cpp +++ b/example/signed_update.cpp @@ -12,11 +12,11 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -24,19 +24,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // A text's bytes, the message: ECDSA over SHA-256 hashes it inside the call. std::span bytes_of(std::string_view text) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): a text's bytes @@ -54,7 +46,7 @@ boost::system::result generate_key() { auto key = secp256k1::keypair::from_secret(secret); if (key || key.error() != crypto::error::invalid_secret_key) { // The key pair keeps its own copy, which it wipes; this one goes now. - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); return key; } } diff --git a/example/silent_payment.cpp b/example/silent_payment.cpp index fbf9cbe0..c643722a 100644 --- a/example/silent_payment.cpp +++ b/example/silent_payment.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include @@ -63,7 +63,7 @@ int main() { // their two public keys. auto const scan_pair = secp256k1::keypair::from_secret(repeated(0x51)); // The spend secret is kept, in a secret<32> that wipes itself, to spend what is found. - webcpp::crypto::secret<32> spend_secret; + webcpp::secure::secret<32> spend_secret; std::ranges::fill(spend_secret.writable(), std::uint8_t{0x52}); auto const spend_pair = secp256k1::keypair::from_secret(spend_secret.bytes()); auto const donor = secp256k1::keypair::from_secret(repeated(0x53)); diff --git a/example/store_token.cpp b/example/store_token.cpp index ba4c3328..7fe17313 100644 --- a/example/store_token.cpp +++ b/example/store_token.cpp @@ -10,10 +10,10 @@ // tag::program[] #include #include +#include #include #include -#include #include #include #include @@ -22,19 +22,11 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; using aead_type = crypto::ciphers::aes256_gcm; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - // What the database holds: the nonce and the tag are not secret, only the key is. struct row { std::array nonce{}; @@ -59,7 +51,7 @@ int main() { } auto aead = aead_type::from_key(storage_key); // The object keeps its own key schedule, which it wipes; this copy goes now. - wipe(std::as_writable_bytes(std::span(storage_key))); + secure::erase_secret(storage_key); if (!aead) { return 1; } @@ -88,7 +80,7 @@ int main() { std::printf("opened for user-42: %.*s\n", static_cast(plain.size()), reinterpret_cast(plain.data())); // The decrypted token is a secret: once used, wipe it. - wipe(std::as_writable_bytes(std::span(plain))); + secure::erase_secret(plain); // end::open[] // The same row copied to user 43's record does not open. diff --git a/example/taproot_tweak.cpp b/example/taproot_tweak.cpp index d0086a50..4727e794 100644 --- a/example/taproot_tweak.cpp +++ b/example/taproot_tweak.cpp @@ -8,34 +8,26 @@ // tweak is a tagged hash of the internal key, and the output key commits to it. The same tweak // applied to the key pair lets the owner sign for the output key, so spending needs no script. // tag::program[] -#include #include #include +#include +#include #include #include #include -#include #include #include #include #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - void print(char const* name, std::span bytes) { std::printf("%s ", name); for (std::uint8_t const b : bytes) { @@ -69,7 +61,7 @@ int main() { std::array secret{}; secret.back() = 0x03; auto key = secp256k1::keypair::from_secret(secret); - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); if (!key) { return 1; } @@ -96,7 +88,7 @@ int main() { return 1; } auto const tweaked_public = key->public_key(); - if (!tweaked_public || !crypto::constant_time_equal(tweaked_public->xonly(), output->key)) { + if (!tweaked_public || !secure::constant_time_equal(tweaked_public->xonly(), output->key)) { return 1; } std::printf("key pair tweaked: same output key\n"); diff --git a/example/wallet_key.cpp b/example/wallet_key.cpp index 4ca19cf6..398ea568 100644 --- a/example/wallet_key.cpp +++ b/example/wallet_key.cpp @@ -9,34 +9,26 @@ // the first thing an attacker looks for, so the copies are wiped as soon as they are not needed. // tag::program[] #include -#include #include #include #include +#include +#include #include #include -#include #include #include #include #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace secp256k1 = webcpp::crypto::curves::secp256k1; namespace { -// Overwrites a secret through a volatile pointer, which the optimiser cannot drop as a dead -// store: crypto wipes its own copies of keys this way, and the program wipes its own. -void wipe(std::span secret) { - std::byte volatile* const bytes = secret.data(); - for (std::size_t i = 0; i < secret.size(); ++i) { - bytes[i] = std::byte{0}; - } -} - std::span bytes_of(std::string_view text) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return {reinterpret_cast(text.data()), text.size()}; @@ -88,12 +80,12 @@ int main() { return 1; } auto aead = crypto::ciphers::aes256_gcm::from_key(device_key); - wipe(std::as_writable_bytes(std::span(device_key))); + secure::erase_secret(device_key); if (!aead) { return 1; } auto stored = secret; - wipe(std::as_writable_bytes(std::span(secret))); + secure::erase_secret(secret); // "wallet v1" ties the ciphertext to its purpose and format version. auto const tag = aead->seal(nonce, bytes_of("wallet v1"), stored); if (!tag) { @@ -106,7 +98,7 @@ int main() { return 1; } auto restored = secp256k1::keypair::from_secret(stored); - wipe(std::as_writable_bytes(std::span(stored))); + secure::erase_secret(stored); if (!restored) { return 1; } diff --git a/example/x25519_agree.cpp b/example/x25519_agree.cpp index 3ec099d4..ec9f831f 100644 --- a/example/x25519_agree.cpp +++ b/example/x25519_agree.cpp @@ -9,10 +9,10 @@ // seeds, agree one through their X25519 forms; and a peer key of low order is refused. Prints // each public key and the shared secrets in hex. // tag::program[] -#include #include #include #include +#include #include #include @@ -20,6 +20,7 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; namespace ed25519 = webcpp::crypto::curves::ed25519; namespace x25519 = webcpp::crypto::curves::x25519; @@ -68,7 +69,7 @@ bool alice_and_bob() { // Printed here only because RFC 7748 publishes it; a program never prints a shared secret, // and derives its keys from it with a KDF. print("shared ", alice_shared->bytes()); - return crypto::constant_time_equal(alice_shared->bytes(), bob_shared->bytes()); + return secure::constant_time_equal(alice_shared->bytes(), bob_shared->bytes()); } // The same agreement from Ed25519 key pairs: one seed for signatures and key agreement. @@ -106,7 +107,7 @@ bool from_ed25519() { auto const first_shared = first_x25519->agree(*first_peer); auto const second_shared = second_x25519->agree(*second_peer); return first_shared && second_shared && - crypto::constant_time_equal(first_shared->bytes(), second_shared->bytes()); + secure::constant_time_equal(first_shared->bytes(), second_shared->bytes()); } // A peer key of low order gives an all-zero secret, which agree refuses. diff --git a/example/xchacha_seal.cpp b/example/xchacha_seal.cpp index 21c59200..5b986ea5 100644 --- a/example/xchacha_seal.cpp +++ b/example/xchacha_seal.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include @@ -23,6 +23,7 @@ #include namespace crypto = webcpp::crypto; +namespace secure = webcpp::secure; using xchacha = crypto::ciphers::xchacha20_poly1305<>; namespace { @@ -73,7 +74,7 @@ int main() { crypto::random_device device; // The conversation's key: in a real app, agreed with the contact (curves::x25519) or // derived from a key the app already keeps; here, drawn once. - crypto::secret<32> key; + secure::secret<32> key; if (!device.fill(key.writable())) { return 1; } diff --git a/include/webcpp/crypto.hpp b/include/webcpp/crypto.hpp index dbdb306e..874829ac 100644 --- a/include/webcpp/crypto.hpp +++ b/include/webcpp/crypto.hpp @@ -30,21 +30,21 @@ #include #include #include -#include #include #include -#include #include #include #include #include #include // lint-world: the system's entropy, a purpose of crypto -#include #include #include #include #include #include +#include +#include +#include #ifdef WEBCPP_CRYPTO_HAS_BEARSSL #include diff --git a/include/webcpp/crypto/async.hpp b/include/webcpp/crypto/async.hpp index 1887f759..fc87f601 100644 --- a/include/webcpp/crypto/async.hpp +++ b/include/webcpp/crypto/async.hpp @@ -10,9 +10,9 @@ `async_initiate`, so that one call works with a callback, `use_awaitable`, Cobalt's `use_op`, `deferred`, `as_tuple`, `use_future` and every other completion token. An operation that returns a value completes with `void(boost::system::error_code, T)`, the value second, and on an error - the empty object a move leaves (a `secret`, a signature or an array of zeros, a `gcm` or a key - pair without a key, whose every member refuses with `invalid_state`); one without a value completes - with `void(boost::system::error_code)`. + the empty object a move leaves (a `secure::secret`, a signature or an array of zeros, a `gcm` or + a key pair without a key, whose every member refuses with `invalid_state`); one without a value + completes with `void(boost::system::error_code)`. - The cheap functions exist on every target, for the algorithms the browser's WebCrypto has, and, on a native backend, for every AEAD and box (design D6). Each takes the executor its @@ -115,14 +115,14 @@ #include #include #include -#include #include #include -#include #include #include #include #include +#include +#include #include #include @@ -177,8 +177,8 @@ namespace detail { * (a key pair, a public key, an AEAD), which, with the bytes the views hold, are the caller's * until the completion, as the public functions say. * The signatures of the completions are the public functions'. The function's guard - * (`detail::timing_guard`) is held by the public function (the member, and the free function that - * calls it) before it calls the engine. + * (`webcpp::secure::timing_guard`, secure's guard) is held by the public function (the member, and + * the free function that calls it) before it calls the engine. * * @tparam Backend `backends::browser`. */ @@ -625,7 +625,7 @@ template auto async_from_secret(Executor const& completion_executor, std::span secret_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (!detail::is_webcrypto_keypair_v) { static_assert(detail::refused_v, "webcpp::crypto: async_from_secret takes a key pair of an algorithm " @@ -663,7 +663,7 @@ auto async_from_secret(Executor const& completion_executor, template auto async_from_key(Executor const& completion_executor, std::span key_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (!secret_key_encryption::aead::cipher && !detail::is_secretbox_v) { static_assert(detail::refused_v, "webcpp::crypto: async_from_key takes an AEAD (a " @@ -700,7 +700,7 @@ auto async_from_key(Executor const& completion_executor, std::span auto async_generate(Executor const& completion_executor, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (!detail::is_webcrypto_keypair_v) { static_assert(detail::refused_v, "webcpp::crypto: async_generate takes a key pair of an algorithm WebCrypto " @@ -744,7 +744,7 @@ auto async_seal(Executor const& completion_executor, Cipher& aead_cipher, std::span nonce_bytes, std::span associated_data_bytes, std::span data_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::refuses_async_aead_v) { detail::refuse_aead_on_asynchronous_backend< typename std::remove_cvref_t::backend_type>(); @@ -784,7 +784,7 @@ auto async_open(Executor const& completion_executor, Cipher& aead_cipher, std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::refuses_async_aead_v) { detail::refuse_aead_on_asynchronous_backend< typename std::remove_cvref_t::backend_type>(); @@ -870,7 +870,7 @@ template auto async_seal(Executor const& completion_executor, Box& keyed_box, std::span nonce_bytes, std::span data_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::refuses_async_aead_v) { detail::refuse_aead_on_asynchronous_backend< typename std::remove_cvref_t::backend_type>(); @@ -907,7 +907,7 @@ template auto async_open(Executor const& completion_executor, Box& keyed_box, std::span nonce_bytes, std::span data_bytes, std::span tag_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::refuses_async_aead_v) { detail::refuse_aead_on_asynchronous_backend< typename std::remove_cvref_t::backend_type>(); @@ -965,7 +965,7 @@ template auto async_sign(Executor const& completion_executor, Keypair const& key_pair, Scheme signing_scheme, Input const& signing_input, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::ed25519ph_on_browser_v) { detail::refuse_ed25519ph_on_asynchronous_backend< typename detail::key_backend::type>(); @@ -1038,7 +1038,7 @@ auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, Signature const& signature_value, Input const& message_bytes, curves::ed25519::public_key const& public_key, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return public_key.template async_verify( completion_executor, signing_scheme, signature_value, message_bytes, std::forward(completion_token)); @@ -1074,7 +1074,7 @@ auto async_verify(Executor const& completion_executor, eddsa_t signing_scheme, curves::ed25519::public_key const& public_key, curves::ed25519::strict_t verification_policy, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return public_key.template async_verify( completion_executor, signing_scheme, signature_value, message_bytes, verification_policy, std::forward(completion_token)); @@ -1117,7 +1117,7 @@ auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing Signature const& signature_value, Input const& digest_input, curves::ed25519::public_key const& public_key, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); } else { @@ -1157,7 +1157,7 @@ auto async_verify(Executor const& completion_executor, eddsa_prehashed_t signing curves::ed25519::public_key const& public_key, curves::ed25519::strict_t verification_policy, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); } else { @@ -1208,7 +1208,7 @@ auto async_verify(Executor const& completion_executor, ecdsa_sha256_t signing_sc Signature const& signature_value, Input const& signing_input, curves::p256::basic_public_key const& public_key, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return public_key.async_verify(completion_executor, signing_scheme, signature_value, signing_input, std::forward(completion_token)); } @@ -1274,7 +1274,7 @@ void async_verify([[maybe_unused]] Executor const& completion_executor, * `curves::x25519::public_key`, or a `curves::p256::basic_public_key` of the key pair's backend, * validated when it was made. * @param completion_token The completion token, of signature - * `void(boost::system::error_code, secret<32>)`: the shared secret, or P-256's shared x, + * `void(boost::system::error_code, secure::secret<32>)`: the shared secret, or P-256's shared x, * big-endian; on an error a secret of zeros (`invalid_state` for an empty key pair, * `weak_public_key` on X25519, `backend_failure`). * @return What the completion token's `async_result` gives. @@ -1283,7 +1283,7 @@ template requires detail::agrees_with_peer auto async_agree(Executor const& completion_executor, Keypair const& key_pair, PublicKey const& peer_public_key, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (!detail::is_x25519_keypair_v && !detail::is_p256_keypair_v) { detail::refuse_async_agree_keypair(); } else { @@ -1338,7 +1338,7 @@ template auto ciphers::gcm::async_from_key(Executor const& completion_executor, std::span key_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_from_key(completion_executor, key_bytes, std::forward(completion_token)); } @@ -1350,7 +1350,7 @@ auto ciphers::gcm::async_seal(Executor const& completion_executor, std::span associated_data_bytes, std::span data_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::seal(completion_executor, *this, nonce_bytes, associated_data_bytes, data_bytes, @@ -1372,7 +1372,7 @@ auto ciphers::gcm::async_open(Executor const& completion_executor, std::span data_bytes, std::span tag_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::open(completion_executor, *this, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes, @@ -1391,7 +1391,7 @@ template auto ciphers::basic_chacha20_poly1305::async_from_key( Executor const& completion_executor, std::span key_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1407,7 +1407,7 @@ auto ciphers::basic_chacha20_poly1305::async_seal( Executor const& completion_executor, std::span nonce_bytes, std::span associated_data_bytes, std::span data_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1425,7 +1425,7 @@ auto ciphers::basic_chacha20_poly1305::async_open( Executor const& completion_executor, std::span nonce_bytes, std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1442,7 +1442,7 @@ template auto secret_key_encryption::basic_secretbox::async_from_key( Executor const& completion_executor, std::span key_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1457,7 +1457,7 @@ template auto secret_key_encryption::basic_secretbox::async_seal( Executor const& completion_executor, std::span nonce_bytes, std::span data_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1473,7 +1473,7 @@ auto secret_key_encryption::basic_secretbox::async_open( Executor const& completion_executor, std::span nonce_bytes, std::span data_bytes, std::span tag_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1489,7 +1489,7 @@ template auto public_key_encryption::basic_box::async_seal( Executor const& completion_executor, std::span nonce_bytes, std::span data_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1505,7 +1505,7 @@ auto public_key_encryption::basic_box::async_open( Executor const& completion_executor, std::span nonce_bytes, std::span data_bytes, std::span tag_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_aead_on_asynchronous_backend(); } else { @@ -1521,7 +1521,7 @@ template auto curves::ed25519::basic_keypair::async_from_secret( Executor const& completion_executor, std::span seed_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_from_secret( completion_executor, seed_bytes, std::forward(completion_token)); } @@ -1530,7 +1530,7 @@ template template auto curves::ed25519::basic_keypair::async_generate(Executor const& completion_executor, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_generate( completion_executor, std::forward(completion_token)); } @@ -1541,7 +1541,7 @@ auto curves::ed25519::basic_keypair::async_sign(Executor const& complet Scheme signing_scheme, Input const& message_input, CompletionToken&& completion_token) const { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::ed25519ph_on_browser_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); } else { @@ -1557,7 +1557,7 @@ auto curves::ed25519::public_key::async_verify(Executor const& completion_execut Signature const& signature_value, Input const& message_input, CompletionToken&& completion_token) const { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (std::is_same_v && detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); @@ -1575,7 +1575,7 @@ auto curves::ed25519::public_key::async_verify(Executor const& completion_execut Signature const& signature_value, Input const& message_input, strict_t verify_policy, CompletionToken&& completion_token) const { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (std::is_same_v && detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); @@ -1591,7 +1591,7 @@ template auto curves::x25519::basic_keypair::async_from_secret( Executor const& completion_executor, std::span secret_bytes, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_from_secret( completion_executor, secret_bytes, std::forward(completion_token)); } @@ -1600,7 +1600,7 @@ template template auto curves::x25519::basic_keypair::async_generate(Executor const& completion_executor, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_generate( completion_executor, std::forward(completion_token)); } @@ -1611,7 +1611,7 @@ template auto curves::x25519::basic_keypair::async_agree(Executor const& completion_executor, public_key_type const& peer_key, CompletionToken&& completion_token) const { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::agree( completion_executor, *this, peer_key, std::forward(completion_token)); @@ -1626,7 +1626,7 @@ template auto curves::p256::basic_keypair::async_from_secret( Executor const& completion_executor, std::span secret_scalar, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_from_secret( completion_executor, secret_scalar, std::forward(completion_token)); } @@ -1635,7 +1635,7 @@ template template auto curves::p256::basic_keypair::async_generate(Executor const& completion_executor, CompletionToken&& completion_token) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_generate( completion_executor, std::forward(completion_token)); } @@ -1646,7 +1646,7 @@ auto curves::p256::basic_keypair::async_sign(Executor const& completion Scheme signing_scheme, Input const& signing_input, CompletionToken&& completion_token) const { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::initiate_sign(completion_executor, *this, signing_scheme, signing_input, std::forward(completion_token)); } @@ -1656,7 +1656,7 @@ template auto curves::p256::basic_keypair::async_agree(Executor const& completion_executor, basic_public_key const& peer_key, CompletionToken&& completion_token) const { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { return detail::async_engine::agree( completion_executor, *this, peer_key, std::forward(completion_token)); @@ -1672,7 +1672,7 @@ auto curves::p256::basic_public_key::async_verify( Executor const& completion_executor, [[maybe_unused]] Scheme signing_scheme, Signature const& signature_value, Input const& signing_input, CompletionToken&& completion_token) const { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (!std::is_same_v) { static_assert(detail::refused_v, "webcpp::crypto: a P-256 public key verifies crypto::ecdsa_sha256."); diff --git a/include/webcpp/crypto/backends/bearssl.hpp b/include/webcpp/crypto/backends/bearssl.hpp index 41d496ae..0a94d6d3 100644 --- a/include/webcpp/crypto/backends/bearssl.hpp +++ b/include/webcpp/crypto/backends/bearssl.hpp @@ -25,13 +25,13 @@ #else #include -#include #include -#include #include #include -#include #include +#include +#include +#include #include #include @@ -220,7 +220,7 @@ struct gcm_engine { // client request, whose memory clobber reaches a mutable object only. // NOLINTNEXTLINE(misc-const-correctness): see above std::uint32_t tag_matches = br_gcm_check_tag(&engine_state.context, tag_bytes.data()); - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&tag_matches, sizeof tag_matches); + secure::declassify(tag_matches); if (tag_matches != 1) { return error::authentication_failed; } @@ -250,7 +250,7 @@ struct gcm_engine { */ static void abandon(state& engine_state) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_BEARSSL_CANARY); - wipe_object(engine_state.context); + secure::erase_secret(std::span(&engine_state.context, 1)); br_gcm_init(&engine_state.context, &engine_state.keys.vtable, bearssl_ghash()); engine_state.sealing = false; } @@ -260,7 +260,9 @@ struct gcm_engine { * * @param engine_state Any state. */ - static void reset(state& engine_state) noexcept { wipe_object(engine_state); } + static void reset(state& engine_state) noexcept { + secure::erase_secret(std::span(&engine_state, 1)); + } }; /** @@ -376,9 +378,9 @@ struct aead_engine { // Not const: the branch below must read the variable again after the declassifying // client request, whose memory clobber reaches a mutable object only. // NOLINTNEXTLINE(misc-const-correctness): see above - bool tag_matches = constant_time_equal(computed_tag, tag_bytes); - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&tag_matches, sizeof tag_matches); - wipe(computed_tag.data(), computed_tag.size()); + bool tag_matches = secure::constant_time_equal(computed_tag, tag_bytes); + secure::declassify(tag_matches); + secure::erase_secret(computed_tag); if (!tag_matches) { return error::authentication_failed; } @@ -393,7 +395,7 @@ struct aead_engine { */ static void move(state& target_state, state& source_state) noexcept { target_state.key = source_state.key; - wipe_object(source_state.key); + secure::erase_secret(source_state.key); } /** @@ -401,7 +403,7 @@ struct aead_engine { * * @param engine_state Any state. */ - static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } + static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; /** @@ -516,7 +518,7 @@ struct p_curve_engine { * @param keyed_state A keyed state. * @param peer_key The peer's uncompressed point, valid (its public key was made by BearSSL's * decoding). - * @param output_bytes 32 bytes, a `secret<32>`'s. + * @param output_bytes 32 bytes, a `secure::secret<32>`'s. * @return Nothing; `backend_failure`, which a valid point and a scalar in range cannot cause. */ [[nodiscard]] static boost::system::result ecdh_x( @@ -531,21 +533,21 @@ struct p_curve_engine { // scalar's range and whether the product is the point at infinity, so a constant-time // checker holds it secret; on br_ec_p256_m31, the decoding alone. Whether a valid point // and a valid scalar multiply is public. - // Not const: the branch reads it again after the mark (detail/declassify.hpp's tip). + // Not const: the branch reads it again after the mark (secure::declassify's tip). // NOLINTNEXTLINE(misc-const-correctness): see above std::uint32_t multiplied_flag = bearssl_p256()->mul(shared_point.data(), shared_point.size(), keyed_state.scalar.data(), keyed_state.scalar.size(), BR_EC_secp256r1); - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&multiplied_flag, sizeof multiplied_flag); + secure::declassify(multiplied_flag); if (multiplied_flag != 1) { - wipe_object(shared_point); + secure::erase_secret(shared_point); return error::backend_failure; // a validated point and a scalar in range never fail } std::size_t x_size = 0; std::size_t const x_offset = bearssl_p256()->xoff(BR_EC_secp256r1, &x_size); std::ranges::copy(std::span(shared_point).subspan(x_offset, x_size), output_bytes.begin()); - wipe_object(shared_point); + secure::erase_secret(shared_point); return {}; } @@ -656,7 +658,7 @@ struct p_curve_engine { * Copies the secret scalar; no BearSSL call. * * @param keyed_state A keyed state. - * @param output_bytes 32 bytes, a `secret<32>`'s. + * @param output_bytes 32 bytes, a `secure::secret<32>`'s. */ static void scalar(state const& keyed_state, std::span output_bytes) noexcept { @@ -669,8 +671,8 @@ struct p_curve_engine { * @param keyed_state Any state. */ static void reset(state& keyed_state) noexcept { - wipe_object(keyed_state.scalar); - wipe_object(keyed_state.point); + secure::erase_secret(keyed_state.scalar); + secure::erase_secret(keyed_state.point); } }; diff --git a/include/webcpp/crypto/backends/ctaes.hpp b/include/webcpp/crypto/backends/ctaes.hpp index 5bde2832..b05bf753 100644 --- a/include/webcpp/crypto/backends/ctaes.hpp +++ b/include/webcpp/crypto/backends/ctaes.hpp @@ -23,7 +23,7 @@ #include #include -#include +#include #include @@ -191,11 +191,13 @@ struct block_engine { /** Copies the schedule and wipes the source. */ static void move(state& target_state, state& source_state) noexcept { target_state = source_state; - wipe_object(source_state); + secure::erase_secret(std::span(&source_state, 1)); } /** Wipes the schedule. */ - static void reset(state& engine_state) noexcept { wipe_object(engine_state); } + static void reset(state& engine_state) noexcept { + secure::erase_secret(std::span(&engine_state, 1)); + } }; /** ctaes exports no GCM, and webcpp builds none on another library's AES. */ diff --git a/include/webcpp/crypto/backends/openssl.hpp b/include/webcpp/crypto/backends/openssl.hpp index 59b7f578..878fdbf4 100644 --- a/include/webcpp/crypto/backends/openssl.hpp +++ b/include/webcpp/crypto/backends/openssl.hpp @@ -46,8 +46,9 @@ #include #include -#include #include +#include +#include #include #include @@ -92,7 +93,8 @@ namespace webcpp::crypto { * A resource that cannot allocate fails as the standard has `do_allocate` fail, by throwing, * never by returning null: libc++ and libstdc++ declare `allocate` never to return null, so an * optimiser removes any check of its result. With exceptions the adapter gives OpenSSL null for - * what it throws; without them such a resource ends the process, as `std::pmr`'s own do. + * what it throws, with the thread's DIT set again where it was set (Windows on ARM64 clears it + * after a catch); without them such a resource ends the process, as `std::pmr`'s own do. * * @return The program's resource. * @see "OpenSSL's allocations in your own memory resource", in the guide. @@ -103,6 +105,20 @@ std::pmr::memory_resource& openssl_memory_resource() noexcept; namespace webcpp::crypto::detail { +/** + * Whether the adapter keeps DIT set across a catch of its own: true where the thread's DIT is set, + * an outer guard's (OpenSSL runs inside a guarded call of crypto's) or the program's. Windows on + * ARM64 clears DIT when it resumes the thread after a catch, and OpenSSL goes on after the + * adapter's null or its swallowed `deallocate` with no guard of its own: the adapter's guard, + * engaged only then, finds DIT set and sets it again at its end, so that OpenSSL continues with + * DIT as the enclosing guard wants. It never sets DIT where it was clear. + * + * @return The guard's `guard_engaged`. + */ +inline bool openssl_adapter_keeps_dit() noexcept { + return secure::dit_is_set(); +} + /** * 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 @@ -134,6 +150,9 @@ inline void* webcpp_crypto_openssl_malloc(std::size_t byte_count, char const* /* return nullptr; } #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + // Sets DIT again after the catch where it was set (openssl_adapter_keeps_dit). + webcpp::secure::timing_guard const keep_dit{ + webcpp::crypto::detail::openssl_adapter_keeps_dit()}; try { #endif // Never null: a resource fails by throwing (openssl_memory_resource()). @@ -163,6 +182,9 @@ inline void webcpp_crypto_openssl_free(void* block_address, char const* /*file*/ std::size_t byte_count = 0; std::memcpy(&byte_count, raw_block, sizeof byte_count); #ifndef WEBCPP_CRYPTO_NO_EXCEPTIONS + // Sets DIT again after the catch where it was set (openssl_adapter_keeps_dit). + webcpp::secure::timing_guard const keep_dit{ + webcpp::crypto::detail::openssl_adapter_keeps_dit()}; try { #endif webcpp::crypto::openssl_memory_resource().deallocate(raw_block, header_size + byte_count, @@ -536,7 +558,7 @@ struct gcm_engine { ERR_clear_error(); // as openssl_failed does for every failure of a message } // The byte holds a keystream byte of the key's: wiped as key material is. - wipe(padding_byte.data(), padding_byte.size()); + secure::erase_secret(padding_byte); } /** Moves the context, leaving the source empty. */ @@ -545,12 +567,12 @@ struct gcm_engine { } // EVP_CIPHER_CTX_free cleanses the expanded key before it frees. The pointer is then - // zeroed by wipe_object: a plain store of null is dead at the end of an object's life, and - // any optimiser may drop it (GCC 15 at -O3 does). + // zeroed by secure::erase_secret: a plain store of null is dead at the end of an object's + // life, and any optimiser may drop it (GCC 15 at -O3 does). /** Frees the context. */ static void reset(state& engine_state) noexcept { EVP_CIPHER_CTX_free(engine_state.context); - wipe_object(engine_state); + secure::erase_secret(std::span(&engine_state, 1)); } }; @@ -662,11 +684,11 @@ struct aead_engine { } // EVP_CIPHER_CTX_free cleanses the key before it frees. The pointer is then zeroed by - // wipe_object, as GCM's is. + // secure::erase_secret, as GCM's is. /** Frees the context. */ static void reset(state& engine_state) noexcept { EVP_CIPHER_CTX_free(engine_state.context); - wipe_object(engine_state); + secure::erase_secret(std::span(&engine_state, 1)); } }; @@ -725,11 +747,11 @@ struct block_engine { target_state.decrypting = std::exchange(source_state.decrypting, nullptr); } - /** Frees both contexts, then zeroes the pointers by wipe_object, as GCM's are. */ + /** Frees both contexts, then zeroes the pointers by secure::erase_secret, as GCM's are. */ static void reset(state& engine_state) noexcept { EVP_CIPHER_CTX_free(engine_state.encrypting); EVP_CIPHER_CTX_free(engine_state.decrypting); - wipe_object(engine_state); + secure::erase_secret(std::span(&engine_state, 1)); } }; diff --git a/include/webcpp/crypto/backends/sodium.hpp b/include/webcpp/crypto/backends/sodium.hpp index 592cb272..f5dd7d39 100644 --- a/include/webcpp/crypto/backends/sodium.hpp +++ b/include/webcpp/crypto/backends/sodium.hpp @@ -23,10 +23,10 @@ #include #include -#include #include -#include #include +#include +#include #include // through /third_party//sodium, as webcpp::hash's header does #include @@ -187,7 +187,7 @@ inline std::uint32_t sodium_entropy_random() noexcept { std::array drawn_bytes{}; sodium_entropy_buf(drawn_bytes.data(), drawn_bytes.size()); auto const drawn_value = std::bit_cast(drawn_bytes); - wipe_object(drawn_bytes); + secure::erase_secret(drawn_bytes); return drawn_value; } @@ -273,7 +273,7 @@ class sodium_draw_watch { if (!initialised_seen.load(std::memory_order_acquire)) { std::array probe_bytes{}; auto const probed = fill_from_system(probe_bytes); - wipe_object(probe_bytes); + secure::erase_secret(probe_bytes); if (!probed) { return probed.error(); } @@ -295,16 +295,16 @@ class sodium_draw_watch { /** Whether a libsodium function that checks a secret refused: its verdict, a tag that does not match or an all-zero shared secret, which webcpp reports and so branches on, here, where it is - marked public for the constant-time checks (`WEBCPP_CRYPTO_DETAIL_DECLASSIFY`). + marked public for the constant-time checks (`secure::declassify`). @param returned_code What the function returned: 0, or -1 when it refused. @return Whether it refused. */ [[nodiscard]] inline bool sodium_refused(int returned_code) noexcept { - // Not const: the comparison reads it again after the mark (detail/declassify.hpp's tip). + // Not const: the comparison reads it again after the mark (secure::declassify's tip). // NOLINTNEXTLINE(misc-const-correctness): see above int call_verdict = returned_code; - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&call_verdict, sizeof call_verdict); + secure::declassify(call_verdict); return call_verdict != 0; } @@ -425,11 +425,11 @@ struct aead_engine { /** Moves the key; the source is wiped. */ static void move(state& target_state, state& source_state) noexcept { target_state.key = source_state.key; - wipe_object(source_state.key); + secure::erase_secret(source_state.key); } /** Wipes the key. */ - static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } + static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; /** libsodium's detached functions of a secret box family, which differ only by name. */ @@ -564,11 +564,11 @@ struct secretbox_engine { /** Moves the key; the source is wiped. */ static void move(state& target_state, state& source_state) noexcept { target_state.key = source_state.key; - wipe_object(source_state.key); + secure::erase_secret(source_state.key); } /** Wipes the key. */ - static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } + static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; } // namespace webcpp::crypto::detail @@ -586,8 +586,6 @@ struct secretbox_engine { /** Defined once libsodium's Ed25519 engines are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_ED25519 -#include - #include #include @@ -738,7 +736,7 @@ struct ed25519_engine { } /** Wipes the secret key. */ - static void reset(state& keyed_state) noexcept { wipe_object(keyed_state.secret_key); } + static void reset(state& keyed_state) noexcept { secure::erase_secret(keyed_state.secret_key); } }; /** What an Ed25519ph signer stores on libsodium: the message's SHA-512 state. */ @@ -859,7 +857,9 @@ struct ed25519ph_engine { } /** Wipes the message's state. */ - static void reset(state& begun_state) noexcept { wipe_object(begun_state.hashing); } + static void reset(state& begun_state) noexcept { + secure::erase_secret(std::span(&begun_state.hashing, 1)); + } }; } // namespace webcpp::crypto::detail @@ -935,8 +935,6 @@ struct x25519_engine { /** Defined once libsodium's box engines are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_BOX -#include - #include #include @@ -1005,7 +1003,7 @@ struct box_engine { } if (sodium_refused(calls::beforenm_call(engine_state.key.data(), peer_public_key.data(), secret_key.data()))) { - wipe_object(engine_state.key); + secure::erase_secret(engine_state.key); return error::weak_public_key; } return {}; @@ -1043,11 +1041,11 @@ struct box_engine { /** Moves the key; the source is wiped. */ static void move(state& target_state, state& source_state) noexcept { target_state.key = source_state.key; - wipe_object(source_state.key); + secure::erase_secret(source_state.key); } /** Wipes the key. */ - static void reset(state& engine_state) noexcept { wipe_object(engine_state.key); } + static void reset(state& engine_state) noexcept { secure::erase_secret(engine_state.key); } }; } // namespace webcpp::crypto::detail @@ -1093,7 +1091,7 @@ struct sealed_box_engine { int const seal_code = crypto_box_seal(output_bytes.data(), message_bytes.data(), message_bytes.size(), recipient_public_key.data()); if (auto const draw_error = seal_draws.draw_error()) { - wipe(output_bytes.data(), output_bytes.size()); + secure::erase_secret(output_bytes); return draw_error; } if (seal_code != 0) { @@ -1138,7 +1136,7 @@ struct sealed_box_engine { /** Defined once libsodium's RFC 8410 layouts are. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_RFC8410 -#include +#include #include #include @@ -1184,7 +1182,7 @@ struct sodium_rfc8410 { std::span der_bytes, std::span key_bytes) noexcept { read_canary(WEBCPP_CRYPTO_DETAIL_SODIUM_CANARY); - if (!constant_time_equal(der_bytes.template first(), prefix_bytes)) { + if (!secure::constant_time_equal(der_bytes.template first(), prefix_bytes)) { return error::invalid_encoding; } std::ranges::copy(der_bytes.template last<32>(), key_bytes.begin()); @@ -1303,8 +1301,6 @@ struct x25519_formats_engine { /** Defined once libsodium's PEM engine is. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_PEM -#include - #include #include @@ -1348,7 +1344,7 @@ struct pem_engine { sodium_base64_VARIANT_ORIGINAL)); std::ranges::copy(std::span(base64_text).first(output_characters.size()), output_characters.begin()); - wipe_object(base64_text); + secure::erase_secret(base64_text); } /** @@ -1385,8 +1381,6 @@ struct pem_engine { /** Defined once libsodium's crypto_kx engine is. */ #define WEBCPP_CRYPTO_BACKENDS_SODIUM_KX -#include - #include #include @@ -1418,7 +1412,7 @@ struct kx_engine { std::array public_key{}; int const seed_result = crypto_kx_seed_keypair(public_key.data(), secret_key.data(), seed_bytes.data()); - wipe_object(public_key); + secure::erase_secret(public_key); if (seed_result != 0) { return error::backend_failure; } diff --git a/include/webcpp/crypto/ciphers/aead.hpp b/include/webcpp/crypto/ciphers/aead.hpp index e06f320e..e28e6eba 100644 --- a/include/webcpp/crypto/ciphers/aead.hpp +++ b/include/webcpp/crypto/ciphers/aead.hpp @@ -26,11 +26,11 @@ #include #include #include -#include -#include #include #include // crypto::from_key, which serves its from_key (design R23) #include // its free seal and open (design D11) +#include +#include #include #include @@ -262,7 +262,7 @@ class basic_chacha20_poly1305 { */ [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { // WebCrypto has no such construction: the refusal names a native backend (design D6). detail::refuse_aead_on_asynchronous_backend(); @@ -373,7 +373,7 @@ class basic_chacha20_poly1305 { std::span nonce_bytes, std::span associated_data_bytes, std::span data_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { // WebCrypto has no such construction: the refusal names a native backend (design D6). detail::refuse_aead_on_asynchronous_backend(); @@ -388,7 +388,7 @@ class basic_chacha20_poly1305 { auto const seal_result = engine::seal(state_, nonce_bytes, associated_data_bytes, data_bytes, tag_bytes); if (!seal_result) { - detail::wipe(data_bytes.data(), data_bytes.size()); + secure::erase_secret(data_bytes); return seal_result.error(); } return tag_bytes; @@ -443,7 +443,7 @@ class basic_chacha20_poly1305 { std::span nonce_bytes, std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { // WebCrypto has no such construction: the refusal names a native backend (design D6). detail::refuse_aead_on_asynchronous_backend(); @@ -460,7 +460,7 @@ class basic_chacha20_poly1305 { auto const open_result = engine::open(state_, nonce_bytes, associated_data_bytes, data_bytes, expected_tag); if (!open_result) { - detail::wipe(data_bytes.data(), data_bytes.size()); + secure::erase_secret(data_bytes); return open_result.error(); } return {}; diff --git a/include/webcpp/crypto/ciphers/aes.hpp b/include/webcpp/crypto/ciphers/aes.hpp index 98d4b30f..056cf8db 100644 --- a/include/webcpp/crypto/ciphers/aes.hpp +++ b/include/webcpp/crypto/ciphers/aes.hpp @@ -24,8 +24,8 @@ #include #include #include -#include #include +#include #include @@ -200,7 +200,7 @@ class basic_aes { */ [[nodiscard]] boost::system::result encrypt( std::span block_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -219,7 +219,7 @@ class basic_aes { */ [[nodiscard]] boost::system::result decrypt( std::span block_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -281,7 +281,7 @@ class aes128 : public detail::basic_aes<16, Backend> { */ [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::basic_aes<16, Backend>::template keyed_as(key_bytes); } @@ -307,7 +307,7 @@ class aes192 : public detail::basic_aes<24, Backend> { */ [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::basic_aes<24, Backend>::template keyed_as(key_bytes); } @@ -333,7 +333,7 @@ class aes256 : public detail::basic_aes<32, Backend> { */ [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return detail::basic_aes<32, Backend>::template keyed_as(key_bytes); } diff --git a/include/webcpp/crypto/ciphers/gcm.hpp b/include/webcpp/crypto/ciphers/gcm.hpp index d2596ee9..3146f121 100644 --- a/include/webcpp/crypto/ciphers/gcm.hpp +++ b/include/webcpp/crypto/ciphers/gcm.hpp @@ -25,11 +25,11 @@ #include #include #include -#include -#include #include #include // crypto::from_key, which serves its from_key (design R23) #include // its free seal and open (design D11) +#include +#include #include #include @@ -169,7 +169,7 @@ class gcm { */ [[nodiscard]] static boost::system::result from_key( std::span key_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: from_key on this backend completes asynchronously: call " "async_from_key."); @@ -223,7 +223,7 @@ class gcm { * @param moved_source The source, empty afterwards. */ gcm(gcm&& moved_source) noexcept : keyed_(std::exchange(moved_source.keyed_, false)) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (keyed_) { moved_source.abandon_message(); engine::move(state_, moved_source.state_); @@ -239,7 +239,7 @@ class gcm { * @return This object. */ gcm& operator=(gcm&& moved_source) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (this != &moved_source) { engine::reset(state_); keyed_ = std::exchange(moved_source.keyed_, false); @@ -280,7 +280,7 @@ class gcm { std::span nonce_bytes, std::span associated_data_bytes, std::span data_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( !detail::asynchronous_backend_v, "webcpp::crypto: seal on this backend completes asynchronously: call async_seal."); @@ -301,7 +301,7 @@ class gcm { if (!tag_result) { // A message without a tag is not to be sent: data is zeroed, and nothing of the // failed message stays in the context, as after an incremental one. - detail::wipe(data_bytes.data(), data_bytes.size()); + secure::erase_secret(data_bytes); engine::abandon(state_); return tag_result.error(); } @@ -357,7 +357,7 @@ class gcm { std::span nonce_bytes, std::span associated_data_bytes, std::span data_bytes, std::span tag_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( !detail::asynchronous_backend_v, "webcpp::crypto: open on this backend completes asynchronously: call async_open."); @@ -379,7 +379,7 @@ class gcm { auto const tag_check_result = open_result ? engine::check(state_, expected_tag) : open_result; if (!tag_check_result) { - detail::wipe(data_bytes.data(), data_bytes.size()); + secure::erase_secret(data_bytes); engine::abandon(state_); return tag_check_result.error(); } @@ -432,7 +432,7 @@ class gcm { [[nodiscard]] boost::system::result begin_seal( std::span nonce_bytes, std::span associated_data_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -466,7 +466,7 @@ class gcm { * `backend_failure`, which ends it. */ [[nodiscard]] boost::system::result update(std::span data_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; auto const phase_result = require_phase(phase::sealing); if (!phase_result) { return phase_result.error(); @@ -477,7 +477,7 @@ class gcm { } auto const run_result = engine::run(state_, data_bytes); if (!run_result) { - detail::wipe(data_bytes.data(), data_bytes.size()); + secure::erase_secret(data_bytes); abandon(); return run_result.error(); } @@ -492,7 +492,7 @@ class gcm { * `backend_failure`, which ends the seal too. */ [[nodiscard]] boost::system::result result() noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; auto const phase_result = require_phase(phase::sealing); if (!phase_result) { return phase_result.error(); @@ -523,7 +523,7 @@ class gcm { [[nodiscard]] boost::system::result begin_open( std::span nonce_bytes, std::span associated_data_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -563,7 +563,7 @@ class gcm { */ [[nodiscard]] boost::system::result authenticate( std::span ciphertext_piece) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; auto const phase_result = require_phase(phase::authenticating); if (!phase_result) { return phase_result.error(); @@ -579,7 +579,7 @@ class gcm { (std::min)(scratch_size, ciphertext_piece.size() - piece_start); std::copy_n(ciphertext_piece.data() + piece_start, block_size, scratch_bytes.data()); auto const run_result = engine::run(state_, std::span(scratch_bytes).first(block_size)); - detail::wipe(scratch_bytes.data(), block_size); + secure::erase_secret(std::span(scratch_bytes).first(block_size)); if (!run_result) { abandon(); return run_result.error(); @@ -600,7 +600,7 @@ class gcm { */ [[nodiscard]] boost::system::result verify( std::span tag_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; auto const phase_result = require_phase(phase::authenticating); if (!phase_result) { return phase_result.error(); @@ -643,7 +643,7 @@ class gcm { * the message; `backend_failure`, which ends it. */ [[nodiscard]] boost::system::result decrypt(std::span data_piece) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; auto const phase_result = require_phase(phase::decrypting); if (!phase_result) { return phase_result.error(); @@ -654,7 +654,7 @@ class gcm { } auto const run_result = engine::run(state_, data_piece); if (!run_result) { - detail::wipe(data_piece.data(), data_piece.size()); + secure::erase_secret(data_piece); abandon(); return run_result.error(); } @@ -670,7 +670,7 @@ class gcm { * which ends the message too. */ [[nodiscard]] boost::system::result end_open() noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; auto const phase_result = require_phase(phase::decrypting); if (!phase_result) { return phase_result.error(); @@ -750,7 +750,7 @@ class gcm { // No message is in progress; the kept nonce is wiped and the counters zeroed. void end_message() noexcept { phase_ = phase::none; - detail::wipe(nonce_.data(), nonce_.size()); + secure::erase_secret(nonce_); nonce_size_ = 0; message_bytes_ = 0; decrypted_bytes_ = 0; diff --git a/include/webcpp/crypto/constant_time_equal.hpp b/include/webcpp/crypto/constant_time_equal.hpp deleted file mode 100644 index 233dec67..00000000 --- a/include/webcpp/crypto/constant_time_equal.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// 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) - -/** - `constant_time_equal`, the constant-time comparison of tags and MACs, Boost.Hash2's included. -*/ -#ifndef WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP -#define WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP - -#include - -#include - -#include - -#include -#include -#include - -namespace webcpp::crypto { - -/** - * Whether two byte sequences are equal, in a time that does not depend on their contents. - * - * Every byte is read, and no branch or index depends on one: the XOR of each pair is - * accumulated with OR in a volatile local, read once after the loop, and reduced to one bit - * without a branch, as BearSSL's tag check does. Sizes are public: spans of different sizes - * compare unequal without reading their contents. On 64-bit ARM the comparison runs with DIT - * set where the CPU has it, and leaves the thread's DIT as it found it. - * - * @param first_operand The first sequence, a tag or a MAC. - * @param second_operand The second. - * @return Whether they have the same size and the same bytes. - */ -[[nodiscard]] inline bool constant_time_equal( - std::span first_operand, - std::span second_operand) noexcept { - detail::timing_guard const timing_scope; - if (first_operand.size() != second_operand.size()) { - return false; - } - unsigned volatile accumulated_difference = 0; - for (std::size_t byte_index = 0; byte_index < first_operand.size(); ++byte_index) { - accumulated_difference = - accumulated_difference | - static_cast(first_operand[byte_index] ^ second_operand[byte_index]); - } - unsigned const total_difference = accumulated_difference; - // all is at most 255: all - 1 wraps to the type's maximum only when all is 0. - return (((total_difference - 1U) >> 8U) & 1U) != 0; -} - -/** - * Whether two digests are equal, in a time that does not depend on their contents. - * - * Boost.Hash2's own `operator==` is `memcmp`, which is not constant time: a MAC is checked - * with this one. - * - * @tparam N The digests' size in bytes. - * @param first_operand The first digest. - * @param second_operand The second. - * @return Whether every byte is equal. - */ -template -[[nodiscard]] bool constant_time_equal(boost::hash2::digest const& first_operand, - boost::hash2::digest const& second_operand) noexcept { - detail::timing_guard const timing_scope; - return constant_time_equal(std::span(first_operand.data(), N), - std::span(second_operand.data(), N)); -} - -} // namespace webcpp::crypto - -#endif // WEBCPP_CRYPTO_CONSTANT_TIME_EQUAL_HPP diff --git a/include/webcpp/crypto/curves/ed25519.hpp b/include/webcpp/crypto/curves/ed25519.hpp index b9cfd8e0..a2506793 100644 --- a/include/webcpp/crypto/curves/ed25519.hpp +++ b/include/webcpp/crypto/curves/ed25519.hpp @@ -34,14 +34,14 @@ #include #include #include -#include #include #include #include // lint-world: random_device draws generate()'s seed -#include #include #include #include // webcpp::hash::sha2_512, Ed25519ph's hash (design D1) +#include +#include #include @@ -255,7 +255,7 @@ class public_key { [[maybe_unused]] Scheme signing_scheme, Signature const& signature_value, Input const& message_input, [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(std::is_same_v, "webcpp::crypto: an Ed25519 public key verifies crypto::eddsa or " "crypto::eddsa_prehashed."); @@ -302,7 +302,7 @@ class public_key { [[maybe_unused]] eddsa_prehashed_t signing_scheme, Signature const& signature_value, Input const& digest_input, [[maybe_unused]] Policy verify_policy = Policy{}) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); } @@ -405,7 +405,7 @@ class public_key { */ template > [[nodiscard]] boost::system::result to_x25519() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; std::array converted_bytes{}; auto const engine_done = detail::ed25519_engine::to_x25519_public(bytes_, @@ -474,7 +474,7 @@ class basic_keypair { */ [[nodiscard]] static boost::system::result from_secret( std::span seed_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: from_secret on this backend completes asynchronously: call " "async_from_secret."); @@ -503,7 +503,7 @@ class basic_keypair { * none; `backend_failure`. */ [[nodiscard]] static boost::system::result generate() noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: generate on this backend completes asynchronously: call " "async_generate."); @@ -511,7 +511,7 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - crypto::secret seed_secret; + secure::secret seed_secret; auto const entropy_drawn = random_device().fill(seed_secret.writable()); // lint-world: the seed if (!entropy_drawn) { @@ -609,7 +609,7 @@ class basic_keypair { * @return The public key; `invalid_state` moved from. */ [[nodiscard]] boost::system::result public_key() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -624,12 +624,12 @@ class basic_keypair { * * @return 32 secret bytes; `invalid_state` moved from. */ - [[nodiscard]] boost::system::result> secret() const noexcept { - detail::timing_guard const timing_scope; + [[nodiscard]] boost::system::result> secret() const noexcept { + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } - crypto::secret seed_secret; + secure::secret seed_secret; engine::seed(state_, seed_secret.writable()); return seed_secret; } @@ -659,7 +659,7 @@ class basic_keypair { template [[nodiscard]] boost::system::result> sign( [[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (std::is_same_v && detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); @@ -734,7 +734,7 @@ class basic_keypair { * @return The X25519 key pair; `invalid_state` moved from; `backend_failure`. */ [[nodiscard]] boost::system::result> to_x25519() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; using converted_type = x25519::basic_keypair; static_assert(supports_v, "webcpp::crypto: to_x25519: this backend has no X25519; libsodium has both."); @@ -745,7 +745,7 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - crypto::secret converted_secret; + secure::secret converted_secret; auto const engine_done = engine::x25519_secret(state_, converted_secret.writable()); if (!engine_done) { return engine_done.error(); @@ -836,7 +836,7 @@ class prehashed_signer { * @return The signer, ready for the message's pieces; `backend_failure`. */ [[nodiscard]] static boost::system::result begin() noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; prehashed_signer begun_hash; auto const begin_result = engine::begin(begun_hash.state_); if (!begin_result) { @@ -889,7 +889,7 @@ class prehashed_signer { */ [[nodiscard]] boost::system::result update( std::span piece_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!begun_) { return error::invalid_state; } @@ -907,7 +907,7 @@ class prehashed_signer { */ [[nodiscard]] boost::system::result<::webcpp::crypto::curves::ed25519::signature> sign( basic_keypair const& key_pair) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!begun_ || !key_pair.keyed_) { return error::invalid_state; } @@ -936,7 +936,7 @@ class prehashed_signer { [[nodiscard]] boost::system::result verify( Signature const& signature_value, ::webcpp::crypto::curves::ed25519::public_key const& verifying_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; auto const& signature_bytes = detail::checked_signature_bytes<::webcpp::crypto::curves::ed25519::signature, detail::ed25519ph_verifier_t>(signature_value); @@ -995,7 +995,7 @@ template , class Signature, [[maybe_unused]] eddsa_t signing_scheme, Signature const& signature_value, Input const& message_input, curves::ed25519::public_key const& public_key, [[maybe_unused]] Policy verify_policy = Policy{}) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); @@ -1040,7 +1040,7 @@ template , class Signature, [[maybe_unused]] eddsa_prehashed_t signing_scheme, Signature const& signature_value, Input const& digest_input, curves::ed25519::public_key const& public_key, [[maybe_unused]] Policy verify_policy = Policy{}) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if constexpr (detail::asynchronous_backend_v) { detail::refuse_ed25519ph_on_asynchronous_backend(); } @@ -1073,7 +1073,7 @@ template [[nodiscard]] auto to_x25519(Value const& converted_value) noexcept requires requires(Value const& candidate_value) { candidate_value.to_x25519(); } { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return converted_value.to_x25519(); } diff --git a/include/webcpp/crypto/curves/ed25519/formats.hpp b/include/webcpp/crypto/curves/ed25519/formats.hpp index 532cb388..26ca3063 100644 --- a/include/webcpp/crypto/curves/ed25519/formats.hpp +++ b/include/webcpp/crypto/curves/ed25519/formats.hpp @@ -23,9 +23,9 @@ #include #include #include -#include #include -#include +#include +#include #include @@ -133,7 +133,7 @@ template > template > [[nodiscard]] boost::system::result decode_spki( std::span spki_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (spki_bytes.size() != max_spki_size) { return error::invalid_encoding; } @@ -186,11 +186,11 @@ template > template > [[nodiscard]] boost::system::result> decode_pkcs8( std::span pkcs8_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (pkcs8_bytes.size() != max_pkcs8_size) { return error::invalid_encoding; } - secret<32> seed_secret; + secure::secret<32> seed_secret; auto const decoded_key = detail::ed25519_formats_engine::decode_pkcs8( pkcs8_bytes.first(), seed_secret.writable()); diff --git a/include/webcpp/crypto/curves/p256.hpp b/include/webcpp/crypto/curves/p256.hpp index 859838e4..3da1b771 100644 --- a/include/webcpp/crypto/curves/p256.hpp +++ b/include/webcpp/crypto/curves/p256.hpp @@ -31,12 +31,12 @@ #include #include #include -#include #include #include #include // lint-world: random_device draws generate()'s scalar -#include #include +#include +#include #include @@ -163,7 +163,7 @@ class basic_public_key { */ [[nodiscard]] static boost::system::result from_bytes( std::span uncompressed_point) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (uncompressed_point.size() != public_key_size || uncompressed_point[0] != 0x04) { return error::invalid_public_key; } @@ -181,7 +181,7 @@ class basic_public_key { [[nodiscard]] static boost::system::result from_coordinates( std::span x_coordinate, std::span y_coordinate) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; std::array point_bytes{0x04}; std::ranges::copy(x_coordinate, point_bytes.begin() + 1); std::ranges::copy(y_coordinate, point_bytes.begin() + 1 + coordinate_size); @@ -222,7 +222,7 @@ class basic_public_key { [[nodiscard]] boost::system::result verify([[maybe_unused]] Scheme signing_scheme, Signature const& signature_value, Input const& signing_input) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(std::is_same_v, "webcpp::crypto: a P-256 public key verifies crypto::ecdsa_sha256."); static_assert(!detail::asynchronous_backend_v, @@ -339,7 +339,7 @@ class basic_keypair { */ [[nodiscard]] static boost::system::result from_secret( std::span secret_scalar) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: from_secret on this backend completes asynchronously: call " "async_from_secret."); @@ -372,7 +372,7 @@ class basic_keypair { * none; `backend_failure`. */ [[nodiscard]] static boost::system::result generate() noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: generate on this backend completes asynchronously: call " "async_generate."); @@ -380,7 +380,7 @@ class basic_keypair { // Never compiled into a program: the assertion above stopped the build. return error::backend_failure; } else { - crypto::secret scalar_bytes; + secure::secret scalar_bytes; random_device random_source; // lint-world: the scalar do { if (!random_source.fill(scalar_bytes.writable())) { @@ -494,11 +494,11 @@ class basic_keypair { * * @return 32 secret bytes, big-endian; `invalid_state` moved from. */ - [[nodiscard]] boost::system::result> secret() const noexcept { + [[nodiscard]] boost::system::result> secret() const noexcept { if (!keyed_) { return error::invalid_state; } - crypto::secret scalar_bytes; + secure::secret scalar_bytes; engine::scalar(state_, scalar_bytes.writable()); return scalar_bytes; } @@ -521,7 +521,7 @@ class basic_keypair { template [[nodiscard]] boost::system::result> sign( [[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(std::is_same_v, "webcpp::crypto: a P-256 key signs with crypto::ecdsa_sha256."); static_assert(!detail::asynchronous_backend_v, @@ -586,9 +586,9 @@ class basic_keypair { * @return 32 secret bytes, big-endian; `invalid_state` moved from; `backend_failure`, which a * valid key pair and a valid public key cannot cause. */ - [[nodiscard]] boost::system::result> agree( + [[nodiscard]] boost::system::result> agree( basic_public_key const& peer_key) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( !detail::asynchronous_backend_v, "webcpp::crypto: agree on this backend completes asynchronously: call async_agree."); @@ -599,7 +599,7 @@ class basic_keypair { if (!keyed_) { return error::invalid_state; } - crypto::secret shared_bytes; + secure::secret shared_bytes; auto const derive_result = engine::ecdh_x( state_, detail::p_curve_access::point(peer_key), shared_bytes.writable()); if (!derive_result) { @@ -626,7 +626,7 @@ class basic_keypair { * @param completion_executor The executor the completion is posted to. * @param peer_key The peer's public key, validated when it was made. * @param completion_token The completion token, of signature - * `void(boost::system::error_code, crypto::secret<32>)`: the shared x, big-endian; on an error + * `void(boost::system::error_code, secure::secret<32>)`: the shared x, big-endian; on an error * a secret of zeros (`invalid_state`, `backend_failure`). * @return What the completion token's `async_result` gives. */ @@ -687,7 +687,7 @@ using keypair = basic_keypair<>; template > [[nodiscard]] boost::system::result to_der( ecdsa_signature const& signature_value, std::span der_output) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; using engine = detail::p_curve_engine; if (der_output.size() < max_der_size) { return error::invalid_input_size; @@ -715,7 +715,7 @@ template > template > [[nodiscard]] boost::system::result from_der( std::span der_signature) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; using engine = detail::p_curve_engine; if (der_signature.empty()) { return error::invalid_signature; @@ -804,7 +804,7 @@ template [[maybe_unused]] ecdsa_sha256_t signing_scheme, Signature const& signature_value, Input const& signing_input, curves::p256::basic_public_key const& public_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(!detail::asynchronous_backend_v, "webcpp::crypto: verify on this backend completes asynchronously: call " "async_verify."); diff --git a/include/webcpp/crypto/curves/p256/formats.hpp b/include/webcpp/crypto/curves/p256/formats.hpp index a0c562f8..aba6cac0 100644 --- a/include/webcpp/crypto/curves/p256/formats.hpp +++ b/include/webcpp/crypto/curves/p256/formats.hpp @@ -18,14 +18,14 @@ #include -#include #include #include -#include #include -#include #include -#include +#include +#include +#include +#include #include @@ -112,10 +112,10 @@ template template > [[nodiscard]] boost::system::result> decode_spki( std::span spki_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; constexpr std::size_t prefix_size = detail::p256_spki_prefix.size(); if (spki_bytes.size() != max_spki_size || - !constant_time_equal(spki_bytes.first(prefix_size), detail::p256_spki_prefix)) { + !secure::constant_time_equal(spki_bytes.first(prefix_size), detail::p256_spki_prefix)) { return error::invalid_encoding; } auto decoded_key = basic_public_key::from_bytes(spki_bytes.subspan(prefix_size)); @@ -138,7 +138,7 @@ template > * @tparam Backend The key pair's backend. * @param key_pair The key pair. * @param output_bytes At least `max_pkcs8_size` bytes; nothing is written on an error. They hold - * the secret scalar after the call: a `secret`'s keeps them wiped. + * the secret scalar after the call: a `secure::secret`'s keeps them wiped. * @return The number of bytes written, `max_pkcs8_size`; `invalid_state` moved from; * `invalid_input_size` when `output_bytes` is shorter than `max_pkcs8_size`. */ @@ -176,18 +176,18 @@ template template > [[nodiscard]] boost::system::result> decode_pkcs8( std::span pkcs8_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; constexpr std::size_t prefix_size = detail::p256_pkcs8_prefix.size(); constexpr std::size_t infix_at = prefix_size + secret_key_size; constexpr std::size_t point_at = infix_at + detail::p256_pkcs8_infix.size(); if (pkcs8_bytes.size() != max_pkcs8_size || - !constant_time_equal(pkcs8_bytes.first(prefix_size), detail::p256_pkcs8_prefix) || - !constant_time_equal(pkcs8_bytes.subspan(infix_at, detail::p256_pkcs8_infix.size()), - detail::p256_pkcs8_infix)) { + !secure::constant_time_equal(pkcs8_bytes.first(prefix_size), detail::p256_pkcs8_prefix) || + !secure::constant_time_equal(pkcs8_bytes.subspan(infix_at, detail::p256_pkcs8_infix.size()), + detail::p256_pkcs8_infix)) { return error::invalid_encoding; } // The scalar's copy is a secret, wiped when it goes, on every path. - secret scalar_bytes; + secure::secret scalar_bytes; std::ranges::copy(pkcs8_bytes.subspan(prefix_size, secret_key_size), scalar_bytes.writable().begin()); auto made_pair = basic_keypair::from_secret(scalar_bytes.bytes()); @@ -202,11 +202,11 @@ template > return public_point.error(); } // The point is d * G, computed from the secret; whether the input's is the same is public. - // Not const: the branch reads it again after the mark (detail/declassify.hpp's tip). + // Not const: the branch reads it again after the mark (secure::declassify's tip). // NOLINTNEXTLINE(misc-const-correctness): see above - bool is_same = constant_time_equal(public_point.unsafe_value().uncompressed(), - pkcs8_bytes.subspan(point_at)); - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&is_same, sizeof is_same); + bool is_same = secure::constant_time_equal(public_point.unsafe_value().uncompressed(), + pkcs8_bytes.subspan(point_at)); + secure::declassify(is_same); if (!is_same) { return error::invalid_encoding; } diff --git a/include/webcpp/crypto/curves/secp256k1.hpp b/include/webcpp/crypto/curves/secp256k1.hpp index 4ea4addf..b230a0b6 100644 --- a/include/webcpp/crypto/curves/secp256k1.hpp +++ b/include/webcpp/crypto/curves/secp256k1.hpp @@ -28,16 +28,16 @@ #include #include -#include #include #include -#include -#include #include #include #include // lint-world: the context's randomisation and generate()'s key -#include #include +#include +#include +#include +#include #ifdef WEBCPP_HASH_HAS_XKCP #include // crypto::ecdsa_keccak256_recoverable's hash of a message @@ -177,7 +177,7 @@ struct secp256k1_access { }; // NOLINTBEGIN(bugprone-signed-bitwise): libsecp256k1's macros shift a signed constant -#if defined(WEBCPP_CRYPTO_DETAIL_CT_VALGRIND) || defined(WEBCPP_CRYPTO_DETAIL_CT_MSAN) +#if defined(WEBCPP_SECURE_CT_VALGRIND) || defined(WEBCPP_SECURE_CT_MSAN) /** * The flags of a context that signs and verifies, under a constant-time checker: * `SECP256K1_CONTEXT_DECLASSIFY`, so that libsecp256k1 marks its own public values public (a @@ -195,26 +195,27 @@ inline constexpr unsigned secp256k1_compressed = SECP256K1_EC_COMPRESSED; /** The flag of the SEC1 uncompressed form. */ inline constexpr unsigned secp256k1_uncompressed = SECP256K1_EC_UNCOMPRESSED; + // NOLINTEND(bugprone-signed-bitwise) /** * Whether libsecp256k1 accepted: what it returned on a secret, marked public for the - * constant-time checks (`WEBCPP_CRYPTO_DETAIL_DECLASSIFY`) where webcpp branches on it, as its + * constant-time checks (`secure::declassify`) where webcpp branches on it, as its * `ctime_tests.c` marks each verdict. * * @param returned_code What the function returned: 1, or 0 when it refused. * @return Whether it accepted. */ [[nodiscard]] inline bool secp256k1_accepted(int returned_code) noexcept { - // Not const: the comparison reads it again after the mark (detail/declassify.hpp's tip). + // Not const: the comparison reads it again after the mark (secure::declassify's tip). // NOLINTNEXTLINE(misc-const-correctness): see above int accepted_verdict = returned_code; - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&accepted_verdict, sizeof accepted_verdict); + secure::declassify(accepted_verdict); return accepted_verdict != 0; } /** - * A key pair's public key, marked public (`WEBCPP_CRYPTO_DETAIL_DECLASSIFY`): libsecp256k1 + * A key pair's public key, marked public (`secure::declassify`): libsecp256k1 * derives it from the secret and marks it public only where it loads the key pair itself, and * its `ctime_tests.c` marks a key pair's public key by hand where it reads one. * @@ -227,7 +228,7 @@ inline constexpr unsigned secp256k1_uncompressed = SECP256K1_EC_UNCOMPRESSED; secp256k1_pubkey public_point{}; // libsecp256k1 returns 1 always: a key pair holds its public key. static_cast(secp256k1_keypair_pub(secp_context, &public_point, &key_pair)); - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&public_point, sizeof public_point); + secure::declassify(public_point); return public_point; } @@ -252,7 +253,7 @@ struct secp256k1_secret { std::array bytes{}; /** Wipes the bytes. */ - ~secp256k1_secret() { wipe(bytes.data(), bytes.size()); } + ~secp256k1_secret() { secure::erase_secret(bytes); } }; /** @@ -282,7 +283,7 @@ class secp256k1_workspace { * after the last, so that the workspace is zero when the function returns, wherever it * starts. */ - ~secp256k1_workspace() { wipe(lent_bytes_.data(), lent_bytes_.size()); } + ~secp256k1_workspace() { secure::erase_secret(lent_bytes_); } /** * The next array of `element_count` elements of `T`, aligned to `alignof(std::max_align_t)`. @@ -712,7 +713,7 @@ class public_key { template > [[nodiscard]] static boost::system::result from_bytes( std::span encoded_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -732,7 +733,7 @@ class public_key { */ [[nodiscard]] std::array> compressed() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return encoded>( webcpp::crypto::detail::secp256k1_compressed); } @@ -744,7 +745,7 @@ class public_key { */ [[nodiscard]] std::array> uncompressed() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return encoded>( webcpp::crypto::detail::secp256k1_uncompressed); } @@ -756,7 +757,7 @@ class public_key { * @return 32 bytes. */ [[nodiscard]] std::array xonly() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); auto const xonly_key = webcpp::crypto::detail::secp256k1_xonly_of(point_value_); @@ -792,7 +793,7 @@ class public_key { [[nodiscard]] boost::system::result verify([[maybe_unused]] Scheme signing_scheme, Signature const& signature_value, Input const& signing_input) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); constexpr bool is_ecdsa = std::is_same_v; @@ -827,7 +828,7 @@ class public_key { */ [[nodiscard]] friend bool operator==(public_key const& left_key, public_key const& right_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return compare(left_key, right_key) == 0; } @@ -840,7 +841,7 @@ class public_key { */ [[nodiscard]] friend std::strong_ordering operator<=>(public_key const& left_key, public_key const& right_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return compare(left_key, right_key) <=> 0; } @@ -933,7 +934,7 @@ class basic_keypair { [[nodiscard]] static boost::system::result from_secret( std::span secret_bytes, std::pmr::memory_resource* memory_resource = std::pmr::get_default_resource()) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (secret_bytes.size() != secret_key_size) { return error::invalid_key_size; } @@ -978,9 +979,9 @@ class basic_keypair { */ [[nodiscard]] static boost::system::result generate( std::pmr::memory_resource* memory_resource = std::pmr::get_default_resource()) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; for (int draw_count = 0; draw_count < max_draws; ++draw_count) { - crypto::secret secret_key; + secure::secret secret_key; auto const entropy_drawn = random_device().fill(secret_key.writable()); // lint-world: the secret key if (!entropy_drawn) { @@ -1006,7 +1007,7 @@ class basic_keypair { memory_(moved_source.memory_), keypair_(moved_source.keypair_), keyed_(std::exchange(moved_source.keyed_, false)) { - webcpp::crypto::detail::wipe_object(moved_source.keypair_); + secure::erase_secret(std::span(&moved_source.keypair_, 1)); } /** @@ -1022,7 +1023,7 @@ class basic_keypair { memory_ = moved_source.memory_; keypair_ = moved_source.keypair_; keyed_ = std::exchange(moved_source.keyed_, false); - webcpp::crypto::detail::wipe_object(moved_source.keypair_); + secure::erase_secret(std::span(&moved_source.keypair_, 1)); } return *this; } @@ -1042,7 +1043,7 @@ class basic_keypair { * @return The public key; `invalid_state` moved from. */ [[nodiscard]] boost::system::result public_key() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -1060,13 +1061,13 @@ class basic_keypair { * * @return 32 secret bytes, big-endian; `invalid_state` moved from. */ - [[nodiscard]] boost::system::result> secret() const noexcept { - detail::timing_guard const timing_scope; + [[nodiscard]] boost::system::result> secret() const noexcept { + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); - crypto::secret secret_key; + secure::secret secret_key; // libsecp256k1 returns 1 always: a key pair holds its secret key. static_cast(secp256k1_keypair_sec(context_, secret_key.writable().data(), &keypair_)); return secret_key; @@ -1102,7 +1103,7 @@ class basic_keypair { [[nodiscard]] boost::system::result< webcpp::crypto::detail::signature_of_t> sign([[maybe_unused]] Scheme signing_scheme, Input const& signing_input) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; constexpr bool has_scheme = std::is_same_v || std::is_same_v || std::is_same_v || @@ -1150,7 +1151,7 @@ class basic_keypair { [[nodiscard]] boost::system::result sign( [[maybe_unused]] ecdsa_sha256_t signing_scheme, Input const& signing_input, std::span extra_entropy) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; detail::check_input(); if constexpr (detail::input_valid_v) { webcpp::crypto::detail::secp256k1_secret nonce_data; @@ -1178,7 +1179,7 @@ class basic_keypair { [[nodiscard]] boost::system::result sign( [[maybe_unused]] schnorr_t signing_scheme, Input const& message_input, std::span auxiliary_random_bytes) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; detail::check_input(); if constexpr (detail::input_valid_v) { return signed_schnorr(detail::message_bytes(message_input), auxiliary_random_bytes); @@ -1200,9 +1201,9 @@ class basic_keypair { * @return 32 secret bytes; `invalid_state` moved from; `backend_failure`, which a valid key * pair and a valid public key cannot cause. */ - [[nodiscard]] boost::system::result> agree( + [[nodiscard]] boost::system::result> agree( public_key_type const& peer_key) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return ecdh_secret<32>(peer_key, webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_x); } @@ -1215,9 +1216,9 @@ class basic_keypair { * @return 32 secret bytes; `invalid_state` moved from; `backend_failure`, which a valid key * pair and a valid public key cannot cause. */ - [[nodiscard]] boost::system::result> agree_hashed( + [[nodiscard]] boost::system::result> agree_hashed( public_key_type const& peer_key) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return ecdh_secret<32>(peer_key, nullptr); } @@ -1228,9 +1229,9 @@ class basic_keypair { * @return 65 secret bytes; `invalid_state` moved from; `backend_failure`, which a valid key * pair and a valid public key cannot cause. */ - [[nodiscard]] boost::system::result> agree_point( + [[nodiscard]] boost::system::result> agree_point( public_key_type const& peer_key) const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return ecdh_secret<65>(peer_key, webcpp::crypto::detail::webcpp_crypto_detail_secp256k1_copy_point); } @@ -1251,7 +1252,7 @@ class basic_keypair { */ [[nodiscard]] boost::system::result tweak_xonly( std::span tweak_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; if (!keyed_) { return error::invalid_state; } @@ -1401,7 +1402,7 @@ class basic_keypair { * @return `N` secret bytes; `invalid_state`; `backend_failure`. */ template - [[nodiscard]] boost::system::result> ecdh_secret( + [[nodiscard]] boost::system::result> ecdh_secret( public_key_type const& peer_key, secp256k1_ecdh_hash_function hash_function) const noexcept { if (!keyed_) { @@ -1410,7 +1411,7 @@ class basic_keypair { webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); webcpp::crypto::detail::secp256k1_secret secret_bytes; secp256k1_keypair_sec(context_, secret_bytes.bytes.data(), &keypair_); - crypto::secret shared_secret; + secure::secret shared_secret; if (!webcpp::crypto::detail::secp256k1_accepted( secp256k1_ecdh(context_, shared_secret.writable().data(), &webcpp::crypto::detail::secp256k1_access::point(peer_key), @@ -1425,7 +1426,7 @@ class basic_keypair { } void release() noexcept { - webcpp::crypto::detail::wipe_object(keypair_); + secure::erase_secret(std::span(&keypair_, 1)); keyed_ = false; if (context_ != nullptr) { secp256k1_context_preallocated_destroy(context_); @@ -1540,7 +1541,7 @@ template , class Signatur [[nodiscard]] boost::system::result recover( [[maybe_unused]] ecdsa_sha256_recoverable_t signing_scheme, Signature const& signature_value, Input const& signing_input) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); auto const& signature_bytes = detail::checked_signature_bytes( @@ -1589,7 +1590,7 @@ template , class Signatur [[nodiscard]] boost::system::result recover( [[maybe_unused]] ecdsa_keccak256_recoverable_t signing_scheme, Signature const& signature_value, Input const& signing_input) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); auto const& signature_bytes = detail::checked_signature_bytes( @@ -1618,7 +1619,7 @@ template , class Signatur template > [[nodiscard]] boost::system::result to_der( ecdsa_signature const& signature_value, std::span der_output) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); if (der_output.size() < max_der_size) { return error::invalid_input_size; @@ -1650,7 +1651,7 @@ template > template > [[nodiscard]] boost::system::result from_der( std::span der_signature) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); if (der_signature.empty()) { return error::invalid_signature; @@ -1682,7 +1683,7 @@ template > template > [[nodiscard]] boost::system::result normalize_low_s( ecdsa_signature const& signature_value) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -1710,7 +1711,7 @@ template > */ template > [[nodiscard]] bool is_low_s(ecdsa_signature const& signature_value) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -1740,7 +1741,7 @@ template > [[nodiscard]] boost::system::result tweak_xonly( std::span xonly_key_bytes, std::span tweak_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -1793,7 +1794,7 @@ template , class Signatur [[nodiscard]] boost::system::result verify( [[maybe_unused]] ecdsa_sha256_t signing_scheme, Signature const& signature_value, Input const& signing_input, curves::secp256k1::public_key const& public_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); return detail::secp256k1_verify_ecdsa( detail::checked_signature_bytes( @@ -1823,7 +1824,7 @@ template , class Signatur [[nodiscard]] boost::system::result verify( [[maybe_unused]] schnorr_t signing_scheme, Signature const& signature_value, Input const& message_input, std::span xonly_public_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); auto const& signature_bytes = detail::checked_signature_bytes( @@ -1866,7 +1867,7 @@ template , class Signatur [[nodiscard]] boost::system::result verify( [[maybe_unused]] schnorr_t signing_scheme, Signature const& signature_value, Input const& message_input, curves::secp256k1::public_key const& public_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(detail::secp256k1_refuses_others); return detail::secp256k1_verify_schnorr_key( detail::checked_signature_bytes( diff --git a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp index 097d4294..d004a985 100644 --- a/include/webcpp/crypto/curves/secp256k1/ellswift.hpp +++ b/include/webcpp/crypto/curves/secp256k1/ellswift.hpp @@ -7,7 +7,7 @@ /** secp256k1's ElligatorSwift on libsecp256k1: a public key written as 64 bytes that cannot be told from random ones, read back from any 64 bytes, made from a key pair's secret, and the - x-only key exchange of two such encodings, hashed as BIP 324 hashes it into a `secret<32>`. + x-only key exchange of two such encodings, hashed as BIP 324 hashes it into a `secure::secret<32>`. @see "ElligatorSwift: keys that look like noise", in the guide's secp256k1 chapter. */ @@ -20,9 +20,9 @@ #include #include #include -#include #include -#include +#include +#include #include @@ -74,7 +74,7 @@ enum class ellswift_party { template > [[nodiscard]] std::array ellswift_encode( public_key const& parsed_key, std::span randomness_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -97,7 +97,7 @@ template > template > [[nodiscard]] public_key ellswift_decode( std::span encoded_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -124,7 +124,7 @@ template [[nodiscard]] boost::system::result> ellswift_create( basic_keypair const& key_pair, std::span randomness_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -161,12 +161,12 @@ template * @return 32 secret bytes; `invalid_state` moved from; `backend_failure`. */ template -[[nodiscard]] boost::system::result> ellswift_xdh( +[[nodiscard]] boost::system::result> ellswift_xdh( basic_keypair const& key_pair, std::span initiator_encoding, std::span responder_encoding, ellswift_party our_party) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -177,7 +177,7 @@ template webcpp::crypto::detail::secp256k1_secret native_secret; secp256k1_keypair_sec(access::context(key_pair), native_secret.bytes.data(), &access::pair(key_pair)); - secret<32> shared_secret; + secure::secret<32> shared_secret; // The secret is valid and BIP 324's hash never fails: libsecp256k1 returns 1. if (!webcpp::crypto::detail::secp256k1_accepted(secp256k1_ellswift_xdh( access::context(key_pair), shared_secret.writable().data(), initiator_encoding.data(), diff --git a/include/webcpp/crypto/curves/secp256k1/formats.hpp b/include/webcpp/crypto/curves/secp256k1/formats.hpp index 0ea3f7e1..e012ac63 100644 --- a/include/webcpp/crypto/curves/secp256k1/formats.hpp +++ b/include/webcpp/crypto/curves/secp256k1/formats.hpp @@ -18,14 +18,14 @@ #include #include -#include #include #include -#include #include -#include -#include #include +#include +#include +#include +#include #include @@ -98,7 +98,7 @@ template > [[nodiscard]] boost::system::result encode_spki( public_key const& parsed_key, std::span output_bytes, point_form encoded_form = point_form::compressed) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); if (output_bytes.size() < max_spki_size) { @@ -133,7 +133,7 @@ template > template > [[nodiscard]] boost::system::result decode_spki( std::span spki_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); @@ -145,7 +145,7 @@ template > webcpp::crypto::detail::secp256k1_spki_uncompressed_prefix); if ((spki_bytes.size() != spki_compressed_size && spki_bytes.size() != spki_uncompressed_size) || - !constant_time_equal(spki_bytes.first(expected_prefix.size()), expected_prefix)) { + !secure::constant_time_equal(spki_bytes.first(expected_prefix.size()), expected_prefix)) { return error::invalid_encoding; } using access = webcpp::crypto::detail::secp256k1_access; @@ -171,7 +171,7 @@ template > template > [[nodiscard]] boost::system::result encode_pkcs8( basic_keypair const& key_pair, std::span output_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); using access = webcpp::crypto::detail::secp256k1_access; @@ -215,14 +215,14 @@ template > [[nodiscard]] boost::system::result> decode_pkcs8( std::span pkcs8_bytes, std::pmr::memory_resource* memory_resource = std::pmr::get_default_resource()) { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert(webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); constexpr std::size_t prefix_size = webcpp::crypto::detail::secp256k1_pkcs8_prefix.size(); if (pkcs8_bytes.size() != max_pkcs8_size || - !constant_time_equal(pkcs8_bytes.first(prefix_size), - webcpp::crypto::detail::secp256k1_pkcs8_prefix)) { + !secure::constant_time_equal(pkcs8_bytes.first(prefix_size), + webcpp::crypto::detail::secp256k1_pkcs8_prefix)) { return error::invalid_encoding; } webcpp::crypto::detail::secp256k1_secret secret_bytes; @@ -238,13 +238,13 @@ template > // The rest, the public key above all, is checked by encoding the key pair again: a PKCS#8 // whose public key is not its secret's is refused. std::array encoded_again{}; - // Not const: the branch reads it again after the mark (detail/declassify.hpp's tip); the + // Not const: the branch reads it again after the mark (secure::declassify's tip); the // comparison runs on the secret's bytes, and its verdict is public. // NOLINTNEXTLINE(misc-const-correctness): see above bool is_same = encode_pkcs8(*made_pair, encoded_again).has_value() && - constant_time_equal(encoded_again, pkcs8_bytes); - WEBCPP_CRYPTO_DETAIL_DECLASSIFY(&is_same, sizeof is_same); - webcpp::crypto::detail::wipe(encoded_again.data(), encoded_again.size()); + secure::constant_time_equal(encoded_again, pkcs8_bytes); + secure::declassify(is_same); + secure::erase_secret(encoded_again); if (!is_same) { return error::invalid_encoding; } diff --git a/include/webcpp/crypto/curves/secp256k1/musig.hpp b/include/webcpp/crypto/curves/secp256k1/musig.hpp index c7224ea2..958946ef 100644 --- a/include/webcpp/crypto/curves/secp256k1/musig.hpp +++ b/include/webcpp/crypto/curves/secp256k1/musig.hpp @@ -21,10 +21,10 @@ #include #include #include -#include -#include #include #include // lint-world: the nonce's session randomness +#include +#include #include @@ -87,7 +87,7 @@ class aggregate_key { * @return 32 bytes, the tweaks included. */ [[nodiscard]] std::array xonly_public_key() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); public_key full_key = full_public_key(); @@ -108,7 +108,7 @@ class aggregate_key { * @return The key, the tweaks included. */ [[nodiscard]] public_key full_public_key() const noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); secp256k1_selftest(); using access = webcpp::crypto::detail::secp256k1_access; @@ -131,7 +131,7 @@ class aggregate_key { */ [[nodiscard]] boost::system::result tweak_add( std::span tweak_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return tweaked(tweak_bytes, secp256k1_musig_pubkey_ec_tweak_add); } @@ -145,7 +145,7 @@ class aggregate_key { */ [[nodiscard]] boost::system::result tweak_xonly_add( std::span tweak_bytes) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; return tweaked(tweak_bytes, secp256k1_musig_pubkey_xonly_tweak_add); } @@ -276,7 +276,7 @@ class secret_nonce { secret_nonce() noexcept = default; - void release() noexcept { webcpp::crypto::detail::wipe_object(native_value_); } + void release() noexcept { secure::erase_secret(std::span(&native_value_, 1)); } webcpp::crypto::detail::secp256k1_nonce_state native_value_{}; }; @@ -316,7 +316,7 @@ struct nonce_pair { template > [[nodiscard]] boost::system::result key_aggregate( std::span signer_keys, workspace pointer_space) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -365,7 +365,7 @@ template basic_keypair const& signer_pair, aggregate_key const& signers_key, std::span message_hash = {}, std::span extra_input = {}) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -421,7 +421,7 @@ template template > [[nodiscard]] boost::system::result nonce_aggregate( std::span signer_nonces, workspace pointer_space) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -463,7 +463,7 @@ template > [[nodiscard]] boost::system::result nonce_process( aggregate_nonce const& nonce_sum, std::span message_bytes, aggregate_key const& signers_key) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -494,7 +494,7 @@ template [[nodiscard]] boost::system::result partial_sign( basic_keypair const& signer_pair, secret_nonce signer_nonce, aggregate_key const& signers_key, session const& signing_session) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -542,7 +542,7 @@ template > partial_signature const& signature_part, public_nonce const& signer_nonce, public_key const& signer_key, aggregate_key const& signers_key, session const& signing_session) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -574,7 +574,7 @@ template > [[nodiscard]] boost::system::result partial_signature_aggregate( session const& signing_session, std::span signature_parts, workspace pointer_space) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -614,7 +614,7 @@ template > template > [[nodiscard]] boost::system::result parse_public_nonce( std::span encoded_nonce) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -641,7 +641,7 @@ template > template > [[nodiscard]] std::array serialize_public_nonce( public_nonce const& parsed_nonce) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -666,7 +666,7 @@ template > template > [[nodiscard]] boost::system::result parse_aggregate_nonce( std::span encoded_nonce) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -693,7 +693,7 @@ template > template > [[nodiscard]] std::array serialize_aggregate_nonce( aggregate_nonce const& parsed_nonce) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -717,7 +717,7 @@ template > template > [[nodiscard]] boost::system::result parse_partial_signature( std::span encoded_signature) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); @@ -745,7 +745,7 @@ template > template > [[nodiscard]] std::array serialize_partial_signature( partial_signature const& parsed_signature) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); webcpp::crypto::detail::read_canary(WEBCPP_CRYPTO_DETAIL_SECP256K1_CANARY); diff --git a/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp index 6cf5b510..1d5278a8 100644 --- a/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp +++ b/include/webcpp/crypto/curves/secp256k1/silent_payments.hpp @@ -20,11 +20,11 @@ #include #include #include -#include #include -#include #include -#include +#include +#include +#include #include @@ -134,7 +134,7 @@ struct found_output { /** The output's x-only key. */ std::array output_key{}; /** The spend secret key plus this tweak is the output's secret key. */ - secret<32> spend_tweak; + secure::secret<32> spend_tweak; /** The label the output was sent to, or none for the address without a label. */ std::optional> label_point; }; @@ -302,7 +302,7 @@ template std::span> const* const> taproot_inputs, std::span> const* const> plain_inputs, std::span> output_keys, workspace pointer_space) noexcept { - detail::timing_guard const timing_scope; + secure::timing_guard const timing_scope; static_assert( webcpp::crypto::detail::secp256k1_refuses_others); @@ -396,7 +396,7 @@ template template [[nodiscard]] boost::system::result