Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
355b03e
crypto: detail::timing_guard sets arm64's DIT for its scope and resto…
Nov 20, 2026
9af474c
crypto: the timing test writes DIT through detail::write_dit, and tim…
Nov 20, 2026
54f442e
crypto: the ciphers, the boxes and PEM set DIT around each operation …
Nov 20, 2026
8ab4f7e
crypto: Ed25519, X25519, kx and their formats set DIT around each ope…
Nov 20, 2026
e677df1
crypto: secp256k1 and its groups set DIT around each operation
Nov 20, 2026
1bec9bb
crypto: the secp256k1 coverage test calls ellswift_decode, pubkey_neg…
Nov 20, 2026
0a3ed3c
crypto: a coverage test per backend proves every public operation ent…
Nov 20, 2026
f20215d
crypto: the timing seam's matcher reads a function's own name, before…
Nov 20, 2026
8ac050d
crypto: the constant-time lane no longer sets DIT and measures what t…
Nov 21, 2026
e5ff7fc
crypto: the guard's cost measured in release and the pages say that w…
Nov 21, 2026
9b72e1f
crypto: the guard's timing program fails when the thread starts with …
Nov 21, 2026
2702f1b
crypto: collect.py links the guard to the DIT section, records each p…
Nov 21, 2026
d5054e7
crypto: the pages state dudect_planted's and wasip2's values from the…
Nov 21, 2026
b3fdc44
crypto: the guard takes a source_location only where a test defines t…
Nov 21, 2026
5947524
crypto: collect.py marks the throughput and the guard provisional eac…
Nov 21, 2026
03486ed
crypto: the changelog names macOS, iOS, Linux and Android where webcp…
Nov 21, 2026
046ab71
crypto: a memory resource fails by throwing, never by returning null,…
Nov 21, 2026
8820988
crypto: the OpenSSL backend zeroes its context pointers with wipe_obj…
Nov 21, 2026
e88b6ff
crypto: the secp256k1 allocation test passes its control block throug…
Nov 21, 2026
0f18d2f
crypto: the AEAD tampering check copies the tag, the additional data …
Nov 21, 2026
0750de8
crypto: collect.py's program_line returns the line only once it is a …
Nov 21, 2026
a8d0593
crypto: comments say a dead store at an object's end may be dropped b…
Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,20 @@ specific to crypto.
same commit (`fixes` for each message, `fixtures` for each fixture, `lane` for the constant-time
lane's paths); the generator names what is missing.
- `generate.py --sizes <json>...` reads the own lane `sizes` (built at `variant=release`) into
`doc/tables/sizes.json`; `doc/performance.json` is `bench/collect.py`'s, release builds only.
Nothing that states a size or a speed is typed by hand.
`doc/tables/sizes.json`; `doc/performance.json` is `bench/collect.py`'s, release builds only,
the throughput (`--exe`) and the timing guard's cost (`--timing`, natively). Nothing that states
a size or a speed is typed by hand.

## Cautions

- An algorithm type does every guard; a backend's header supplies only the six traits of
`detail/engines.hpp` (`block_state`, `block_engine`, `gcm_state`, `gcm_engine`, `aead_state`,
`aead_engine`) and, for the curves and `hybrid`, the functions of its own header.
- A new public function that calls a backend holds `detail::timing_guard` as its
first statement (it sets arm64's DIT for the call, `detail/timing.hpp`) and joins the coverage
test of its backend, `test/timing_coverage_<backend>_test.cpp`, which checks through the seam
that each call entered its own guard. A function that only copies or encodes bytes, with no
backend call, holds none.
- A test of a backend is a `.cpp` of its own per backend, never a define that changes the backend
of one source (spec section 4.3's pitfall).
- Every C library is unchanged upstream code. A moved pin is a change of its own
Expand Down
21 changes: 16 additions & 5 deletions bench/Jamfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
# https://www.boost.org/LICENSE_1_0.txt)

# The throughput of each family's fixed operation per backend (throughput.cpp,
# bench/operations.hpp). throughput_check is the correctness test of the
# measured program, run in every lane of test/ (test/Jamfile builds this
# project): each operation checked once, never timed. The measurement itself
# is made by hand by collect.py, which runs the program built here at
# variant=release and writes doc/performance.adoc; no lane measures it.
# bench/operations.hpp), and the cost of the timing guard every operation runs
# in (timing.cpp). throughput_check and timing_check are the correctness tests
# of the measured programs, run in every lane of test/ (test/Jamfile builds
# this project): each operation checked once, never timed, and the guard's
# measurement run at 10^3 iterations, its line's form and the thread's DIT
# checked. The measurements themselves are made by hand by collect.py, which
# runs the programs built here at variant=release and writes
# doc/performance.adoc; no lane measures them.

project : requirements <library>/webcpp/crypto//crypto ;

Expand All @@ -36,3 +39,11 @@ webcpp.run throughput_check : throughput.cpp : $(.requirements) ;
# run by hand (doc/performance.adoc); no lane measures it.
exe throughput : throughput.cpp : $(.requirements) <variant>release ;
explicit throughput ;

# The guard's cost needs no backend: detail/timing.hpp alone.
webcpp.run timing_check : timing.cpp ;

# The same program at variant=release, the one collect.py --timing measures,
# built and run by hand (doc/performance.adoc); no lane measures it.
exe timing : timing.cpp : <variant>release ;
explicit timing ;
353 changes: 334 additions & 19 deletions bench/collect.py

Large diffs are not rendered by default.

226 changes: 226 additions & 0 deletions bench/timing.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
// 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 cost of detail::timing_guard, the scope every public operation of crypto runs in, which sets
// 64-bit ARM's DIT (data-independent timing) bit where the CPU has it and restores the thread's
// state after it.
//
// Run as `timing --measure`, it times, in one process, 10^7 iterations each of an empty loop body,
// of a guard entered from a thread whose DIT is clear (it sets DIT and clears it again), and of a
// guard entered with DIT already set (it reads DIT and leaves it; the program sets DIT for that
// part with the same `msr` as the guard, and clears it after), five runs of each, interleaved, and
// prints one JSON line: `{"dit": true|false, "clear": <ns>, "set": <ns>, ...}`, each cost the
// median of its runs minus the empty loop's median, in nanoseconds per guard, then each part's
// fastest and slowest run (minus the same median), the iterations, the runs, the target and the
// compiler. "dit" says whether the guard sets DIT here (a target it covers, on a CPU that has it);
// where it does not, the guard executes no instruction and both costs are the loop's noise. Both
// modes fail when the process starts with DIT set, or when the thread's DIT is not as the guard
// must leave it after a part. Run with no argument, it is the correctness test: the same
// measurement at 10^3 iterations, whose line must also have that form, and whose "dit" must be
// what the library reads. A measurement never fails on its time; bench/collect.py --timing runs
// it and writes doc/performance.adoc.

#include <webcpp/crypto/detail/timing.hpp>

#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <span>
#include <string_view>

namespace detail = webcpp::crypto::detail;

namespace {

#ifdef WEBCPP_TARGET_WASIP2
constexpr std::string_view target = "wasip2";
#elif defined(WEBCPP_TARGET_WASIP3)
constexpr std::string_view target = "wasip3";
#elif defined(WEBCPP_TARGET_EMSCRIPTEN)
constexpr std::string_view target = "emscripten";
#else
constexpr std::string_view target = "native";
#endif

// The compiler, as it names itself: MSVC defines no __VERSION__.
#ifdef __VERSION__
constexpr std::string_view compiler = __VERSION__;
#elif defined(_MSC_FULL_VER)
#define WEBCPP_CRYPTO_BENCH_STRING(x) #x
#define WEBCPP_CRYPTO_BENCH_VERSION(x) WEBCPP_CRYPTO_BENCH_STRING(x)
constexpr std::string_view compiler = "MSVC " WEBCPP_CRYPTO_BENCH_VERSION(_MSC_FULL_VER);
#else
constexpr std::string_view compiler = "unknown";
#endif

// The iterations of a measured run, and of the correctness test's.
constexpr std::uint64_t measured_iterations = 10'000'000;
constexpr std::uint64_t checked_iterations = 1'000;

// The runs of each part; their median is the part's time.
constexpr std::size_t runs = 5;

// Whether the guard sets DIT on this target and CPU.
bool guard_sets_dit() noexcept {
#ifdef WEBCPP_CRYPTO_DETAIL_TIMING_COVERED
return detail::cpu_has_dit();
#else
return false;
#endif
}

// Sets or clears this thread's DIT where the guard would, as a program that asks for it does.
void force_dit([[maybe_unused]] bool set) noexcept {
#ifdef WEBCPP_CRYPTO_DETAIL_TIMING_COVERED
if (detail::cpu_has_dit()) {
detail::write_dit(set ? detail::dit_bit : 0);
}
#endif
}

// The nanoseconds of one iteration of body, over iterations of it.
template <class Body>
double nanoseconds_per_iteration(std::uint64_t iterations, Body body) {
auto const start = std::chrono::steady_clock::now();
for (std::uint64_t i = 0; i < iterations; ++i) {
body(i);
}
std::chrono::duration<double, std::nano> const elapsed =
std::chrono::steady_clock::now() - start;
return elapsed.count() / static_cast<double>(iterations);
}

// A part's runs, each less the empty loop's median: their median, fastest and slowest.
struct summary {
double median = 0;
double fastest = 0;
double slowest = 0;
};

summary summarise(std::array<double, runs> values, double loop) {
std::ranges::sort(values);
return {
.median = values[runs / 2] - loop,
.fastest = values.front() - loop,
.slowest = values.back() - loop,
};
}

// What one measurement gives: the guard's two costs, and whether DIT was as the guard must leave
// it before and after each part.
struct result {
summary clear;
summary set;
bool restored = true;
};

result measure(std::uint64_t iterations) {
std::array<double, runs> empty{};
std::array<double, runs> clear{};
std::array<double, runs> set{};
// A process that starts with DIT set would measure the set part twice.
bool restored = !detail::dit_is_set();
// Written by every iteration of every part, so that no loop is removed or merged.
std::uint64_t volatile sink = 0;
for (std::size_t run = 0; run < runs; ++run) {
empty[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { sink = i; });
clear[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) {
detail::timing_guard const guard;
sink = i;
});
restored = restored && !detail::dit_is_set();
force_dit(true);
set[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) {
detail::timing_guard const guard;
sink = i;
});
restored = restored && detail::dit_is_set() == guard_sets_dit();
force_dit(false);
restored = restored && !detail::dit_is_set();
}
double const loop = summarise(empty, 0).median;
return {.clear = summarise(clear, loop), .set = summarise(set, loop), .restored = restored};
}

// Writes the JSON line of a measurement into line; the number of characters, or -1.
int format(std::span<char> line, result const& measured, std::uint64_t iterations) {
return std::snprintf(
line.data(), line.size(),
R"({"dit": %s, "clear": %.3f, "set": %.3f, "clear_fastest": %.3f, )"
R"("clear_slowest": %.3f, "set_fastest": %.3f, "set_slowest": %.3f, )"
R"("iterations": %llu, "runs": %zu, "target": "%.*s", "compiler": "%.*s"})",
guard_sets_dit() ? "true" : "false", measured.clear.median, measured.set.median,
measured.clear.fastest, measured.clear.slowest, measured.set.fastest, measured.set.slowest,
static_cast<unsigned long long>(iterations), runs, static_cast<int>(target.size()),
target.data(), static_cast<int>(compiler.size()), compiler.data());
}

// Skips prefix at the start of text, or returns null when text does not start with it.
char const* skip(char const* text, std::string_view prefix) {
return text != nullptr && std::string_view(text).starts_with(prefix) ? text + prefix.size()
: nullptr;
}

// Reads a finite number at the start of text into value; what follows it, or null.
char const* number(char const* text, double& value) {
if (text == nullptr) {
return nullptr;
}
char* end = nullptr;
value = std::strtod(text, &end);
return end != text && std::isfinite(value) ? end : nullptr;
}

// Whether line opens with the form collect.py reads: "dit" as the library reads it, then the two
// costs as finite numbers.
bool well_formed(char const* line) {
double clear = 0;
double set = 0;
char const* rest =
skip(line, guard_sets_dit() ? R"({"dit": true, "clear": )" : R"({"dit": false, "clear": )");
rest = number(skip(number(rest, clear), R"(, "set": )"), set);
return skip(rest, R"(, "clear_fastest": )") != nullptr;
}

int usage() {
static_cast<void>(std::fprintf(stderr, "usage: timing [--measure]\n"));
return 2;
}

} // namespace

int main(int argument_count, char** arguments) {
std::span<char*> const given(arguments, static_cast<std::size_t>(argument_count));
bool const measuring = given.size() == 2 && std::string_view(given[1]) == "--measure";
if (given.size() != 1 && !measuring) {
return usage();
}
std::uint64_t const iterations = measuring ? measured_iterations : checked_iterations;
result const measured = measure(iterations);
std::array<char, 512> line{};
int const written = format(line, measured, iterations);
if (written < 0 || static_cast<std::size_t>(written) >= line.size()) {
static_cast<void>(std::fprintf(stderr, "timing: the line does not fit\n"));
return 1;
}
std::printf("%s\n", line.data());
if (!measured.restored) {
static_cast<void>(std::fprintf(
stderr, "timing: the thread's DIT was set at the start or not restored by a guard\n"));
}
if (measuring) {
return measured.restored ? 0 : 1;
}
bool const formed = well_formed(line.data());
std::printf("form %s\nstate restored %s\n", formed ? "ok" : "FAILED",
measured.restored ? "ok" : "FAILED");
return formed && measured.restored ? 0 : 1;
}
69 changes: 53 additions & 16 deletions doc/backends.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -99,24 +99,18 @@ by memcheck alone. dudect's statistics
BearSSL's two AEADs' seal and open, ctaes, `equal`, libsodium's X25519
agreement and Ed25519 signing, and libsecp256k1's `ecdh_x` natively, on Linux
and macOS, and under wasmtime.
On 64-bit ARM under macOS and Linux, each dudect program first sets the CPU's
DIT (data-independent timing) bit, with which the instructions Arm lists take
a time independent of their data, and which Apple requires of constant-time
code
(link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, enable DIT for constant-time cryptographic operations]);
it prints whether it is set, and fails where the CPU has DIT and it is not, or
where macOS cannot say whether the CPU has it. Elsewhere (x86, WebAssembly, and
64-bit ARM systems the harness does not cover, MSVC on ARM64 among them) it
sets nothing, prints so, and measures without DIT. The lane's `dudect_planted`
shows that DIT does not hide a leak: X25519's `agree` after an early-exit scan
of its secret key, which dudect must find.
None of the C libraries sets DIT, and neither does webcpp: a program on Apple
silicon sets it around its secret operations, as Apple describes
(`timingsafe_enable_if_supported` from macOS 15.2). Without it, libsodium's
X25519 is measurably not constant time there, listed under the table.
dudect's programs set nothing themselves: they measure what a program gets,
which on 64-bit ARM is the DIT webcpp sets in each call (<<crypto-backends-dit>>).
Each prints whether the CPU has DIT, and fails where DIT is set on its thread
outside the measured calls, which would measure something a program does not
get. The lane's `dudect_planted` shows that DIT does not hide a leak: X25519's
`agree` after an early-exit scan of its secret key, the scan run inside the
library's own guard as a public operation's code would be, which dudect must
find: |t| 66.72 and 65.53 against the threshold 10 (2026-11-21 UTC, two runs,
an Apple M5 Max, a release build).

