From 256226724dac13127e76bea71271bb02a59e99ec Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 14:27:18 -0300 Subject: [PATCH 01/42] secure: the library's skeleton, its configuration and the test rules secure-run and secure-compile --- AGENTS.md | 24 +++++++++++++++++++ README.md | 20 ++++++++++++++++ build.jam | 18 ++++++++++++++ doc/Jamfile | 10 ++++++++ doc/changelog.adoc | 20 ++++++++++++++++ doc/secure.adoc | 34 ++++++++++++++++++++++++++ example/.clang-tidy | 25 +++++++++++++++++++ example/Jamfile | 11 +++++++++ include/webcpp/secure.hpp | 16 +++++++++++++ include/webcpp/secure/config.hpp | 41 ++++++++++++++++++++++++++++++++ meta/libraries.json | 10 ++++++++ test/.clang-tidy | 26 ++++++++++++++++++++ test/Jamfile | 39 ++++++++++++++++++++++++++++++ test/config_test.cpp | 41 ++++++++++++++++++++++++++++++++ 14 files changed, 335 insertions(+) create mode 100644 AGENTS.md create mode 100644 build.jam create mode 100644 doc/Jamfile create mode 100644 doc/changelog.adoc create mode 100644 doc/secure.adoc create mode 100644 example/.clang-tidy create mode 100644 example/Jamfile create mode 100644 include/webcpp/secure.hpp create mode 100644 include/webcpp/secure/config.hpp create mode 100644 meta/libraries.json create mode 100644 test/.clang-tidy create mode 100644 test/Jamfile create mode 100644 test/config_test.cpp diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..3a6b3f6 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,24 @@ +# Working on secure + +webcpp's rules apply here: read the superproject's +[CODING-GUIDELINES.md](../../CODING-GUIDELINES.md) +() and its +[AGENTS.md](../../AGENTS.md) +() first. This file holds only what is +specific to secure. + +## What secure is + +- **webcpp's own library** (`"port-of": null`), with **no algorithm**: the side-channel and + secret-in-memory primitives that crypto, hash and the codecs share (the DIT timing guard, + `erase_secret`, `secret`, `constant_time_equal`, `declassify` and the constant-time building + blocks). +- **Header-only**, every function `noexcept`; it raises no exception. + +## Cautions + +- A test is declared through `secure-run` (or `secure-compile`) in `test/Jamfile`, which builds it + with exceptions and without. +- A test that defines a seam includes the seam's header first, before any header of secure. +- `detail` is not API: another library's header never includes it. Test code may call + `secure::detail::write_dit`. diff --git a/README.md b/README.md index d2c4b35..f618e63 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,26 @@ algorithm: the DIT timing guard, `erase_secret`, `secret`, `constant_time_equ The library is being built; its design is the genesis of `libraries/secure` in [webcpporg/proposals](https://github.com/webcpporg/proposals). +## Build and test + +secure is built inside the [webcpp](https://github.com/webcpporg/webcpp) superproject, where it is +the submodule `libs/secure`; a program names `/webcpp/secure//secure`: + +```jam +exe app : app.cpp /webcpp/secure//secure ; +``` + +From the superproject's root: + +``` +./b2 toolset=clang libs/secure/test libs/secure/example +``` + +## Documentation + +The library's page is built with `./b2 libs/secure/doc doc` and published with webcpp's +documentation, at . + ## Licence Distributed under the Boost Software License, Version 1.0 (`LICENSE_1_0.txt`). diff --git a/build.jam b/build.jam new file mode 100644 index 0000000..c4fed6b --- /dev/null +++ b/build.jam @@ -0,0 +1,18 @@ +# 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) + +# secure: the side-channel and secret-in-memory primitives webcpp's libraries +# share; a program names /webcpp/secure//secure: +# +# exe app : app.cpp /webcpp/secure//secure ; + +import webcpp-target ; + +project /webcpp/secure ; + +# tag::secure[] +alias secure : : : : include /boost//headers /webcpp/config//config ; +# end::secure[] diff --git a/doc/Jamfile b/doc/Jamfile new file mode 100644 index 0000000..ce479fb --- /dev/null +++ b/doc/Jamfile @@ -0,0 +1,10 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +import webcpp ; + +webcpp.doc secure : secure.adoc ; +webcpp.reference secure ; diff --git a/doc/changelog.adoc b/doc/changelog.adoc new file mode 100644 index 0000000..a2b1a72 --- /dev/null +++ b/doc/changelog.adoc @@ -0,0 +1,20 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[appendix] +[#secure-changelog] +== Changelog + +What changed in secure in each version of webcpp, newest first, one line +per change. "Unreleased" is what the next version brings. The release notes +of every version are on webcpp's index page. + +[#secure-changelog-unreleased] +=== Unreleased + +// tag::unreleased[] +* Added webcpp::secure's skeleton and configuration. +// end::unreleased[] diff --git a/doc/secure.adoc b/doc/secure.adoc new file mode 100644 index 0000000..88e7473 --- /dev/null +++ b/doc/secure.adoc @@ -0,0 +1,34 @@ +// 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) + += secure: side-channel and secret-in-memory primitives for {cpp} +:toc: left +:toclevels: 1 +:idprefix: +:sectanchors: +:example-caption!: +:attribute-missing: warn + +secure holds the side-channel and secret-in-memory primitives that the +libraries of https://github.com/webcpporg/webcpp[webcpp] share, for a +{cpp}20 program on every target webcpp has. It is not a cryptographic library: +it holds no algorithm, only what an algorithm's implementation needs so that +its timing and its secrets in memory do not leak. + +The <> that closes this page lists every name the headers +declare. + +[#reference] +== Reference + +Every name secure declares, in the namespace `webcpp::secure`, from the Doc +Comments of its headers: each class, function, type and enumerator with its +declaration, what it does, what it asks of its caller and how it fails. The +other sections teach the library; this one is where a name is looked up. + +include::{reference}[leveloffset=+1] + +include::changelog.adoc[] diff --git a/example/.clang-tidy b/example/.clang-tidy new file mode 100644 index 0000000..28ee5be --- /dev/null +++ b/example/.clang-tidy @@ -0,0 +1,25 @@ +# The examples inherit the superproject's configuration and switch off one +# check and one option. +# +# bugprone-exception-escape.CheckMain treats every example's main as a +# function that should not throw. An example is a short program that lets +# what the standard library may throw, a std::bad_alloc or a +# std::length_error from a container that grows, end the process uncaught, +# the way Boost's own examples do; that is main's ordinary role, not a +# defect. The check stays on for everything else: a noexcept function, a +# destructor, a move or a swap. +# +# bugprone-forward-declaration-namespace reports a tag declared and never +# referenced when another namespace declares one of the same name. Three +# examples include webcpp::crypto beside hash, and both libraries name their +# backend tags alike on purpose (backends::openssl, backends::bearssl, each +# declared and never defined), so every example of both reports the tag it +# does not name, in either library's header. The check stays on for the +# library's headers (the aggregate) and its tests. +--- +InheritParentConfig: true +Checks: > + -bugprone-forward-declaration-namespace +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/example/Jamfile b/example/Jamfile new file mode 100644 index 0000000..6bbc3a6 --- /dev/null +++ b/example/Jamfile @@ -0,0 +1,11 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/secure//secure ; + +import webcpp ; + +webcpp.targets native wasip2 wasip3 emscripten ; diff --git a/include/webcpp/secure.hpp b/include/webcpp/secure.hpp new file mode 100644 index 0000000..d0f857f --- /dev/null +++ b/include/webcpp/secure.hpp @@ -0,0 +1,16 @@ +// 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) + +/** + Every public header of webcpp::secure: the side-channel and secret-in-memory + primitives that webcpp's libraries share. +*/ +#ifndef WEBCPP_SECURE_HPP +#define WEBCPP_SECURE_HPP + +#include + +#endif // WEBCPP_SECURE_HPP diff --git a/include/webcpp/secure/config.hpp b/include/webcpp/secure/config.hpp new file mode 100644 index 0000000..bb52830 --- /dev/null +++ b/include/webcpp/secure/config.hpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The configuration of secure, which each of its headers includes first: whether + secure is built without exceptions. + + @see "Targets", in the guide. +*/ +#ifndef WEBCPP_SECURE_CONFIG_HPP +#define WEBCPP_SECURE_CONFIG_HPP + +#include + +// MrDocs parses secure as a build with exceptions does, where the macro is not +// defined: this definition, undone at once, is the one the reference lists. +#ifdef __MRDOCS__ +/** + Defined when secure is built without exceptions: when webcpp has none (the + compiler has none, or the developer defined `WEBCPP_NO_EXCEPTIONS` for every + webcpp library), or when the developer defines it alone, to disable secure's + in a build that has them. + + secure raises no exception: every function is `noexcept`, so the macro changes + nothing in it. It is provided so that a program can set it for every webcpp + library alike. + + @see "Targets", in the guide. +*/ +#define WEBCPP_SECURE_NO_EXCEPTIONS +#undef WEBCPP_SECURE_NO_EXCEPTIONS +#endif + +#if !defined(WEBCPP_HAS_EXCEPTIONS) && !defined(WEBCPP_SECURE_NO_EXCEPTIONS) +#define WEBCPP_SECURE_NO_EXCEPTIONS +#endif + +#endif // WEBCPP_SECURE_CONFIG_HPP diff --git a/meta/libraries.json b/meta/libraries.json new file mode 100644 index 0000000..b3941f1 --- /dev/null +++ b/meta/libraries.json @@ -0,0 +1,10 @@ +{ + "key": "secure", + "name": "secure", + "authors": ["R"], + "description": "The side-channel and secret-in-memory primitives webcpp's libraries share: the DIT timing guard, erase_secret, secret, constant_time_equal, declassify and constant-time building blocks, no algorithm.", + "category": ["Cryptography"], + "maintainers": ["R "], + "cxxstd": "20", + "port-of": null +} diff --git a/test/.clang-tidy b/test/.clang-tidy new file mode 100644 index 0000000..6cca041 --- /dev/null +++ b/test/.clang-tidy @@ -0,0 +1,26 @@ +# The tests inherit the superproject's configuration and switch off one check +# and one option. +# +# bugprone-unchecked-optional-access reports an optional that a test reads +# where its value must be there. Either the test has asserted it first, with +# `if (!BOOST_TEST(x.has_value())) { return; }`, and BOOST_TEST is a call +# returning whether its condition held, which the checker does not look into; +# or the test calls value(), whose failure on an empty optional ends the +# program, with std::bad_optional_access or, built without exceptions, an +# abort, and so fails the test. The library's headers are still analysed with +# it, through the aggregate translation unit tools/lint/compile_commands.py +# writes. +# +# bugprone-exception-escape.CheckMain treats every test's main as a function +# that should not throw. A test's main lets what a failing case throws, a +# boost::system::system_error from value() on a failed result or a +# std::bad_alloc, end the process uncaught, which fails the test as it should; +# example/.clang-tidy says the same of the examples. The check stays on for +# everything else: a noexcept function, a destructor, a move or a swap. +--- +InheritParentConfig: true +Checks: > + -bugprone-unchecked-optional-access +CheckOptions: + - key: bugprone-exception-escape.CheckMain + value: 'false' diff --git a/test/Jamfile b/test/Jamfile new file mode 100644 index 0000000..7f1c670 --- /dev/null +++ b/test/Jamfile @@ -0,0 +1,39 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/secure//secure ; + +import webcpp ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +# Every program that runs, runs with exceptions on and off, and every check +# that compiles, compiles both ways: the second has the suffix _no_exceptions +# and is built with exception-handling=off. +rule secure-run ( name : sources + : requirements * : targets * ) +{ + webcpp.run $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.run $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} +rule secure-compile ( name : sources + : requirements * : targets * ) +{ + webcpp.compile $(name) : $(sources) : $(requirements) : $(targets) ; + webcpp.compile $(name)_no_exceptions : $(sources) + : $(requirements) off : $(targets) ; +} + +webcpp.headers-alone secure : ../include ; + +# config.hpp defines WEBCPP_SECURE_NO_EXCEPTIONS exactly when webcpp has no +# exceptions, keeps it when a developer defines it, and defines it when +# WEBCPP_NO_EXCEPTIONS is. +webcpp.compile config : config_test.cpp ; +webcpp.compile config_no_exceptions : config_test.cpp : off ; +webcpp.compile config_all_off : config_test.cpp + : WEBCPP_NO_EXCEPTIONS WEBCPP_TEST_SECURE_ALL_OFF ; +webcpp.compile config_developer_defined : config_test.cpp + : WEBCPP_SECURE_NO_EXCEPTIONS WEBCPP_TEST_SECURE_DEVELOPER_DEFINED ; diff --git a/test/config_test.cpp b/test/config_test.cpp new file mode 100644 index 0000000..b593bb9 --- /dev/null +++ b/test/config_test.cpp @@ -0,0 +1,41 @@ +// 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) + +// defines WEBCPP_SECURE_NO_EXCEPTIONS exactly when +// webcpp has no exceptions, and keeps the developer's own definition in a build +// that has them. test/Jamfile builds this file as the build asks; without +// exceptions; with WEBCPP_NO_EXCEPTIONS defined as a developer defines it for +// every webcpp library, which WEBCPP_TEST_SECURE_ALL_OFF tells this file; and +// with the macro itself defined on the command line, which +// WEBCPP_TEST_SECURE_DEVELOPER_DEFINED tells this file. + +#include + +// webcpp's configuration, which config.hpp includes, has said whether webcpp +// has exceptions and which target the program is for. +#ifndef WEBCPP_CONFIG_HPP +#error "config.hpp does not include " +#endif + +#ifndef WEBCPP_VERSION +#error "webcpp's configuration does not define WEBCPP_VERSION" +#endif + +#ifdef WEBCPP_TEST_SECURE_ALL_OFF +#ifndef WEBCPP_SECURE_NO_EXCEPTIONS +#error "WEBCPP_NO_EXCEPTIONS does not define WEBCPP_SECURE_NO_EXCEPTIONS" +#endif +#elif defined(WEBCPP_TEST_SECURE_DEVELOPER_DEFINED) +#ifndef WEBCPP_SECURE_NO_EXCEPTIONS +#error "config.hpp drops WEBCPP_SECURE_NO_EXCEPTIONS, which the developer defined" +#endif +#elif defined(WEBCPP_HAS_EXCEPTIONS) == defined(WEBCPP_SECURE_NO_EXCEPTIONS) +#error "WEBCPP_SECURE_NO_EXCEPTIONS is not defined exactly when webcpp has no exceptions" +#endif + +int main() { + return 0; +} From a1126f75efbe758f37cf1bcd31820f20b815077b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 14:45:00 -0300 Subject: [PATCH 02/42] secure: declare namespace webcpp::secure and give the guide its Exceptions section, so the reference and doc-check pass --- doc/secure.adoc | 6 ++++++ include/webcpp/secure/config.hpp | 11 +++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/doc/secure.adoc b/doc/secure.adoc index 88e7473..97a23e4 100644 --- a/doc/secure.adoc +++ b/doc/secure.adoc @@ -21,6 +21,12 @@ its timing and its secrets in memory do not leak. The <> that closes this page lists every name the headers declare. +== Exceptions + +secure raises no exception: every function is `noexcept`. It builds the same +with exceptions on and off, and `WEBCPP_SECURE_NO_EXCEPTIONS` is defined when +webcpp has none, or when a program defines it alone. + [#reference] == Reference diff --git a/include/webcpp/secure/config.hpp b/include/webcpp/secure/config.hpp index bb52830..745588d 100644 --- a/include/webcpp/secure/config.hpp +++ b/include/webcpp/secure/config.hpp @@ -8,7 +8,7 @@ The configuration of secure, which each of its headers includes first: whether secure is built without exceptions. - @see "Targets", in the guide. + @see "Exceptions", in the guide. */ #ifndef WEBCPP_SECURE_CONFIG_HPP #define WEBCPP_SECURE_CONFIG_HPP @@ -28,7 +28,7 @@ nothing in it. It is provided so that a program can set it for every webcpp library alike. - @see "Targets", in the guide. + @see "Exceptions", in the guide. */ #define WEBCPP_SECURE_NO_EXCEPTIONS #undef WEBCPP_SECURE_NO_EXCEPTIONS @@ -38,4 +38,11 @@ #define WEBCPP_SECURE_NO_EXCEPTIONS #endif +/** + The side-channel and secret-in-memory primitives that webcpp's libraries + share. +*/ +namespace webcpp::secure { +} // namespace webcpp::secure + #endif // WEBCPP_SECURE_CONFIG_HPP From c8f2722a12390c11ff546f9ed1c1573586e81497 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 16:09:27 -0300 Subject: [PATCH 03/42] secure: format the namespace declaration --- include/webcpp/secure/config.hpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/include/webcpp/secure/config.hpp b/include/webcpp/secure/config.hpp index 745588d..c3c8ba2 100644 --- a/include/webcpp/secure/config.hpp +++ b/include/webcpp/secure/config.hpp @@ -42,7 +42,6 @@ The side-channel and secret-in-memory primitives that webcpp's libraries share. */ -namespace webcpp::secure { -} // namespace webcpp::secure +namespace webcpp::secure {} // namespace webcpp::secure #endif // WEBCPP_SECURE_CONFIG_HPP From a259d191fca7f26eeadcaf505eec88d3b23799b6 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 16:26:34 -0300 Subject: [PATCH 04/42] secure: timing_guard, cpu_has_dit and dit_is_set, the DIT guard moved from config's withdrawn change, with its seam, its test support and its tests --- example/.clang-tidy | 11 +- include/webcpp/secure.hpp | 1 + include/webcpp/secure/timing_guard.hpp | 289 +++++++++++++++++++++++++ test/Jamfile | 20 ++ test/support/timing_dit.hpp | 34 +++ test/support/timing_seam.hpp | 109 ++++++++++ test/timing_guard_header_test.cpp | 32 +++ test/timing_guard_nesting_test.cpp | 104 +++++++++ test/timing_guard_seam_test.cpp | 147 +++++++++++++ test/timing_guard_test.cpp | 120 ++++++++++ test/timing_guard_threads_test.cpp | 72 ++++++ test/timing_guard_windows_test.cpp | 114 ++++++++++ test/timing_seam_support_test.cpp | 101 +++++++++ 13 files changed, 1148 insertions(+), 6 deletions(-) create mode 100644 include/webcpp/secure/timing_guard.hpp create mode 100644 test/support/timing_dit.hpp create mode 100644 test/support/timing_seam.hpp create mode 100644 test/timing_guard_header_test.cpp create mode 100644 test/timing_guard_nesting_test.cpp create mode 100644 test/timing_guard_seam_test.cpp create mode 100644 test/timing_guard_test.cpp create mode 100644 test/timing_guard_threads_test.cpp create mode 100644 test/timing_guard_windows_test.cpp create mode 100644 test/timing_seam_support_test.cpp diff --git a/example/.clang-tidy b/example/.clang-tidy index 28ee5be..bb3c779 100644 --- a/example/.clang-tidy +++ b/example/.clang-tidy @@ -10,12 +10,11 @@ # destructor, a move or a swap. # # bugprone-forward-declaration-namespace reports a tag declared and never -# referenced when another namespace declares one of the same name. Three -# examples include webcpp::crypto beside hash, and both libraries name their -# backend tags alike on purpose (backends::openssl, backends::bearssl, each -# declared and never defined), so every example of both reports the tag it -# does not name, in either library's header. The check stays on for the -# library's headers (the aggregate) and its tests. +# referenced when another namespace declares one of the same name. Libraries +# that name their tags alike on purpose, each declared and never defined, make +# an example that includes several of them report the tag it does not name, in +# either library's header. The check stays on for the library's headers (the +# aggregate) and its tests. --- InheritParentConfig: true Checks: > diff --git a/include/webcpp/secure.hpp b/include/webcpp/secure.hpp index d0f857f..f8bf231 100644 --- a/include/webcpp/secure.hpp +++ b/include/webcpp/secure.hpp @@ -12,5 +12,6 @@ #define WEBCPP_SECURE_HPP #include +#include #endif // WEBCPP_SECURE_HPP diff --git a/include/webcpp/secure/timing_guard.hpp b/include/webcpp/secure/timing_guard.hpp new file mode 100644 index 0000000..6fc35e2 --- /dev/null +++ b/include/webcpp/secure/timing_guard.hpp @@ -0,0 +1,289 @@ +// 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) + +#ifndef WEBCPP_SECURE_TIMING_GUARD_HPP +#define WEBCPP_SECURE_TIMING_GUARD_HPP + +#include + +/* + * timing_guard sets 64-bit ARM's DIT (Data Independent Timing) bit, PSTATE.DIT, for the scope of + * one secret computation and restores the thread's state after it. With DIT set, the instructions + * Arm lists take a time independent of their data; Apple requires it of constant-time code on + * Apple silicon, and none of the C libraries webcpp calls sets it. It is the one guard of webcpp's + * libraries: every function of crypto, hash or codecs that computes on a secret holds one as its + * first statement, and none keeps a copy. It is public: crypto, hash and codecs hold it, and a + * program may hold one around its own constant-time code. + * + * Some functions are keyed only by their arguments (a BLAKE2b digest of a call that passes a key), + * and an unkeyed call computes on public data and must not pay for DIT: such a function constructs + * the guard with `engaged` false when the call is not keyed. A disengaged guard sets nothing, + * clears nothing and runs no seam, on every target. + * + * The guard applies on arm64 under macOS, iOS, Linux and Android, where the system says whether + * the CPU has FEAT_DIT, and on Windows on ARM64 built by MSVC or clang-cl, where one read of the + * register under structured exception handling says it (probe_dit, below). Everywhere else (x86, + * ARM64EC, WebAssembly, where the engine decides) it is an empty class that executes no + * instruction. + */ +#if defined(__aarch64__) && (defined(__APPLE__) || defined(__linux__)) +/** Defined where timing_guard sets DIT: arm64 under an Apple system or Linux, Android included. */ +#define WEBCPP_SECURE_TIMING_COVERED 1 +#include +#include +#ifdef __APPLE__ +#include +#else +#include +#endif +#elif defined(_MSC_VER) && defined(_M_ARM64) && !defined(_M_ARM64EC) +/** Defined where timing_guard sets DIT: Windows on ARM64, MSVC and clang-cl, not ARM64EC. */ +#define WEBCPP_SECURE_TIMING_COVERED 1 +#include +#include +#include +#include +#endif + +/* + * WEBCPP_SECURE_TIMING_ENTERED(where), the seam, is defined by a test alone, before its + * first include, to record the guards a call enters, so that a guarded function that forgets its + * guard fails on every lane, also where DIT does not apply and also when it calls another guarded + * function. Then timing_guard's constructor takes the std::source_location of the guard's + * declaration, whose function_name() is the function that holds it and whose file_name() tells + * which library declares it (webcpp/crypto/, webcpp/hash/, webcpp/codecs/), and runs the seam with + * it first, on every target, when the guard is engaged. Nothing in a program's build: without the + * seam the constructor takes no location, so that no function's name or header's path reaches a + * program, whether the constructor is inlined or not. + */ +#ifdef WEBCPP_SECURE_TIMING_ENTERED +#include +#endif + +namespace webcpp::secure { + +#ifdef WEBCPP_SECURE_TIMING_COVERED +namespace detail { + +/** DIT's bit in the value of the register s3_3_c4_c2_5, bit 24 as in PSTATE. */ +inline constexpr std::uint64_t dit_bit = std::uint64_t{1} << 24U; + +#ifdef _MSC_VER +/** DIT's register for `_ReadStatusReg` and `_WriteStatusReg`: `ARM64_SYSREG(3, 3, 4, 2, 5)`. */ +inline constexpr int dit_register = (1 << 14) | (3 << 11) | (4 << 7) | (2 << 3) | 5; +#ifdef ARM64_SYSREG +static_assert(dit_register == ARM64_SYSREG(3, 3, 4, 2, 5), "dit_register is DIT's encoding"); +#endif + +/** The full-system option of `isb`, `_ARM64_BARRIER_SY`. */ +inline constexpr unsigned int isb_full_system = 0xFU; +#ifdef _ARM64_BARRIER_SY +static_assert(isb_full_system == _ARM64_BARRIER_SY, "isb_full_system is isb sy"); +#endif + +/** The code of the exception an undefined instruction raises, `STATUS_ILLEGAL_INSTRUCTION`. */ +inline constexpr unsigned long status_illegal_instruction = 0xC000001DUL; +#endif + +/** + * Writes the DIT register, then executes `isb`. + * + * The register is named by its encoding (op0 3, op1 3, CRn 4, CRm 2, op2 5), which every + * assembler takes, with or without an architecture flag. Apple's "Writing ARM64 code for Apple + * platforms" ("Enable DIT for constant-time cryptographic operations") asks for a speculation + * barrier after turning DIT on, so that the timing of the instructions after it reflects the new + * state: `sb` where the CPU has FEAT_SB, else `dsb nsh` then `isb sy`; it asks for none after + * turning DIT off. The `isb` here, after both writes, is not that barrier: which barrier each + * write needs is the open measurement of crypto's change data-independent-timing. + * + * MSVC takes no inline assembly on ARM64, and clang-cl takes the same intrinsics, so that one + * spelling serves both: `_WriteStatusReg` writes the register and `__isb` executes `isb sy`, + * between two `std::atomic_signal_fence(seq_cst)`, which stand for the asm's `memory` clobber. + * + * @param dit_value `dit_bit` to set DIT, 0 to clear it. + */ +inline void write_dit(std::uint64_t dit_value) noexcept { +#ifdef _MSC_VER + std::atomic_signal_fence(std::memory_order_seq_cst); + _WriteStatusReg(dit_register, static_cast<__int64>(dit_value)); + __isb(isb_full_system); + std::atomic_signal_fence(std::memory_order_seq_cst); +#else + __asm__ volatile("msr s3_3_c4_c2_5, %0\n\tisb" : : "r"(dit_value) : "memory"); +#endif +} + +#ifdef _MSC_VER +/** + * Whether the CPU has FEAT_DIT, by reading the DIT register once under structured exception + * handling: Windows documents no processor feature flag for DIT and no user-mode read of + * ID_AA64PFR0_EL1, and on a CPU without FEAT_DIT the read is undefined and raises + * STATUS_ILLEGAL_INSTRUCTION, which the filter takes as "absent"; any other exception continues + * its search. A function of its own holding no object that needs unwinding, which `__try` refuses + * beside one (C2712); structured exception handling is not C++'s, so it works with exceptions on + * or off. The value read is kept in a volatile, so that the read is never dropped. + * + * @return Whether the read succeeded. + */ +inline bool probe_dit() noexcept { + __try { + std::uint64_t volatile const state = + static_cast(_ReadStatusReg(dit_register)); + static_cast(state); + return true; + } __except (GetExceptionCode() == status_illegal_instruction ? EXCEPTION_EXECUTE_HANDLER + : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} +#endif + +} // namespace detail +#endif + +/** + * Whether the CPU has DIT, read once per process. + * + * `hw.optional.arm.FEAT_DIT` on Apple's systems, where a value that cannot be read counts as + * absent; on Windows, probe_dit's one read of the register under structured exception handling, + * an illegal instruction meaning absent; `HWCAP_DIT` (bit 24 of `AT_HWCAP`) on Linux. Executing + * DIT's instructions on a CPU without it traps, so nothing else reads or writes the register + * unless this is true. + * + * @return Whether the CPU has FEAT_DIT; `false` on every target the guard does not cover. + */ +[[nodiscard]] inline bool cpu_has_dit() noexcept { +#if defined(WEBCPP_SECURE_TIMING_COVERED) && defined(__APPLE__) + static bool const has_dit = [] { + int dit_feature = 0; + std::size_t byte_count = sizeof dit_feature; + return sysctlbyname("hw.optional.arm.FEAT_DIT", &dit_feature, &byte_count, nullptr, 0) == + 0 && + dit_feature != 0; + }(); + return has_dit; +#elif defined(WEBCPP_SECURE_TIMING_COVERED) && defined(_MSC_VER) + static bool const has_dit = detail::probe_dit(); + return has_dit; +#elif defined(WEBCPP_SECURE_TIMING_COVERED) + constexpr unsigned long hwcap_dit = 1UL << 24U; // HWCAP_DIT, asm/hwcap.h + static bool const has_dit = (getauxval(AT_HWCAP) & hwcap_dit) != 0; + return has_dit; +#else + return false; +#endif +} + +/** + * Whether DIT is set for the calling thread. + * + * @return PSTATE.DIT, read with `mrs` (`_ReadStatusReg` on MSVC and clang-cl), where the CPU has + * DIT on a target the guard covers; `false` elsewhere, without executing `mrs`. + */ +[[nodiscard]] inline bool dit_is_set() noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (!cpu_has_dit()) { + return false; + } +#ifdef _MSC_VER + std::uint64_t const saved_state = + static_cast(_ReadStatusReg(detail::dit_register)); +#else + std::uint64_t saved_state = 0; + __asm__ volatile("mrs %0, s3_3_c4_c2_5" : "=r"(saved_state) : : "memory"); +#endif + return (saved_state & detail::dit_bit) != 0; +#else + return false; +#endif +} + +/** + * Sets DIT for its scope where the CPU has it, and leaves the thread's DIT as it found it. + * + * Construction, when engaged, finds DIT clear, sets it and remembers to clear it; the destructor + * clears it then only. A guard that finds DIT set does nothing and leaves it set: the program set + * it itself (as Apple's `timingsafe_enable_if_supported` does), or an outer guard did, of the same + * library or of another, so that guards nest in any order of libraries and a thread whose program + * asked for DIT keeps it after every call. DIT is a thread's own state, so a guard never changes + * another thread's. The writes' `memory` clobber orders them against memory accesses and calls + * (the backends' out-of-line C calls, a volatile accumulator), not against arithmetic on + * registers alone, which the compiler may move across them: the same limit as every program that + * sets DIT. + */ +class timing_guard { +public: +#ifdef WEBCPP_SECURE_TIMING_ENTERED + /** + * Where `engaged`, runs the seam, then sets DIT where the CPU has it and it is clear: a test's + * build alone. + * + * @param engaged Whether the call computes on a secret; false makes the guard do nothing, the + * seam included. + * @param where Where the guard is declared, the default: the seam's argument alone. + */ + explicit timing_guard(bool engaged = true, + std::source_location where = std::source_location::current()) noexcept { + if (!engaged) { + return; + } + WEBCPP_SECURE_TIMING_ENTERED(where); + enter(); + } +#else + /** + * Where `engaged`, sets DIT where the CPU has it and it is clear. + * + * @param engaged Whether the call computes on a secret; false makes the guard do nothing. + */ + explicit timing_guard(bool engaged = true) noexcept { + if (engaged) { + enter(); + } + } +#endif + + /** Clears DIT when this guard set it. */ + ~timing_guard() { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (armed_) { + detail::write_dit(0); + } +#endif + } + + /** Not copyable: the state it restores is the scope's. */ + timing_guard(timing_guard const&) = delete; + + /** Not assignable. */ + timing_guard& operator=(timing_guard const&) = delete; + + /** Not movable: the state it restores is the scope's. */ + timing_guard(timing_guard&&) = delete; + + /** Not move-assignable. */ + timing_guard& operator=(timing_guard&&) = delete; + +private: + /** Sets DIT where the CPU has it and it is clear, and remembers to clear it. */ + void enter() noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (cpu_has_dit() && !dit_is_set()) { + detail::write_dit(detail::dit_bit); + armed_ = true; + } +#endif + } + +#ifdef WEBCPP_SECURE_TIMING_COVERED + /** Whether this guard set DIT, and so clears it. */ + bool armed_ = false; +#endif +}; + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_TIMING_GUARD_HPP diff --git a/test/Jamfile b/test/Jamfile index 7f1c670..fc417d3 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -28,6 +28,26 @@ rule secure-compile ( name : sources + : requirements * : targets * ) webcpp.headers-alone secure : ../include ; +# compiles first and alone, brings config.hpp, +# and defines WEBCPP_SECURE_TIMING_COVERED exactly where the guard acts. +secure-compile timing_guard_header : timing_guard_header_test.cpp ; +# webcpp::secure::timing_guard, the one DIT guard of webcpp's libraries: it +# sets DIT for its scope where the CPU has it and leaves the thread's state as +# it found it; disengaged, it does nothing; nested, in every order; its seam +# names the guard's function and file; another thread's DIT is untouched +# (natively, with threads). On a target it does not cover, it is empty. +secure-run timing_guard : timing_guard_test.cpp ; +secure-run timing_guard_nesting : timing_guard_nesting_test.cpp ; +secure-run timing_guard_seam : timing_guard_seam_test.cpp ; +secure-run timing_guard_threads : timing_guard_threads_test.cpp + : multi : native ; +# Windows on ARM64: FEAT_DIT read once by an SEH-guarded read of the register, +# the guard set and kept across sleeps (the Windows ARM64 lane, MSVC 14.3 and +# 14.5); on every other target, the empty guard. +secure-run timing_guard_windows : timing_guard_windows_test.cpp ; +# The test support's recorder: what it counts, and which paths are secure's. +secure-run timing_seam_support : timing_seam_support_test.cpp ; + # config.hpp defines WEBCPP_SECURE_NO_EXCEPTIONS exactly when webcpp has no # exceptions, keeps it when a developer defines it, and defines it when # WEBCPP_NO_EXCEPTIONS is. diff --git a/test/support/timing_dit.hpp b/test/support/timing_dit.hpp new file mode 100644 index 0000000..5ba8536 --- /dev/null +++ b/test/support/timing_dit.hpp @@ -0,0 +1,34 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A test's control of the thread's DIT: force_dit sets or clears it, as a program can, so that a +// check starts from a known state. A test that defines the seam of webcpp::secure::timing_guard +// ("support/timing_seam.hpp") includes it before this header, which includes the guard's. + +#ifndef WEBCPP_TEST_SECURE_SUPPORT_TIMING_DIT_HPP +#define WEBCPP_TEST_SECURE_SUPPORT_TIMING_DIT_HPP + +#include + +namespace webcpp::secure::test { + +/** + * Sets or clears DIT for this thread, as a program can; only where the CPU has DIT, since the + * instruction traps on a CPU without it, and nothing where the guard does not act. + * + * @param set Whether to set DIT. + */ +inline void force_dit([[maybe_unused]] bool set) noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (cpu_has_dit()) { + detail::write_dit(set ? detail::dit_bit : 0); + } +#endif +} + +} // namespace webcpp::secure::test + +#endif // WEBCPP_TEST_SECURE_SUPPORT_TIMING_DIT_HPP diff --git a/test/support/timing_seam.hpp b/test/support/timing_seam.hpp new file mode 100644 index 0000000..60f24c8 --- /dev/null +++ b/test/support/timing_seam.hpp @@ -0,0 +1,109 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The seam of webcpp::secure::timing_guard, recorded for secure's tests: a test includes this +// header before any webcpp header, so that the seam is defined before +// is first read and every engaged guard a call enters is +// counted, on every target, also where DIT does not apply. A guard is the library's own when one of +// the library's headers declares it: its source_location's file_name() holds +// include/webcpp//, with `/` or `\` around each word (MSVC writes backslashes, and joins +// an include directory to a header's path with either); the include root keeps a checkout whose +// own folders read webcpp// from counting a test file's guard. timing_entries counts the +// library's own guards and timing_all_entries every guard: another library's, which a call may +// enter inside its own, and a test's own. timing_first_entry and timing_last_entry keep the +// function of the first guard since a reset and of the last, which a library's checks read. + +#ifndef WEBCPP_TEST_SECURE_SUPPORT_TIMING_SEAM_HPP +#define WEBCPP_TEST_SECURE_SUPPORT_TIMING_SEAM_HPP + +#ifdef WEBCPP_SECURE_TIMING_GUARD_HPP +#error "\"support/timing_seam.hpp\" must be included before any webcpp header" +#endif + +#include +#include +#include + +namespace webcpp::secure::test { + +/** Every timing guard this thread entered: the library's, another's, a test's. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +inline thread_local std::size_t timing_all_entries = 0; + +/** The timing guards of the library's headers this thread has entered. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's counter +inline thread_local std::size_t timing_entries = 0; + +/** + * The `function_name()` of the first guard, of any file, this thread entered since it was last + * reset to null: the function that holds that guard, as the compiler spells it. + */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline thread_local char const* timing_first_entry = nullptr; + +/** The `function_name()` of the last guard, of any file, this thread entered. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +inline thread_local char const* timing_last_entry = nullptr; + +/** The library whose guards timing_entries counts. */ +inline constexpr std::string_view timing_library = "secure"; + +/** Whether `character` separates a path's components, on any system webcpp builds on. */ +constexpr bool path_separator(char character) noexcept { + return character == '/' || character == '\\'; +} + +/** + * Whether a path names a file under a library's include directory: the components `include`, + * `webcpp` and `library`, in that order, each followed by a separator, `/` or `\` in any mix, and + * `include` the path's first component or after a separator. + * + * @param path A `file_name()`. + * @param library The library's directory name. + * @return Whether the path is under `include/webcpp//`. + */ +constexpr bool path_in_library(std::string_view path, std::string_view library) noexcept { + constexpr std::string_view include_root = "include"; + constexpr std::string_view root = "webcpp"; + for (std::size_t at = path.find(include_root); at != std::string_view::npos; + at = path.find(include_root, at + 1)) { + std::size_t const root_at = at + include_root.size() + 1; + std::size_t const library_at = root_at + root.size() + 1; + std::size_t const after = library_at + library.size(); + if ((at == 0 || path_separator(path[at - 1])) && after < path.size() && + path_separator(path[root_at - 1]) && path.substr(root_at, root.size()) == root && + path_separator(path[library_at - 1]) && + path.substr(library_at, library.size()) == library && path_separator(path[after])) { + return true; + } + } + return false; +} + +/** + * Records the entry into a webcpp::secure::timing_guard: counts it, as the library's when + * its file is under the library's include directory, and keeps its function as the first since + * timing_first_entry was reset and as the last. + * + * @param where Where the guard is declared. + */ +inline void timing_entered(std::source_location const& where) noexcept { + ++timing_all_entries; + if (path_in_library(where.file_name(), timing_library)) { + ++timing_entries; + } + if (timing_first_entry == nullptr) { + timing_first_entry = where.function_name(); + } + timing_last_entry = where.function_name(); +} + +} // namespace webcpp::secure::test + +/** Records the entry into a webcpp::secure::timing_guard declared at `where`. */ +#define WEBCPP_SECURE_TIMING_ENTERED(where) (::webcpp::secure::test::timing_entered(where)) + +#endif // WEBCPP_TEST_SECURE_SUPPORT_TIMING_SEAM_HPP diff --git a/test/timing_guard_header_test.cpp b/test/timing_guard_header_test.cpp new file mode 100644 index 0000000..9c00320 --- /dev/null +++ b/test/timing_guard_header_test.cpp @@ -0,0 +1,32 @@ +// 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) + +// compiles first and alone, brings with +// it, and defines WEBCPP_SECURE_TIMING_COVERED exactly on the targets the guard covers: +// arm64 under an Apple system or Linux (Android included), and Windows on ARM64 with MSVC or +// clang-cl (not ARM64EC). + +#include + +#ifndef WEBCPP_SECURE_TIMING_GUARD_HPP +#error "the timing guard's header does not define WEBCPP_SECURE_TIMING_GUARD_HPP" +#endif + +#ifndef WEBCPP_VERSION +#error " does not include " +#endif + +#if defined(__aarch64__) && (defined(__APPLE__) || defined(__linux__)) +#ifndef WEBCPP_SECURE_TIMING_COVERED +#error "the guard does not act on arm64 under an Apple system or Linux" +#endif +#elif defined(_MSC_VER) && defined(_M_ARM64) && !defined(_M_ARM64EC) +#ifndef WEBCPP_SECURE_TIMING_COVERED +#error "the guard does not act on Windows on ARM64" +#endif +#elif defined(WEBCPP_SECURE_TIMING_COVERED) +#error "the guard acts on a target it does not cover" +#endif diff --git a/test/timing_guard_nesting_test.cpp b/test/timing_guard_nesting_test.cpp new file mode 100644 index 0000000..8bf4e99 --- /dev/null +++ b/test/timing_guard_nesting_test.cpp @@ -0,0 +1,104 @@ +// 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) + +// Guards nest, as one library's guarded function calls another's (crypto inside hash, hash inside +// crypto, codecs inside either): the guard is one class, so the nesting is the class with itself. +// Three levels in every order of engaged and disengaged guards, from DIT clear and from DIT set: +// inside each level DIT is set when it was set before or when any guard at or above that level is +// engaged (on a CPU with DIT); after each level it is as inside the level above; after the +// outermost, as before. Then the spec's scenario: three engaged guards with a disengaged one +// between them. + +#include +#include +#include "support/timing_dit.hpp" + +#include + +namespace { + +using webcpp::secure::cpu_has_dit; +using webcpp::secure::dit_is_set; +using webcpp::secure::timing_guard; +using webcpp::secure::test::force_dit; + +/** + * Three guards nested, engaged as `pattern`'s bits say (bit 0 the outermost, bit 2 the innermost), + * from DIT set or clear. + */ +void nest(unsigned pattern, bool initially_set) { + force_dit(initially_set); + bool const offered = cpu_has_dit(); + bool const before = initially_set && offered; + bool const outer_engaged = (pattern & 1U) != 0; + bool const middle_engaged = (pattern & 2U) != 0; + bool const inner_engaged = (pattern & 4U) != 0; + auto const expected = [before, offered](bool any_engaged) { + return before || (offered && any_engaged); + }; + BOOST_TEST_EQ(dit_is_set(), before); + { + timing_guard const outer{outer_engaged}; + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged)); + { + timing_guard const middle{middle_engaged}; + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged || middle_engaged)); + { + timing_guard const inner{inner_engaged}; + BOOST_TEST_EQ(dit_is_set(), + expected(outer_engaged || middle_engaged || inner_engaged)); + } + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged || middle_engaged)); + } + BOOST_TEST_EQ(dit_is_set(), expected(outer_engaged)); + } + BOOST_TEST_EQ(dit_is_set(), before); + force_dit(false); +} + +// Every order of engaged and disengaged guards over three levels, from clear and from set. +void every_order() { + for (unsigned pattern = 0; pattern < 8; ++pattern) { + nest(pattern, false); + nest(pattern, true); + } +} + +// The spec's scenario: codecs' guard, a disengaged one (an unkeyed hash call), hash's, crypto's, +// from clear on a CPU with DIT: set inside every level, still set after each inner guard ends, +// clear after the outermost. +void three_libraries_with_a_disengaged_guard_between() { + force_dit(false); + bool const offered = cpu_has_dit(); + { + timing_guard const codecs; + BOOST_TEST_EQ(dit_is_set(), offered); + { + timing_guard const unkeyed{false}; + BOOST_TEST_EQ(dit_is_set(), offered); + { + timing_guard const hash; + BOOST_TEST_EQ(dit_is_set(), offered); + { + timing_guard const crypto; + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST_EQ(dit_is_set(), offered); + } + BOOST_TEST(!dit_is_set()); +} + +} // namespace + +int main() { + every_order(); + three_libraries_with_a_disengaged_guard_between(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_guard_seam_test.cpp b/test/timing_guard_seam_test.cpp new file mode 100644 index 0000000..1ceaec8 --- /dev/null +++ b/test/timing_guard_seam_test.cpp @@ -0,0 +1,147 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The seam of webcpp::secure::timing_guard, WEBCPP_SECURE_TIMING_ENTERED, defined +// here before the first include as a library's test defines it: every engaged guard runs it once, +// with the std::source_location of the guard's declaration, before DIT is touched, on every target; +// a disengaged guard never runs it. The location's function_name() names the function that holds +// the guard and its file_name() the file that declares it, which is how a library's coverage test +// tells its own guards from another library's. Without the seam the constructor takes no +// location: timing_guard_test checks that. + +#include +#include + +namespace webcpp::secure::test { +namespace { + +/** Records one engaged guard's entry; defined below, once the guard's header is included. */ +void timing_entered(std::source_location const& where) noexcept; + +} // namespace +} // namespace webcpp::secure::test + +/** The seam: records the entry into a guard declared at `where`. */ +#define WEBCPP_SECURE_TIMING_ENTERED(where) (::webcpp::secure::test::timing_entered(where)) + +#include +#include +#include "support/timing_dit.hpp" + +#include + +#include +#include + +namespace webcpp::secure::test { +namespace { + +/** The seam's runs on this thread. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +thread_local std::size_t entries = 0; + +/** Where the last guard the seam saw is declared. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +thread_local std::source_location last_entry{}; + +/** Whether DIT was set when the seam last ran. */ +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +thread_local bool dit_at_seam = false; + +void timing_entered(std::source_location const& where) noexcept { + ++entries; + last_entry = where; + dit_at_seam = webcpp::secure::dit_is_set(); +} + +} // namespace +} // namespace webcpp::secure::test + +namespace { + +using webcpp::secure::cpu_has_dit; +using webcpp::secure::dit_is_set; +using webcpp::secure::timing_guard; +using webcpp::secure::test::force_dit; + +static_assert(std::is_nothrow_constructible_v, + "with the seam, the constructor takes the guard's location after engaged"); + +namespace seam_probe { + +/** Holds an engaged guard, as a library's guarded function does. */ +void guarded_function() { + timing_guard const guard; +} + +/** Holds a guard engaged explicitly, as a function keyed by its arguments does for a keyed call. */ +void engaged_function() { + timing_guard const guard{true}; +} + +/** Holds a disengaged guard, as a function keyed by its arguments does for an unkeyed call. */ +void disengaged_function() { + timing_guard const guard{false}; +} + +} // namespace seam_probe + +// An engaged guard, made either way, runs the seam exactly once, at its construction. +void engaged_guard_runs_the_seam_once() { + std::size_t const before = webcpp::secure::test::entries; + { + timing_guard const guard; + BOOST_TEST_EQ(webcpp::secure::test::entries, before + 1); + } + BOOST_TEST_EQ(webcpp::secure::test::entries, before + 1); + { + timing_guard const guard{true}; + } + BOOST_TEST_EQ(webcpp::secure::test::entries, before + 2); +} + +// A disengaged guard runs no seam. +void disengaged_guard_runs_no_seam() { + std::size_t const before = webcpp::secure::test::entries; + seam_probe::disengaged_function(); + BOOST_TEST_EQ(webcpp::secure::test::entries, before); +} + +// The seam's location names the function that holds the guard, and the file that declares it, +// for a guard made either way: timing_guard{} and timing_guard{true}. +void seam_names_function_and_file() { + seam_probe::guarded_function(); + std::string_view function = webcpp::secure::test::last_entry.function_name(); + std::string_view file = webcpp::secure::test::last_entry.file_name(); + BOOST_TEST(function.find("seam_probe::guarded_function") != std::string_view::npos); + BOOST_TEST(file.ends_with("timing_guard_seam_test.cpp")); + seam_probe::engaged_function(); + function = webcpp::secure::test::last_entry.function_name(); + file = webcpp::secure::test::last_entry.file_name(); + BOOST_TEST(function.find("seam_probe::engaged_function") != std::string_view::npos); + BOOST_TEST(file.ends_with("timing_guard_seam_test.cpp")); +} + +// The seam runs before DIT is touched: from clear, it finds DIT clear; then the guard sets it. +void seam_runs_before_dit() { + force_dit(false); + { + timing_guard const guard; + BOOST_TEST(!webcpp::secure::test::dit_at_seam); + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); +} + +} // namespace + +int main() { + engaged_guard_runs_the_seam_once(); + disengaged_guard_runs_no_seam(); + seam_names_function_and_file(); + seam_runs_before_dit(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_guard_test.cpp b/test/timing_guard_test.cpp new file mode 100644 index 0000000..d0ebb52 --- /dev/null +++ b/test/timing_guard_test.cpp @@ -0,0 +1,120 @@ +// 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) + +// webcpp::secure::timing_guard, secure's data-independent-timing guard, without the seam: +// an engaged guard (timing_guard{} or timing_guard{true}) sets DIT for its scope where the CPU has +// it and clears it after when it found it clear; a guard that finds DIT set, as a program that set +// it itself, leaves it set; a disengaged guard (timing_guard{false}) does nothing; cpu_has_dit() +// answers the same at every call. Without the seam the constructor takes a bool and no +// std::source_location, so that no function's name or header's path reaches a program. On a +// target the guard does not cover, it is an empty class and both functions answer false. + +#include +#include +#include "support/timing_dit.hpp" + +#include + +#include +#include + +namespace { + +using webcpp::secure::cpu_has_dit; +using webcpp::secure::dit_is_set; +using webcpp::secure::timing_guard; +using webcpp::secure::test::force_dit; + +static_assert(!std::is_copy_constructible_v && + !std::is_copy_assignable_v, + "a guard is not copyable: the state it restores is its scope's"); +static_assert(!std::is_move_constructible_v && + !std::is_move_assignable_v, + "a guard is not movable: the state it restores is its scope's"); +static_assert(std::is_nothrow_default_constructible_v && + std::is_nothrow_constructible_v, + "a guard is made from nothing or from engaged, and never throws"); +static_assert(!std::is_convertible_v, "the constructor is explicit"); +static_assert(!std::is_constructible_v && + !std::is_constructible_v, + "without the seam, a guard takes no source_location"); +#ifndef WEBCPP_SECURE_TIMING_COVERED +static_assert(std::is_empty_v, "where the guard does not act, it is an empty class"); +#endif + +// Where the guard does not act, both functions answer false. +void uncovered_answers_false() { +#ifndef WEBCPP_SECURE_TIMING_COVERED + BOOST_TEST(!cpu_has_dit()); + BOOST_TEST(!dit_is_set()); +#endif +} + +// cpu_has_dit() is read once per process: every call answers as the first. +void cpu_answer_is_stable() { + bool const first = cpu_has_dit(); + for (int call = 0; call < 3; ++call) { + BOOST_TEST_EQ(cpu_has_dit(), first); + } +} + +// From clear: set inside an engaged guard, made either way, and clear after it. +void engaged_guard_sets_and_clears() { + force_dit(false); + BOOST_TEST(!dit_is_set()); + { + // tag::guard[] + webcpp::secure::timing_guard const guard; // DIT set from here to the end of the scope + // end::guard[] + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); + { + timing_guard const guard{true}; + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); +} + +// From set, as a program sets it: still set inside and after a guard (spec: a program that set +// DIT keeps it). +void program_set_dit_is_kept() { + force_dit(true); + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + { + timing_guard const guard; + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + force_dit(false); + BOOST_TEST(!dit_is_set()); +} + +// A disengaged guard leaves DIT as it found it, clear or set. +void disengaged_guard_does_nothing() { + for (bool const initially_set : {false, true}) { + force_dit(initially_set); + bool const before = dit_is_set(); + BOOST_TEST_EQ(before, initially_set && cpu_has_dit()); + { + timing_guard const guard{false}; + BOOST_TEST_EQ(dit_is_set(), before); + } + BOOST_TEST_EQ(dit_is_set(), before); + } + force_dit(false); +} + +} // namespace + +int main() { + uncovered_answers_false(); + cpu_answer_is_stable(); + engaged_guard_sets_and_clears(); + program_set_dit_is_kept(); + disengaged_guard_does_nothing(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_guard_threads_test.cpp b/test/timing_guard_threads_test.cpp new file mode 100644 index 0000000..8d2bdea --- /dev/null +++ b/test/timing_guard_threads_test.cpp @@ -0,0 +1,72 @@ +// 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) + +// DIT is a thread's own state, and a guard never changes another thread's: while a guard holds DIT +// on this thread, another thread reads it clear; while another thread holds a guard, this thread +// reads it clear. Each other thread is started before the guard it reads against, so that it +// cannot inherit the state at its creation (Linux's clone copies PSTATE). Built natively, with +// threads. + +#include +#include +#include "support/timing_dit.hpp" + +#include + +#include +#include +#include + +namespace { + +using webcpp::secure::cpu_has_dit; +using webcpp::secure::dit_is_set; +using webcpp::secure::timing_guard; +using webcpp::secure::test::force_dit; + +// A guard on this thread leaves another thread's DIT clear. +void other_thread_untouched() { + force_dit(false); + std::promise guard_entered; + std::promise other_reading; + std::thread other([entered = guard_entered.get_future(), &other_reading]() mutable { + entered.wait(); + other_reading.set_value(dit_is_set()); + }); + { + timing_guard const guard; + guard_entered.set_value(); + BOOST_TEST(!other_reading.get_future().get()); + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + other.join(); + BOOST_TEST(!dit_is_set()); +} + +// A guard on another thread leaves this thread's DIT clear, while it holds it and after. +void this_thread_untouched() { + force_dit(false); + std::promise other_guarded; + std::promise release; + std::thread other([&other_guarded, released = release.get_future()]() mutable { + timing_guard const guard; + other_guarded.set_value(); + released.wait(); + }); + other_guarded.get_future().wait(); + BOOST_TEST(!dit_is_set()); + release.set_value(); + other.join(); + BOOST_TEST(!dit_is_set()); +} + +} // namespace + +int main() { + other_thread_untouched(); + this_thread_untouched(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_guard_windows_test.cpp b/test/timing_guard_windows_test.cpp new file mode 100644 index 0000000..2381d4c --- /dev/null +++ b/test/timing_guard_windows_test.cpp @@ -0,0 +1,114 @@ +// 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) + +// webcpp::secure::timing_guard on Windows on ARM64 (_M_ARM64, not ARM64EC), where FEAT_DIT +// is read by one read of the register under structured exception handling: on the Windows 11 ARM64 +// machine of the Windows ARM64 lane, whose CPU has FEAT_DIT (every Armv8.4 CPU does), cpu_has_dit() +// is true; DIT is set inside a guard, still set after the thread sleeps inside it (Windows keeps +// PSTATE across a context switch), and clear after it; a guard that finds DIT set leaves it set. +// Built on every target secure runs: on one the guard does not cover (Windows x64 among them) the +// guard is an empty class and both functions answer false, even after a program's attempt to set +// DIT; on arm64 under an Apple system or Linux it checks only that a guard restores a clear DIT, +// and timing_guard_test checks the rest there. + +#include +#include +#include "support/timing_dit.hpp" + +#include + +#include + +#if defined(_MSC_VER) && defined(_M_ARM64) && !defined(_M_ARM64EC) +#define WEBCPP_TEST_TIMING_WINDOWS_ARM64 1 +#include +#include +#endif + +namespace { + +using webcpp::secure::cpu_has_dit; +using webcpp::secure::dit_is_set; +using webcpp::secure::timing_guard; +using webcpp::secure::test::force_dit; + +#ifdef WEBCPP_TEST_TIMING_WINDOWS_ARM64 +// The CPU has FEAT_DIT, and the probe answers the same at every call. +bool cpu_has_dit_here() { + bool const offered = cpu_has_dit(); + BOOST_TEST(offered); + BOOST_TEST_EQ(cpu_has_dit(), offered); + return offered; +} + +// From clear: set inside a guard, still set after each of ten sleeps inside it, clear after it. +void guard_survives_sleeps() { + force_dit(false); + BOOST_TEST(!dit_is_set()); + { + timing_guard const guard; + BOOST_TEST(dit_is_set()); + for (int round = 0; round < 10; ++round) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + BOOST_TEST(dit_is_set()); + } + } + BOOST_TEST(!dit_is_set()); +} + +// From set, as a program sets it: still set after a guard; a disengaged guard changes nothing. +void program_set_dit_is_kept() { + force_dit(true); + { + timing_guard const guard; + BOOST_TEST(dit_is_set()); + } + BOOST_TEST(dit_is_set()); + force_dit(false); + { + timing_guard const guard{false}; + BOOST_TEST(!dit_is_set()); + } + BOOST_TEST(!dit_is_set()); +} +#elif defined(WEBCPP_SECURE_TIMING_COVERED) +// arm64 under an Apple system or Linux: a guard entered from clear leaves DIT clear (the full +// checks are timing_guard_test's; this program's subject is Windows). +void guard_restores_clear_dit() { + force_dit(false); + { + timing_guard const guard; + BOOST_TEST_EQ(dit_is_set(), cpu_has_dit()); + } + BOOST_TEST(!dit_is_set()); +} +#else +static_assert(std::is_empty_v, "where the guard does not act, it is empty"); + +// Where the guard does not act, both functions answer false, also after force_dit(true), which +// does nothing there. +void uncovered_answers_false() { + force_dit(true); + BOOST_TEST(!cpu_has_dit()); + BOOST_TEST(!dit_is_set()); +} +#endif + +} // namespace + +int main() { +#ifdef WEBCPP_TEST_TIMING_WINDOWS_ARM64 + if (cpu_has_dit_here()) { + guard_survives_sleeps(); + program_set_dit_is_kept(); + } +#elif defined(WEBCPP_SECURE_TIMING_COVERED) + guard_restores_clear_dit(); +#else + uncovered_answers_false(); +#endif + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/timing_seam_support_test.cpp b/test/timing_seam_support_test.cpp new file mode 100644 index 0000000..cb9c926 --- /dev/null +++ b/test/timing_seam_support_test.cpp @@ -0,0 +1,101 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The test support's recorder, "support/timing_seam.hpp": a guard declared in this test is counted +// by timing_all_entries and not by timing_entries (this file is not under include/webcpp/secure/), +// timing_first_entry keeps the first guard's function and timing_last_entry the last's, and +// path_in_library tells secure's headers from every other path, in the spellings of clang, GCC and +// MSVC and on near misses. + +#include "support/timing_seam.hpp" + +#include +#include + +#include + +#include +#include + +namespace { + +using webcpp::secure::timing_guard; +using webcpp::secure::test::path_in_library; +using webcpp::secure::test::timing_all_entries; +using webcpp::secure::test::timing_entries; +using webcpp::secure::test::timing_first_entry; +using webcpp::secure::test::timing_last_entry; + +/** Holds a guard, as a guarded function of secure does. */ +void first_guarded_function() { + timing_guard const guard; +} + +/** Holds another guard. */ +void second_guarded_function() { + timing_guard const guard; +} + +/** Holds a disengaged guard, which the recorder never sees. */ +void disengaged_function() { + timing_guard const guard{false}; +} + +void library_is_secure() { + BOOST_TEST(webcpp::secure::test::timing_library == "secure"); +} + +// A guard declared here raises timing_all_entries by one and timing_entries by none. +void counts_every_guard_and_secures_own() { + std::size_t const all_before = timing_all_entries; + std::size_t const own_before = timing_entries; + first_guarded_function(); + BOOST_TEST_EQ(timing_all_entries, all_before + 1); + BOOST_TEST_EQ(timing_entries, own_before); + disengaged_function(); + BOOST_TEST_EQ(timing_all_entries, all_before + 1); +} + +// The first entry since a reset is kept, the last is the latest. +void names_first_and_last_function() { + timing_first_entry = nullptr; + timing_last_entry = nullptr; + first_guarded_function(); + second_guarded_function(); + BOOST_TEST(timing_first_entry != nullptr); + BOOST_TEST(timing_last_entry != nullptr); + if (timing_first_entry != nullptr && timing_last_entry != nullptr) { + BOOST_TEST(std::string_view{timing_first_entry}.find("first_guarded_function") != + std::string_view::npos); + BOOST_TEST(std::string_view{timing_last_entry}.find("second_guarded_function") != + std::string_view::npos); + } +} + +// The paths of secure's headers, in each compiler's spelling, and the near misses. +void path_in_library_spellings() { + constexpr std::string_view library = "secure"; + BOOST_TEST(path_in_library("/w/libs/secure/include/webcpp/secure/timing_guard.hpp", library)); + BOOST_TEST(path_in_library("../include/webcpp/secure/x.hpp", library)); + BOOST_TEST(path_in_library("include/webcpp/secure/x.hpp", library)); + BOOST_TEST(path_in_library(R"(C:\t\a\libs\secure\include\webcpp\secure\x.hpp)", library)); + BOOST_TEST(path_in_library(R"(C:\t\a\include\webcpp/secure\detail\wipe.hpp)", library)); + BOOST_TEST(!path_in_library("/w/libs/secure/test/x_test.cpp", library)); + BOOST_TEST(!path_in_library("/w/include/webcpp/securex/x.hpp", library)); + BOOST_TEST(!path_in_library("/w/myinclude/webcpp/secure/x.hpp", library)); + BOOST_TEST(!path_in_library("/w/include/webcpp/crypto/x.hpp", library)); + BOOST_TEST(!path_in_library("/w/include/webcpp/secure", library)); +} + +} // namespace + +int main() { + library_is_secure(); + counts_every_guard_and_secures_own(); + names_first_and_last_function(); + path_in_library_spellings(); + return webcpp::test::exit_status(boost::report_errors()); +} From 3d9e36ffc90e750599575fbb242f9ad0fd2209de Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 17:02:43 -0300 Subject: [PATCH 05/42] secure: erase_secret and secret, moved from crypto, over secure's wipe and its test seam --- include/webcpp/secure.hpp | 2 + include/webcpp/secure/detail/wipe.hpp | 56 +++++ include/webcpp/secure/erase_secret.hpp | 82 ++++++++ include/webcpp/secure/secret.hpp | 146 +++++++++++++ test/Jamfile | 13 ++ test/erase_secret_test.cpp | 167 +++++++++++++++ test/messages/Jamfile | 12 ++ .../messages/erase_secret_const_range/Jamfile | 14 ++ .../erase_secret_const_range.cpp | 31 +++ test/messages/secret_of_no_bytes/Jamfile | 12 ++ .../secret_of_no_bytes/secret_of_no_bytes.cpp | 19 ++ test/secret_test.cpp | 195 ++++++++++++++++++ test/wipe_record_test.cpp | 184 +++++++++++++++++ 13 files changed, 933 insertions(+) create mode 100644 include/webcpp/secure/detail/wipe.hpp create mode 100644 include/webcpp/secure/erase_secret.hpp create mode 100644 include/webcpp/secure/secret.hpp create mode 100644 test/erase_secret_test.cpp create mode 100644 test/messages/Jamfile create mode 100644 test/messages/erase_secret_const_range/Jamfile create mode 100644 test/messages/erase_secret_const_range/erase_secret_const_range.cpp create mode 100644 test/messages/secret_of_no_bytes/Jamfile create mode 100644 test/messages/secret_of_no_bytes/secret_of_no_bytes.cpp create mode 100644 test/secret_test.cpp create mode 100644 test/wipe_record_test.cpp diff --git a/include/webcpp/secure.hpp b/include/webcpp/secure.hpp index f8bf231..ae1385d 100644 --- a/include/webcpp/secure.hpp +++ b/include/webcpp/secure.hpp @@ -12,6 +12,8 @@ #define WEBCPP_SECURE_HPP #include +#include +#include #include #endif // WEBCPP_SECURE_HPP diff --git a/include/webcpp/secure/detail/wipe.hpp b/include/webcpp/secure/detail/wipe.hpp new file mode 100644 index 0000000..392cbc3 --- /dev/null +++ b/include/webcpp/secure/detail/wipe.hpp @@ -0,0 +1,56 @@ +// 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) + +#ifndef WEBCPP_SECURE_DETAIL_WIPE_HPP +#define WEBCPP_SECURE_DETAIL_WIPE_HPP + +#include + +#include +#include + +#ifdef WEBCPP_SECURE_TEST_WIPE_RECORD +namespace webcpp::secure::test { + +/** + The test seam through which @ref webcpp::secure::detail::wipe reports each wipe. A program built + with `WEBCPP_SECURE_TEST_WIPE_RECORD` defines this function, which each wipe calls once its + bytes are zero, with what it wiped. A program built without the macro neither declares nor + calls it. + + @param wiped_data The first byte wiped, or null when `byte_count` is 0. + @param byte_count How many bytes. +*/ +void wipe_record(void const* wiped_data, std::size_t byte_count) noexcept; + +} // namespace webcpp::secure::test +#endif + +namespace webcpp::secure::detail { + +/** + Zeroes `byte_count` bytes at `wiped_data` with stores the optimiser cannot drop. + + Tip: a `memset` before an object dies is a dead store a compiler may remove; stores through a + volatile pointer, then a signal fence, are kept. + + @param wiped_data The first byte, or null when `byte_count` is 0. + @param byte_count How many bytes. +*/ +inline void wipe(void* wiped_data, std::size_t byte_count) noexcept { + auto* const wiped_bytes = static_cast(wiped_data); + for (std::size_t byte_index = 0; byte_index < byte_count; ++byte_index) { + wiped_bytes[byte_index] = 0; + } + std::atomic_signal_fence(std::memory_order_seq_cst); +#ifdef WEBCPP_SECURE_TEST_WIPE_RECORD + test::wipe_record(wiped_data, byte_count); +#endif +} + +} // namespace webcpp::secure::detail + +#endif // WEBCPP_SECURE_DETAIL_WIPE_HPP diff --git a/include/webcpp/secure/erase_secret.hpp b/include/webcpp/secure/erase_secret.hpp new file mode 100644 index 0000000..2f80a56 --- /dev/null +++ b/include/webcpp/secure/erase_secret.hpp @@ -0,0 +1,82 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + `erase_secret`, which zeroes a buffer the program owns, a password, a key or a plaintext, with + stores the optimiser keeps. + + A `memset` of a buffer that is not read again is a dead store, which a compiler may remove: + the secret then stays in memory after the program is done with it. `erase_secret` writes + through a volatile pointer, then a signal fence, as `secret` does when it dies. + + @see "Erasing a secret from a buffer", in the guide. +*/ +#ifndef WEBCPP_SECURE_ERASE_SECRET_HPP +#define WEBCPP_SECURE_ERASE_SECRET_HPP + +#include + +#include + +#include +#include +#include + +namespace webcpp::secure { + +namespace detail { + +/** Names a template parameter in a `static_assert` that fails only when the template is used. */ +template +inline constexpr bool dependent_false = false; + +/** A contiguous sized range whose elements the program may write and copy as bytes. */ +template +concept erasable_range = + std::ranges::contiguous_range && std::ranges::sized_range && + (!std::is_const_v>>) && + std::is_trivially_copyable_v>; + +} // namespace detail + +/** + * Zeroes every byte of a buffer the program owns, with stores the optimiser keeps. + * + * It erases `size() * sizeof(element)` bytes from the range's first element: a `std::string`'s + * size, not its capacity, and nothing a reallocation left behind. It calls no backend. + * + * @tparam Range A contiguous sized range of non-const, trivially copyable elements: a + * `std::vector`, a `std::string`, a `std::array`, a `std::span`, a + * C array. + * @param erased_range The buffer. + */ +template + requires detail::erasable_range +void erase_secret(Range&& erased_range) noexcept { + detail::wipe(std::ranges::data(erased_range), + std::ranges::size(erased_range) * sizeof(std::ranges::range_value_t)); +} + +/** + * A contiguous sized range of const or non-trivially-copyable elements: it stops the build with + * a message naming the ranges `erase_secret` takes. + * + * @tparam Range The range refused. + */ +template + requires std::ranges::contiguous_range && std::ranges::sized_range && + (!detail::erasable_range) +void erase_secret(Range&& /*refused_range*/) noexcept { + static_assert(detail::dependent_false, + "webcpp::secure: 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."); +} + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_ERASE_SECRET_HPP diff --git a/include/webcpp/secure/secret.hpp b/include/webcpp/secure/secret.hpp new file mode 100644 index 0000000..9325dff --- /dev/null +++ b/include/webcpp/secure/secret.hpp @@ -0,0 +1,146 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** A secret held by a program of webcpp's libraries, which wipes itself. */ +#ifndef WEBCPP_SECURE_SECRET_HPP +#define WEBCPP_SECURE_SECRET_HPP + +#include + +#include + +#include +#include +#include +#include + +namespace webcpp::secure { + +/** + `N` secret bytes: a shared secret, a session key, a converted secret key. + + They are wiped by volatile stores when the object is destroyed or moved from; a copy is made + only by `clone`. + + The wipe covers the object's own storage only: a move or a `clone` may leave copies of the bytes in + registers or temporaries, which the library does not reach. + + @tparam N The number of bytes. +*/ +template +class secret { + static_assert(N > 0, "webcpp::secure: a secret of no bytes holds nothing."); + +public: + /** The number of bytes. */ + static constexpr std::size_t size_bytes = N; + + /** Zero bytes. */ + secret() noexcept = default; + + /** + Takes the bytes of `moved_secret`, which is wiped. + + @param moved_secret The secret to take the bytes of. + */ + secret(secret&& moved_secret) noexcept : bytes_(moved_secret.bytes_) { + detail::wipe(moved_secret.bytes_.data(), N); + } + + /** + Wipes these bytes, then takes the bytes of `moved_secret`, which is wiped; a move to itself + changes nothing. + + @param moved_secret The secret to take the bytes of. + @return This secret. + */ + secret& operator=(secret&& moved_secret) noexcept { + if (this != &moved_secret) { + detail::wipe(bytes_.data(), N); + bytes_ = moved_secret.bytes_; + detail::wipe(moved_secret.bytes_.data(), N); + } + return *this; + } + + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret(secret const&) = delete; + /** Not copyable: a copy is asked for by name, with `clone`. */ + secret& operator=(secret const&) = delete; + + /** Wipes the bytes. */ + ~secret() { detail::wipe(bytes_.data(), N); } + + /** + A copy of the bytes, which the caller then owns. + + @return A secret of the same bytes. + */ + [[nodiscard]] secret clone() const noexcept { + secret secret_copy; + secret_copy.bytes_ = bytes_; + return secret_copy; + } + + /** + The bytes, to read. + + @return A view of the bytes. + */ + [[nodiscard]] std::span bytes() const& noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + [[nodiscard]] std::span bytes() const&& = delete; + + /** + The bytes, for a library's code to write. + + @return A writable view of the bytes. + */ + [[nodiscard]] std::span writable() & noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + std::span writable() && = delete; + + /** + The bytes, as a span of fixed size. + + @return A view of the bytes. + */ + // Implicit, as the spec asks, so that a secret is passed where a function takes the span of + // its bytes: misc-explicit-constructor is silenced for it. + // NOLINTNEXTLINE(misc-explicit-constructor) + operator std::span() const& noexcept { return bytes_; } + + /** + Not available on a secret that is about to be destroyed: the view would dangle. + + @return Nothing. + */ + operator std::span() const&& = delete; + + /** + The number of bytes. + + @return `N`. + */ + static constexpr std::size_t size() noexcept { return N; } + +private: + std::array bytes_{}; +}; + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_SECRET_HPP diff --git a/test/Jamfile b/test/Jamfile index fc417d3..465406a 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -57,3 +57,16 @@ webcpp.compile config_all_off : config_test.cpp : WEBCPP_NO_EXCEPTIONS WEBCPP_TEST_SECURE_ALL_OFF ; webcpp.compile config_developer_defined : config_test.cpp : WEBCPP_SECURE_NO_EXCEPTIONS WEBCPP_TEST_SECURE_DEVELOPER_DEFINED ; + +OPTIMISED = speed emscripten:off ; +# secure::erase_secret zeroes the bytes of any contiguous range the program may +# write, and a buffer erased as its scope ends stays zero: optimised, with every +# call inlined, where a wipe the compiler could drop as a dead store would be. +secure-run erase_secret : erase_secret_test.cpp : $(OPTIMISED) full ; +# secret: not copyable, moves wipe the source, the destructor wipes the +# storage; optimised and inlined as erase_secret's. +secure-run secret : secret_test.cpp : $(OPTIMISED) full ; +# The wipe's test seam (B9): every wipe reported once, its bytes already zero. +secure-run wipe_record : wipe_record_test.cpp + : WEBCPP_SECURE_TEST_WIPE_RECORD ; +build-project messages ; diff --git a/test/erase_secret_test.cpp b/test/erase_secret_test.cpp new file mode 100644 index 0000000..60d12c2 --- /dev/null +++ b/test/erase_secret_test.cpp @@ -0,0 +1,167 @@ +// 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) + +// secure::erase_secret zeroes every byte of a contiguous range the program may write, and none +// around it; it takes no range that is not contiguous, and no pointer with a size; and a buffer +// erased just before its scope ends is zero in its storage afterwards, read at -O2 with every +// call inlined (the Jamfile's speed full), where a store the optimiser +// may drop is the case. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace secure = webcpp::secure; + +// Written through a concept, so that a range with no viable overload reads as false instead of +// stopping the build (a requires-expression outside a template is a hard error). +template +concept erasable = + requires(Range&& erased_range) { secure::erase_secret(std::forward(erased_range)); }; + +static_assert(erasable&>); +static_assert(erasable>); +static_assert(!erasable&>); +static_assert(!erasable&>); + +// Whether erase_secret takes a pointer and a size, the overload it has none of: a range carries +// its own size (design D10). +template +concept erasable_by_pointer_and_size = requires(Pointer erased_data, std::size_t byte_count) { + secure::erase_secret(erased_data, byte_count); +}; + +static_assert(!erasable_by_pointer_and_size); +static_assert(!erasable_by_pointer_and_size); +static_assert(!erasable_by_pointer_and_size); +static_assert(noexcept(secure::erase_secret(std::declval&>()))); + +// A function the optimiser cannot see into, so that what it is handed is read from memory. +#if defined(_MSC_VER) && !defined(__clang__) +#define WEBCPP_TEST_NOINLINE __declspec(noinline) +#else +#define WEBCPP_TEST_NOINLINE __attribute__((noinline)) +#endif + +// Whether every byte at `where` is zero, read through a volatile pointer in a function that is +// never inlined: a store that was dropped before the call is found here. It may be handed the +// address of an object that is gone (the point of the scope's check), so it is exempt from the +// sanitizers that would stop that read. +#if defined(__clang__) || defined(__GNUC__) +__attribute__((no_sanitize("address"))) +#endif +WEBCPP_TEST_NOINLINE bool memory_is_zero(void const* where, std::size_t count) { + auto const volatile* const bytes = static_cast(where); + for (std::size_t i = 0; i < count; ++i) { + if (bytes[i] != 0) { + return false; + } + } + return true; +} + +// A buffer in a scope of its own, which a call the optimiser cannot see into is handed, is +// erased as the scope's last statement; its storage, in this frame, is read after the scope. An +// erasure that is a dead store (a plain write to an object about to die) is dropped by the +// optimiser and the bytes remain. +WEBCPP_TEST_NOINLINE bool erasure_before_scope_end_stays() { + std::uint8_t const* where = nullptr; + constexpr std::size_t count = 32; + { + std::array password{}; + for (std::size_t i = 0; i < count; ++i) { + password[i] = static_cast(i + 1); + } + where = password.data(); + if (memory_is_zero(where, count)) { + return false; + } + secure::erase_secret(password); + } + return memory_is_zero(where, count); +} + +} // namespace + +int main() { + // A vector of bytes. + std::vector key(32, 0xa5); + secure::erase_secret(key); + BOOST_TEST_EQ(key.size(), 32U); + BOOST_TEST(memory_is_zero(key.data(), key.size())); + + // A string: its size() bytes, its terminator kept, its size unchanged. + // tag::erase[] + std::string password(200, '\0'); + password = "correct horse battery staple"; // read into a buffer reserved beforehand + // ... the password is checked or hashed ... + webcpp::secure::erase_secret(password); + // end::erase[] + BOOST_TEST_EQ(password.size(), 28U); + BOOST_TEST(memory_is_zero(password.data(), password.size())); + BOOST_TEST_EQ(password[password.size()], '\0'); + + // An array of 33 bytes, a compressed public key's size. + std::array point{}; + point.fill(0x5a); + secure::erase_secret(point); + BOOST_TEST(memory_is_zero(point.data(), point.size())); + + // A span of std::byte over part of a stack buffer: the bytes around it are untouched. + std::array framed{}; + framed.fill(std::byte{0xc3}); + secure::erase_secret(std::span(framed).subspan(1, 16)); + BOOST_TEST(framed.front() == std::byte{0xc3}); + BOOST_TEST(framed.back() == std::byte{0xc3}); + BOOST_TEST(memory_is_zero(framed.data() + 1, 16)); + + // A C array, which erase_secret takes as a program may hold one. + // NOLINTNEXTLINE(modernize-avoid-c-arrays): the C array is what this case erases + unsigned char raw[16]; + for (auto& byte : raw) { + byte = 0x77; + } + secure::erase_secret(raw); + BOOST_TEST(memory_is_zero(raw, sizeof raw)); + + // A vector of words: size() * sizeof(element) bytes. + std::vector words(8, 0xdeadbeefU); + secure::erase_secret(words); + BOOST_TEST(memory_is_zero(words.data(), words.size() * sizeof(std::uint32_t))); + + // detail::wipe, the function under erase_secret: it zeroes the bytes it is given and none + // around them, and a null pointer with no bytes is a call that does nothing. + std::array framed_bytes{}; + framed_bytes.fill(0xa5); + webcpp::secure::detail::wipe(framed_bytes.data() + 1, 32); + BOOST_TEST_EQ(framed_bytes.front(), 0xa5); + BOOST_TEST_EQ(framed_bytes.back(), 0xa5); + BOOST_TEST(memory_is_zero(framed_bytes.data() + 1, 32)); + webcpp::secure::detail::wipe(nullptr, 0); + + // An empty vector: nothing to erase. + std::vector empty; + secure::erase_secret(empty); + BOOST_TEST(empty.empty()); + + // A buffer erased as its scope ends is zero afterwards, at -O2 with every call inlined. + BOOST_TEST(erasure_before_scope_end_stays()); + + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/messages/Jamfile b/test/messages/Jamfile new file mode 100644 index 0000000..4c64bd2 --- /dev/null +++ b/test/messages/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# Each message test in a directory of its own (spec section 4.3's pitfall): a +# directory's Jamfile gives its case the requirements that raise the message, +# and nothing else. + +build-project secret_of_no_bytes ; +build-project erase_secret_const_range ; diff --git a/test/messages/erase_secret_const_range/Jamfile b/test/messages/erase_secret_const_range/Jamfile new file mode 100644 index 0000000..61a6fec --- /dev/null +++ b/test/messages/erase_secret_const_range/Jamfile @@ -0,0 +1,14 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/secure//secure ; + +import webcpp ; + +# alone: the refusal is the compile's only error, so a regression that puts +# another error before or after it fails the test. +webcpp.compile-diagnostic erase_secret_const_range : erase_secret_const_range.cpp + : : native wasip2 wasip3 : alone ; diff --git a/test/messages/erase_secret_const_range/erase_secret_const_range.cpp b/test/messages/erase_secret_const_range/erase_secret_const_range.cpp new file mode 100644 index 0000000..6138623 --- /dev/null +++ b/test/messages/erase_secret_const_range/erase_secret_const_range.cpp @@ -0,0 +1,31 @@ +// 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) + +// erase_secret writes the buffer it erases: a program that hands it a const string stops at the +// call, with a message that names the ranges it takes, and with that error alone. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/secure/erase_secret.hpp:* {{webcpp::secure: 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.}} +// clang-format on + +#include + +#include + +namespace { + +void forget(std::string const& password) { + webcpp::secure::erase_secret(password); +} + +} // namespace + +int main() { + forget("correct horse battery staple"); + return 0; +} diff --git a/test/messages/secret_of_no_bytes/Jamfile b/test/messages/secret_of_no_bytes/Jamfile new file mode 100644 index 0000000..1e3329e --- /dev/null +++ b/test/messages/secret_of_no_bytes/Jamfile @@ -0,0 +1,12 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +project : requirements /webcpp/secure//secure ; + +import webcpp ; + +webcpp.compile-diagnostic secret_of_no_bytes : secret_of_no_bytes.cpp + : : native wasip2 wasip3 ; diff --git a/test/messages/secret_of_no_bytes/secret_of_no_bytes.cpp b/test/messages/secret_of_no_bytes/secret_of_no_bytes.cpp new file mode 100644 index 0000000..b2dae57 --- /dev/null +++ b/test/messages/secret_of_no_bytes/secret_of_no_bytes.cpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A program that names a secret of no bytes stops where it names it. + +// clang's -verify reads a directive from one comment line: wrapped, it checks nothing, so each +// whole text stays on one line. +// clang-format off +// expected-error@webcpp/secure/secret.hpp:* {{webcpp::secure: a secret of no bytes holds nothing.}} +// clang-format on + +#include + +int main() { + return static_cast(webcpp::secure::secret<0>::size_bytes); +} diff --git a/test/secret_test.cpp b/test/secret_test.cpp new file mode 100644 index 0000000..d00fa00 --- /dev/null +++ b/test/secret_test.cpp @@ -0,0 +1,195 @@ +// 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) + +// secret is not copyable, clone copies by name, a move leaves the source zero, it converts to +// a span of fixed size, and its storage is zero after its destructor, read at -O2 (the Jamfile's +// speed), where a store the optimiser may drop is the case. + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace secure = webcpp::secure; + +using key = secure::secret<32>; + +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(std::is_convertible_v>); +static_assert(key::size() == 32 && key::size_bytes == 32); +static_assert(sizeof(key) == 32); + +// A view of a secret that is about to die does not compile: it would dangle. +template +concept views_lvalue = requires(T& k) { k.bytes(); } && requires(T& k) { k.writable(); }; +template +concept views_const_lvalue = requires(T const& k) { k.bytes(); }; +template +concept writes_const_lvalue = requires(T const& k) { k.writable(); }; +template +concept views_rvalue_bytes = requires { T{}.bytes(); }; +template +concept views_rvalue_writable = requires { T{}.writable(); }; +template +concept spans_rvalue = std::is_convertible_v>; + +static_assert(views_lvalue); +static_assert(views_const_lvalue); +static_assert(!writes_const_lvalue); +static_assert(!views_rvalue_bytes); +static_assert(!views_rvalue_writable); +static_assert(!spans_rvalue); + +void fill(key& target, std::uint8_t first) { + auto const bytes = target.writable(); + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(first + i); + } +} + +// A function the optimiser cannot see into, so that what it is handed is read from memory. +#if defined(_MSC_VER) && !defined(__clang__) +#define WEBCPP_TEST_NOINLINE __declspec(noinline) +#else +#define WEBCPP_TEST_NOINLINE __attribute__((noinline)) +#endif + +// Whether every byte at `where` is zero, read through a volatile pointer in a function that is +// never inlined: a store that was dropped before the call is found here. It may be handed the +// address of an object that is gone (the point of the destructor's check), so it is exempt from +// the sanitizers that would stop that read. +#if defined(__clang__) || defined(__GNUC__) +__attribute__((no_sanitize("address"))) +#endif +WEBCPP_TEST_NOINLINE bool memory_is_zero(std::uint8_t const* where, std::size_t count) { + auto const volatile* const bytes = where; + for (std::size_t i = 0; i < count; ++i) { + if (bytes[i] != 0) { + return false; + } + } + return true; +} + +// The same, for a secret that is alive. +bool is_zero(key const& source) { + return memory_is_zero(source.bytes().data(), source.bytes().size()); +} + +// A secret in a scope of its own, which a call the optimiser cannot see into is handed, is +// destroyed; its storage, in this frame, is read after the scope. A wipe that is a dead store +// (a plain write to an object about to die) is dropped by the optimiser and the bytes remain. +WEBCPP_TEST_NOINLINE bool destruction_leaves_zero() { + std::uint8_t const* where = nullptr; + { + key local; + fill(local, 1); + where = local.bytes().data(); + if (memory_is_zero(where, key::size())) { + return false; + } + } + return memory_is_zero(where, key::size()); +} + +// Whether any byte of the storage is not zero, read through a volatile pointer. +bool any_set(std::array const& storage) { + auto const* const bytes = reinterpret_cast(storage.data()); + for (std::size_t i = 0; i < storage.size(); ++i) { + if (bytes[i] != 0) { + return true; + } + } + return false; +} + +} // namespace + +int main() { + // A new secret is zero. + key const zero; + BOOST_TEST(is_zero(zero)); + + // A secret that is destroyed in an ordinary scope leaves zero behind, at -O2. + BOOST_TEST(destruction_leaves_zero()); + + // clone copies, and the two are then independent. + key original; + fill(original, 1); + key copy = original.clone(); + BOOST_TEST(!is_zero(original)); + BOOST_TEST(std::equal(copy.bytes().begin(), copy.bytes().end(), original.bytes().begin())); + copy.writable()[0] = 0xee; + BOOST_TEST_EQ(original.bytes()[0], 1); + + // A move construction leaves the source zero and the destination with the bytes. + key from; + fill(from, 7); + key const expected = from.clone(); + key const to(std::move(from)); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from secret's bytes are what is tested + BOOST_TEST(is_zero(from)); + BOOST_TEST(std::equal(to.bytes().begin(), to.bytes().end(), expected.bytes().begin())); + + // A move assignment does too, over the destination's own bytes. + key assigned; + fill(assigned, 100); + key source; + fill(source, 7); + assigned = std::move(source); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from secret's bytes are what is tested + BOOST_TEST(is_zero(source)); + BOOST_TEST( + std::equal(assigned.bytes().begin(), assigned.bytes().end(), expected.bytes().begin())); + + // A move assignment to itself keeps the bytes; clone of a moved-from secret is zero. + { + key self; + fill(self, 9); + key& alias = self; + self = std::move(alias); + BOOST_TEST(!is_zero(self)); + BOOST_TEST_EQ(self.bytes()[0], 9); + + key gone; + fill(gone, 5); + key const taker(std::move(gone)); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from secret's clone is what is tested + key const empty = gone.clone(); + BOOST_TEST(is_zero(empty)); + BOOST_TEST(!is_zero(taker)); + } + + // The conversion to a span of fixed size views the same bytes. + std::span const view = expected; + BOOST_TEST(view.data() == expected.bytes().data()); + BOOST_TEST_EQ(view.size(), 32u); + + // After the destructor, the storage is zero. + alignas(key) std::array storage{}; + auto* const placed = new (storage.data()) key; + fill(*placed, 1); + BOOST_TEST(any_set(storage)); + std::destroy_at(placed); + BOOST_TEST(!any_set(storage)); + + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/wipe_record_test.cpp b/test/wipe_record_test.cpp new file mode 100644 index 0000000..071f46d --- /dev/null +++ b/test/wipe_record_test.cpp @@ -0,0 +1,184 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The wipe's test seam: built with WEBCPP_SECURE_TEST_WIPE_RECORD, every wipe is reported to this +// test once, after its bytes are zero, with the address and the size it wiped. The test checks +// what erase_secret and secret report: one record for an erased range, one for a destroyed +// secret, two for a move assignment (the target before it takes the bytes, the source after), +// one for a move construction, and one of size 0 for an empty range. + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef WEBCPP_SECURE_TEST_WIPE_RECORD +#error "wipe_record_test is built with WEBCPP_SECURE_TEST_WIPE_RECORD (test/Jamfile)" +#endif + +namespace { + +namespace secure = webcpp::secure; + +// One wipe: where, how many bytes, and whether they read zero when it was reported. +struct wipe_entry { + void const* at = nullptr; + std::size_t size = 0; + bool zero = false; +}; + +// The wipes reported since the last clear. +struct record { + std::array entries{}; + std::size_t count = 0; +}; + +// The seam's record, which detail::wipe reaches through a function of this test. +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the seam's record +record wipes; + +void clear() { + wipes = record{}; +} + +} // namespace + +void webcpp::secure::test::wipe_record(void const* wiped_data, std::size_t byte_count) noexcept { + bool zero = true; + auto const* const bytes = static_cast(wiped_data); + for (std::size_t i = 0; i < byte_count; ++i) { + if (bytes[i] != 0) { + zero = false; + break; + } + } + if (wipes.count < wipes.entries.size()) { + wipes.entries[wipes.count] = wipe_entry{.at = wiped_data, .size = byte_count, .zero = zero}; + } + ++wipes.count; +} + +namespace { + +struct context { + std::uint64_t key[4]; // NOLINT(modernize-avoid-c-arrays): a C library's plain state +}; + +void test_erase_array() { + std::array bytes{}; + bytes.fill(0xa5); + clear(); + secure::erase_secret(bytes); + BOOST_TEST_EQ(wipes.count, 1U); + BOOST_TEST(wipes.entries[0].at == bytes.data()); + BOOST_TEST_EQ(wipes.entries[0].size, 32U); + BOOST_TEST(wipes.entries[0].zero); +} + +void test_erase_span_of_object() { + context object{{1, 2, 3, 4}}; + clear(); + secure::erase_secret(std::span(&object, 1)); + BOOST_TEST_EQ(wipes.count, 1U); + BOOST_TEST(wipes.entries[0].at == &object); + BOOST_TEST_EQ(wipes.entries[0].size, sizeof(context)); + BOOST_TEST(wipes.entries[0].zero); + BOOST_TEST_EQ(object.key[0] | object.key[1] | object.key[2] | object.key[3], 0U); +} + +void test_erase_subspan() { + std::array framed{}; + framed.fill(0xa5); + clear(); + secure::erase_secret(std::span(framed).subspan(1, 32)); + BOOST_TEST_EQ(wipes.count, 1U); + BOOST_TEST(wipes.entries[0].at == framed.data() + 1); + BOOST_TEST_EQ(wipes.entries[0].size, 32U); + BOOST_TEST(wipes.entries[0].zero); + BOOST_TEST_EQ(framed.front(), 0xa5); + BOOST_TEST_EQ(framed.back(), 0xa5); +} + +// An empty range is one report of size 0: the wipe is called, and has no byte to write. +void test_erase_empty() { + clear(); + secure::erase_secret(std::span()); + BOOST_TEST_EQ(wipes.count, 1U); + BOOST_TEST(wipes.entries[0].at == nullptr); + BOOST_TEST_EQ(wipes.entries[0].size, 0U); + BOOST_TEST(wipes.entries[0].zero); + + clear(); + secure::detail::wipe(nullptr, 0); + BOOST_TEST_EQ(wipes.count, 1U); + BOOST_TEST_EQ(wipes.entries[0].size, 0U); +} + +void test_destroy_secret() { + alignas(secure::secret<16>) std::array)> storage{}; + auto* const placed = new (storage.data()) secure::secret<16>; + for (auto& byte : placed->writable()) { + byte = 0x5a; + } + clear(); + std::destroy_at(placed); + BOOST_TEST_EQ(wipes.count, 1U); + BOOST_TEST(wipes.entries[0].at == storage.data()); + BOOST_TEST_EQ(wipes.entries[0].size, 16U); + BOOST_TEST(wipes.entries[0].zero); +} + +void test_move_secret() { + secure::secret<16> source; + secure::secret<16> target; + for (auto& byte : source.writable()) { + byte = 0x5a; + } + for (auto& byte : target.writable()) { + byte = 0xc3; + } + clear(); + target = std::move(source); + // The target's old bytes first, then the source after the move. + BOOST_TEST_EQ(wipes.count, 2U); + BOOST_TEST(wipes.entries[0].at == &target); + BOOST_TEST(wipes.entries[1].at == &source); + for (std::size_t i = 0; i < 2; ++i) { + BOOST_TEST_EQ(wipes.entries[i].size, 16U); + BOOST_TEST(wipes.entries[i].zero); + } + BOOST_TEST_EQ(target.bytes()[0], 0x5a); + + clear(); + secure::secret<16> const taker(std::move(target)); + BOOST_TEST_EQ(wipes.count, 1U); + BOOST_TEST(wipes.entries[0].at == &target); + BOOST_TEST_EQ(wipes.entries[0].size, 16U); + BOOST_TEST(wipes.entries[0].zero); + BOOST_TEST_EQ(taker.bytes()[0], 0x5a); +} + +} // namespace + +int main() { + test_erase_array(); + test_erase_span_of_object(); + test_erase_subspan(); + test_erase_empty(); + test_destroy_secret(); + test_move_secret(); + return webcpp::test::exit_status(boost::report_errors()); +} From 860ddbc20c3cc5323cce72f72e74dcdadebf5a8d Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 17:30:18 -0300 Subject: [PATCH 06/42] secure: wipe_record_test names the moved-from addresses before the move --- test/wipe_record_test.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/test/wipe_record_test.cpp b/test/wipe_record_test.cpp index 071f46d..914df02 100644 --- a/test/wipe_record_test.cpp +++ b/test/wipe_record_test.cpp @@ -150,12 +150,14 @@ void test_move_secret() { for (auto& byte : target.writable()) { byte = 0xc3; } + void const* const source_at = &source; + void const* const target_at = ⌖ clear(); target = std::move(source); // The target's old bytes first, then the source after the move. BOOST_TEST_EQ(wipes.count, 2U); - BOOST_TEST(wipes.entries[0].at == &target); - BOOST_TEST(wipes.entries[1].at == &source); + BOOST_TEST(wipes.entries[0].at == target_at); + BOOST_TEST(wipes.entries[1].at == source_at); for (std::size_t i = 0; i < 2; ++i) { BOOST_TEST_EQ(wipes.entries[i].size, 16U); BOOST_TEST(wipes.entries[i].zero); @@ -165,7 +167,7 @@ void test_move_secret() { clear(); secure::secret<16> const taker(std::move(target)); BOOST_TEST_EQ(wipes.count, 1U); - BOOST_TEST(wipes.entries[0].at == &target); + BOOST_TEST(wipes.entries[0].at == target_at); BOOST_TEST_EQ(wipes.entries[0].size, 16U); BOOST_TEST(wipes.entries[0].zero); BOOST_TEST_EQ(taker.bytes()[0], 0x5a); From c2acc2db3bc660eeeecc077d08ce902ef2c9a9c9 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 17:46:12 -0300 Subject: [PATCH 07/42] secure: constant_time_equal over any two byte sequences, and declassify with its checkers' marks as test support --- include/webcpp/secure.hpp | 2 + include/webcpp/secure/constant_time_equal.hpp | 128 ++++++++++ include/webcpp/secure/declassify.hpp | 57 +++++ test/Jamfile | 9 + test/constant_time_equal_test.cpp | 231 ++++++++++++++++++ test/declassify_compile_test.cpp | 95 +++++++ test/support/constant_time_marks.hpp | 135 ++++++++++ .../support/valgrind_stub/valgrind/memcheck.h | 30 +++ 8 files changed, 687 insertions(+) create mode 100644 include/webcpp/secure/constant_time_equal.hpp create mode 100644 include/webcpp/secure/declassify.hpp create mode 100644 test/constant_time_equal_test.cpp create mode 100644 test/declassify_compile_test.cpp create mode 100644 test/support/constant_time_marks.hpp create mode 100644 test/support/valgrind_stub/valgrind/memcheck.h diff --git a/include/webcpp/secure.hpp b/include/webcpp/secure.hpp index ae1385d..392499c 100644 --- a/include/webcpp/secure.hpp +++ b/include/webcpp/secure.hpp @@ -12,6 +12,8 @@ #define WEBCPP_SECURE_HPP #include +#include +#include #include #include #include diff --git a/include/webcpp/secure/constant_time_equal.hpp b/include/webcpp/secure/constant_time_equal.hpp new file mode 100644 index 0000000..cbdbce8 --- /dev/null +++ b/include/webcpp/secure/constant_time_equal.hpp @@ -0,0 +1,128 @@ +// 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 two byte sequences: tags, MACs, digests. + + It includes no header of a hash library: a hash library's digest, a `std::array`, a `std::span`, a + `std::string_view`, a `secret` are byte sequences by their shape. +*/ +#ifndef WEBCPP_SECURE_CONSTANT_TIME_EQUAL_HPP +#define WEBCPP_SECURE_CONSTANT_TIME_EQUAL_HPP + +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::secure { + +namespace detail { + +/** An element type that is one byte: `std::uint8_t`, `unsigned char`, `char`, `std::byte`. */ +template +concept byte_element = + std::same_as, std::uint8_t> || + std::same_as, unsigned char> || std::same_as, char> || + std::same_as, std::byte>; + +/** + A contiguous sized range of bytes, or a type whose `bytes()` gives a span of them, as `secret` + does. +*/ +template +concept byte_sequence = + (std::ranges::contiguous_range && std::ranges::sized_range && + byte_element>) || + requires(T const& value) { + { value.bytes() } -> std::convertible_to>; + }; + +/** + The bytes of a sequence, as an address and a size. + + @tparam Element The element type, without cv. +*/ +template +struct byte_view { + /** The first element; null when the sequence has none. */ + Element const* first; + /** The number of elements. */ + std::size_t count; +}; + +/** + Views a sequence as its `bytes()` when it has one, else as its range. + + @param sequence The sequence. + @return Its bytes' address and size; nothing is read. +*/ +template +[[nodiscard]] constexpr auto view_bytes(Sequence const& sequence) noexcept { + if constexpr (requires { + { sequence.bytes() } -> std::convertible_to>; + }) { + std::span const bytes = sequence.bytes(); + return byte_view{.first = bytes.data(), .count = bytes.size()}; + } else { + using element = std::remove_cv_t>; + return byte_view{ + .first = std::ranges::data(sequence), + .count = std::ranges::size(sequence), + }; + } +} + +} // namespace detail + +/** + * 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: sequences 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. + * + * @tparam First The first operand's type. + * @tparam Second The second operand's type. + * @param first_operand The first sequence, a tag or a MAC: a contiguous sized range of bytes + * (`std::span`, `std::array`, `std::vector`, `std::string_view`, a hash library's digest), or a + * type whose `bytes()` gives the bytes, as `secret`. + * @param second_operand The second. + * @return Whether they have the same size and the same bytes. + */ +template + requires detail::byte_sequence && detail::byte_sequence +[[nodiscard]] bool constant_time_equal(First const& first_operand, + Second const& second_operand) noexcept { + timing_guard const timing_scope; + auto const first = detail::view_bytes(first_operand); + auto const second = detail::view_bytes(second_operand); + if (first.count != second.count) { + return false; + } + unsigned volatile accumulated_difference = 0; + for (std::size_t byte_index = 0; byte_index < first.count; ++byte_index) { + auto const first_byte = static_cast(first.first[byte_index]); + auto const second_byte = static_cast(second.first[byte_index]); + accumulated_difference = + accumulated_difference | static_cast(first_byte ^ second_byte); + } + unsigned const total_difference = accumulated_difference; + // total_difference is at most 255: minus 1 wraps to the type's maximum only when it is 0. + return (((total_difference - 1U) >> 8U) & 1U) != 0; +} + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_CONSTANT_TIME_EQUAL_HPP diff --git a/include/webcpp/secure/declassify.hpp b/include/webcpp/secure/declassify.hpp new file mode 100644 index 0000000..22ed5ff --- /dev/null +++ b/include/webcpp/secure/declassify.hpp @@ -0,0 +1,57 @@ +// 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) + +/** + `declassify`, which marks a value derived from secrets as public, where webcpp's code branches on + it by design: the verdict of a tag's check. + + It does nothing in a program's build and includes nothing. A constant-time test defines + `WEBCPP_SECURE_CT_VALGRIND` or `WEBCPP_SECURE_CT_MSAN`, and the mark is then Valgrind's or + MemorySanitizer's, so that the checker reports every other branch on a secret and not this one. +*/ +#ifndef WEBCPP_SECURE_DECLASSIFY_HPP +#define WEBCPP_SECURE_DECLASSIFY_HPP + +#include + +#if defined(WEBCPP_SECURE_CT_VALGRIND) && defined(WEBCPP_SECURE_CT_MSAN) +#error "define WEBCPP_SECURE_CT_VALGRIND or WEBCPP_SECURE_CT_MSAN, not both" +#endif + +#ifdef WEBCPP_SECURE_CT_VALGRIND +#include +#elif defined(WEBCPP_SECURE_CT_MSAN) +#include +#endif + +#include + +namespace webcpp::secure { + +/** + * Marks a value as public for the constant-time checkers; nothing in a program's build. + * + * The object is never const, so the branch that follows reads it again after the mark instead of + * a register the compiler kept from before it (BoringSSL's practice). + * + * @tparam T The value's type, trivially copyable. + * @param value The value, derived from secrets, that the code branches on. + */ +template + requires std::is_trivially_copyable_v && (!std::is_const_v) +void declassify(T& value) noexcept { +#ifdef WEBCPP_SECURE_CT_VALGRIND + static_cast(VALGRIND_MAKE_MEM_DEFINED(&value, sizeof value)); +#elif defined(WEBCPP_SECURE_CT_MSAN) + __msan_unpoison(&value, sizeof value); +#else + static_cast(value); +#endif +} + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_DECLASSIFY_HPP diff --git a/test/Jamfile b/test/Jamfile index 465406a..eeb54ba 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -69,4 +69,13 @@ secure-run secret : secret_test.cpp : $(OPTIMISED) full ; # The wipe's test seam (B9): every wipe reported once, its bytes already zero. secure-run wipe_record : wipe_record_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +# constant_time_equal over any two byte sequences, its guard through the seam. +secure-run constant_time_equal : constant_time_equal_test.cpp ; +# declassify with the memcheck build's marks, on every lane, against a stand-in +# for Valgrind's header; and with MemorySanitizer's under clang natively. +secure-run declassify_compile : declassify_compile_test.cpp + : WEBCPP_SECURE_CT_VALGRIND support/valgrind_stub ; +secure-compile declassify_compile_msan : declassify_compile_test.cpp + : WEBCPP_SECURE_CT_MSAN gcc:no msvc:no + : native ; build-project messages ; diff --git a/test/constant_time_equal_test.cpp b/test/constant_time_equal_test.cpp new file mode 100644 index 0000000..07b362a --- /dev/null +++ b/test/constant_time_equal_test.cpp @@ -0,0 +1,231 @@ +// 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 compares any two byte sequences (spans, arrays of bytes, secrets, string +// views, Boost.Hash2 digests), tells them apart by any bit, calls sequences of different sizes +// unequal without reading them, and enters the guard of once +// per call, from its own header. + +#include "support/timing_seam.hpp" + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace secure = webcpp::secure; +namespace seam = webcpp::secure::test; + +static_assert(!secure::detail::byte_sequence>); +static_assert(!secure::detail::byte_sequence>); +static_assert(!secure::detail::byte_sequence); +static_assert(secure::detail::byte_sequence>); +static_assert(secure::detail::byte_sequence); +static_assert(secure::detail::byte_sequence>); +static_assert(secure::detail::byte_sequence>); +static_assert(secure::detail::byte_sequence>); + +/** A sequence with no storage that claims `size()` elements: reading one would crash. */ +struct null_sequence { + std::size_t claimed; + + [[nodiscard]] static unsigned char const* begin() noexcept { return nullptr; } + + [[nodiscard]] static unsigned char const* end() noexcept { return nullptr; } + + [[nodiscard]] static unsigned char const* data() noexcept { return nullptr; } + + [[nodiscard]] std::size_t size() const noexcept { return claimed; } +}; + +static_assert(secure::detail::byte_sequence); + +secure::secret<32> make_secret(std::uint8_t first) { + secure::secret<32> made; + auto const bytes = made.writable(); + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(first + i); + } + return made; +} + +std::array base_bytes() { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(0x80U + i); + } + return bytes; +} + +/** Checks a representation of the base sequence against each of its one-bit flips. */ +template +void check_flips(Make make) { + auto const base = base_bytes(); + auto const same = make(base); + BOOST_TEST(secure::constant_time_equal(same, make(base))); + for (std::size_t byte = 0; byte < base.size(); ++byte) { + for (unsigned bit = 0; bit < 8; ++bit) { + auto flipped = base; + flipped[byte] ^= static_cast(1U << bit); + BOOST_TEST(!secure::constant_time_equal(same, make(flipped))); + BOOST_TEST(!secure::constant_time_equal(make(flipped), same)); + } + } +} + +void shapes() { + check_flips([](std::array const& bytes) { + return std::span(bytes); + }); + check_flips([](std::array const& bytes) { return bytes; }); + check_flips([](std::array const& bytes) { + std::array made{}; + for (std::size_t i = 0; i < made.size(); ++i) { + made[i] = static_cast(bytes[i]); + } + return made; + }); + check_flips([](std::array const& bytes) { + secure::secret<32> made; + std::ranges::copy(bytes, made.writable().begin()); + return made; + }); + check_flips([](std::array const& bytes) { + boost::hash2::digest<32> made{}; + std::ranges::copy(bytes, made.data()); + return made; + }); + check_flips([](std::array const& bytes) { + return std::vector(bytes.begin(), bytes.end()); + }); + // A std::string_view of bytes 0x80 to 0x9F: char is signed on most targets. + static constexpr std::string_view high = + "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" + "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f"; + static_assert(high.size() == 32); + BOOST_TEST(secure::constant_time_equal(high, high)); + BOOST_TEST(secure::constant_time_equal(high, base_bytes())); + for (std::size_t byte = 0; byte < high.size(); ++byte) { + for (unsigned bit = 0; bit < 8; ++bit) { + auto flipped = base_bytes(); + flipped[byte] ^= static_cast(1U << bit); + BOOST_TEST(!secure::constant_time_equal(high, flipped)); + BOOST_TEST(!secure::constant_time_equal(flipped, high)); + } + } +} + +void mixed_pairs() { + auto const base = base_bytes(); + boost::hash2::digest<32> digest{}; + std::ranges::copy(base, digest.data()); + BOOST_TEST(secure::constant_time_equal(digest, base)); + BOOST_TEST(secure::constant_time_equal(base, digest)); + secure::secret<32> const secret_bytes = make_secret(0x80); + BOOST_TEST(secure::constant_time_equal(secret_bytes, std::span(base))); + BOOST_TEST(secure::constant_time_equal(std::span(base), secret_bytes)); + // A temporary secret, bound to the const& for the call. + BOOST_TEST(secure::constant_time_equal(make_secret(0x80), base)); + BOOST_TEST(!secure::constant_time_equal(make_secret(0x81), base)); + BOOST_TEST(secure::constant_time_equal(make_secret(1), make_secret(1))); + BOOST_TEST(!secure::constant_time_equal(make_secret(1), make_secret(2))); + BOOST_TEST(secure::constant_time_equal(secret_bytes, digest)); +} + +void sizes() { + std::array const thirty_two = base_bytes(); + std::span const thirty_one(thirty_two.data(), 31); + BOOST_TEST(!secure::constant_time_equal(thirty_one, thirty_two)); + BOOST_TEST(!secure::constant_time_equal(thirty_two, thirty_one)); + // Sizes are compared first: no byte of a sequence with no storage is read. + BOOST_TEST(!secure::constant_time_equal(null_sequence{31}, thirty_two)); + BOOST_TEST(!secure::constant_time_equal(thirty_two, null_sequence{31})); + BOOST_TEST(secure::constant_time_equal(null_sequence{0}, std::span())); + BOOST_TEST(secure::constant_time_equal(std::span(), + std::span())); + boost::hash2::digest<16> const sixteen{}; + std::array const fifteen{}; + BOOST_TEST(!secure::constant_time_equal(sixteen, fifteen)); +} + +void guard_through_the_seam() { + std::array const bytes = base_bytes(); + seam::timing_entries = 0; + seam::timing_first_entry = nullptr; + BOOST_TEST(secure::constant_time_equal(bytes, bytes)); + BOOST_TEST_EQ(seam::timing_entries, 1U); + BOOST_TEST(seam::timing_first_entry != nullptr); + if (seam::timing_first_entry != nullptr) { + BOOST_TEST(std::string_view(seam::timing_first_entry).find("constant_time_equal") != + std::string_view::npos); + } + // Each call is one guard, equal or not, and with unequal sizes too. + seam::timing_entries = 0; + BOOST_TEST( + !secure::constant_time_equal(bytes, std::span(bytes.data(), 31))); + BOOST_TEST_EQ(seam::timing_entries, 1U); + BOOST_TEST(secure::constant_time_equal(make_secret(3), make_secret(3))); + BOOST_TEST_EQ(seam::timing_entries, 2U); +} + +} // namespace + +int main() { + // The prior's cases: digests, arrays, spans, Hash2's MAC. + boost::hash2::digest<16> const a{}; + boost::hash2::digest<16> b{}; + BOOST_TEST(secure::constant_time_equal(a, b)); + for (std::size_t i = 0; i < a.size(); ++i) { + for (unsigned bit = 0; bit < 8; ++bit) { + b = a; + b.data()[i] ^= static_cast(1U << bit); + BOOST_TEST(!secure::constant_time_equal(a, b)); + } + } + std::array const array{}; + BOOST_TEST(secure::constant_time_equal(a, array)); + std::array const eight{1, 2, 3, 4, 5, 6, 7, 8}; + auto different_first = eight; + different_first.front() ^= 0x80U; + auto different_last = eight; + different_last.back() ^= 0x01U; + BOOST_TEST(secure::constant_time_equal(std::span(eight), std::span(eight))); + BOOST_TEST(!secure::constant_time_equal(std::span(eight), + std::span(different_first))); + BOOST_TEST(!secure::constant_time_equal(std::span(eight), + std::span(different_last))); + boost::hash2::digest<32> const first_digest{}; + boost::hash2::digest<32> second_digest{}; + BOOST_TEST(secure::constant_time_equal(first_digest, second_digest)); + second_digest.data()[31] = 1; + BOOST_TEST(!secure::constant_time_equal(first_digest, second_digest)); + boost::hash2::hmac_sha2_256 first(reinterpret_cast("key"), 3); + boost::hash2::hmac_sha2_256 second(reinterpret_cast("key"), 3); + first.update("message", 7); + second.update("message", 7); + BOOST_TEST(secure::constant_time_equal(first.result(), second.result())); + + shapes(); + mixed_pairs(); + sizes(); + guard_through_the_seam(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/declassify_compile_test.cpp b/test/declassify_compile_test.cpp new file mode 100644 index 0000000..48a9180 --- /dev/null +++ b/test/declassify_compile_test.cpp @@ -0,0 +1,95 @@ +// 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) + +// declassify and the checkers' marks (support/constant_time_marks.hpp) compile with the marks +// on: Valgrind's (WEBCPP_SECURE_CT_VALGRIND, the Jamfile's, against a stand-in header that reads +// its arguments, on every lane) or MemorySanitizer's (WEBCPP_SECURE_CT_MSAN, compiled under clang +// natively). The test defines neither macro itself. Outside those builds declassify expands to +// nothing, so a mark that names a local no longer there compiles everywhere else; here it stops +// the build. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "support/constant_time_marks.hpp" + +#include +#include +#include + +#if !defined(WEBCPP_SECURE_CT_VALGRIND) && !defined(WEBCPP_SECURE_CT_MSAN) +#error \ + "the test compiles the marks of a checker's build: define WEBCPP_SECURE_CT_VALGRIND or WEBCPP_SECURE_CT_MSAN" +#endif + +namespace { + +namespace secure = webcpp::secure; +namespace marks = webcpp::secure::test; + +#ifdef WEBCPP_SECURE_CT_VALGRIND +using checker = marks::memcheck; +#else +using checker = marks::memory_sanitizer; +#endif + +template +concept declassifiable = requires(T& value) { secure::declassify(value); }; + +static_assert(declassifiable); +static_assert(declassifiable); +static_assert(declassifiable>); +static_assert(!declassifiable); +static_assert(!declassifiable); + +/** Marks bytes with the checker's primitives and reads its shadow, so that all are compiled. */ +bool uses_marks() { + std::array bytes{}; + checker::mark_secret(bytes); + checker::mark_public(bytes); + bool const verdict = true; + checker::verdict(verdict); + return marks::carries_mark(bytes) && verdict; +} + +} // namespace + +int main() { + bool verdict = + secure::constant_time_equal(std::array{}, std::array{}); + secure::declassify(verdict); + std::uint32_t word = 7; + secure::declassify(word); + std::array bytes{1, 2, 3, 4}; + secure::declassify(bytes); + int failed = 0; + if (!verdict) { + ++failed; + } + if (word != 7) { + ++failed; + } + if (bytes[3] != 4) { + ++failed; + } +#ifdef WEBCPP_SECURE_CT_VALGRIND + // The stand-in's shadow is not readable: no byte carries the mark. + if (uses_marks()) { + ++failed; + } +#else + // MemorySanitizer's marks need an instrumented program: compiled, not run. + static_cast(&uses_marks); +#endif + return webcpp::test::exit_status(failed); +} diff --git a/test/support/constant_time_marks.hpp b/test/support/constant_time_marks.hpp new file mode 100644 index 0000000..7a01914 --- /dev/null +++ b/test/support/constant_time_marks.hpp @@ -0,0 +1,135 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The primitives of the constant-time checkers, for secure's tests and the constant-time lane's +// programs: under WEBCPP_SECURE_CT_VALGRIND memcheck's, under WEBCPP_SECURE_CT_MSAN +// MemorySanitizer's. A checker is a type with +// +// - `static void mark_secret(std::span)`: the bytes are secret from now on; +// - `static void mark_public(std::span)`: the bytes are public; +// - `static std::optional traced(std::span)`: whether the secret mark +// reached some byte of these; empty when the checker could not read its own shadow; +// - `static void verdict(bool const&)`: the verdict, whether a tag matched, must be public, the +// checker reports it otherwise; +// +// and two facts about its shadow: `exact_subtraction`, whether the mark follows a subtraction's +// carry (memcheck's does, MemorySanitizer's approximation drops it), and `reads_destroyed`, +// whether a destroyed object's bytes can be read back (MemorySanitizer marks them by itself). +// Crypto keeps its own copies of the two structs. + +#ifndef WEBCPP_TEST_SECURE_SUPPORT_CONSTANT_TIME_MARKS_HPP +#define WEBCPP_TEST_SECURE_SUPPORT_CONSTANT_TIME_MARKS_HPP + +#if defined(WEBCPP_SECURE_CT_VALGRIND) && defined(WEBCPP_SECURE_CT_MSAN) +#error "define WEBCPP_SECURE_CT_VALGRIND or WEBCPP_SECURE_CT_MSAN, not both" +#endif + +#ifdef WEBCPP_SECURE_CT_VALGRIND +#include +#elif defined(WEBCPP_SECURE_CT_MSAN) +#include +#endif + +#include +#include +#include +#include +#include +#include + +namespace webcpp::secure::test { + +#ifdef WEBCPP_SECURE_CT_VALGRIND + +/** memcheck's primitives. */ +struct memcheck { + /** memcheck follows a subtraction's carry. */ + static constexpr bool exact_subtraction = true; + /** A destroyed object's bytes keep their definedness. */ + static constexpr bool reads_destroyed = true; + + /** Marks bytes secret: memcheck's undefined. */ + static void mark_secret(std::span bytes) { + VALGRIND_MAKE_MEM_UNDEFINED(bytes.data(), bytes.size()); + } + + /** Marks bytes public: defined. */ + static void mark_public(std::span bytes) { + VALGRIND_MAKE_MEM_DEFINED(bytes.data(), bytes.size()); + } + + /** + * Whether memcheck holds some bit of the first 64 of `bytes` undefined, read from its own + * shadow without an error; empty when memcheck cannot read it (not under Valgrind, or the + * bytes are not addressable). + */ + static std::optional traced(std::span bytes) { + std::array bits{}; + std::size_t const size = (std::min)(bytes.size(), bits.size()); + if (VALGRIND_GET_VBITS(bytes.data(), bits.data(), size) != 1) { + return std::nullopt; + } + return std::any_of(bits.begin(), bits.begin() + static_cast(size), + [](std::uint8_t bit) { return bit != 0; }); + } + + /** Reports the verdict when it is undefined. */ + static void verdict(bool const& value) { + static_cast(VALGRIND_CHECK_VALUE_IS_DEFINED(value)); + } +}; + +#elif defined(WEBCPP_SECURE_CT_MSAN) + +/** MemorySanitizer's primitives. */ +struct memory_sanitizer { + /** A subtraction's shadow drops the carry. */ + static constexpr bool exact_subtraction = false; + /** + * A destroyed object is poisoned by MemorySanitizer itself (-fsanitize-memory-use-after-dtor, + * on by default). + */ + static constexpr bool reads_destroyed = false; + + /** Poisons bytes: they are secret. */ + static void mark_secret(std::span bytes) { + __msan_poison(bytes.data(), bytes.size()); + } + + /** Unpoisons bytes: they are public. */ + static void mark_public(std::span bytes) { + __msan_unpoison(bytes.data(), bytes.size()); + } + + /** Whether some byte of `bytes` is poisoned; MemorySanitizer always reads its shadow. */ + static std::optional traced(std::span bytes) { + return __msan_test_shadow(bytes.data(), bytes.size()) != -1; + } + + /** Reports the verdict when it is poisoned. */ + static void verdict(bool const& value) { + __msan_check_mem_is_initialized(&value, sizeof value); + } +}; + +#endif + +/** + * Whether the checker read its shadow and the secret mark reached `bytes`. + * + * @tparam Checker `memcheck` or `memory_sanitizer`. + * @param bytes The bytes to look at. + * @return Whether the mark reached them. + */ +template +bool carries_mark(std::span bytes) { + std::optional const traced = Checker::traced(bytes); + return traced.has_value() && *traced; +} + +} // namespace webcpp::secure::test + +#endif // WEBCPP_TEST_SECURE_SUPPORT_CONSTANT_TIME_MARKS_HPP diff --git a/test/support/valgrind_stub/valgrind/memcheck.h b/test/support/valgrind_stub/valgrind/memcheck.h new file mode 100644 index 0000000..5acaed3 --- /dev/null +++ b/test/support/valgrind_stub/valgrind/memcheck.h @@ -0,0 +1,30 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// A stand-in for Valgrind's , for declassify_compile_test.cpp alone: the +// client requests that secure's declassify and the constant-time marks header +// (support/constant_time_marks.hpp) name under WEBCPP_SECURE_CT_VALGRIND, each reading its +// arguments, so that every lane compiles the marks the constant-time lane alone runs. + +#ifndef WEBCPP_TEST_SECURE_SUPPORT_VALGRIND_STUB_MEMCHECK_H +#define WEBCPP_TEST_SECURE_SUPPORT_VALGRIND_STUB_MEMCHECK_H + +/** Reads the address and the size, as Valgrind's request does, and marks nothing. */ +#define VALGRIND_MAKE_MEM_DEFINED(address, size) \ + (static_cast(address), static_cast(size), 0) + +/** Reads the address and the size, as Valgrind's request does, and marks nothing. */ +#define VALGRIND_MAKE_MEM_UNDEFINED(address, size) \ + (static_cast(address), static_cast(size), 0) + +/** Reads its arguments and, as outside Valgrind, returns 0: the shadow is not readable. */ +#define VALGRIND_GET_VBITS(address, vbits, size) \ + (static_cast(address), static_cast(vbits), static_cast(size), 0) + +/** Reads its argument and, as outside Valgrind, reports nothing. */ +#define VALGRIND_CHECK_VALUE_IS_DEFINED(lvalue) (static_cast(lvalue), 0) + +#endif // WEBCPP_TEST_SECURE_SUPPORT_VALGRIND_STUB_MEMCHECK_H From 7a9d92b46d6cddb9c40ec563e3f750ba33093858 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 18:37:54 -0300 Subject: [PATCH 08/42] secure: constant_time_equal holds a by-value bytes() result for the whole comparison --- include/webcpp/secure/constant_time_equal.hpp | 37 ++++++++++++++----- test/constant_time_equal_test.cpp | 28 ++++++++++++++ 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/include/webcpp/secure/constant_time_equal.hpp b/include/webcpp/secure/constant_time_equal.hpp index cbdbce8..0f3edfa 100644 --- a/include/webcpp/secure/constant_time_equal.hpp +++ b/include/webcpp/secure/constant_time_equal.hpp @@ -61,23 +61,40 @@ struct byte_view { }; /** - Views a sequence as its `bytes()` when it has one, else as its range. + Holds a sequence's `bytes()` result, or the sequence itself when it has no `bytes()`. + + The caller binds the result with `auto&&`, which extends the life of a result returned by value. @param sequence The sequence. - @return Its bytes' address and size; nothing is read. + @return Its `bytes()` result, else a reference to it. */ template -[[nodiscard]] constexpr auto view_bytes(Sequence const& sequence) noexcept { +[[nodiscard]] constexpr decltype(auto) held_bytes(Sequence const& sequence) noexcept { if constexpr (requires { { sequence.bytes() } -> std::convertible_to>; }) { - std::span const bytes = sequence.bytes(); + return sequence.bytes(); + } else { + return (sequence); + } +} + +/** + Views what `held_bytes` returned: the address and size of its bytes. + + @param held The held result, which must outlive the view. + @return Its bytes' address and size; nothing is read. +*/ +template +[[nodiscard]] constexpr auto view_bytes(Held const& held) noexcept { + if constexpr (std::convertible_to>) { + std::span const bytes = held; return byte_view{.first = bytes.data(), .count = bytes.size()}; } else { - using element = std::remove_cv_t>; + using element = std::remove_cv_t>; return byte_view{ - .first = std::ranges::data(sequence), - .count = std::ranges::size(sequence), + .first = std::ranges::data(held), + .count = std::ranges::size(held), }; } } @@ -106,8 +123,10 @@ template [[nodiscard]] bool constant_time_equal(First const& first_operand, Second const& second_operand) noexcept { timing_guard const timing_scope; - auto const first = detail::view_bytes(first_operand); - auto const second = detail::view_bytes(second_operand); + auto&& first_held = detail::held_bytes(first_operand); + auto&& second_held = detail::held_bytes(second_operand); + auto const first = detail::view_bytes(first_held); + auto const second = detail::view_bytes(second_held); if (first.count != second.count) { return false; } diff --git a/test/constant_time_equal_test.cpp b/test/constant_time_equal_test.cpp index 07b362a..1457f94 100644 --- a/test/constant_time_equal_test.cpp +++ b/test/constant_time_equal_test.cpp @@ -58,6 +58,15 @@ struct null_sequence { static_assert(secure::detail::byte_sequence); +/** A type whose `bytes()` returns its bytes by value, as crypto's ed25519 public key does. */ +struct by_value_bytes { + std::array stored; + + [[nodiscard]] std::array bytes() const { return stored; } +}; + +static_assert(secure::detail::byte_sequence); + secure::secret<32> make_secret(std::uint8_t first) { secure::secret<32> made; auto const bytes = made.writable(); @@ -150,6 +159,24 @@ void mixed_pairs() { BOOST_TEST(secure::constant_time_equal(secret_bytes, digest)); } +void bytes_by_value() { + auto const base = base_bytes(); + by_value_bytes const same{base}; + BOOST_TEST(secure::constant_time_equal(same, by_value_bytes{base})); + BOOST_TEST(secure::constant_time_equal(same, same)); + BOOST_TEST(secure::constant_time_equal(same, std::span(base))); + BOOST_TEST(secure::constant_time_equal(std::span(base), same)); + for (std::size_t byte = 0; byte < base.size(); ++byte) { + for (unsigned bit = 0; bit < 8; ++bit) { + auto flipped = base; + flipped[byte] ^= static_cast(1U << bit); + BOOST_TEST(!secure::constant_time_equal(same, by_value_bytes{flipped})); + BOOST_TEST(!secure::constant_time_equal(same, std::span(flipped))); + BOOST_TEST(!secure::constant_time_equal(std::span(flipped), same)); + } + } +} + void sizes() { std::array const thirty_two = base_bytes(); std::span const thirty_one(thirty_two.data(), 31); @@ -225,6 +252,7 @@ int main() { shapes(); mixed_pairs(); + bytes_by_value(); sizes(); guard_through_the_seam(); return webcpp::test::exit_status(boost::report_errors()); From d64c5ed1ead45c7f71f7fb677cc29684d108754b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 18:49:23 -0300 Subject: [PATCH 09/42] secure: constant_time_equal returns the sequence without redundant parentheses --- include/webcpp/secure/constant_time_equal.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/webcpp/secure/constant_time_equal.hpp b/include/webcpp/secure/constant_time_equal.hpp index 0f3edfa..d6c82c6 100644 --- a/include/webcpp/secure/constant_time_equal.hpp +++ b/include/webcpp/secure/constant_time_equal.hpp @@ -75,7 +75,7 @@ template }) { return sequence.bytes(); } else { - return (sequence); + return static_cast(sequence); } } From 40aa42df662be01e6926ac0811ea73e0f70d52eb Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 19:01:05 -0300 Subject: [PATCH 10/42] secure: constant_time_equal returns the sequence through as_const --- include/webcpp/secure/constant_time_equal.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/webcpp/secure/constant_time_equal.hpp b/include/webcpp/secure/constant_time_equal.hpp index d6c82c6..d916d7c 100644 --- a/include/webcpp/secure/constant_time_equal.hpp +++ b/include/webcpp/secure/constant_time_equal.hpp @@ -23,6 +23,7 @@ #include #include #include +#include namespace webcpp::secure { @@ -75,7 +76,7 @@ template }) { return sequence.bytes(); } else { - return static_cast(sequence); + return std::as_const(sequence); } } From a58a769805d95e51949c16433ced703a12a6408b Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 19:17:47 -0300 Subject: [PATCH 11/42] secure: the constant-time building blocks, masks, select, lookup and byte comparisons, checked against a plain reference --- include/webcpp/secure.hpp | 1 + include/webcpp/secure/constant_time.hpp | 293 ++++++++++++++++++++++++ test/Jamfile | 8 + test/constant_time_sizes_test.cpp | 85 +++++++ test/constant_time_test.cpp | 248 ++++++++++++++++++++ 5 files changed, 635 insertions(+) create mode 100644 include/webcpp/secure/constant_time.hpp create mode 100644 test/constant_time_sizes_test.cpp create mode 100644 test/constant_time_test.cpp diff --git a/include/webcpp/secure.hpp b/include/webcpp/secure.hpp index 392499c..e838e22 100644 --- a/include/webcpp/secure.hpp +++ b/include/webcpp/secure.hpp @@ -12,6 +12,7 @@ #define WEBCPP_SECURE_HPP #include +#include #include #include #include diff --git a/include/webcpp/secure/constant_time.hpp b/include/webcpp/secure/constant_time.hpp new file mode 100644 index 0000000..5baa211 --- /dev/null +++ b/include/webcpp/secure/constant_time.hpp @@ -0,0 +1,293 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +/** + The constant-time building blocks: masks, selection, table lookup and byte comparisons that + neither branch on nor index memory by the values they receive, BoringSSL's `constant_time_*`. + + A mask is all zeros or all ones of its type, never a `bool`, so that callers combine masks with + `&`, `|` and `~` without making a value the compiler may branch on. Every mask a block makes + passes through `value_barrier`, which hides it from the optimiser. This is what the source can + do; a compiler may still, in principle, rewrite arithmetic into a branch, which is why the + constant-time lanes check the machine code under Valgrind's memcheck and MemorySanitizer and + measure it with dudect. +*/ +#ifndef WEBCPP_SECURE_CONSTANT_TIME_HPP +#define WEBCPP_SECURE_CONSTANT_TIME_HPP + +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace webcpp::secure { + +namespace detail { + +/** + A type a mask is made of: any unsigned integral type but `bool`, which `std::unsigned_integral` + accepts. +*/ +template +concept mask_word = std::unsigned_integral && !std::same_as; + +/** + The most significant bit of a word, moved to the least significant place. + + @param value The word. + @return 1 when its top bit is set, else 0. +*/ +template +[[nodiscard]] constexpr U top_bit(U value) noexcept { + constexpr auto shift = static_cast(std::numeric_limits::digits - 1); + return static_cast(value >> shift); +} + +} // namespace detail + +namespace constant_time { + +/** + * Returns its argument, hidden from the optimiser, so that it cannot reason about which values + * a mask may take and turn the arithmetic that uses it back into a branch. + * + * On GCC and clang it is an empty `asm` statement with the value in a register (BoringSSL's + * `value_barrier_w`); on MSVC and on WebAssembly, which have no such statement, a round trip + * through a `volatile` local. In a constant expression it is the identity. The barrier holds + * the value in this one place: it does not stop the compiler from transforming the code around + * it. + * + * @tparam U Any unsigned integral type but `bool`. + * @param value The value. + * @return The same value. + */ +template +[[nodiscard]] constexpr U value_barrier(U value) noexcept { + if (std::is_constant_evaluated()) { + return value; + } +#if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) + __asm__("" : "+r"(value)); + return value; +#else + U volatile held = value; + return held; +#endif +} + +/** + * Spreads a bit across a whole word: 0 to the zero mask, 1 to the all-ones mask. + * + * @tparam U Any unsigned integral type but `bool`. + * @param bit 0 or 1; any other value gives a word that is not a mask. + * @return The mask, through `value_barrier`. + */ +template +[[nodiscard]] constexpr U mask_from_bit(U bit) noexcept { + return value_barrier(static_cast(U{0} - bit)); +} + +/** + * The all-ones mask when a word is zero, else the zero mask. + * + * @tparam U Any unsigned integral type but `bool`. + * @param value The word. + * @return The mask. + */ +template +[[nodiscard]] constexpr U is_zero_mask(U value) noexcept { + // ~value & (value - 1) has its top bit set exactly when value is zero. + return mask_from_bit( + detail::top_bit(static_cast(static_cast(~value) & static_cast(value - U{1})))); +} + +/** + * The all-ones mask when two words are equal, else the zero mask. + * + * @tparam U Any unsigned integral type but `bool`. + * @param first The first word. + * @param second The second. + * @return The mask. + */ +template +[[nodiscard]] constexpr U is_equal_mask(U first, U second) noexcept { + return is_zero_mask(static_cast(first ^ second)); +} + +/** + * The all-ones mask when one word is less than another, as unsigned numbers, else the zero mask. + * + * @tparam U Any unsigned integral type but `bool`. + * @param first The first word. + * @param second The second. + * @return The mask of `first < second`. + */ +template +[[nodiscard]] constexpr U is_less_mask(U first, U second) noexcept { + // BoringSSL's constant_time_lt_w: the top bit of first ^ ((first ^ second) | ((first - second) + // ^ first)) is the borrow of first - second. + auto const difference = static_cast(first ^ second); + auto const wrapped = static_cast(static_cast(first - second) ^ first); + return mask_from_bit( + detail::top_bit(static_cast(first ^ static_cast(difference | wrapped)))); +} + +/** + * The all-ones mask when a word lies in a closed range, `low <= value <= high`, else the zero + * mask: an alphabet's character class, a digit's range. + * + * @tparam U Any unsigned integral type but `bool`. + * @param value The word. + * @param low The range's first value. + * @param high Its last value; a range with `high < low` holds no value. + * @return The mask, through `value_barrier`. + */ +template +[[nodiscard]] constexpr U is_in_range_mask(U value, U low, U high) noexcept { + return value_barrier(static_cast(static_cast(~is_less_mask(value, low)) & + static_cast(~is_less_mask(high, value)))); +} + +/** + * Chooses between two words by a mask, with no branch: `mask ? when_set : when_clear`. + * + * @tparam U Any unsigned integral type but `bool`. + * @param mask The zero or the all-ones mask; any other word mixes the two words' bits. + * @param when_set The word chosen by the all-ones mask. + * @param when_clear The word chosen by the zero mask. + * @return The chosen word. + */ +template +[[nodiscard]] constexpr U select(U mask, U when_set, U when_clear) noexcept { + return static_cast(static_cast(value_barrier(mask) & when_set) | + static_cast(static_cast(~value_barrier(mask)) & when_clear)); +} + +/** + * The entry of a table at an index, reading every entry in order so that neither the time nor + * the addresses read depend on the index: an alphabet, a generator's constants. + * + * Its cost is the table's size. An index past the table selects no entry. + * + * @tparam Element The entries' type: any unsigned integral type but `bool`. + * @tparam N The table's extent, or `std::dynamic_extent`. + * @param table The table, whose size is public. + * @param index The index, which may be secret. + * @return `table[index]`, or a value-initialised `Element` when `index` is past the table. + */ +template +[[nodiscard]] constexpr Element lookup(std::span table, + std::size_t index) noexcept { + Element result{}; + for (std::size_t position = 0; position < table.size(); ++position) { + auto const keep = static_cast(is_equal_mask(position, index)); + result = static_cast(result | static_cast(table[position] & keep)); + } + return result; +} + +/** + * Writes one of two byte sequences into a third by a mask, byte by byte, with no branch. + * + * The three sizes are public and must be equal: `BOOST_ASSERT` checks it, and with assertions + * off unequal sizes write nothing. + * + * @param mask The zero or the all-ones mask. + * @param destination Where the chosen bytes are written; it may be either source. + * @param when_set The bytes chosen by the all-ones mask. + * @param when_clear The bytes chosen by the zero mask. + */ +constexpr void select_bytes(std::uint8_t mask, std::span destination, + std::span when_set, + std::span when_clear) noexcept { + BOOST_ASSERT(destination.size() == when_set.size() && destination.size() == when_clear.size()); + if (destination.size() != when_set.size() || destination.size() != when_clear.size()) { + return; + } + for (std::size_t position = 0; position < destination.size(); ++position) { + destination[position] = + select(mask, when_set[position], when_clear[position]); + } +} + +/** + * The all-ones byte mask when two byte sequences are equal, else the zero mask; every byte of + * both is read. + * + * The sizes are public and must be equal: `BOOST_ASSERT` checks it, and with assertions off + * unequal sizes give the zero mask without reading a byte. + * + * @param first The first sequence. + * @param second The second. + * @return The mask. + */ +[[nodiscard]] constexpr std::uint8_t equal_mask(std::span first, + std::span second) noexcept { + BOOST_ASSERT(first.size() == second.size()); + if (first.size() != second.size()) { + return 0; + } + std::uint8_t difference = 0; + for (std::size_t position = 0; position < first.size(); ++position) { + difference = static_cast( + difference | static_cast(first[position] ^ second[position])); + } + return is_zero_mask(difference); +} + +/** + * The all-ones byte mask when every byte of a sequence is zero, else the zero mask; every byte + * is read. An empty sequence is all zeros. + * + * @param bytes The sequence. + * @return The mask. + */ +[[nodiscard]] constexpr std::uint8_t is_zero_mask(std::span bytes) noexcept { + std::uint8_t accumulated = 0; + for (std::uint8_t const byte : bytes) { + accumulated = static_cast(accumulated | byte); + } + return is_zero_mask(accumulated); +} + +/** + * The all-ones byte mask when one byte sequence is less than another as big-endian unsigned + * numbers, else the zero mask: a scalar against a group order, a value against a bound. + * + * Every byte of both is read, from the last to the first, carrying the borrow of the subtraction + * through each. The sizes are public and must be equal: `BOOST_ASSERT` checks it, and with + * assertions off unequal sizes give the zero mask without reading a byte. + * + * @param first The first number, most significant byte first. + * @param second The second. + * @return The mask of `first < second`. + */ +[[nodiscard]] constexpr std::uint8_t less_mask(std::span first, + std::span second) noexcept { + BOOST_ASSERT(first.size() == second.size()); + if (first.size() != second.size()) { + return 0; + } + std::uint8_t borrow = 0; + for (std::size_t position = first.size(); position != 0; --position) { + auto const difference = + static_cast(first[position - 1] - second[position - 1] - borrow); + borrow = static_cast((static_cast(difference) >> 8U) & 1U); + } + return mask_from_bit(borrow); +} + +} // namespace constant_time + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_CONSTANT_TIME_HPP diff --git a/test/Jamfile b/test/Jamfile index eeb54ba..2bb59c7 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -71,6 +71,14 @@ secure-run wipe_record : wipe_record_test.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; # constant_time_equal over any two byte sequences, its guard through the seam. secure-run constant_time_equal : constant_time_equal_test.cpp ; +# The constant-time building blocks against a plain reference: every pair and +# triple of bytes, edges and random values of 16, 32 and 64 bits, lookup past +# its table, the byte comparisons against the standard algorithms. +secure-run constant_time : constant_time_test.cpp ; +# With the size assertion off, the byte blocks given unequal sizes read and +# write nothing and give the zero mask. +secure-run constant_time_sizes : constant_time_sizes_test.cpp + : BOOST_DISABLE_ASSERTS ; # declassify with the memcheck build's marks, on every lane, against a stand-in # for Valgrind's header; and with MemorySanitizer's under clang natively. secure-run declassify_compile : declassify_compile_test.cpp diff --git a/test/constant_time_sizes_test.cpp b/test/constant_time_sizes_test.cpp new file mode 100644 index 0000000..ba973b6 --- /dev/null +++ b/test/constant_time_sizes_test.cpp @@ -0,0 +1,85 @@ +// 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) + +// Built with BOOST_DISABLE_ASSERTS (the Jamfile): with the size assertion off, the byte blocks +// that take two or three sequences of unequal sizes read and write nothing. equal_mask and +// less_mask give the zero mask; select_bytes leaves the destination as it was. In a constant +// expression a read past the sequences' storage would stop the build; at run time their data() +// is null, so a read would crash. + +#include +#include + +#include + +#include +#include +#include +#include + +#ifndef BOOST_DISABLE_ASSERTS +#error "constant_time_sizes_test is built with BOOST_DISABLE_ASSERTS" +#endif + +namespace { + +namespace constant_time = webcpp::secure::constant_time; + +constexpr std::array one_byte{0}; + +/** A sequence of `size` bytes from one_byte's storage: reading past its first byte stops the build. + */ +constexpr std::span claimed(std::size_t size) { + return {one_byte.data(), size}; +} + +static_assert(constant_time::equal_mask(claimed(31), claimed(32)) == 0); +static_assert(constant_time::equal_mask(claimed(1), claimed(0)) == 0); +static_assert(constant_time::less_mask(claimed(31), claimed(32)) == 0); +static_assert(constant_time::less_mask(claimed(0), claimed(1)) == 0); + +constexpr bool select_bytes_writes_nothing() { + std::array destination{7, 9}; + constant_time::select_bytes(0xFF, std::span(destination).first(1), claimed(31), claimed(1)); + constant_time::select_bytes(0x00, std::span(destination).first(1), claimed(1), claimed(32)); + constant_time::select_bytes(0xFF, destination, claimed(2), claimed(3)); + return destination[0] == 7 && destination[1] == 9; +} + +static_assert(select_bytes_writes_nothing()); + +/** A span of `size` bytes whose data() is null: reading one would crash natively. */ +std::span null_bytes(std::size_t size) { + std::uint8_t const* const nowhere = nullptr; + return {nowhere, size}; +} + +void at_run_time() { + BOOST_TEST_EQ(constant_time::equal_mask(null_bytes(31), null_bytes(32)), 0); + BOOST_TEST_EQ(constant_time::equal_mask(null_bytes(32), null_bytes(31)), 0); + BOOST_TEST_EQ(constant_time::less_mask(null_bytes(31), null_bytes(32)), 0); + BOOST_TEST_EQ(constant_time::less_mask(null_bytes(32), null_bytes(31)), 0); + + std::array destination{}; + destination.fill(0x5A); + std::array const shorter{}; + std::array const longer{}; + constant_time::select_bytes(0xFF, destination, shorter, longer); + constant_time::select_bytes(0x00, destination, longer, shorter); + constant_time::select_bytes(0xFF, destination, null_bytes(31), null_bytes(31)); + for (std::uint8_t const byte : destination) { + BOOST_TEST_EQ(byte, 0x5A); + } + std::uint8_t* const nowhere = nullptr; + constant_time::select_bytes(0xFF, std::span(nowhere, 31), longer, longer); +} + +} // namespace + +int main() { + at_run_time(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/constant_time_test.cpp b/test/constant_time_test.cpp new file mode 100644 index 0000000..e1fdd88 --- /dev/null +++ b/test/constant_time_test.cpp @@ -0,0 +1,248 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// The constant-time building blocks of equal a plain reference +// on every input: every pair (and triple) of bytes, the edges and random values of 16, 32 and 64 +// bits; lookup at every index and past the table, narrow and wide, of static and dynamic extent; +// the byte comparisons against the standard algorithms; in constant expressions too; and no +// block accepts `bool` or a signed type. + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace constant_time = webcpp::secure::constant_time; + +template +concept maskable = requires(U value) { constant_time::is_equal_mask(value, value); }; + +static_assert(maskable && maskable && maskable && + maskable && maskable); +static_assert(!maskable && !maskable && !maskable && !maskable); + +template +concept lookup_entry = + requires(std::span table) { constant_time::lookup(table, std::size_t{0}); }; + +static_assert(lookup_entry && lookup_entry); +static_assert(!lookup_entry && !lookup_entry); + +/** The plain reference: a mask from a bool, with a branch. */ +template +constexpr U reference_mask(bool on) { + return on ? static_cast(~U{0}) : U{0}; +} + +// Constant expressions. +static_assert(constant_time::select(0xFF, 0x12, 0x34) == 0x12); +static_assert(constant_time::select(0x00, 0x12, 0x34) == 0x34); +static_assert(constant_time::select(~std::uint64_t{0}, 7, 9) == 7); +static_assert(constant_time::is_in_range_mask('m', 'a', 'z') == 0xFF); +static_assert(constant_time::is_in_range_mask('A', 'a', 'z') == 0x00); +static_assert(constant_time::is_in_range_mask(10, 10, 10) == 0xFFFFFFFFU); +static_assert(constant_time::is_less_mask(1, 2) == 0xFFFF); +static_assert(constant_time::mask_from_bit(1) == 0xFF); +static_assert(constant_time::value_barrier(42) == 42); + +constexpr std::array small_table{10, 20, 30, 40}; +static_assert(constant_time::lookup(std::span(small_table), 2) == 30); +static_assert(constant_time::lookup(std::span(small_table), 4) == 0); +static_assert(constant_time::lookup(std::span(small_table), 0) == 10); + +constexpr std::array three_a{1, 2, 3}; +constexpr std::array three_b{1, 2, 4}; +static_assert(constant_time::equal_mask(three_a, three_a) == 0xFF); +static_assert(constant_time::equal_mask(three_a, three_b) == 0x00); +static_assert(constant_time::less_mask(three_a, three_b) == 0xFF); +static_assert(constant_time::less_mask(three_b, three_a) == 0x00); +static_assert(constant_time::is_zero_mask(std::span(three_a)) == 0x00); +static_assert(constant_time::is_zero_mask(std::span{}) == 0xFF); + +/** Every single-operand and two-operand block against the reference, at one pair. */ +template +void check_pair(U first, U second) { + BOOST_TEST_EQ(constant_time::value_barrier(first), first); + BOOST_TEST_EQ(constant_time::mask_from_bit(static_cast(first & U{1})), + reference_mask((first & U{1}) != 0)); + BOOST_TEST_EQ(constant_time::is_zero_mask(first), reference_mask(first == 0)); + BOOST_TEST_EQ(constant_time::is_equal_mask(first, second), reference_mask(first == second)); + BOOST_TEST_EQ(constant_time::is_less_mask(first, second), reference_mask(first < second)); + bool const chooses_set = (second & U{1}) != 0; + auto const complement = static_cast(~first); + BOOST_TEST_EQ(constant_time::select(reference_mask(chooses_set), first, complement), + chooses_set ? first : complement); +} + +/** is_in_range_mask against the reference, at one triple. */ +template +void check_triple(U value, U low, U high) { + BOOST_TEST_EQ(constant_time::is_in_range_mask(value, low, high), + reference_mask(low <= value && value <= high)); +} + +void exhaustive_bytes() { + for (unsigned first = 0; first <= 0xFFU; ++first) { + for (unsigned second = 0; second <= 0xFFU; ++second) { + check_pair(static_cast(first), static_cast(second)); + } + } + // Counted outside BOOST_TEST, so that 2^24 checks do not each pass through the reporter. + std::size_t mismatches = 0; + for (unsigned value = 0; value <= 0xFFU; ++value) { + for (unsigned low = 0; low <= 0xFFU; ++low) { + for (unsigned high = 0; high <= 0xFFU; ++high) { + auto const mask = constant_time::is_in_range_mask(static_cast(value), + static_cast(low), + static_cast(high)); + if (mask != reference_mask(low <= value && value <= high)) { + ++mismatches; + } + } + } + } + BOOST_TEST_EQ(mismatches, 0U); +} + +template +void edges_and_random() { + constexpr U max = std::numeric_limits::max(); + constexpr std::array edges{ + 0, 1, 2, static_cast(max / 2), static_cast((max / 2) + 1), static_cast(max - 1), + max, + }; + for (U const first : edges) { + for (U const second : edges) { + check_pair(first, second); + for (U const third : edges) { + check_triple(first, second, third); + } + } + } + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): reproducible + std::mt19937_64 generator{20261124}; + auto const draw = [&generator] { return static_cast(generator()); }; + for (std::size_t round = 0; round < (std::size_t{1} << 16U); ++round) { + U const first = draw(); + U const second = draw(); + U const third = draw(); + check_pair(first, second); + check_pair(first, first); + check_pair(first, static_cast(first + 1)); + check_triple(first, second, third); + check_triple(first, std::min(first, second), std::max(first, third)); + check_triple(first, first, first); + } +} + +template +void check_lookup(std::array const& table) { + std::span const fixed(table); + std::span const dynamic(table); + for (std::size_t index = 0; index < N; ++index) { + BOOST_TEST_EQ(constant_time::lookup(fixed, index), table[index]); + BOOST_TEST_EQ(constant_time::lookup(dynamic, index), table[index]); + } + for (std::size_t const past : + {N, N + 1, std::size_t{64}, std::size_t{65}, std::numeric_limits::max()}) { + BOOST_TEST_EQ(constant_time::lookup(fixed, past), Element{}); + BOOST_TEST_EQ(constant_time::lookup(dynamic, past), Element{}); + } +} + +void lookups() { + std::array bytes{}; + for (std::size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast((i * 7) + 3); + } + check_lookup(bytes); + std::array words{}; + for (std::size_t i = 0; i < words.size(); ++i) { + words[i] = static_cast(0x9E3779B9U * (i + 1)); + } + check_lookup(words); + check_lookup(std::array{0xFF}); + check_lookup(std::array{0xFEDCBA9876543210U}); + // The entry at the top of a narrow element: the size_t mask narrowed keeps every bit. + check_lookup(std::array{0xFFFF, 0x8001}); +} + +/** The byte blocks against the standard algorithms, at one pair of equal sizes. */ +void check_bytes(std::vector const& left, std::vector const& right) { + std::span const left_view(left); + std::span const right_view(right); + BOOST_TEST_EQ(constant_time::equal_mask(left_view, right_view), + reference_mask(std::ranges::equal(left, right))); + BOOST_TEST_EQ(constant_time::less_mask(left_view, right_view), + reference_mask(std::ranges::lexicographical_compare(left, right))); + BOOST_TEST_EQ(constant_time::is_zero_mask(left_view), + reference_mask( + std::ranges::all_of(left, [](auto byte) { return byte == 0; }))); + std::vector destination(left.size(), 0x5A); + constant_time::select_bytes(0xFF, destination, left_view, right_view); + BOOST_TEST_ALL_EQ(destination.begin(), destination.end(), left.begin(), left.end()); + constant_time::select_bytes(0x00, destination, left_view, right_view); + BOOST_TEST_ALL_EQ(destination.begin(), destination.end(), right.begin(), right.end()); +} + +void byte_comparisons() { + // NOLINTNEXTLINE(bugprone-random-generator-seed,cert-msc32-c,cert-msc51-cpp): reproducible + std::mt19937_64 generator{20261124}; + for (std::size_t const size : {0U, 1U, 31U, 32U}) { + std::vector const zeros(size, 0x00); + std::vector const ones(size, 0xFF); + check_bytes(zeros, zeros); + check_bytes(zeros, ones); + check_bytes(ones, zeros); + check_bytes(ones, ones); + for (std::size_t round = 0; round < 256; ++round) { + std::vector first(size); + std::vector second(size); + for (std::size_t i = 0; i < size; ++i) { + first[i] = static_cast(generator()); + second[i] = static_cast(generator()); + } + check_bytes(first, second); + check_bytes(first, first); + if (size == 0) { + continue; + } + for (std::size_t const position : {std::size_t{0}, size - 1}) { + auto differs = first; + differs[position] = static_cast(differs[position] + 1); + check_bytes(first, differs); + check_bytes(differs, first); + auto one_set = zeros; + one_set[position] = static_cast(first[position] | 1U); + check_bytes(one_set, zeros); + check_bytes(zeros, one_set); + } + } + } +} + +} // namespace + +int main() { + exhaustive_bytes(); + edges_and_random(); + edges_and_random(); + edges_and_random(); + lookups(); + byte_comparisons(); + return webcpp::test::exit_status(boost::report_errors()); +} From f69c4a4be37cdb3b2bb7fd5d92922aa39c0e6017 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 19:18:54 -0300 Subject: [PATCH 12/42] secure: lookup compares the index in the wider of size_t and the entry, so a 64-bit entry keeps its top half on WebAssembly --- include/webcpp/secure/constant_time.hpp | 10 ++++++++-- test/constant_time_test.cpp | 5 +++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/include/webcpp/secure/constant_time.hpp b/include/webcpp/secure/constant_time.hpp index 5baa211..1a6f1fe 100644 --- a/include/webcpp/secure/constant_time.hpp +++ b/include/webcpp/secure/constant_time.hpp @@ -176,7 +176,10 @@ template * The entry of a table at an index, reading every entry in order so that neither the time nor * the addresses read depend on the index: an alphabet, a generator's constants. * - * Its cost is the table's size. An index past the table selects no entry. + * Its cost is the table's size. An index past the table selects no entry. The index is compared + * in the wider of `std::size_t` and `Element`, so that the mask covers every bit of an entry + * wider than `std::size_t` (a 64-bit entry on WebAssembly's 32-bit `std::size_t`) and narrows + * to all ones for a narrower one. * * @tparam Element The entries' type: any unsigned integral type but `bool`. * @tparam N The table's extent, or `std::dynamic_extent`. @@ -187,9 +190,12 @@ template template [[nodiscard]] constexpr Element lookup(std::span table, std::size_t index) noexcept { + using index_word = + std::conditional_t<(sizeof(Element) > sizeof(std::size_t)), Element, std::size_t>; Element result{}; for (std::size_t position = 0; position < table.size(); ++position) { - auto const keep = static_cast(is_equal_mask(position, index)); + auto const keep = static_cast(is_equal_mask( + static_cast(position), static_cast(index))); result = static_cast(result | static_cast(table[position] & keep)); } return result; diff --git a/test/constant_time_test.cpp b/test/constant_time_test.cpp index e1fdd88..e2e2e17 100644 --- a/test/constant_time_test.cpp +++ b/test/constant_time_test.cpp @@ -63,6 +63,10 @@ constexpr std::array small_table{10, 20, 30, 40}; static_assert(constant_time::lookup(std::span(small_table), 2) == 30); static_assert(constant_time::lookup(std::span(small_table), 4) == 0); static_assert(constant_time::lookup(std::span(small_table), 0) == 10); +// An entry wider than std::size_t (WebAssembly's is 32 bits) keeps its top bits. +constexpr std::array wide_table{0xFEDCBA9876543210U, 1}; +static_assert(constant_time::lookup(std::span(wide_table), 0) == + 0xFEDCBA9876543210U); constexpr std::array three_a{1, 2, 3}; constexpr std::array three_b{1, 2, 4}; @@ -176,6 +180,7 @@ void lookups() { } check_lookup(words); check_lookup(std::array{0xFF}); + // Wider than WebAssembly's std::size_t: the mask covers the entry's top half too. check_lookup(std::array{0xFEDCBA9876543210U}); // The entry at the top of a narrow element: the size_t mask narrowed keeps every bit. check_lookup(std::array{0xFFFF, 0x8001}); From 4bbfc723fa19e0df6be62220b5161631b9777635 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 19:42:17 -0300 Subject: [PATCH 13/42] secure: constant_time_test accepts plain char exactly where it is unsigned, as on Linux on ARM --- test/constant_time_test.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/constant_time_test.cpp b/test/constant_time_test.cpp index e2e2e17..f8cca3b 100644 --- a/test/constant_time_test.cpp +++ b/test/constant_time_test.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -33,7 +34,11 @@ concept maskable = requires(U value) { constant_time::is_equal_mask(value, value static_assert(maskable && maskable && maskable && maskable && maskable); -static_assert(!maskable && !maskable && !maskable && !maskable); +static_assert(!maskable && !maskable && !maskable && + !maskable); +// Plain char is unsigned on some targets (Linux on ARM) and signed on others: it is accepted +// exactly where it is an unsigned integral type. +static_assert(maskable == std::unsigned_integral); template concept lookup_entry = From d7b4e8e133cd0531db9fdd15754ab2880dd1f19f Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 22:13:46 -0300 Subject: [PATCH 14/42] secure: no function allocates, and the convenience header compiles alone --- test/Jamfile | 8 + test/allocation_test.cpp | 287 ++++++++++++++++++++++++++++ test/convenience_header_test.cpp | 59 ++++++ test/support/counting.hpp | 311 +++++++++++++++++++++++++++++++ 4 files changed, 665 insertions(+) create mode 100644 test/allocation_test.cpp create mode 100644 test/convenience_header_test.cpp create mode 100644 test/support/counting.hpp diff --git a/test/Jamfile b/test/Jamfile index 2bb59c7..0052bbe 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -86,4 +86,12 @@ secure-run declassify_compile : declassify_compile_test.cpp secure-compile declassify_compile_msan : declassify_compile_test.cpp : WEBCPP_SECURE_CT_MSAN gcc:no msvc:no : native ; + +# No function of the library allocates: under support/counting.hpp's replacement of +# every form of operator new (and the C library's allocator where a program can +# count it), every function of every header leaves the count where it was. +secure-run allocation : allocation_test.cpp ; +# alone brings every header, one name of each used. +secure-run convenience_header : convenience_header_test.cpp ; + build-project messages ; diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp new file mode 100644 index 0000000..ce9f705 --- /dev/null +++ b/test/allocation_test.cpp @@ -0,0 +1,287 @@ +// 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) + +// webcpp::secure allocates nothing: every function of the library is called under the counter of +// support/counting.hpp, which replaces every form of the global operator new (plain, array, +// sized-delete, nothrow and aligned) and, where the target lets a program count it, the C +// library's allocator, and the count does not move. A control first calls each form of operator +// new once and checks that each is counted, so a zero is not a replacement that never ran. + +#include "support/counting.hpp" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace secure = webcpp::secure; +namespace ct = webcpp::secure::constant_time; +namespace counting = webcpp::secure::test; + +constexpr std::size_t big = 64; +constexpr std::align_val_t aligned{big}; + +/** Runs `body` and checks that it moved neither counter. */ +template +void expect_no_allocation(char const* what, Body body) { + std::size_t const new_before = counting::counted_new.load(); + std::size_t const c_before = counting::counted_c.load(); + body(); + std::size_t const new_after = counting::counted_new.load(); + std::size_t const c_after = counting::counted_c.load(); + if (new_after != new_before || c_after != c_before) { + std::printf("allocated: %s\n", what); + } + BOOST_TEST_EQ(new_after - new_before, 0U); + BOOST_TEST_EQ(c_after - c_before, 0U); +} + +/** Runs `body`, one allocation of operator new's form, and checks that the counter saw it. */ +template +void expect_counted(char const* form, Body body) { + std::size_t const before = counting::counted_new.load(); + body(); + std::size_t const counted = counting::counted_new.load() - before; + if (counted != 1) { + std::printf("not counted once: %s\n", form); + } + BOOST_TEST_EQ(counted, 1U); +} + +/** Every form of operator new moves the counter: the control of the zeros below. */ +void control_counts_every_form() { + expect_counted("new", [] { + void* volatile block = ::operator new(24); + ::operator delete(block); + }); + expect_counted("new[]", [] { + void* volatile block = ::operator new[](24); + ::operator delete[](block); + }); + expect_counted("sized delete", [] { + void* volatile block = ::operator new(24); + ::operator delete(block, std::size_t{24}); + }); + expect_counted("sized delete[]", [] { + void* volatile block = ::operator new[](24); + ::operator delete[](block, std::size_t{24}); + }); + expect_counted("nothrow new", [] { + void* volatile block = ::operator new(24, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete(block, std::nothrow); + }); + expect_counted("nothrow new[]", [] { + void* volatile block = ::operator new[](24, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete[](block, std::nothrow); + }); + expect_counted("aligned new", [] { + void* volatile block = ::operator new(24, aligned); + ::operator delete(block, aligned); + }); + expect_counted("aligned new[]", [] { + void* volatile block = ::operator new[](24, aligned); + ::operator delete[](block, aligned); + }); + expect_counted("aligned nothrow new", [] { + void* volatile block = ::operator new(24, aligned, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete(block, aligned, std::nothrow); + }); + expect_counted("aligned nothrow new[]", [] { + void* volatile block = ::operator new[](24, aligned, std::nothrow); + BOOST_TEST(block != nullptr); + ::operator delete[](block, aligned, std::nothrow); + }); + expect_counted("a vector's storage", [] { + std::vector bytes(16); + // A volatile store keeps the optimiser from removing the storage, as it may a new and a + // delete nothing observes. + static_cast(bytes.data())[0] = 1; + BOOST_TEST_EQ(bytes.size(), 16U); + }); + expect_counted("new int[]", [] { + int const* volatile block = new int[4]; + delete[] block; + }); +} + +/** The blocks of one mask word, each called with values the optimiser cannot fold. */ +template +void check_word_blocks() { + U volatile first_source = 0x5a; + U volatile second_source = 0xa5; + U const first = first_source; + U const second = second_source; + U volatile sink = 0; + expect_no_allocation("top_bit", [&] { sink = secure::detail::top_bit(first); }); + expect_no_allocation("value_barrier", [&] { sink = ct::value_barrier(first); }); + expect_no_allocation("mask_from_bit", [&] { sink = ct::mask_from_bit(U{1}); }); + expect_no_allocation("is_zero_mask", [&] { sink = ct::is_zero_mask(first); }); + expect_no_allocation("is_equal_mask", [&] { sink = ct::is_equal_mask(first, second); }); + expect_no_allocation("is_less_mask", [&] { sink = ct::is_less_mask(first, second); }); + expect_no_allocation("is_in_range_mask", + [&] { sink = ct::is_in_range_mask(first, first, second); }); + expect_no_allocation("select", [&] { sink = ct::select(first, first, second); }); + std::array const table{U{1}, U{2}, U{3}, U{4}}; + std::size_t volatile index = 2; + expect_no_allocation("lookup", [&] { + sink = ct::lookup(std::span(table), index); + sink = ct::lookup(std::span(table), index + 9); + }); + BOOST_TEST_EQ(sink, U{0}); +} + +void check_constant_time_blocks() { + check_word_blocks(); + check_word_blocks(); + std::array first{}; + std::array second{}; + std::array destination{}; + first.fill(0x11); + second.fill(0x22); + std::uint8_t volatile sink = 0; + expect_no_allocation("select_bytes", [&] { + ct::select_bytes(0xff, destination, first, second); + ct::select_bytes(0x00, destination, first, second); + }); + expect_no_allocation("equal_mask", [&] { sink = ct::equal_mask(first, second); }); + expect_no_allocation("is_zero_mask of bytes", [&] { sink = ct::is_zero_mask(first); }); + expect_no_allocation("less_mask", [&] { sink = ct::less_mask(first, second); }); + BOOST_TEST_EQ(destination[0], 0x22U); + BOOST_TEST_EQ(sink, 0xffU); +} + +void check_constant_time_equal() { + std::array const first{}; + std::array second{}; + std::array const raw{}; + std::vector const heap_first(32); // built before the window + std::vector const heap_short(31); + std::string_view const view = "constant-time"; + secure::secret<32> const held; + bool equal_result = false; + expect_no_allocation("constant_time_equal on arrays", + [&] { equal_result = secure::constant_time_equal(first, second); }); + BOOST_TEST(equal_result); + expect_no_allocation("constant_time_equal on spans", [&] { + equal_result = secure::constant_time_equal(std::span(first), + std::span(second)); + }); + BOOST_TEST(equal_result); + expect_no_allocation("constant_time_equal on a std::byte array", + [&] { equal_result = secure::constant_time_equal(raw, raw); }); + BOOST_TEST(equal_result); + expect_no_allocation("constant_time_equal on vectors", + [&] { equal_result = secure::constant_time_equal(heap_first, first); }); + BOOST_TEST(equal_result); + expect_no_allocation("constant_time_equal on unequal sizes", [&] { + equal_result = secure::constant_time_equal(heap_first, heap_short); + }); + BOOST_TEST(!equal_result); + expect_no_allocation("constant_time_equal on string views", + [&] { equal_result = secure::constant_time_equal(view, view); }); + BOOST_TEST(equal_result); + expect_no_allocation("constant_time_equal on a secret", + [&] { equal_result = secure::constant_time_equal(held, first); }); + BOOST_TEST(equal_result); + expect_no_allocation("constant_time_equal on a temporary secret", [&] { + equal_result = secure::constant_time_equal(secure::secret<32>{}, held); + }); + BOOST_TEST(equal_result); + second[7] = 1; + expect_no_allocation("constant_time_equal on different bytes", + [&] { equal_result = secure::constant_time_equal(first, second); }); + BOOST_TEST(!equal_result); +} + +void check_erase_secret() { + std::array buffer{}; + std::vector heap_buffer(32, 0x7f); // built before the window + std::array words{1, 2, 3, 4}; + buffer.fill(0x7f); + expect_no_allocation("erase_secret", [&] { + secure::erase_secret(buffer); + secure::erase_secret(heap_buffer); + secure::erase_secret(words); + }); + BOOST_TEST_EQ(buffer[0], 0U); + BOOST_TEST_EQ(heap_buffer[31], 0U); + BOOST_TEST_EQ(words[3], 0U); +} + +void check_secret() { + expect_no_allocation("secret", [] { + secure::secret<32> original; + original.writable()[0] = 0x42; + secure::secret<32> moved(std::move(original)); + BOOST_TEST_EQ(moved.bytes()[0], 0x42U); + BOOST_TEST_EQ(original.bytes()[0], 0U); + secure::secret<32> assigned; + assigned = std::move(moved); + secure::secret<32> copy = assigned.clone(); + BOOST_TEST_EQ(copy.bytes()[0], 0x42U); + std::span const viewed = copy; + BOOST_TEST_EQ(viewed.size(), 32U); + BOOST_TEST_EQ(secure::secret<32>::size(), 32U); + }); +} + +void check_timing_guard() { + bool volatile sink = false; + expect_no_allocation("timing_guard", [&] { + sink = secure::cpu_has_dit(); + { + secure::timing_guard const engaged; + sink = secure::dit_is_set(); + secure::timing_guard const nested(true); + sink = secure::dit_is_set(); + } + { + secure::timing_guard const disengaged(false); + sink = secure::dit_is_set(); + } + }); + static_cast(sink); +} + +void check_declassify() { + std::uint64_t verdict = 0x1234; + bool flag = true; + expect_no_allocation("declassify", [&] { + secure::declassify(verdict); + secure::declassify(flag); + }); + BOOST_TEST_EQ(verdict, 0x1234U); + BOOST_TEST(flag); +} + +} // namespace + +int main() { + std::printf("c_allocations_counted=%d\n", counting::c_allocations_counted ? 1 : 0); + control_counts_every_form(); + check_constant_time_blocks(); + check_constant_time_equal(); + check_erase_secret(); + check_secret(); + check_timing_guard(); + check_declassify(); + return webcpp::test::exit_status(boost::report_errors()); +} diff --git a/test/convenience_header_test.cpp b/test/convenience_header_test.cpp new file mode 100644 index 0000000..cd1c4b0 --- /dev/null +++ b/test/convenience_header_test.cpp @@ -0,0 +1,59 @@ +// 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) + +// , included alone, brings every public header of the library: this program +// names one function or type of each of them and nothing else is included. + +#include + +#include +#include +#include + +#ifndef WEBCPP_VERSION +#error " must bring config.hpp, which defines WEBCPP_VERSION" +#endif + +// config.hpp: WEBCPP_SECURE_NO_EXCEPTIONS is defined exactly where webcpp has no exceptions. +#if defined(WEBCPP_HAS_EXCEPTIONS) == defined(WEBCPP_SECURE_NO_EXCEPTIONS) +#error "config.hpp must define WEBCPP_SECURE_NO_EXCEPTIONS exactly when webcpp has no exceptions" +#endif + +int main() { + namespace secure = webcpp::secure; + int failures = 0; + + // timing_guard.hpp + { + secure::timing_guard const guard; + static_cast(secure::cpu_has_dit()); + static_cast(secure::dit_is_set()); + } + + // erase_secret.hpp, with detail/wipe.hpp + std::array buffer{1, 2, 3, 4}; + secure::erase_secret(buffer); + failures += buffer[0] != 0 ? 1 : 0; + + // constant_time_equal.hpp + std::array const zeros{}; + failures += secure::constant_time_equal(buffer, zeros) ? 0 : 1; + + // secret.hpp + secure::secret<4> const held; + failures += secure::secret<4>::size() == 4 ? 0 : 1; + + // constant_time.hpp + failures += secure::constant_time::is_zero_mask(0) == 0xff ? 0 : 1; + + // declassify.hpp + std::uint8_t verdict = 1; + secure::declassify(verdict); + failures += verdict == 1 ? 0 : 1; + + static_cast(held); + return failures; +} diff --git a/test/support/counting.hpp b/test/support/counting.hpp new file mode 100644 index 0000000..d0fbaa3 --- /dev/null +++ b/test/support/counting.hpp @@ -0,0 +1,311 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Counts every allocation of the program that includes this header once (spec section 8.5): +// every form of the global operator new (plain, array, aligned, nothrow, aligned nothrow), and +// the C library's malloc, calloc, realloc, aligned_alloc and posix_memalign, where a program +// can see them: glibc's replaced and forwarded to its __libc_* functions, Emscripten's replaced +// and forwarded to its emscripten_builtin_* (its dlmalloc defines them weak), macOS's through +// malloc_logger, the hook libsystem_malloc calls on every allocation. The glibc functions +// memalign, valloc, pvalloc and reallocarray are not replaced and so not counted. WASI's +// wasi-libc defines malloc and its __libc_malloc in one object (dlmalloc.c.obj, measured with +// nm), so a program cannot replace one and keep the other, and MSVC's C runtime has no hook: +// there the C library's allocations are not counted, and c_allocations_counted says so, which +// the tests print. +// A block of operator new is counted twice where the C library is counted (once by new, once +// by the malloc it calls): every test compares a count before and after a window, so this +// changes no verdict. The replaced throwing operator new does not run the new_handler loop: a +// failed allocation throws std::bad_alloc (or aborts without exceptions) at once. +// Nothing here reads a thread_local: on macOS the first read of one on a thread allocates +// through dyld (_tlv_get_addr), inside malloc_logger, which recursed until the stack ended +// (N1: measured with a malloc_logger that read a thread_local, which crashed before main). +// On macOS the hook is installed at static initialisation, relies on the private malloc_logger +// symbol of libsystem_malloc, and overwrites any hook already there (MallocStackLogging's, a +// sanitizer's). + +#ifndef WEBCPP_TEST_SECURE_SUPPORT_COUNTING_HPP +#define WEBCPP_TEST_SECURE_SUPPORT_COUNTING_HPP + +#include +#include +#include +#include +#include +#include + +#include + +#ifdef __APPLE__ +#include +#elif defined(__EMSCRIPTEN__) +#include +#endif + +namespace webcpp::secure::test { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the replaced new's count +inline std::atomic counted_new{0}; +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables): the C library's count +inline std::atomic counted_c{0}; +static_assert(std::atomic::is_always_lock_free, + "the counters are called from inside the allocator and must not allocate or lock"); + +/** Every allocation counted so far: operator new's and the C library's. */ +inline std::size_t allocations() { + return counted_new.load() + counted_c.load(); +} + +/** Whether this target counts the C library's allocations too. */ +inline constexpr bool c_allocations_counted = +#if defined(__GLIBC__) || defined(__EMSCRIPTEN__) || defined(__APPLE__) + true; +#else + false; +#endif + +inline void count_c() noexcept { + ++counted_c; +} + +/** + * Allocates for an operator new form: plain forms use malloc, aligned forms the aligned + * allocator of the platform (on Windows always _aligned_malloc, so that _aligned_free matches). + */ +inline void* new_block(std::size_t size, std::size_t alignment, bool aligned) { + ++counted_new; + std::size_t const bytes = size == 0 ? 1 : size; + if (!aligned) { + return std::malloc(bytes); + } +#ifdef _WIN32 + return _aligned_malloc(bytes, alignment); +#else + alignment = std::max(alignment, sizeof(void*)); // posix_memalign's and macOS's minimum + std::size_t const padded = bytes + alignment - 1; + if (padded < bytes) { + return nullptr; // the rounding overflows: a failure, never a small block + } + return std::aligned_alloc(alignment, padded / alignment * alignment); +#endif +} + +} // namespace webcpp::secure::test + +[[noreturn]] inline void webcpp_test_out_of_memory() { +#ifdef __cpp_exceptions + throw std::bad_alloc(); // the replaced operator's contract +#else + std::abort(); +#endif +} + +// The replaceable global allocation functions cannot be inline: they are defined here, in the +// one translation unit of a program that includes this header, under the standard's names. None is +// ever inlined: GCC 15 at -O3, seeing the malloc or the free inside one, pairs it with the other's +// call (a std::allocator's operator new, an exception's) and warns of a mismatch +// (-Wmismatched-new-delete), though both replaced forms use the C library. +// NOLINTBEGIN(misc-definitions-in-headers,readability-inconsistent-declaration-parameter-name) +BOOST_NOINLINE void* operator new(std::size_t size) { + if (void* const p = webcpp::secure::test::new_block(size, alignof(std::max_align_t), false)) { + return p; + } + webcpp_test_out_of_memory(); +} + +BOOST_NOINLINE void* operator new[](std::size_t size) { + return operator new(size); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment) { + if (void* const p = + webcpp::secure::test::new_block(size, static_cast(alignment), true)) { + return p; + } + webcpp_test_out_of_memory(); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment) { + return operator new(size, alignment); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::nothrow_t const& /*unused*/) noexcept { + return webcpp::secure::test::new_block(size, alignof(std::max_align_t), false); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::nothrow_t const& /*unused*/) noexcept { + return webcpp::secure::test::new_block(size, alignof(std::max_align_t), false); +} + +BOOST_NOINLINE void* operator new(std::size_t size, std::align_val_t alignment, + std::nothrow_t const& /*unused*/) noexcept { + return webcpp::secure::test::new_block(size, static_cast(alignment), true); +} + +BOOST_NOINLINE void* operator new[](std::size_t size, std::align_val_t alignment, + std::nothrow_t const& /*unused*/) noexcept { + return webcpp::secure::test::new_block(size, static_cast(alignment), true); +} + +BOOST_NOINLINE void operator delete(void* p) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} +#ifdef _WIN32 +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + _aligned_free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + _aligned_free(p); +} +#else +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::size_t /*unused*/, + std::align_val_t /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete(void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} + +BOOST_NOINLINE void operator delete[](void* p, std::align_val_t /*unused*/, + std::nothrow_t const& /*unused*/) noexcept { + std::free(p); +} +#endif +// NOLINTEND(misc-definitions-in-headers,readability-inconsistent-declaration-parameter-name) + +#if defined(__GLIBC__) || defined(__EMSCRIPTEN__) +#ifdef __GLIBC__ +extern "C" { +void* __libc_malloc(std::size_t); +void* __libc_calloc(std::size_t, std::size_t); +void* __libc_realloc(void*, std::size_t); +void* __libc_memalign(std::size_t, std::size_t); +void __libc_free(void*); +} +#define WEBCPP_TEST_C(name) __libc_##name +// glibc declares these with __THROW, noexcept in C++11 and later: a replacement must match. +#define WEBCPP_TEST_C_NOEXCEPT noexcept +#else +#define WEBCPP_TEST_C(name) emscripten_builtin_##name +// Emscripten's musl declares them without an exception specification. +#define WEBCPP_TEST_C_NOEXCEPT +#endif +// The C library's allocation functions, replaced for this program alone; cert-dcl58-cpp takes +// a replacement of what declares for a change to namespace std. +// misc-definitions-in-headers: a replacement is a definition, and each test program includes +// this header in one translation unit. +// NOLINTBEGIN(misc-definitions-in-headers) +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) +extern "C" { +void* malloc(std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::secure::test::count_c(); + return WEBCPP_TEST_C(malloc)(size); +} + +void* calloc(std::size_t count, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::secure::test::count_c(); + return WEBCPP_TEST_C(calloc)(count, size); +} + +void* realloc(void* p, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::secure::test::count_c(); + return WEBCPP_TEST_C(realloc)(p, size); +} + +void* aligned_alloc(std::size_t alignment, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::secure::test::count_c(); + return WEBCPP_TEST_C(memalign)(alignment, size); +} + +int posix_memalign(void** p, std::size_t alignment, std::size_t size) WEBCPP_TEST_C_NOEXCEPT { + webcpp::secure::test::count_c(); + *p = WEBCPP_TEST_C(memalign)(alignment, size); + return *p == nullptr ? 12 /* ENOMEM */ : 0; +} + +void free(void* p) WEBCPP_TEST_C_NOEXCEPT { + WEBCPP_TEST_C(free)(p); +} +} +// NOLINTEND(readability-inconsistent-declaration-parameter-name,cert-dcl58-cpp) +// NOLINTEND(misc-definitions-in-headers) +#elif defined(__APPLE__) +// libsystem_malloc's hook, called on every allocation and release of the process. +using webcpp_test_malloc_logger = void(std::uint32_t, std::uintptr_t, std::uintptr_t, + std::uintptr_t, std::uintptr_t, std::uint32_t); +extern "C" webcpp_test_malloc_logger* malloc_logger; + +inline void webcpp_test_count_c_allocation(std::uint32_t type, std::uintptr_t /*unused*/, + std::uintptr_t /*unused*/, std::uintptr_t /*unused*/, + std::uintptr_t /*unused*/, std::uint32_t /*unused*/) { + constexpr std::uint32_t allocate = 2; // MALLOC_LOG_TYPE_ALLOCATE + if ((type & allocate) != 0) { + webcpp::secure::test::count_c(); + } +} + +namespace webcpp::secure::test { +/** Installs the hook at static initialisation, before main, as this inline variable is defined. */ +inline bool const logger_installed = (malloc_logger = &webcpp_test_count_c_allocation, true); +} // namespace webcpp::secure::test +#endif + +#endif From 7dfe06b8f5d97618b7c77e229aa4fcb212d7d701 Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 22:34:59 -0300 Subject: [PATCH 15/42] secure: allocation_test keeps clang-tidy quiet, and the Jamfile's comment keeps to 80 columns --- test/Jamfile | 7 ++++--- test/allocation_test.cpp | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/test/Jamfile b/test/Jamfile index 0052bbe..e63e196 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -87,9 +87,10 @@ secure-compile declassify_compile_msan : declassify_compile_test.cpp : WEBCPP_SECURE_CT_MSAN gcc:no msvc:no : native ; -# No function of the library allocates: under support/counting.hpp's replacement of -# every form of operator new (and the C library's allocator where a program can -# count it), every function of every header leaves the count where it was. +# No function of the library allocates: under support/counting.hpp's +# replacement of every form of operator new (and the C library's allocator +# where a program can count it), every function of every header leaves the +# count where it was. secure-run allocation : allocation_test.cpp ; # alone brings every header, one name of each used. secure-run convenience_header : convenience_header_test.cpp ; diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp index ce9f705..497e8fe 100644 --- a/test/allocation_test.cpp +++ b/test/allocation_test.cpp @@ -232,10 +232,11 @@ void check_secret() { original.writable()[0] = 0x42; secure::secret<32> moved(std::move(original)); BOOST_TEST_EQ(moved.bytes()[0], 0x42U); + // NOLINTNEXTLINE(bugprone-use-after-move): the move wipes its source, which this reads. BOOST_TEST_EQ(original.bytes()[0], 0U); secure::secret<32> assigned; assigned = std::move(moved); - secure::secret<32> copy = assigned.clone(); + secure::secret<32> const copy = assigned.clone(); BOOST_TEST_EQ(copy.bytes()[0], 0x42U); std::span const viewed = copy; BOOST_TEST_EQ(viewed.size(), 32U); From 69f9f135a26c11f3ef2c643bc55ce9d8aaded8fc Mon Sep 17 00:00:00 2001 From: R Date: Tue, 24 Nov 2026 23:00:10 -0300 Subject: [PATCH 16/42] secure: value_barrier is an asm volatile statement, as D8 states, so the compiler cannot merge, hoist or drop it --- include/webcpp/secure/constant_time.hpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/include/webcpp/secure/constant_time.hpp b/include/webcpp/secure/constant_time.hpp index 1a6f1fe..c84da1c 100644 --- a/include/webcpp/secure/constant_time.hpp +++ b/include/webcpp/secure/constant_time.hpp @@ -60,11 +60,12 @@ namespace constant_time { * Returns its argument, hidden from the optimiser, so that it cannot reason about which values * a mask may take and turn the arithmetic that uses it back into a branch. * - * On GCC and clang it is an empty `asm` statement with the value in a register (BoringSSL's - * `value_barrier_w`); on MSVC and on WebAssembly, which have no such statement, a round trip - * through a `volatile` local. In a constant expression it is the identity. The barrier holds - * the value in this one place: it does not stop the compiler from transforming the code around - * it. + * On GCC and clang it is an empty `asm volatile` statement with the value in a register + * (BoringSSL's `value_barrier_w`); the `volatile` keeps the compiler from merging, hoisting or + * dropping the statement, which has an output and would otherwise be an ordinary expression; on + * MSVC and on WebAssembly, which have no such statement, a round trip through a `volatile` local. + * In a constant expression it is the identity. The barrier holds the value in this one place: it + * does not stop the compiler from transforming the code around it. * * @tparam U Any unsigned integral type but `bool`. * @param value The value. @@ -76,7 +77,7 @@ template return value; } #if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) - __asm__("" : "+r"(value)); + __asm__ volatile("" : "+r"(value)); return value; #else U volatile held = value; From 1195d7eb8735a3d77d04cd799b68162a1233263c Mon Sep 17 00:00:00 2001 From: R Date: Wed, 25 Nov 2026 01:20:09 -0300 Subject: [PATCH 17/42] secure: value_barrier is a volatile round trip under MemorySanitizer, which reports an asm statement's uninitialised register input --- include/webcpp/secure/constant_time.hpp | 43 ++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/include/webcpp/secure/constant_time.hpp b/include/webcpp/secure/constant_time.hpp index c84da1c..1b3f75b 100644 --- a/include/webcpp/secure/constant_time.hpp +++ b/include/webcpp/secure/constant_time.hpp @@ -52,6 +52,34 @@ template return static_cast(value >> shift); } +/** + Whether the program is built with clang's MemorySanitizer, which takes an `asm` statement's + register input for a use and reports it when it is uninitialised: `value_barrier` then makes its + round trip through a `volatile` local instead, which carries the value's shadow to its result, so + that MemorySanitizer reports a branch or an index on a secret mask, not the barrier. +*/ +#ifdef __has_feature +#if __has_feature(memory_sanitizer) +inline constexpr bool memory_sanitizer = true; +#else +inline constexpr bool memory_sanitizer = false; +#endif +#else +inline constexpr bool memory_sanitizer = false; +#endif + +/** + A value's round trip through a `volatile` local, which the compiler must store and load again. + + @param value The value. + @return The same value. +*/ +template +[[nodiscard]] U volatile_round_trip(U value) noexcept { + U volatile held = value; + return held; +} + } // namespace detail namespace constant_time { @@ -63,7 +91,9 @@ namespace constant_time { * On GCC and clang it is an empty `asm volatile` statement with the value in a register * (BoringSSL's `value_barrier_w`); the `volatile` keeps the compiler from merging, hoisting or * dropping the statement, which has an output and would otherwise be an ordinary expression; on - * MSVC and on WebAssembly, which have no such statement, a round trip through a `volatile` local. + * MSVC and on WebAssembly, which have no such statement, and under MemorySanitizer, which would + * report the statement's input when it is a secret marked uninitialised, a round trip through a + * `volatile` local. * In a constant expression it is the identity. The barrier holds the value in this one place: it * does not stop the compiler from transforming the code around it. * @@ -77,11 +107,14 @@ template return value; } #if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) - __asm__ volatile("" : "+r"(value)); - return value; + if constexpr (detail::memory_sanitizer) { + return detail::volatile_round_trip(value); + } else { + __asm__ volatile("" : "+r"(value)); + return value; + } #else - U volatile held = value; - return held; + return detail::volatile_round_trip(value); #endif } From 09e8176421510c4be90781386f5c24dfc63ba1b0 Mon Sep 17 00:00:00 2001 From: R Date: Wed, 25 Nov 2026 01:20:09 -0300 Subject: [PATCH 18/42] secure: the constant-time lane, memcheck, MemorySanitizer and dudect over every block, each with a planted leak that must fail --- AGENTS.md | 8 +- test/Jamfile | 2 + test/constant_time/Jamfile | 123 ++++ test/constant_time/ctgrind_planted_test.cpp | 13 + test/constant_time/ctgrind_test.cpp | 24 + test/constant_time/dudect.hpp | 696 ++++++++++++++++++++ test/constant_time/dudect_harness_test.cpp | 255 +++++++ test/constant_time/dudect_judge.py | 147 +++++ test/constant_time/dudect_planted_test.cpp | 79 +++ test/constant_time/dudect_test.cpp | 189 ++++++ test/constant_time/msan_planted_test.cpp | 12 + test/constant_time/msan_report.mjs | 49 ++ test/constant_time/msan_test.cpp | 33 + test/constant_time/package-lock.json | 10 + test/constant_time/package.json | 1 + test/constant_time/paths.hpp | 335 ++++++++++ test/constant_time/valgrind.mjs | 39 ++ 17 files changed, 2014 insertions(+), 1 deletion(-) create mode 100644 test/constant_time/Jamfile create mode 100644 test/constant_time/ctgrind_planted_test.cpp create mode 100644 test/constant_time/ctgrind_test.cpp create mode 100644 test/constant_time/dudect.hpp create mode 100644 test/constant_time/dudect_harness_test.cpp create mode 100755 test/constant_time/dudect_judge.py create mode 100644 test/constant_time/dudect_planted_test.cpp create mode 100644 test/constant_time/dudect_test.cpp create mode 100644 test/constant_time/msan_planted_test.cpp create mode 100644 test/constant_time/msan_report.mjs create mode 100644 test/constant_time/msan_test.cpp create mode 100644 test/constant_time/package-lock.json create mode 100644 test/constant_time/package.json create mode 100644 test/constant_time/paths.hpp create mode 100644 test/constant_time/valgrind.mjs diff --git a/AGENTS.md b/AGENTS.md index 3a6b3f6..11c560d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,13 @@ specific to secure. ## Cautions - A test is declared through `secure-run` (or `secure-compile`) in `test/Jamfile`, which builds it - with exceptions and without. + with exceptions and without. The one exception is the own lane `constant-time` + (`test/constant_time/`): its programs (memcheck, MemorySanitizer and dudect) are native only, + one checker build each, and have no `_no_exceptions` twins; its Jamfile says so. +- A constant-time path that both checkers run goes in `test/constant_time/paths.hpp`, with its + operands marked secret through `test/support/constant_time_marks.hpp`; a planted leak is a + `[[gnu::noinline]]` function of its own, which the drivers require the report's first frame to + name. - A test that defines a seam includes the seam's header first, before any header of secure. - `detail` is not API: another library's header never includes it. Test code may call `secure::detail::write_dit`. diff --git a/test/Jamfile b/test/Jamfile index e63e196..3e2f50e 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -96,3 +96,5 @@ secure-run allocation : allocation_test.cpp ; secure-run convenience_header : convenience_header_test.cpp ; build-project messages ; +# The own lane constant-time: memcheck, MemorySanitizer and dudect. +build-project constant_time ; diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile new file mode 100644 index 0000000..c6e9876 --- /dev/null +++ b/test/constant_time/Jamfile @@ -0,0 +1,123 @@ +# 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: Valgrind's memcheck and MemorySanitizer on Linux, and dudect's +# statistics natively, as the own lane constant-time, outside the ordinary +# lanes. Both checkers run the same paths, paths.hpp: every block of +# constant_time.hpp on std::uint8_t, std::uint32_t and std::uint64_t, the byte +# blocks, constant_time_equal and secret<32>'s moves, clone and destruction, +# each with its operands marked secret. Each checker is shown to fail on +# planted leaks, each in a function of its own that the report must name: a +# select that branches on its mask, a lookup that indexes its table, and, for +# memcheck, a branch on constant_time_equal's verdict that was never +# declassified; dudect to find one, an early-exit comparison +# (dudect_planted). +# +# The lane's programs are native only, each one build of its checker: they are +# not declared through test/Jamfile's secure-run, and have no _no_exceptions +# twins (this is a project of its own, where that rule is not visible, and a +# checker's build is a release build of one configuration). +project : requirements /webcpp/secure//secure ; + +import webcpp os ; + +webcpp.targets native ; + +webcpp.original node ; + +# Valgrind and MemorySanitizer run on Linux alone: elsewhere their programs +# are not built, and the lane runs dudect alone. +rule linux-only ( properties * ) +{ + if ! linux in $(properties) + { + return no ; + } +} + +# MemorySanitizer is clang's alone: its programs are built with clang on +# Linux, and not with GCC (-fsanitize=memory is no option of GCC's). +rule clang-on-linux ( properties * ) +{ + if ! linux in $(properties) || ! clang in $(properties) + { + return no ; + } +} + +CTGRIND = release on @linux-only + WEBCPP_SECURE_CT_VALGRIND 300 ; + +webcpp.drive ctgrind : ctgrind_test.cpp : $(CTGRIND) : valgrind.mjs : : native ; +# The blocks compile in the user's translation unit, so they are checked at +# both optimisations: ctgrind is release, which is +# speed in b2, and ctgrind_space the other, a program of its +# own, where an optimiser may if-convert a mask differently. +webcpp.drive ctgrind_space : ctgrind_test.cpp : $(CTGRIND) space + : valgrind.mjs : : native ; +# The planted leaks, each run before every path: memcheck must report each in +# its own function (valgrind.mjs --in). The same source, its own define, and +# each but the first its own directory (), or b2 would link +# another's objects. +webcpp.drive ctgrind_planted_select : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_SECURE_PLANTED_SELECT + : valgrind.mjs : --expect-leak --in planted_select : native ; +webcpp.drive ctgrind_planted_lookup : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_SECURE_PLANTED_LOOKUP ctgrind_planted_lookup + : valgrind.mjs : --expect-leak --in planted_lookup : native ; +webcpp.drive ctgrind_planted_verdict : ctgrind_planted_test.cpp + : $(CTGRIND) WEBCPP_TEST_SECURE_PLANTED_VERDICT + ctgrind_planted_verdict + : valgrind.mjs : --expect-leak --in planted_verdict : native ; + +# MemorySanitizer's checking of what a function is passed and returns, eager +# since clang 16, is off: a value derived from a secret is passed and returned +# by design, and only a branch or an index on one is a leak. +MSAN_FLAGS = -fsanitize=memory -fno-sanitize-memory-param-retval ; +MSAN = WEBCPP_SECURE_CT_MSAN $(MSAN_FLAGS) -fsanitize=memory + release on @clang-on-linux ; + +webcpp.run msan : msan_test.cpp : $(MSAN) : native ; +# The planted leaks under MemorySanitizer: each passes only on its report whose +# first frame is the planted function (msan_report.mjs --in). No planted +# verdict: MemorySanitizer drops a subtraction's carry, and so takes +# constant_time_equal's verdict for initialised (msan_test.cpp says why); +# memcheck's ctgrind_planted_verdict shows that branch reported. +webcpp.drive msan_planted_select : msan_planted_test.cpp + : $(MSAN) WEBCPP_TEST_SECURE_PLANTED_SELECT + : msan_report.mjs : --in planted_select : native ; +webcpp.drive msan_planted_lookup : msan_planted_test.cpp + : $(MSAN) WEBCPP_TEST_SECURE_PLANTED_LOOKUP msan_planted_lookup + : msan_report.mjs : --in planted_lookup : native ; + +# dudect's statistics on constant_time_equal, lookup, select_bytes and +# less_mask, each with its A/A control, natively. The programs never set DIT +# for a measurement: constant_time_equal holds secure's guard, which sets DIT +# in each call on macOS and Linux on arm64 where the CPU has it, and the +# program fails if DIT is set outside the calls, or not set inside a guard +# (dudect.hpp). On a runner GitHub hosts, a virtual machine shared with other +# tenants whose processor changes from run to run, each |t| is printed and the +# program does not judge it: there it moved with what the measurement cannot +# control (dudect.hpp, judged), so the CI's dudect_judge.py warns at 10 and +# measures a case over 10 again in two fresh processes, failing when two of the +# three are 10 or more. dudect_planted is judged everywhere. +DUDECT = release ; +if [ os.environ RUNNER_ENVIRONMENT ] = github-hosted +{ + DUDECT += WEBCPP_TEST_DUDECT_UNJUDGED ; +} +# Named dudect_blocks, not dudect: the CI's judge reads every dudect_*.output. +webcpp.run dudect_blocks : dudect_test.cpp : $(DUDECT) : native ; +webcpp.run dudect_planted : dudect_planted_test.cpp : release : native ; + +# dudect.hpp itself, on synthetic data and without timing: the statistics, the +# A/A control's preparation, --case and the lines the CI's judge reads. +webcpp.run dudect_harness : dudect_harness_test.cpp : : native ; + +webcpp.lane constant-time : ctgrind ctgrind_space ctgrind_planted_select + ctgrind_planted_lookup ctgrind_planted_verdict msan msan_planted_select + msan_planted_lookup dudect_blocks dudect_planted dudect_harness + : native ; diff --git a/test/constant_time/ctgrind_planted_test.cpp b/test/constant_time/ctgrind_planted_test.cpp new file mode 100644 index 0000000..6f4327d --- /dev/null +++ b/test/constant_time/ctgrind_planted_test.cpp @@ -0,0 +1,13 @@ +// 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) + +// ctgrind_test.cpp with a planted leak, a source of its own so that b2 compiles it with its own +// defines: the builds the lane expects memcheck to fail, each in its planted function (paths.hpp), +// run before every path. With WEBCPP_TEST_SECURE_PLANTED_SELECT, a select that branches on its +// secret mask; with WEBCPP_TEST_SECURE_PLANTED_LOOKUP, a lookup that indexes its table by the +// secret index; with WEBCPP_TEST_SECURE_PLANTED_VERDICT, a branch on constant_time_equal's verdict +// that was never declassified. +#include "ctgrind_test.cpp" // NOLINT(bugprone-suspicious-include) diff --git a/test/constant_time/ctgrind_test.cpp b/test/constant_time/ctgrind_test.cpp new file mode 100644 index 0000000..06f46d7 --- /dev/null +++ b/test/constant_time/ctgrind_test.cpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Under Valgrind's memcheck, the operands of every block, of constant_time_equal and of +// secret<32>'s moves are marked undefined (paths.hpp, shared with msan_test.cpp): a branch or a +// memory index that depends on them is an error, and the run fails (valgrind.mjs's +// --error-exitcode). memcheck follows a subtraction's carry, so each result is also checked to be +// undefined until it is declassified: the mark reaches it, so the path is traced. A planted +// program (ctgrind_planted_test.cpp) runs its planted leak first, which memcheck must report. + +#include "paths.hpp" + +#include + +int main() { + using checker = webcpp::secure::test::memcheck; + webcpp::secure::test::run_planted(); + int const failures = webcpp::secure::test::common_paths(); + std::printf("constant time under memcheck: %s\n", failures == 0 ? "ok" : "FAILED"); + return failures == 0 ? 0 : 1; +} diff --git a/test/constant_time/dudect.hpp b/test/constant_time/dudect.hpp new file mode 100644 index 0000000..bd55083 --- /dev/null +++ b/test/constant_time/dudect.hpp @@ -0,0 +1,696 @@ +// 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) + +// Welch's t-test over two classes of timings, with dudect's cropping. Copied from crypto's +// test/constant_time/dudect.hpp, which keeps its own (secure's tests keep their own support): the +// measurements its comments cite were made on crypto's lane, whose cases the reasons were found on. + +#ifndef WEBCPP_TEST_SECURE_DUDECT_HPP +#define WEBCPP_TEST_SECURE_DUDECT_HPP + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#include +#endif + +#ifdef __APPLE__ +#include +#endif + +namespace webcpp::secure::test { + +/** + * Waits until every instruction before it has completed, so that a clock read after it does + * not start while the preparation's last instructions still run: `isb` on 64-bit ARM, `lfence` + * on x86. Without it the clock is read out of order, and what the preparation does by class + * (it copies the fixed input or just-drawn bytes) leaks into the measured time (measured + * natively on an Apple M5, 2026-11-18: |t| 25 to 35 on a ChaCha20-Poly1305 decryption that + * never reads the classes' input, below 2 with the barriers; an early-exit comparison's |t| + * rose from 18 to 42). WebAssembly has no such instruction: there the clock is a host call. + */ +inline void serialise() noexcept { +#ifdef __aarch64__ + __asm__ volatile("isb" ::: "memory"); +#elif defined(__x86_64__) || defined(__i386__) + __asm__ volatile("lfence" ::: "memory"); +#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + _mm_lfence(); +#elif defined(_MSC_VER) && defined(_M_ARM64) + __isb(_ARM64_BARRIER_SY); +#endif +} + +/** + * Prints, in one line, what the program finds of 64-bit ARM's DIT (Data Independent Timing) bit, + * PSTATE.DIT, and whether the measurements may go on. The harness never sets DIT for the + * measurements: `constant_time_equal` sets it in each call through secure's guard + * (`secure::timing_guard`), and the lane measures that, what a program gets; the blocks hold no + * guard, and a caller that wants DIT over them holds its own. Where the CPU has DIT, the line + * also shows the guard at work, once, before any measurement: DIT set inside a guard's scope and + * clear again after it. It must be clear on this thread outside the calls, or the timings would + * be those of a DIT the program set itself, not the guard's. + * @return false where the CPU has DIT and it is set on this thread outside a guard, or not set + * inside one, so that the program fails rather than measure it; true otherwise: where the CPU has + * DIT and the guard sets and clears it, where the CPU has none, and where the guard does not + * apply (not macOS or Linux on arm64: x86, WebAssembly, where the engine decides, and Windows on + * ARM64). + */ +inline bool report_data_independent_timing() noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (!secure::cpu_has_dit()) { + std::printf("DIT (data-independent timing): not on this CPU\n"); + return true; + } + bool const set_before = secure::dit_is_set(); + bool set_inside = false; + { + secure::timing_guard const timing_scope; + set_inside = secure::dit_is_set(); + } + bool const set_after = secure::dit_is_set(); + bool const outside_set = set_before || set_after; + std::printf( + "DIT (data-independent timing): the CPU has it; secure's guard sets it in each call of " + "constant_time_equal, the harness does not (%s inside a guard; %s)\n", + set_inside ? "set" : "NOT set", + outside_set ? "set on this thread outside the calls: not measured" + : "clear on this thread outside the calls"); + return set_inside && !outside_set; +#else + std::printf( + "DIT (data-independent timing): not applicable here (not macOS or Linux on arm64)\n"); + return true; +#endif +} + +/** Online mean and variance of one class, Welford's. */ +struct moments { + /** The number of values pushed. */ + double n = 0; + /** Their mean. */ + double mean = 0; + /** The sum of squared differences from the mean. */ + double m2 = 0; + + /** + * Adds a value. + * @param x The value. + */ + void push(double x) { + n += 1; + double const delta = x - mean; + mean += delta / n; + m2 += delta * (x - mean); + } + + /** + * The sample variance. + * @return The variance, 0 below two values. + */ + [[nodiscard]] double variance() const { return n > 1 ? m2 / (n - 1) : 0; } +}; + +/** + * Welch's t of two classes. + * @param a The first class. + * @param b The second class. + * @return t, 0 when both variances are 0. + */ +inline double welch(moments const& a, moments const& b) { + double const denominator = std::sqrt((a.variance() / a.n) + (b.variance() / b.n)); + return denominator == 0 ? 0 : (a.mean - b.mean) / denominator; +} + +/** One class's count and mean at a cropping. */ +struct class_summary { + /** The number of its timings kept. */ + std::size_t count; + /** Their mean, in nanoseconds. */ + double mean_ns; +}; + +/** The largest |t| of a set of timings, with what gave it. */ +struct t_statistic { + /** The largest |t| over the whole set and dudect's 100 croppings. */ + double t; + /** The cropping that gave it: -1 for the whole set, else 0 to 99. */ + int crop; + /** The largest timing that cropping kept, in nanoseconds. */ + double limit_ns; + /** Each class's count and mean at that cropping. */ + std::array classes; +}; + +/** + * A |t| as the lines print it, rounded to two decimals: every decision reads this value (the + * evidence's condition, a case's pass, `twice`'s second run, the planted leak's verdict), so that + * a |t| of 9.996 prints 10.00, with its evidence, and fails as 10.00 does, and the CI's judge, + * which reads the printed value, agrees with the program. + * @param t The |t|. + * @return It rounded to two decimals. + */ +inline double printed(double t) { + return std::round(t * 100) / 100; +} + +/** + * The largest |t| over the whole set and dudect's 100 croppings, each of which keeps the timings + * at or below a percentile, with the cropping that gave it and each class's count and mean there. + * A cropping that leaves a class empty has no t and is skipped; of equal values the first, the + * whole set before the croppings, is kept. + * @param timings The measurements, at least one. + * @param classes The class, 0 or 1, of each. + * @return The largest |t| and what gave it. + */ +inline t_statistic largest_t(std::vector const& timings, std::vector const& classes) { + std::vector sorted = timings; + std::ranges::sort(sorted); + t_statistic largest{.t = 0, .crop = -1, .limit_ns = sorted.back(), .classes = {}}; + for (int k = -1; k < 100; ++k) { + double const keep = k < 0 ? 1.0 : 1.0 - std::pow(0.5, 10.0 * (k + 1) / 100.0); + double const limit = + sorted[static_cast(keep * static_cast(sorted.size() - 1))]; + std::array m{}; + for (std::size_t i = 0; i < timings.size(); ++i) { + if (timings[i] <= limit) { + m[static_cast(classes[i])].push(timings[i]); + } + } + double const t = std::fabs(welch(m[0], m[1])); + if (!std::isfinite(t) || (k >= 0 && !(t > largest.t))) { + continue; + } + largest = { + .t = t, + .crop = k, + .limit_ns = limit, + .classes = + { + class_summary{.count = static_cast(m[0].n), .mean_ns = m[0].mean}, + class_summary{.count = static_cast(m[1].n), .mean_ns = m[1].mean}, + }, + }; + } + return largest; +} + +/** + * Draws `Size` bytes, then writes into `input` either `fixed`, for class 0, or the drawn bytes, + * for class 1, so that the two classes differ in the bytes written and in nothing else. Both + * classes draw the same bytes, read both `fixed` and the drawn bytes, and write `input` with the + * same instructions: each byte is blended through a mask read from a volatile, which the + * compiler cannot see through, so that it can neither split the work by class nor read one + * source alone. Whatever a class does differently before the measured call leaks the class into + * it. A copy from a volatile pointer to the chosen source (until 2026-11-20) read the fixed + * input for class 0 and the bytes just drawn, still in the store buffer, for class 1: on the + * CI's x86-64 runners the measured call then differed by class whatever it computed (measured + * on GitHub's ubuntu-24.04 runners, 2026-11-20: equal at |t| 31 to 56 on an Intel Xeon 6975P-C + * and ChaCha20-Poly1305's seal at 28 to 85 on AMD EPYC 9V45 and 9V74; through this blend, on + * the Xeon, the EPYC 9V74 and an AMD EPYC 7763, idle and with every processor busy, every case + * of 23 runs of 24 stayed below 4.4, the 24th is in `judged`). Before it, + * a choice the optimiser made of `which == 0 ? 0 : drawn` split the copy into a store of + * constants and a store of drawn bytes (measured natively on an Apple M5, 2026-11-18: |t| 16 to + * 18 on equal and 9 to 26 on open with the split, below 3 for both without it). + * With `Control`, the A/A control: the bytes are drawn, then overwritten with `fixed`, and blended + * through the same volatile mask, so that both classes write the fixed value with the same + * instructions as a case's and the generator advances as it does; its |t| shows what the + * measurement on that machine finds where nothing differs. + * @tparam Control Whether both classes write `fixed`. + * @param which The class, 0 or 1. + * @param generator The seeded generator. + * @param fixed The class 0 input. + * @param input Where the input of the class is written. + */ +template +void choose(int which, Generator& generator, std::array const& fixed, + std::array& input) { + std::array drawn{}; + for (auto& byte : drawn) { + byte = static_cast(generator()); + } + if constexpr (Control) { + // Read through a volatile, so that the compiler cannot know the two sources of the blend + // below equal and fold it into a copy: the control blends as every case does. + for (std::size_t index = 0; index < Size; ++index) { + drawn[index] = static_cast(fixed[index]); + } + } + std::uint8_t volatile const chosen = which == 0 ? 0xFFU : 0x00U; + unsigned const keep = chosen; + unsigned const drop = keep ^ 0xFFU; + for (std::size_t index = 0; index < Size; ++index) { + input[index] = static_cast((unsigned{fixed[index]} & keep) | + (unsigned{drawn[index]} & drop)); + } +} + +/** + * The largest |t| of `count` measurements of `run`, each after `prepare(class, generator)` + * with a class drawn at random from the seeded generator, prepare unmeasured; each clock read + * is fenced by `serialise`. + * @param seed The generator's seed. + * @param count The number of measurements. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The largest |t|, with what gave it. + */ +template +t_statistic measure(std::uint64_t seed, std::size_t count, Prepare&& prepare, Run&& run) { + std::mt19937_64 generator(seed); + std::vector timings; + std::vector classes; + timings.reserve(count); + classes.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + int const which = static_cast(generator() & 1U); + prepare(which, generator); + serialise(); + auto const start = std::chrono::steady_clock::now(); + serialise(); + run(); + serialise(); + auto const end = std::chrono::steady_clock::now(); + timings.push_back(std::chrono::duration(end - start).count()); + classes.push_back(which); + } + return largest_t(timings, classes); +} + +/** + * The largest |t| of a first run, and of a second with another seed when the first, as printed, + * is at least 10. + * @param count The number of measurements of each run. + * @param prepare Sets up the class's input, unmeasured. + * @param run The operation measured. + * @return The first run's statistic when its |t|, as printed, is below 10, else that of the run + * with the smaller |t|. + */ +template +t_statistic twice(std::size_t count, Prepare&& prepare, Run&& run) { + t_statistic const first = measure(20261011, count, prepare, run); + if (printed(first.t) < 10) { + return first; + } + t_statistic const second = measure(20261012, count, prepare, run); + return second.t < first.t ? second : first; +} + +/** A buffer a case measures, named in its addresses line. */ +struct address { + /** + * Names a buffer, as `{"data", data.data()}` does in a case's list. + * @param name Its name in the line, as `data` or `object`. + * @param buffer Where it is. + */ + constexpr address(char const* name, void const* buffer) noexcept : label(name), where(buffer) {} + + /** Its name in the line, as `data` or `object`. */ + char const* label; + /** Where it is. */ + void const* where; +}; + +/** + * The lines of a case, which the CI's judge reads (design D6 of the change api-gaps): `dudect + * case= t=<|t|> threshold=10 judged=`, and, when |t| is at least 10, `dudect + * evidence case= crop= limit_ns= class0_n= class0_mean_ns= class1_n= + * class1_mean_ns=`, the cropping that gave |t| and each class there, and `dudect addresses + * case=