One measurement is an open finding, listed under the table with its numbers:
libsodium's X25519 `agree` under wasmtime, on wasip2. Its cause is the same:
libsodium's X25519 `agree` under wasmtime, on wasip2. Its cause is measured:
wasmtime does not set DIT, and with DIT set in wasmtime's main thread, an
experiment and not the lane, the case passes. The WebAssembly cannot set it,
so the lane prints its value on wasip2 without judging it, and judges
Expand Down Expand Up @@ -153,6 +147,49 @@ marks. OpenSSL's verdict is OpenSSL's own internal
branch, which webcpp cannot mark: OpenSSL is checked with the key secret during
`seal` only.

[#crypto-backends-dit]
==== Data-independent timing (DIT)

64-bit ARM's DIT (data-independent timing) bit, PSTATE.DIT, makes the
instructions Arm lists take a time independent of their data, and Apple
requires it of constant-time code
(link:https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations[Apple, enable DIT for constant-time cryptographic operations]).
None of the C libraries sets it, so webcpp does: every public function that
runs a backend's cryptographic code, and `equal`, runs its whole body with DIT
set on 64-bit ARM under macOS, iOS, Linux and Android where the CPU has
FEAT_DIT (`hw.optional.arm.FEAT_DIT` on Apple's systems, `HWCAP_DIT` on
Linux), and returns with the thread's DIT as it found it: clear when it was
clear, set when the program set it itself (Apple's
`timingsafe_enable_if_supported`, from macOS 15.2) or an outer call did. An
error and an exception leave it as found too, and DIT is a thread's own
state, so a call never changes another thread's. A program does nothing.

Elsewhere webcpp sets nothing:

* On x86, the counterpart is Intel's DOITM (data operand independent timing
mode), a model-specific register that only the kernel writes: it is the
system's choice, out of webcpp's reach.
* On WebAssembly, the engine that compiles the code decides, and the
WebAssembly cannot set DIT: X25519 on wasip2 is the open finding above.
* On Windows on ARM64, no documented way to ask Windows whether the CPU has
FEAT_DIT was found, and DIT's instructions trap on a CPU without it: the
guard is empty there, and untested.

What the guard adds to a call, measured from a release build beside the
shortest operation's time, is in <<crypto-performance-timing>>.

`silent_payments::scan_outputs` calls the program's `LabelLookup` inside its
guard: the lookup runs with DIT set, which only makes it data-independent too.

The lane's dudect used to set DIT itself; it now sets nothing and
measures the library's guard. libsodium's X25519 `agree`, an all-zero secret
key against random ones, on an Apple M5 Max from a release build, against the
threshold 10: with the library's guard, |t| 1.8 to 2.8 (2026-11-21, five runs);
with no DIT at all, |t| 4.3 to 7.8 (2026-11-21, three runs), below the
threshold but higher, and 6.7 to 14.5 (2026-11-19), above it; with the
harness setting DIT, as the lane did before, |t| 1.5 to 2.4 (2026-11-21, three
runs). Dates are UTC.

[#crypto-backends-sizes]
=== Size

Expand Down
2 changes: 1 addition & 1 deletion doc/changelog.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ of every version are on webcpp's index page.
=== Unreleased

// tag::unreleased[]
* Added crypto, primitives over C backends: ciphers, curves and randomness, errors of fixed values in webcpp.crypto, every result `+[[nodiscard]]+`, and WEBCPP_CRYPTO_HAS_THREADS, defined natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is.
* Added crypto, C-backed primitives setting DIT on arm64 macOS, iOS, Linux and Android: ciphers, curves, randomness, fixed-value webcpp.crypto errors, `+[[nodiscard]]+` results, WEBCPP_CRYPTO_HAS_THREADS natively and with Emscripten's -pthread unless WEBCPP_CRYPTO_NO_THREADS is.
* Added equal, random_device, pem (PEM on libsodium), ciphers::aes128, aes192 and aes256, the AES block cipher, and ciphers::gcm, aes128_gcm and aes256_gcm: AES-GCM in place, incremental seal, failed opens zeroing data.
* Added supports_v with its family tags, the capability table per target, default_backend_t and /webcpp/crypto//<family>-default per family and target (secp256k1's modules among them), and refusals naming their Jamfile line.
* Added backends::bearssl (AES-GCM alone, allocating nothing), backends::openssl via /webcpp/crypto//openssl natively and on WASI (allocating at make only, or natively in openssl_memory_resource with WEBCPP_CRYPTO_OPENSSL_MEMORY_RESOURCE), and backends::ctaes (block cipher alone).
Expand Down
Loading
Loading