diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..75b2877 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,47 @@ +# 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. 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`. + +## The guard's measured cost + +`doc/performance.adoc` is generated: never edit it. `bench/collect.py` writes it, and +`doc/measurements.json` beside it, from `bench/timing.cpp` built at `variant=release` +(`b2 libs/secure/bench//timing`, explicit); it refuses a program built at another variant. Measure +only on an idle machine, release builds only: check `uptime` and the heavy queue first, then, from +the superproject's root: + +``` +python3 libs/secure/bench/collect.py --timing \ + --data libs/secure/doc/measurements.json --page libs/secure/doc/performance.adoc +``` + +The page states the load averages the run saw. `--render-only` rewrites the page from the data. +`tools/test/secure_collect_test.py` tests the script, and `bench//timing_check` is the correctness +test of the measured program, run in every lane. diff --git a/README.md b/README.md index d2c4b35..f0870a4 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,31 @@ secure holds the side-channel and secret-in-memory primitives that the libraries algorithm: the DIT timing guard, `erase_secret`, `secret`, `constant_time_equal`, the `declassify` marker and the constant-time building blocks, every name in `webcpp::secure`. -The library is being built; its design is the genesis of `libraries/secure` in +Every function is `noexcept` and none allocates; the library is header-only. Its page, +`doc/secure.adoc`, teaches each primitive with a program of `example/` and states what each covers +and what it does not; 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/bench/Jamfile b/bench/Jamfile new file mode 100644 index 0000000..23798ca --- /dev/null +++ b/bench/Jamfile @@ -0,0 +1,29 @@ +# Copyright (c) 2026 WebCpp.org +# +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# https://www.boost.org/LICENSE_1_0.txt) + +# The cost of timing_guard, the scope every function of webcpp that computes on +# a secret runs in (timing.cpp, doc/performance.adoc). timing_check is the +# correctness test of the measured program, run in every lane of test/ +# (test/Jamfile builds this project): the measurement at 10^3 iterations, its +# line's form and the thread's DIT checked, never timed against anything. It +# needs no backend: alone. The measurement +# itself is made by hand by collect.py, which runs the program built here at +# variant=release and writes doc/measurements.json and doc/performance.adoc; +# no lane measures it. + +project : requirements /webcpp/secure//secure ; + +import webcpp ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +webcpp.run timing_check : timing.cpp ; +webcpp.run timing_check_no_exceptions : timing.cpp : off ; + +# The same program at variant=release, the one collect.py --timing measures, +# natively and by hand (doc/performance.adoc); no lane measures it. +exe timing : timing.cpp : release /webcpp//node-test ; +explicit timing ; diff --git a/bench/collect.py b/bench/collect.py new file mode 100755 index 0000000..ba8167b --- /dev/null +++ b/bench/collect.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +# 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) + +"""Measures bench/timing.cpp natively and renders doc/performance.adoc from its data, after +webcpp::hash's collect.py reduced to the guard. + + collect.py --timing \\ + --data libs/secure/doc/measurements.json --page libs/secure/doc/performance.adoc + collect.py --render-only \\ + --data libs/secure/doc/measurements.json --page libs/secure/doc/performance.adoc + +Run from the superproject's root, with the program bench/Jamfile builds at variant=release, +`b2 libs/secure/bench//timing`; --data and --page are relative to the same root. `--render-only` +rewrites the page from the data and measures nothing. + +The page is built only from release builds: a program whose build directory, b2's +bench///..., is not variant=release, or does not say, is refused before it runs, +and `--render-only` refuses data whose build is not BUILD. A measurement is for an idle machine: +it records the machine's 1, 5 and 15 minute load averages before and after the run, and the page +states them, so that a measurement taken under load says so. + +The guard's cost (secure::timing_guard, which every function of webcpp that computes on a secret +holds and which sets 64-bit ARM's DIT where the CPU has it) is `timing --measure`'s one line: +whether the guard sets DIT on this machine, and the nanoseconds a guard adds to a call entered from +a thread whose DIT is clear, from one where it is already set, and a disengaged guard's (a call +keyed only by its arguments, made without a key), each the median of five runs of 10^7 guards minus +an empty loop's, with the fastest and slowest run. The data keeps it with the date (UTC's), the +machine and the load. A line or a data file that is not the form this script writes (an older +program's, a key missing or of another type) is refused with a message naming what is wrong, before +anything is written. +""" + +import argparse +import datetime +import json +import os +import platform +import subprocess +import sys +from pathlib import Path + +# What the page is built from, and only from: bench/Jamfile's timing, at variant=release. +BUILD = "variant=release" +# The 1 minute load average at or above which a measurement says the machine was not idle. +IDLE_LOAD = 2 +RELEASE_ONLY = "the page is built only from release builds: bench/Jamfile's timing at " + BUILD + + +def variant_of(exe): + """The variant b2 built exe at, as its build directory names it, bench///...; + None when its path does not say.""" + parts = Path(exe).resolve().parts + if "bench" not in parts: + return None + last = len(parts) - 1 - parts[::-1].index("bench") + after = parts[last + 1:] + return after[1] if len(after) > 2 else None + + +def check_release(exe): + """Exits naming exe when it was not built at variant=release, before anything runs.""" + variant = variant_of(exe) + if variant is None: + sys.exit(f"collect.py: timing={exe} is not in b2's bench///..., so its " + f"variant cannot be read: {RELEASE_ONLY}") + if variant != "release": + sys.exit(f"collect.py: timing={exe} was built at variant={variant}: {RELEASE_ONLY}") + + +NUMBER = (int, float) +# bench/timing.cpp's line, and the data this script writes from it: each key's type, or the shape +# of a nested object. +LINE_SHAPE = {"dit": bool, "clear": NUMBER, "set": NUMBER, "disengaged": NUMBER, + "clear_fastest": NUMBER, "clear_slowest": NUMBER, "set_fastest": NUMBER, + "set_slowest": NUMBER, "disengaged_fastest": NUMBER, "disengaged_slowest": NUMBER, + "iterations": int, "runs": int, "target": str, "compiler": str} +DATA_SHAPE = {"date": str, "build": str, "target": str, "compiler": str, "iterations": int, + "runs": int, "dit": bool, + "machine": {"cpu": str, "architecture": str, "cores": int, "os": str}, + "load_average_before_after": [[NUMBER]], + **{f"{part}{spread}_ns": NUMBER for part in ("clear", "set", "disengaged") + for spread in ("", "_fastest", "_slowest")}} + + +def wrong(value, shape, where): + """The first place in value that shape requires and value lacks or holds otherwise, named as + a path from where; None when value has the shape. A one-element list is a non-empty list of + that shape; a bool is never a number.""" + if isinstance(shape, dict): + if not isinstance(value, dict): + return f"{where} (not an object)" + for key, inner in shape.items(): + if key not in value: + return f"{where}.{key} (missing)" + found = wrong(value[key], inner, f"{where}.{key}") + if found is not None: + return found + return None + if isinstance(shape, list): + if not isinstance(value, list) or not value: + return f"{where} (not a list, or empty)" + return next((found for index, item in enumerate(value) + if (found := wrong(item, shape[0], f"{where}[{index}]")) is not None), None) + types = shape if isinstance(shape, tuple) else (shape,) + if isinstance(value, bool) and bool not in types: + return where + return None if isinstance(value, types) else where + + +def utc_today(): + """Today's date in UTC, the date every measurement of the page states.""" + return datetime.datetime.now(datetime.timezone.utc).date().isoformat() + + +def sysctl(name): + try: + out = subprocess.run(["sysctl", "-n", name], capture_output=True, text=True, check=False) + return out.stdout.strip() + except OSError: + return "" + + +def measure_timing(exe): + """The guard's cost, timing --measure's line, natively, with when, where and under what load + it was measured; exits naming what is wrong when the program fails or its line is not the + form this script reads.""" + loads = [os.getloadavg()] + done = subprocess.run([exe, "--measure"], capture_output=True, text=True, check=False) + loads.append(os.getloadavg()) + if done.returncode != 0: + sys.exit(f"collect.py: timing --measure: exit {done.returncode}\n" + f"{done.stdout}{done.stderr}") + lines = done.stdout.strip().splitlines() + try: + line = json.loads(lines[-1]) if lines else None + except ValueError: + line = None + found = wrong(line, LINE_SHAPE, "line") if line is not None else "line (not JSON)" + # LINE_SHAPE is an object's, so wrong finds nothing only in a dict; the isinstance states that + # to the type checker. + if found is not None or not isinstance(line, dict): + printed = lines[-1] if lines else "" + sys.exit(f"collect.py: timing --measure printed {printed!r}, which is not the form " + f"collect.py reads: {found} is wrong; build bench/Jamfile's timing again from " + "this tree") + return { + "measurement": "the nanoseconds secure::timing_guard adds to a call, bench/timing.cpp", + "date": utc_today(), + "machine": { + "cpu": sysctl("machdep.cpu.brand_string") or platform.processor() or platform.machine(), + "architecture": platform.machine(), + "cores": os.cpu_count() or 1, + "os": f"{platform.system()} {platform.release()}", + }, + "load_average_before_after": [list(loads[0]), list(loads[1])], + "build": BUILD, + "target": line["target"], + "compiler": line["compiler"], + "iterations": line["iterations"], + "runs": line["runs"], + "dit": line["dit"], + **{f"{part}{spread}_ns": line[f"{part}{spread}"] + for part in ("clear", "set", "disengaged") for spread in ("", "_fastest", "_slowest")}, + } + + +def fmt_load(load): + return "/".join(f"{x:.2f}" for x in load) + + +def fmt_ns(value): + """Nanoseconds as the page shows them: one decimal, a figure that rounds to zero or below it + shown as 0.0, the empty loop's noise.""" + return "0.0" if round(value, 1) <= 0 else f"{value:.1f}" + + +def render(data, page): + machine_info = data["machine"] + load = data["load_average_before_after"] + sets = ("The guard sets DIT on this machine." if data["dit"] else + "The guard does not set DIT on this machine (no FEAT_DIT, or a target it does not " + "cover): every row is the loop's noise.") + lines = [ + "// Copyright (c) 2026 WebCpp.org", + "//", + "// Distributed under the Boost Software License, Version 1.0. (See", + "// accompanying file LICENSE_1_0.txt or copy at", + "// https://www.boost.org/LICENSE_1_0.txt)", + "", + "// Generated by bench/collect.py from doc/measurements.json: do not edit.", + "", + "[#secure-performance]", + "== The guard's cost", + "", + "Every function of webcpp that computes on a secret (a MAC, a key derivation, a tag's", + "comparison, a cipher) runs inside `timing_guard`, which on 64-bit ARM under macOS, iOS,", + "Linux, Android and Windows, where the CPU has FEAT_DIT, sets DIT (data-independent", + "timing) for the call and restores the thread's state after it (<>): one", + "`mrs`; where DIT was clear, two `msr` each followed by an `isb`; where it was set, a", + "second `mrs` on the way out (and an `msr` if something inside cleared it). Elsewhere", + "(x86, WebAssembly, ARM64EC) it executes no instruction. A function keyed only by its", + "arguments, called without a key, holds a disengaged guard, which reads its flag and", + "does nothing else.", + "", + f"Measured natively on {data['date']} (UTC) on {machine_info['cpu']}", + f"({machine_info['architecture']}), {machine_info['os']}, built with {data['build']}", + f"by {data['compiler']} (bench/timing.cpp): each row is the median of", + f"{data['runs']} runs of {data['iterations']:,} guards around a store, with the", + "fastest and slowest run beside it, each minus the median of the same loop without the", + "guard, in nanoseconds per call; a figure that rounds to zero or below, the loop's", + "noise, shows as 0.0.", + f"{sets} The machine's 1, 5 and 15 minute load averages were {fmt_load(load[0])}", + f"before and {fmt_load(load[1])} after, on {machine_info['cores']} cores: the figures", + f"are to be taken on an idle machine, one whose 1 minute load average is below " + f"{IDLE_LOAD}.", + "", + ] + if max(load[0][0], load[1][0]) >= IDLE_LOAD: + lines += [ + f"NOTE: the 1 minute load average was {load[0][0]:.2f} before and {load[1][0]:.2f}", + f"after, and that rule asks for below {IDLE_LOAD} at both: read the figures", + "as an upper bound of an idle machine's.", + "", + ] + rows = ( + ("clear", "clear, as a program that sets nothing has it", + "reads DIT, sets it, and clears it on the way out"), + ("set", "already set, by the program or by an outer guard", + "reads DIT, and reads it again on the way out"), + ("disengaged", "any: a function keyed by its arguments, called without a key", + "reads its flag and does nothing else"), + ) + lines += [ + '[cols="2,4,1,1,1",options="header"]', + "|===", + "| The thread's DIT on entry | What the guard does | Median (ns) | Fastest (ns) " + "| Slowest (ns)", + ] + for part, entry, does in rows: + lines += [ + "", + f"| {entry}", + f"| {does}", + f"| {fmt_ns(data[part + '_ns'])}", + f"| {fmt_ns(data[part + '_fastest_ns'])}", + f"| {fmt_ns(data[part + '_slowest_ns'])}", + ] + lines += ["|===", ""] + with open(page, "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + + +def release_data(path): + """The data at path and None, or None and what is wrong with it: it cannot be read, was not + built at BUILD, or is not the form this script writes.""" + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + except (OSError, ValueError) as error: + return None, f"{path} cannot be read ({error}); --timing writes it" + if not isinstance(data, dict) or data.get("build") != BUILD: + build = data.get("build") if isinstance(data, dict) else None + return None, f"{path} was measured with build {build}, not {BUILD}: {RELEASE_ONLY}" + found = wrong(data, DATA_SHAPE, "data") + if found is not None: + return None, (f"{path} is not the data collect.py writes: {found} is wrong; measure the " + "guard again with --timing") + return data, None + + +def main(): + parser = argparse.ArgumentParser(description="Measures bench/timing.cpp and renders its page.") + parser.add_argument("--data", required=True) + parser.add_argument("--page", required=True) + parser.add_argument("--timing", metavar="PATH", + help="bench/Jamfile's timing at variant=release, run natively") + parser.add_argument("--render-only", action="store_true", + help="rewrite the page from the data and measure nothing") + args = parser.parse_args() + if args.render_only == (args.timing is not None): + sys.exit("collect.py: give --timing to measure, or --render-only to render the data") + if args.render_only: + data, fault = release_data(args.data) + if data is None: + sys.exit(f"collect.py: {fault}") + else: + check_release(args.timing) + data = measure_timing(args.timing) + with open(args.data, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + f.write("\n") + render(data, args.page) + + +if __name__ == "__main__": + main() diff --git a/bench/timing.cpp b/bench/timing.cpp new file mode 100644 index 0000000..336f38e --- /dev/null +++ b/bench/timing.cpp @@ -0,0 +1,256 @@ +// 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 secure::timing_guard, the scope every function of webcpp that computes on a secret +// runs in (a MAC, a key derivation, a tag's comparison, a cipher), 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), of a +// guard entered with DIT already set (it reads DIT, and again at its end; the program sets DIT +// for that part with the same `msr` as the guard, and clears it after), and of a disengaged guard +// (what a call keyed only by its arguments pays when it is made without a key: the flag, read from +// memory as a member is, and a branch), five runs of each, interleaved, and prints one JSON line: +// `{"dit": true|false, "clear": , "set": , "disengaged": , ...}`, 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 the 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/measurements.json and doc/performance.adoc. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace secure = webcpp::secure; + +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_SECURE_BENCH_STRING(x) #x +#define WEBCPP_SECURE_BENCH_VERSION(x) WEBCPP_SECURE_BENCH_STRING(x) +constexpr std::string_view compiler = "MSVC " WEBCPP_SECURE_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_SECURE_TIMING_COVERED + return secure::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_SECURE_TIMING_COVERED + if (secure::cpu_has_dit()) { + secure::detail::write_dit(set ? secure::detail::dit_bit : 0); + } +#endif +} + +// The nanoseconds of one iteration of body, over iterations of it. +template +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 const elapsed = + std::chrono::steady_clock::now() - start; + return elapsed.count() / static_cast(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 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 three costs, and whether DIT was as the guard must leave +// it before and after each part. +struct result { + summary clear; + summary set; + summary disengaged; + bool restored = true; +}; + +result measure(std::uint64_t iterations) { + std::array empty{}; + std::array clear{}; + std::array set{}; + std::array disengaged{}; + // A process that starts with DIT set would measure the set part twice. + bool restored = !secure::dit_is_set(); + // Written by every iteration of every part, so that no loop is removed or merged. + std::uint64_t volatile sink = 0; + // The disengaged guard's flag, read at each iteration as a keyed function reads its member. + bool volatile keyed = false; + 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) { + secure::timing_guard const guard; + sink = i; + }); + restored = restored && !secure::dit_is_set(); + force_dit(true); + set[run] = nanoseconds_per_iteration(iterations, [&sink](std::uint64_t i) { + secure::timing_guard const guard; + sink = i; + }); + restored = restored && secure::dit_is_set() == guard_sets_dit(); + force_dit(false); + restored = restored && !secure::dit_is_set(); + disengaged[run] = nanoseconds_per_iteration(iterations, [&sink, &keyed](std::uint64_t i) { + secure::timing_guard const guard{keyed}; + sink = i; + }); + restored = restored && !secure::dit_is_set(); + } + double const loop = summarise(empty, 0).median; + return { + .clear = summarise(clear, loop), + .set = summarise(set, loop), + .disengaged = summarise(disengaged, loop), + .restored = restored, + }; +} + +// Writes the JSON line of a measurement into line; the number of characters, or -1. +int format(std::span line, result const& measured, std::uint64_t iterations) { + return std::snprintf( + line.data(), line.size(), + R"({"dit": %s, "clear": %.3f, "set": %.3f, "disengaged": %.3f, "clear_fastest": %.3f, )" + R"("clear_slowest": %.3f, "set_fastest": %.3f, "set_slowest": %.3f, )" + R"("disengaged_fastest": %.3f, "disengaged_slowest": %.3f, )" + R"("iterations": %llu, "runs": %zu, "target": "%.*s", "compiler": "%.*s"})", + guard_sets_dit() ? "true" : "false", measured.clear.median, measured.set.median, + measured.disengaged.median, measured.clear.fastest, measured.clear.slowest, + measured.set.fastest, measured.set.slowest, measured.disengaged.fastest, + measured.disengaged.slowest, static_cast(iterations), runs, + static_cast(target.size()), target.data(), static_cast(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 three +// costs as finite numbers. +bool well_formed(char const* line) { + double clear = 0; + double set = 0; + double disengaged = 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); + rest = number(skip(rest, R"(, "disengaged": )"), disengaged); + return skip(rest, R"(, "clear_fastest": )") != nullptr; +} + +int usage() { + static_cast(std::fprintf(stderr, "usage: timing [--measure]\n")); + return 2; +} + +// The program, given its arguments; main hands its status to webcpp's test support. +int run(std::span const given) { + 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 line{}; + int const written = format(line, measured, iterations); + if (written < 0 || static_cast(written) >= line.size()) { + static_cast(std::fprintf(stderr, "timing: the line does not fit\n")); + return 1; + } + std::printf("%s\n", line.data()); + if (!measured.restored) { + static_cast(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; +} + +} // namespace + +// The status goes through webcpp::test::exit_status, as every test's does: under Emscripten node +// then ends with it, whatever runs later. Emscripten itself loses only the return value of a main +// that suspended under Asyncify, which this one does not. +int main(int argument_count, char** arguments) { + return webcpp::test::exit_status( + run(std::span(arguments, static_cast(argument_count)))); +} 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/blocks.adoc b/doc/blocks.adoc new file mode 100644 index 0000000..ee369a9 --- /dev/null +++ b/doc/blocks.adoc @@ -0,0 +1,155 @@ +// 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-blocks] +== Constant-time building blocks + +A decoder that turns a secret into text, a signature scheme that picks one of +two values by a secret bit, a table that a secret index selects an entry from: +each needs a few operations that neither branch on nor index memory by the +values they receive. `webcpp::secure::constant_time`, in +``, holds them, after 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. The word blocks take any unsigned integral type but `bool` +(`std::uint8_t`, `std::uint16_t`, `std::uint32_t`, `std::uint64_t`, `std::size_t`). + +[cols="2,5",options="header"] +|=== +| Block | What it gives + +| `value_barrier(word_value)` +| the value, hidden from the optimiser + +| `mask_from_bit(low_bit)` +| 0 to the zero mask, 1 to the all-ones mask + +| `is_zero_mask(word_value)`, `is_equal_mask(first_word, second_word)`, `is_less_mask(first_word, second_word)` +| the all-ones mask when the word is zero, when two words are equal, when `first_word < second_word` as unsigned numbers; else the zero mask + +| `is_in_range_mask(word_value, low_bound, high_bound)` +| the all-ones mask when `+low_bound <= word_value <= high_bound+`: a character class, a digit's range + +| `select(choice_mask, when_set, when_clear)` +| `choice_mask ? when_set : when_clear`, without a branch + +| `lookup(table_entries, entry_index)` +| `table_entries[entry_index]`, reading every entry in order; a value-initialised element for an index past the table + +| `select_bytes(choice_mask, destination_bytes, when_set, when_clear)` +| writes one of two byte sequences into a third by a mask + +| `equal_mask(first_bytes, second_bytes)`, `is_zero_mask(tested_bytes)`, `less_mask(first_bytes, second_bytes)` +| the all-ones byte mask when two byte sequences are equal, when a sequence is all zeros, when `first_bytes < second_bytes` as big-endian numbers +|=== + +[source,cpp] +---- +include::{examples}/hex_digit.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/hex_digit.expected[] +---- + +The example is libsodium's method for `sodium_bin2hex` and `sodium_hex2bin`: a +nibble to its character and back, with the masks of `is_in_range_mask` and +`select` where a plain program would write `if (c >= 'a')`. Every mask in it +passes through `value_barrier`. + +[#secure-blocks-cost] +=== What each block costs + +`lookup` reads every entry of the table, so its cost is the table's size, once +per lookup: a codec's alphabet is at most 64 entries, which is what it is for. +A caller with a large public table, whose index is not secret, indexes it +directly. The byte blocks read every byte of both sequences. The sizes of byte +sequences are public and must be equal: a debug build asserts it +(`BOOST_ASSERT`), and with assertions off, unequal sizes give the zero mask or +write nothing. An index past the +table's end selects no entry, whatever the index's width: even `SIZE_MAX` and a +64-bit entry on WebAssembly's 32-bit `std::size_t`. + +[#secure-blocks-limits] +=== What the blocks cover, and what the compiler may still do + +*What `value_barrier` is.* It 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 volatile` statement with the value in a register; the `volatile` keeps the +compiler from merging, hoisting or dropping the statement. On MSVC and on +WebAssembly, which have no such statement, it is a round trip through a +`volatile` local. In a constant expression it is the identity. It holds the +value in this one place: it does not stop the compiler from transforming the +code around it. + +*What the source can do, and what it cannot.* The blocks are written without +branches or indexed loads, with every mask through the barrier. A compiler may +still, in principle, rewrite arithmetic into a branch (if-conversion run +backwards), or a table's loads into an indexed one: the {cpp} standard promises +nothing about time. That is why the constant-time lane checks the machine code +of every block, at the speed and the space optimisation, rather than trusting +the source: + +* *memcheck* (Valgrind, with the operands marked uninitialised) reports a + branch or an index that depends on a marked value, in every block, in + `constant_time_equal` and in the moves of `secret`. +* *MemorySanitizer* does the same on clang, over every block. +* *dudect*, natively, a statistical test of the running time on two classes of + input, over `constant_time_equal`, `lookup`, `select_bytes` and `less_mask`, + with a control of two identical classes that must pass. Each block runs inside + a `timing_guard`, as in the guarded functions that call it (below). +* Each checker runs planted leaks that it must report: memcheck and + MemorySanitizer a `select` written with a branch and a `lookup` that indexes + (memcheck also a branch on an undeclassified verdict), dudect a comparison + that returns at the first byte that differs. A checker that cannot see a leak + fails the lane. + +*The limits of those checks, as measured.* + +* *MemorySanitizer does not report a branch on an undeclassified verdict.* + MemorySanitizer drops a subtraction's carry, so the `(difference - 1) >> 8` + at the end of `constant_time_equal` comes out initialised, and a branch on + the verdict that was not declassified is not reported. memcheck reports it: + the lane's planted `ctgrind_planted_verdict`, a branch on + the result of `constant_time_equal` with no `declassify`, is reported with its + own function as the first frame. A verdict's branch is therefore checked by + memcheck, not by MemorySanitizer. +* *Under MemorySanitizer `value_barrier` is the volatile round trip, not the + `asm` statement.* clang's MemorySanitizer reports the register input of an + `asm` statement when it is a secret marked uninitialised, so no block could + run on a marked operand with the statement in place; the round trip carries + the shadow instead. memcheck and dudect check the `asm` statement's machine + code, and a MemorySanitizer build is a checker's build, never a program's. +* *The guard covers DIT's instructions, not memory access patterns or + branches* (<>): a block that was compiled to a branch is + not saved by DIT. +* *On 64-bit ARM, the blocks' time is independent of their data only with DIT + set.* Branch-free and index-free code is not enough: Arm promises a time + independent of the operands only for the instructions it lists, and only with + DIT set. Measured on the Windows 11 ARM64 machine of the MSVC lane (Apple + silicon), MSVC 14.5's `lookup` over 64 entries, whose machine code has no + branch and no load indexed by the secret (a mask from `eor`, `sub`, `bic` and + `neg`, the barrier's store and load, then `and` and `orr` into the result, for + each entry), gave a dudect `|t|` of 11 to 17.5 between index 0 and random + indexes with DIT clear, and under 3 with DIT set, the program otherwise the + same (2026-11-25). Every function of webcpp that computes on a secret holds a + guard, so the blocks it calls run with DIT set; a program that calls the + blocks on its own secrets holds one too (<>), and the lane's + dudect measures them inside one. +* *dudect is statistical.* It can show a leak, with a large `|t|`, and cannot + prove there is none: a run that stays under its threshold, as the lane's do, + is the absence of evidence of a leak at that number of measurements. +* *A checker sees one compiler and one build.* The lane's memcheck runs on Linux (its Jamfile builds it + for any compiler there; the runs for this page used gcc 14, as gcc 15 was not + available in the lane's container) and MemorySanitizer on clang on Linux, and + the planted leaks are reported there; another compiler or + optimisation level may turn a mask back into a branch that this lane did not + build. A program that needs the guarantee for its own build runs the checkers + on it. diff --git a/doc/changelog.adoc b/doc/changelog.adoc new file mode 100644 index 0000000..8b4009f --- /dev/null +++ b/doc/changelog.adoc @@ -0,0 +1,27 @@ +// 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: config.hpp, WEBCPP_SECURE_NO_EXCEPTIONS. +* Added timing_guard.hpp: the one DIT guard of webcpp's libraries, engaged or not, nested in any order, with a seam for tests, on arm64 under Apple, Linux, Android and Windows. +* Added erase_secret.hpp: erase_secret, which zeroes any contiguous trivially copyable range with stores the optimiser keeps, and the wipe's test seam WEBCPP_SECURE_TEST_WIPE_RECORD. +* Added constant_time_equal.hpp: constant_time_equal, over any two byte sequences, a secret included. +* Added secret.hpp: secret, N bytes that wipe themselves on destruction and on move. +* Added declassify.hpp: declassify, the mark of a verdict for the constant-time checkers, WEBCPP_SECURE_CT_VALGRIND and WEBCPP_SECURE_CT_MSAN. +* Added constant_time.hpp: value_barrier, the masks, select, lookup and the byte comparisons of webcpp::secure::constant_time. +* Added secure.hpp, which includes every header, and the guide, whose figure for the guard's cost is measured from a release build. +// end::unreleased[] diff --git a/doc/constant_time_equal.adoc b/doc/constant_time_equal.adoc new file mode 100644 index 0000000..f00fbb1 --- /dev/null +++ b/doc/constant_time_equal.adoc @@ -0,0 +1,58 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#secure-constant-time-equal] +== Comparing tags in constant time + +A *timing attack* recovers a secret by measuring how long a program takes to +handle different inputs +(link:https://en.wikipedia.org/wiki/Timing_attack[Wikipedia]). The commonest +target is a comparison: `==` and `memcmp` stop at the first byte that differs, +so they take longer the more leading bytes match. A server that checks a +request's MAC that way tells an attacker, through its response time, how many +bytes of a forged MAC are right; with enough requests the attacker builds a +valid one byte by byte +(link:https://cwe.mitre.org/data/definitions/208.html[CWE-208]). + +`constant_time_equal`, in ``, compares in +a time that depends only on the length. It reads every byte, combines the +differences without a branch, and reduces them to one bit without a branch, +as BearSSL's tag check does. It is one function over byte ranges and names no +type of a hash library: a digest, a `std::array`, a `std::span`, a `std::vector`, +a `std::string_view` and a `secret` are byte sequences by their shape, so +that tags of different containers compare with each other. + +[source,cpp] +---- +include::{examples}/compare.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/compare.expected[] +---- + +* *Sizes are public.* Sequences of different sizes compare unequal without +reading any of their bytes, so that a call with a truncated tag does not read +past what it was given. +* *Bytes are bytes.* A `char` counts as the byte it holds, whatever its sign: a +`std::string_view` of bytes 0x80 to 0xFF compares as unsigned bytes. +* *A temporary works.* A temporary `secret` is bound for the call and viewed +through `bytes()` for the call, so `constant_time_equal(mac, derive_key())` is +safe when `derive_key()` returns a `secret<32>`. +* *The guard.* On 64-bit ARM the comparison runs inside a `timing_guard`, so DIT +is set where the CPU has it and the thread's state is as it was after +(<>). + +*Pitfalls.* + +* Comparing the hex strings of two MACs with `==` brings the leak back. +* Returning early when the lengths differ is fine, since a length is public; +reading the contents first is not. +* A MAC checked after the request has been acted on protects nothing: check +first. +* The verdict is public by design: a program branches on it. That branch is the +one `declassify` marks for the checkers (<>). diff --git a/doc/declassify.adoc b/doc/declassify.adoc new file mode 100644 index 0000000..e23dab3 --- /dev/null +++ b/doc/declassify.adoc @@ -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) + +[#secure-declassify] +== Marking a verdict public: `declassify` + +Constant-time code is checked by tools that follow a secret through a program +and report every branch or index that depends on it: Valgrind's memcheck, with +the secret's bytes marked uninitialised (the technique is called ctgrind), and +MemorySanitizer. Some branches on a value derived from secrets are the design: +the verdict of a tag's check, `true` or `false`, is what the program acts on. +The checker must not report that one, and must report every other. + +`declassify`, in ``, marks such a value public: + +[source,cpp] +---- +include::{examples}/compare.cpp[tag=verdict,indent=0] +---- + +In a program's build it does nothing and includes nothing: the value is +unchanged and no header is read. A constant-time test defines +`WEBCPP_SECURE_CT_VALGRIND` or `WEBCPP_SECURE_CT_MSAN` (not both), and the mark is +then Valgrind's `VALGRIND_MAKE_MEM_DEFINED` or MemorySanitizer's +`__msan_unpoison`. The value is never const, so that the branch that follows +reads it again after the mark instead of a register the compiler kept from +before it. It takes a trivially copyable object by reference. + +*Pitfalls.* + +* Declassify a verdict, never a secret. A secret declassified in a test's build + hides exactly the leak the test exists to find. +* It is a statement about the code, for the checkers, and changes nothing in + the program's build: it does not make a leak safe. +* A branch on an undeclassified verdict is reported by memcheck and not by + MemorySanitizer (<>). diff --git a/doc/erase_secret.adoc b/doc/erase_secret.adoc new file mode 100644 index 0000000..110fe74 --- /dev/null +++ b/doc/erase_secret.adoc @@ -0,0 +1,90 @@ +// 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] +== Erasing a secret from a buffer + +A password read from a form, a key loaded from a file or a plaintext just +decrypted sits in a buffer of the program's own: a `std::string`, a +`std::vector`, an array. Once the program is done with it, the secret should +not stay in memory, where a crash dump, a swapped page or a later bug that reads +freed memory would find it. + +`memset` does not do that reliably. A buffer that is zeroed and then never read +again is a dead store, and an optimising compiler removes it: the zeroes are +never written and the secret stays +(link:https://cwe.mitre.org/data/definitions/14.html[CWE-14]). +`erase_secret`, in ``, writes through a +volatile pointer and then a signal fence, as `secret` does when it is +destroyed, so the stores are kept. It takes any contiguous sized range of +elements the program may write and that are trivially copyable: a +`std::vector`, a `std::string`, a `std::array`, a +`std::span`, a C array. It erases `size() * sizeof(element)` bytes +from the first element: a string's size, not its capacity. It calls no backend, +allocates nothing, and never fails. + +[source,cpp] +---- +include::{examples}/erase.cpp[tags=example;!check,indent=0] +---- + +[listing] +---- +include::{examples}/erase.expected[] +---- + +A const range, or one of elements that are not trivially copyable, stops the +build with a message naming the ranges it takes; a range that is not +contiguous, such as a `std::list`, has no `erase_secret`. + +[#secure-erase-object] +=== An object, and a C library's state + +There is no second function for an object: it is erased as a range of one, +`erase_secret(std::span(&object, 1))`, as the example does for a C library's +plain state. This is how crypto erases BearSSL's contexts. The object must be +trivially copyable, which a C library's plain structure is. + +[#secure-erase-seam] +=== The wipe's seam, for a test + +A test that checks that a function wipes what it should defines +`WEBCPP_SECURE_TEST_WIPE_RECORD`, in its Jamfile, so that every translation +unit of the program agrees, and defines +`void webcpp::secure::test::wipe_record(void const*, std::size_t) noexcept`. +The wipe then calls it once, after its bytes are zero, with what it zeroed: +`erase_secret`, the destructor and the moves of `secret`, and every library's own +wipes, through the one function. A program built without the macro neither +declares nor calls it. The example's program is built with the seam, which +counts what it wiped: + +[source,cpp] +---- +include::{examples}/erase.cpp[tag=seam,indent=0] +---- + +Its `main` ends by printing the count, the last line of the output above, and checking it: + +[source,cpp] +---- +include::{examples}/erase.cpp[tag=check,indent=0] +---- + +The check is in `main`, where its result is the program's status on every +target: Emscripten, by default, destroys no static object when `main` returns, +so a static object's destructor that prints or checks never runs there. + +*What it is not.* + +* It erases the bytes it is given, and only those. A `std::string` or a + `std::vector` that grew has left earlier copies in the memory it freed, and a + copy, a move or a temporary may hold the secret in another object or a + register: reserve the buffer's size first, and keep the secret in one place. +* It does not lock the memory: the page may still be swapped to disk before the + call. Locking it (`mlock`, `VirtualLock`) is the program's, and has no + equivalent on WebAssembly. +* A secret that crypto returns is already a `secret`, which erases itself: + `erase_secret` is for the buffers the program fills itself. diff --git a/doc/guard.adoc b/doc/guard.adoc new file mode 100644 index 0000000..9590227 --- /dev/null +++ b/doc/guard.adoc @@ -0,0 +1,187 @@ +// 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-guard] +== The timing guard + +64-bit ARM's DIT bit (Data Independent Timing, `PSTATE.DIT`) makes the +instructions that Arm lists take a time independent of their operands: with it +set, a multiplication or an addition of secret numbers does not run faster for +some values than for others. Apple requires it of constant-time code on Apple +silicon +(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]), +and none of the C libraries webcpp calls sets it. + +`timing_guard`, in ``, is the one guard of +webcpp's libraries. It sets DIT for its scope where the CPU has it, and +restores the thread's state when the scope ends. Every function of crypto, hash +and the codecs that computes on a secret holds one as its first statement, and +none keeps a copy; a program may hold one around its own constant-time code. + +[source,cpp] +---- +include::{examples}/guard.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/guard.expected[] +---- + +[#secure-guard-coverage] +=== Where the guard acts + +The guard acts where the compiler is told how to read and write the register, +and the system says whether the CPU has it. Everywhere else it is an empty +class that executes no instruction, and `cpu_has_dit()` and `dit_is_set()` +return `false`. `WEBCPP_SECURE_TIMING_COVERED` is defined exactly where the +guard acts. + +[cols="3,1,4,4",options="header"] +|=== +| Target | Covered | FEAT_DIT is detected by | The register is reached by + +| 64-bit ARM, Apple's systems (macOS, iOS) +| yes +| `sysctlbyname("hw.optional.arm.FEAT_DIT")`, once +| `mrs` and `msr s3_3_c4_c2_5`, then `isb` + +| 64-bit ARM, Linux and Android +| yes +| `getauxval(AT_HWCAP)` and `HWCAP_DIT` (bit 24), once +| the same + +| 64-bit ARM, Windows, MSVC and clang-cl (not ARM64EC) +| yes +| one read of the register under structured exception handling, once (below) +| `_ReadStatusReg` and `_WriteStatusReg` of `ARM64_SYSREG(3, 3, 4, 2, 5)`, `__isb` + +| x86, x86-64, ARM64EC, WebAssembly, anything else +| no +| none +| none: the guard is an empty class +|=== + +DIT's instructions trap on a CPU without FEAT_DIT, so nothing reads or writes +the register unless `cpu_has_dit()` says the CPU has it. On x86 the counterpart, +DOITM, is a register only the kernel writes; on WebAssembly the engine decides. + +*Windows on ARM64.* Windows documents no processor feature flag for DIT and no +user-mode read of `ID_AA64PFR0_EL1`. The guard reads the DIT register once per +process inside `+__try+` and `+__except+`: on a CPU without FEAT_DIT the read +raises `STATUS_ILLEGAL_INSTRUCTION`, which the filter takes as "absent", and +any other exception continues its search. It needs `` and +``, not ``, and works with {cpp} exceptions on or off. That +read is the only DIT instruction executed where FEAT_DIT may be absent. +The guard's lane runs on a Windows 11 ARM64 virtual machine, whose CPU has +FEAT_DIT, with MSVC 14.3 and 14.5, in debug and release builds: the guard is set +and stays set across sleeps. *The path where FEAT_DIT is absent is not tested*: +no machine without FEAT_DIT that runs Windows on ARM64 was available. The filter +is small and was reviewed, and it fails closed, as no DIT and an empty guard's +effect, but no program has run it. + +[#secure-guard-nesting] +=== Nesting, and a guard that is not engaged + +A guard that finds DIT already set 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: a keyed call of hash inside a +guarded call of crypto, each holding its own, nests in either order, and a +thread whose program asked for DIT keeps it after every call. Only the guard +that set DIT clears it, in its destructor; a guard that found DIT set reads it +again in its destructor and sets it if something inside its scope cleared it +(<>). So the thread's state after the scope is the +state before it, whatever happened inside, an error and an exception included. +DIT is a thread's own state: a guard never changes another thread's. + +Some functions are keyed only by their arguments: a BLAKE2b digest of a call +that passes a key computes on a secret, and the same call without a key +computes on public data and must not pay for DIT. Such a function constructs +the guard with `guard_engaged` false when the call is not keyed, +`secure::timing_guard const guard\{key_given};`, as the last block of the example +does with `false`. + +A disengaged guard sets nothing, clears nothing and runs no seam, on every +target. An engaged one, on a target the guard covers and a CPU that has FEAT_DIT, +costs tens of nanoseconds when it sets and clears DIT, and about a nanosecond +when DIT is already set (<>). + +The guard is neither copyable nor movable: the state it restores is the +scope's. + +[#secure-guard-exceptions] +=== Exceptions + +An exception that leaves a guard's scope runs the guard's destructor during the +unwinding, which leaves DIT as the guard found it, as at the scope's normal end. + +*Windows on ARM64 clears DIT after a catch.* The system keeps DIT through the +search for a handler and the unwinding: it does not change DIT then, so a +filter, each destructor run during the unwinding and the catch block see DIT as +the code before them left it. Then it resumes the thread after the catch block, +or in an `+__except+` block, with DIT clear, from set as from clear: +`RtlRestoreContext`, the unwinder's last step, clears DIT whatever bit 24 of the +context's `Cpsr` says, and `RtlCaptureContext` records NZCV alone. This was observed on the Windows 11 ARM64 +machine of the guard's lane with MSVC 14.3 and 14.5, debug and release; Microsoft +documents none of it. Two things follow. + +* An exception caught inside a guard's scope leaves the rest of that scope with +DIT clear. A guard that set DIT clears it at its end anyway; one that found it +set sets it again at its end, so that the thread's state after the guard is the +state before it. Code that catches an exception inside a guarded scope and then +computes on a secret holds a guard of its own after the catch, which sets DIT +again for its scope. Code that catches inside a guarded scope and returns to +code that cannot hold a guard (a C library's callback, as webcpp::crypto's +OpenSSL memory adapter) holds, around its `try`, a guard engaged only when DIT +is set, `secure::timing_guard const keep{secure::dit_is_set()};`: it never sets +DIT, and sets it again after the catch where it was set. +* After a catch outside every guard, DIT is clear, guard or no guard: no +destructor can change what the system does once the unwinding is over. A program +that sets DIT for its own code and catches exceptions sets it again after the +catch. + +On Apple's systems and Linux, DIT after a catch is as the unwinding left it. +`test/timing_guard_exceptions_test.cpp` checks all of this on every target, with +exceptions on and off. + +[#secure-guard-seam] +=== The seam, for a test + +A test that checks that a function holds its guard cannot read DIT where DIT +does not apply, so the guard has a seam. A test defines +`WEBCPP_SECURE_TIMING_ENTERED(where)` before its first include of a webcpp +header; the guard's constructor then takes the `std::source_location` of the +guard's declaration, whose `function_name()` is the function that holds it and +whose `file_name()` says which library declares it, and runs the seam with it +first, on every target, when the guard is engaged: + +[source,cpp] +---- +include::{library-root}/test/timing_guard_seam_test.cpp[tag=seam,indent=0] +---- + +The macro changes the constructor's signature, so every translation unit of one +program defines it alike (the One Definition Rule). A program's own build +defines nothing: its constructor takes no location, and no function's name or +header's path reaches the program. + +[#secure-guard-limits] +=== What the guard does not cover + +* *Only DIT's instructions.* DIT makes the instructions Arm lists take a +constant time. It does not make memory accesses independent of their addresses +(a table indexed by a secret is still a cache-timing channel, and +`constant_time::lookup` exists for that), and it does not make a branch on a +secret safe. Code that branches on a secret leaks through the branch whatever +DIT says. +* *Not arithmetic on registers alone.* The writes of the register carry a +`memory` clobber, which orders them against memory accesses and calls (the +backends' out-of-line C calls, a volatile accumulator), not against arithmetic +on registers, which the compiler may move across them: the same limit as every +program that sets DIT. +* *Not where it is not covered*, per the table, and not on a CPU without +FEAT_DIT, where it does nothing. +* *Not tested where FEAT_DIT is absent on Windows*, as said above. diff --git a/doc/measurements.json b/doc/measurements.json new file mode 100644 index 0000000..05a3e8f --- /dev/null +++ b/doc/measurements.json @@ -0,0 +1,37 @@ +{ + "measurement": "the nanoseconds secure::timing_guard adds to a call, bench/timing.cpp", + "date": "2026-11-26", + "machine": { + "cpu": "Apple M5 Max", + "architecture": "arm64", + "cores": 18, + "os": "Darwin 27.0.0" + }, + "load_average_before_after": [ + [ + 1.87548828125, + 2.7275390625, + 3.205078125 + ], + [ + 1.87548828125, + 2.7275390625, + 3.205078125 + ] + ], + "build": "variant=release", + "target": "native", + "compiler": "Apple LLVM 21.0.0 (clang-2100.4.1.1)", + "iterations": 10000000, + "runs": 5, + "dit": true, + "clear_ns": 37.015, + "clear_fastest_ns": 36.981, + "clear_slowest_ns": 39.577, + "set_ns": 1.195, + "set_fastest_ns": 1.191, + "set_slowest_ns": 1.267, + "disengaged_ns": 0.0, + "disengaged_fastest_ns": -0.0, + "disengaged_slowest_ns": 0.003 +} diff --git a/doc/overview.adoc b/doc/overview.adoc new file mode 100644 index 0000000..b9a627c --- /dev/null +++ b/doc/overview.adoc @@ -0,0 +1,79 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +[#secure-overview] +== What secure is, and is not + +A program that handles a secret leaks it in two ways that have nothing to do +with the algorithm: through *time* and *memory access* (a comparison that stops +at the first byte that differs, a branch or an index that depends on a key), and +through *memory* (a key left in a buffer after its use, where a crash dump, a +swapped page or a later bug that reads freed memory finds it). secure is the +small set of tools that closes both, in one place, so that +webcpp's libraries do not each carry a copy: crypto, hash and the codecs use it, +and so can a program. + +secure is *not* a cryptographic library. It holds no cipher, no hash, no +signature and no key derivation: choose those in crypto and hash. It does not +make a program's secrets safe by being included; it gives the primitives that +a careful implementation of an algorithm needs, and says, for each, what it +covers and what it does not. + +[cols="3,3,4",options="header"] +|=== +| Name | Header | What it is for + +| `timing_guard`, `cpu_has_dit`, `dit_is_set` +| `` +| sets 64-bit ARM's DIT bit for the scope of a secret computation (<>) + +| `erase_secret` +| `` +| zeroes a buffer the program owns, with stores the optimiser keeps (<>) + +| `secret` +| `` +| `N` secret bytes that wipe themselves (<>) + +| `constant_time_equal` +| `` +| compares two byte sequences, a tag or a MAC, in a time that does not depend on them (<>) + +| `declassify` +| `` +| marks a verdict public for the constant-time checkers (<>) + +| `constant_time::*` +| `` +| masks, `select`, `lookup` and byte comparisons that do not branch on their values (<>) + +| every name above +| `` +| the convenience header, which includes each of the others +|=== + +secure is header-only, depends on webcpp's config library and on Boost's +assert and no other library, and allocates nothing: no function of it +allocates, which a test that counts every form of `operator new` and the C +library's allocator checks. A program names `/webcpp/secure//secure` in its +Jamfile, as it names any library of webcpp: + +[listing] +---- +exe app : app.cpp /webcpp/secure//secure ; +---- + +Every name is in `webcpp::secure` (the blocks in `webcpp::secure::constant_time`), +and `webcpp::secure::detail` is not API: no header of another library includes +a header of `detail/`. + +[#secure-exceptions] +== 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. Every test of secure runs +both ways. diff --git a/doc/performance.adoc b/doc/performance.adoc new file mode 100644 index 0000000..88dbf24 --- /dev/null +++ b/doc/performance.adoc @@ -0,0 +1,54 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// Generated by bench/collect.py from doc/measurements.json: do not edit. + +[#secure-performance] +== The guard's cost + +Every function of webcpp that computes on a secret (a MAC, a key derivation, a tag's +comparison, a cipher) runs inside `timing_guard`, which on 64-bit ARM under macOS, iOS, +Linux, Android and Windows, where the CPU has FEAT_DIT, sets DIT (data-independent +timing) for the call and restores the thread's state after it (<>): one +`mrs`; where DIT was clear, two `msr` each followed by an `isb`; where it was set, a +second `mrs` on the way out (and an `msr` if something inside cleared it). Elsewhere +(x86, WebAssembly, ARM64EC) it executes no instruction. A function keyed only by its +arguments, called without a key, holds a disengaged guard, which reads its flag and +does nothing else. + +Measured natively on 2026-11-26 (UTC) on Apple M5 Max +(arm64), Darwin 27.0.0, built with variant=release +by Apple LLVM 21.0.0 (clang-2100.4.1.1) (bench/timing.cpp): each row is the median of +5 runs of 10,000,000 guards around a store, with the +fastest and slowest run beside it, each minus the median of the same loop without the +guard, in nanoseconds per call; a figure that rounds to zero or below, the loop's +noise, shows as 0.0. +The guard sets DIT on this machine. The machine's 1, 5 and 15 minute load averages were 1.88/2.73/3.21 +before and 1.88/2.73/3.21 after, on 18 cores: the figures +are to be taken on an idle machine, one whose 1 minute load average is below 2. + +[cols="2,4,1,1,1",options="header"] +|=== +| The thread's DIT on entry | What the guard does | Median (ns) | Fastest (ns) | Slowest (ns) + +| clear, as a program that sets nothing has it +| reads DIT, sets it, and clears it on the way out +| 37.0 +| 37.0 +| 39.6 + +| already set, by the program or by an outer guard +| reads DIT, and reads it again on the way out +| 1.2 +| 1.2 +| 1.3 + +| any: a function keyed by its arguments, called without a key +| reads its flag and does nothing else +| 0.0 +| 0.0 +| 0.0 +|=== diff --git a/doc/secret.adoc b/doc/secret.adoc new file mode 100644 index 0000000..40a05bf --- /dev/null +++ b/doc/secret.adoc @@ -0,0 +1,45 @@ +// 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-secret] +== Secrets that wipe themselves: `secret` + +A shared secret, a session key or a converted secret key is `N` bytes that +should live in one object and leave memory with it. `secret`, in +``, holds its bytes in an array of its own and wipes +them, with the volatile stores and the fence of `erase_secret`, when it is +destroyed and when it is moved from. Every secret that crypto gives back is a +`secret`. + +[source,cpp] +---- +include::{examples}/secret.cpp[tag=example,indent=0] +---- + +[listing] +---- +include::{examples}/secret.expected[] +---- + +It is not copyable: a copy is asked for by name, `clone()`, and the caller owns +it. A move takes the bytes and wipes the source, and a move to itself changes +nothing. `bytes()` gives a `std::span` to read, which a +cipher's key schedule or an HKDF takes as its input without a copy, and a +`secret` converts to that span where a function takes it. `writable()` gives +the span for the code that fills it, as a library does. Neither view is offered +on a temporary `secret`, whose bytes would be wiped before the span is read: +the program keeps the secret in a variable first. A secret of no bytes does not +compile, and `constant_time_equal` takes a `secret` directly +(<>). + +*What it is not.* + +* It wipes its own storage, and only that. A copy of `bytes()` into a string, + a vector or a log is the program's, to erase with `erase_secret`, and a move + or a `clone` may leave copies in registers or temporaries that no library + reaches. +* It does not lock the memory, as `erase_secret` does not: the page may be + swapped to disk while the secret is in it. diff --git a/doc/secure.adoc b/doc/secure.adoc new file mode 100644 index 0000000..b6f041d --- /dev/null +++ b/doc/secure.adoc @@ -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) + += secure: side-channel and secret-in-memory primitives for {cpp} +:toc: left +:toclevels: 2 +: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, and what a program needs +around an algorithm to do the same. + +The page teaches one primitive in each chapter, opening with what it guards +against, showing a program of `example/` that the build compiles and runs on +every target with the output it prints, and ending with what the primitive does +not do: <> (the DIT guard), <>, +<>, <>, <> and +<> (masks, selection and table lookup). <> +is what the guard costs, measured. The <> that closes the +page lists every name the headers declare. + +include::overview.adoc[] + +include::guard.adoc[] + +include::erase_secret.adoc[] + +include::secret.adoc[] + +include::constant_time_equal.adoc[] + +include::declassify.adoc[] + +include::blocks.adoc[] + +include::performance.adoc[] + +[#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..bb3c779 --- /dev/null +++ b/example/.clang-tidy @@ -0,0 +1,24 @@ +# 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. 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: > + -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..2055dae --- /dev/null +++ b/example/Jamfile @@ -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) + +project : requirements /webcpp/secure//secure ; + +import webcpp ; + +webcpp.targets native wasip2 wasip3 emscripten ; + +# The guide's programs: each section's example, built and run on every target, +# its output compared with the .expected beside it. +webcpp.example guard.cpp ; +# Built with the wipe's test seam, which the program defines to count wipes. +webcpp.example erase.cpp : WEBCPP_SECURE_TEST_WIPE_RECORD ; +webcpp.example secret.cpp ; +webcpp.example compare.cpp ; +webcpp.example hex_digit.cpp ; diff --git a/example/compare.cpp b/example/compare.cpp new file mode 100644 index 0000000..5eb42a8 --- /dev/null +++ b/example/compare.cpp @@ -0,0 +1,77 @@ +// 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: whether two byte sequences are equal, in a time that does not depend on +// their contents. A MAC is checked the way a server checks a webhook's: the tag it computes against +// the tag it was sent, any sequence of bytes on either side. + +// tag::example[] +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace secure = webcpp::secure; + +// tag::verdict[] +namespace { + +// Whether a received tag is the one computed: the verdict is public, and the caller branches on it. +bool accept(std::span computed, std::span received) { + bool verdict = secure::constant_time_equal(computed, received); + // The one branch on a value derived from secrets that is the design: public for the checkers, + // and nothing in a program's build. + secure::declassify(verdict); + return verdict; +} + +} // namespace + +// end::verdict[] + +int main() { + std::array computed{}; + std::iota(computed.begin(), computed.end(), std::uint8_t{0x10}); + std::vector received(computed.begin(), computed.end()); + + // Different containers of bytes compare: an array, a vector, a span, a string_view, a + // secret. + std::cout << "same tag: " << (accept(computed, received) ? "equal" : "different") << '\n'; + + // The last byte differs: every byte is still read, and the answer is the same kind of time. + received.back() ^= 1U; + std::cout << "last byte flipped: " + << (secure::constant_time_equal(computed, received) ? "equal" : "different") << '\n'; + + // Sizes are public: different sizes are different, and no byte is read. + std::cout << "a truncated tag: " + << (secure::constant_time_equal(computed, std::span(received).first(15)) + ? "equal" + : "different") + << '\n'; + + // Characters count as bytes, whatever their sign. + std::string_view const text = "\xff\x80"; + std::array const bytes{0xff, 0x80}; + std::cout << "text and bytes: " + << (secure::constant_time_equal(text, bytes) ? "equal" : "different") << '\n'; + + // A secret is compared through its bytes. + secure::secret<16> mac; + std::ranges::copy(computed, mac.writable().begin()); + std::cout << "secret and array: " + << (secure::constant_time_equal(mac, computed) ? "equal" : "different") << '\n'; +} + +// end::example[] diff --git a/example/compare.expected b/example/compare.expected new file mode 100644 index 0000000..21a9154 --- /dev/null +++ b/example/compare.expected @@ -0,0 +1,5 @@ +same tag: equal +last byte flipped: different +a truncated tag: different +text and bytes: equal +secret and array: equal diff --git a/example/erase.cpp b/example/erase.cpp new file mode 100644 index 0000000..b47bc6b --- /dev/null +++ b/example/erase.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) + +// erase_secret zeroes a buffer the program owns, whatever the buffer: a password in a std::string, +// a key in a std::vector, a C library's context as a range of one. Built with the wipe's test seam, +// so that the program counts what was wiped and main checks it. The check is main's, not a static +// object's destructor: Emscripten (EXIT_RUNTIME=0, its default) destroys no static object when main +// returns, and the check's result must be the program's status. + +// tag::seam[] +// The test seam: WEBCPP_SECURE_TEST_WIPE_RECORD (the Jamfile defines it for every translation unit +// of the program) makes every wipe call this function once its bytes are zero. This program counts +// them. +#include + +#include + +namespace { + +struct wipe_counts { + std::size_t wipes = 0; + std::size_t bytes = 0; +}; + +wipe_counts& counts() { + static wipe_counts instance; + return instance; +} + +} // namespace + +void webcpp::secure::test::wipe_record(void const* /*wiped_data*/, + std::size_t byte_count) noexcept { + ++counts().wipes; + counts().bytes += byte_count; +} + +// end::seam[] + +// The page's listing of the example leaves the check out (tags=example;!check): it stands alone, +// its too, and its main ends where the check begins. +// NOLINTBEGIN(readability-duplicate-include) +// tag::example[] +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace secure = webcpp::secure; + +namespace { + +// A C library's plain state, as BearSSL's contexts are. +struct context { + std::array state; + std::uint32_t counter; +}; + +} // namespace + +int main() { + std::string password = "correct horse battery staple"; + std::size_t const password_size = password.size(); + secure::erase_secret(password); // size() bytes, not capacity() + std::cout << "password: " << password_size << " bytes zeroed, size kept " + << (password.size() == password_size ? "yes" : "NO") << '\n'; + + std::vector key(32, 0xA5); + secure::erase_secret(key); + std::cout << "key all zero: " + << (std::ranges::all_of(key, [](auto b) { return b == 0; }) ? "yes" : "NO") << '\n'; + + // An object is erased as a span of one: there is no second function for it. + context ctx{.state = {1, 2, 3}, .counter = 7}; + secure::erase_secret(std::span(&ctx, 1)); + std::cout << "context counter: " << ctx.counter << '\n'; + // tag::check[] + std::cout << "wipes seen: " << counts().wipes << ", bytes: " << counts().bytes << '\n'; + if (counts().wipes != 3 || counts().bytes != password_size + key.size() + sizeof(ctx)) { + return 1; + } + // end::check[] +} + +// end::example[] +// NOLINTEND(readability-duplicate-include) diff --git a/example/erase.expected b/example/erase.expected new file mode 100644 index 0000000..3b7e4fd --- /dev/null +++ b/example/erase.expected @@ -0,0 +1,4 @@ +password: 28 bytes zeroed, size kept yes +key all zero: yes +context counter: 0 +wipes seen: 3, bytes: 80 diff --git a/example/guard.cpp b/example/guard.cpp new file mode 100644 index 0000000..63df176 --- /dev/null +++ b/example/guard.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) + +// timing_guard around a computation on a secret: where the CPU has DIT the guard sets it for the +// scope and clears it after; guards nest, and a disengaged guard does nothing. The output is the +// same on every target: on one the guard does not cover, every line holds because nothing is set. + +// tag::example[] +#include + +#include + +namespace secure = webcpp::secure; + +int main() { + bool const before = secure::dit_is_set(); + bool inside = false; + bool nested_inside = false; + bool nested_after_inner = false; + bool disengaged_inside = false; + { + // The first statement of a function that computes on a secret. + secure::timing_guard const guard; + inside = secure::dit_is_set(); + { + // A guard that finds DIT set leaves it set, and at its end sets it again if + // something inside its scope cleared it. + secure::timing_guard const inner; + nested_inside = secure::dit_is_set(); + } + nested_after_inner = secure::dit_is_set(); + } + bool const after = secure::dit_is_set(); + { + // A call keyed only by its arguments, made without a key, computes on public data. + secure::timing_guard const unkeyed{false}; + disengaged_inside = secure::dit_is_set(); + } + + // Where the CPU has DIT the guard set it; where it does not, nothing was set. + std::cout << "set inside the guard: " + << (inside == secure::cpu_has_dit() ? "as the CPU allows" : "WRONG") << '\n'; + std::cout << "set inside a nested guard: " << (nested_inside == inside ? "same" : "WRONG") + << '\n'; + std::cout << "still set after the inner guard: " + << (nested_after_inner == inside ? "yes" : "WRONG") << '\n'; + std::cout << "restored after the outer guard: " << (after == before ? "yes" : "WRONG") << '\n'; + std::cout << "disengaged guard sets nothing: " << (!disengaged_inside ? "yes" : "WRONG") + << '\n'; + if (inside != secure::cpu_has_dit() || nested_inside != inside || + nested_after_inner != inside || after != before || disengaged_inside) { + return 1; + } +} + +// end::example[] diff --git a/example/guard.expected b/example/guard.expected new file mode 100644 index 0000000..26701b3 --- /dev/null +++ b/example/guard.expected @@ -0,0 +1,5 @@ +set inside the guard: as the CPU allows +set inside a nested guard: same +still set after the inner guard: yes +restored after the outer guard: yes +disengaged guard sets nothing: yes diff --git a/example/hex_digit.cpp b/example/hex_digit.cpp new file mode 100644 index 0000000..1ff25cd --- /dev/null +++ b/example/hex_digit.cpp @@ -0,0 +1,83 @@ +// 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 4-bit value to its hex character and back without a branch or a table index that depends on the +// value, by is_in_range_mask and select: libsodium's method for sodium_bin2hex and sodium_hex2bin, +// the shape of every codec that turns a secret into text. On 64-bit ARM the blocks' time is +// independent of their data only with DIT set, so the computation runs inside a +// secure::timing_guard, which sets DIT where the CPU has it. + +// tag::example[] +#include +#include + +#include +#include +#include + +namespace ct = webcpp::secure::constant_time; + +namespace { + +// 0 to 15 to '0'..'9', 'a'..'f'. +constexpr std::uint8_t hex_character(std::uint8_t nibble) { + auto const is_digit = ct::is_in_range_mask(nibble, 0, 9); + auto const digit = static_cast('0' + nibble); + auto const letter = static_cast('a' - 10 + nibble); + return ct::select(is_digit, digit, letter); +} + +// The value of a hex character, and in valid whether it was one: 0xff for a hex digit, else 0. +struct decoded { + std::uint8_t value; + std::uint8_t valid; +}; + +constexpr decoded hex_value(std::uint8_t character) { + auto const is_digit = ct::is_in_range_mask(character, '0', '9'); + auto const is_lower = ct::is_in_range_mask(character, 'a', 'f'); + auto const is_upper = ct::is_in_range_mask(character, 'A', 'F'); + auto const from_digit = static_cast(character - '0'); + auto const from_lower = static_cast(character - 'a' + 10); + auto const from_upper = static_cast(character - 'A' + 10); + auto value = ct::select(is_upper, from_upper, 0); + value = ct::select(is_lower, from_lower, value); + value = ct::select(is_digit, from_digit, value); + auto valid = ct::select(is_upper, 0xff, 0); + valid = ct::select(is_lower, std::uint8_t{0xff}, valid); + valid = ct::select(is_digit, std::uint8_t{0xff}, valid); + return {.value = value, .valid = valid}; +} + +} // namespace + +int main() { + std::string text; + bool round_trip = true; + decoded upper{}; + decoded bad{}; + { + // DIT set for the blocks, on 64-bit ARM where the CPU has it; as found after the scope. + webcpp::secure::timing_guard const guard; + for (std::uint8_t nibble = 0; nibble < 16; ++nibble) { + text += static_cast(hex_character(nibble)); + } + for (std::uint8_t nibble = 0; nibble < 16; ++nibble) { + decoded const back = hex_value(hex_character(nibble)); + round_trip = round_trip && back.value == nibble && back.valid == 0xff; + } + upper = hex_value('C'); + bad = hex_value('g'); + } + std::cout << "encoded: " << text << '\n'; + std::cout << "round trip of all 16: " << (round_trip ? "yes" : "NO") << '\n'; + std::cout << "'C': value " << static_cast(upper.value) << ", valid " + << (upper.valid == 0xff ? "yes" : "no") << '\n'; + std::cout << "'g': valid " << (bad.valid == 0xff ? "yes" : "no") << '\n'; + return round_trip && upper.value == 12 && bad.valid == 0 ? 0 : 1; +} + +// end::example[] diff --git a/example/hex_digit.expected b/example/hex_digit.expected new file mode 100644 index 0000000..6b7dff5 --- /dev/null +++ b/example/hex_digit.expected @@ -0,0 +1,4 @@ +encoded: 0123456789abcdef +round trip of all 16: yes +'C': value 12, valid yes +'g': valid no diff --git a/example/secret.cpp b/example/secret.cpp new file mode 100644 index 0000000..b915b1d --- /dev/null +++ b/example/secret.cpp @@ -0,0 +1,54 @@ +// Copyright (c) 2026 WebCpp.org +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// https://www.boost.org/LICENSE_1_0.txt) + +// secret: bytes that wipe themselves. It cannot be copied by accident, a move leaves the source +// zero, a clone is asked for by name, and its bytes are viewed, never taken. + +// tag::example[] +#include +#include + +#include +#include +#include +#include +#include + +namespace secure = webcpp::secure; + +namespace { + +bool all_zero(std::span bytes) { + return std::ranges::all_of(bytes, [](std::uint8_t byte) { return byte == 0; }); +} + +} // namespace + +int main() { + // A new secret holds zeros; the library that fills it writes through writable(). + secure::secret<32> key; + std::ranges::fill(key.writable(), std::uint8_t{0x42}); + std::cout << "size: " << secure::secret<32>::size() << " bytes\n"; + + // A copy is asked for by name; two secrets of the same bytes compare in constant time. + secure::secret<32> const copy = key.clone(); + std::cout << "clone equals the original: " + << (secure::constant_time_equal(copy, key) ? "yes" : "no") << '\n'; + + // A move takes the bytes and wipes the source. + secure::secret<32> const moved = std::move(key); + // NOLINTNEXTLINE(bugprone-use-after-move): a moved-from secret is all zeros, by contract. + std::cout << "moved-from secret is zero: " << (all_zero(key.bytes()) ? "yes" : "no") << '\n'; + std::cout << "the destination has the bytes: " + << (secure::constant_time_equal(moved, copy) ? "yes" : "no") << '\n'; + + // A secret is passed where a function takes the span of its bytes. + std::span const view = moved; + std::cout << "first byte through the view: " << static_cast(view[0]) << '\n'; + // A view of a temporary would dangle, so secure::secret<32>{}.bytes() does not compile. +} + +// end::example[] diff --git a/example/secret.expected b/example/secret.expected new file mode 100644 index 0000000..24e68b3 --- /dev/null +++ b/example/secret.expected @@ -0,0 +1,5 @@ +size: 32 bytes +clone equals the original: yes +moved-from secret is zero: yes +the destination has the bytes: yes +first byte through the view: 66 diff --git a/include/webcpp/secure.hpp b/include/webcpp/secure.hpp new file mode 100644 index 0000000..e838e22 --- /dev/null +++ b/include/webcpp/secure.hpp @@ -0,0 +1,22 @@ +// 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 +#include +#include +#include +#include +#include +#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..c3c8ba2 --- /dev/null +++ b/include/webcpp/secure/config.hpp @@ -0,0 +1,47 @@ +// 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 "Exceptions", 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 "Exceptions", 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 + +/** + The side-channel and secret-in-memory primitives that webcpp's libraries + share. +*/ +namespace webcpp::secure {} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_CONFIG_HPP diff --git a/include/webcpp/secure/constant_time.hpp b/include/webcpp/secure/constant_time.hpp new file mode 100644 index 0000000..1e13dda --- /dev/null +++ b/include/webcpp/secure/constant_time.hpp @@ -0,0 +1,360 @@ +// 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. + + On 64-bit ARM, branch-free and index-free code is not enough: Arm promises a time independent of + the operands only for the instructions it lists, and only with DIT set. A caller that runs the + blocks on a secret holds a `webcpp::secure::timing_guard` around them, as every function of + webcpp that computes on a secret does: with DIT clear, MSVC 14.5's `lookup` was measured to take a + time that depends on its index on Windows on ARM64. +*/ +#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 word_value The word. + @return 1 when its top bit is set, else 0. +*/ +template +[[nodiscard]] constexpr U top_bit(U word_value) noexcept { + constexpr auto shift_count = static_cast(std::numeric_limits::digits - 1); + return static_cast(word_value >> shift_count); +} + +#ifdef __has_feature +#if __has_feature(memory_sanitizer) +/** + 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. +*/ +inline constexpr bool memory_sanitizer = true; +#else +/** + 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. +*/ +inline constexpr bool memory_sanitizer = false; +#endif +#else +/** + Whether the program is built with clang's MemorySanitizer: not, on a compiler without + `__has_feature`. +*/ +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 word_value The value. + @return The same value. +*/ +template +[[nodiscard]] U volatile_round_trip(U word_value) noexcept { + U volatile held_value = word_value; + return held_value; +} + +} // 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 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, 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. + * + * @tparam U Any unsigned integral type but `bool`. + * @param word_value The value. + * @return The same value. + */ +template +[[nodiscard]] constexpr U value_barrier(U word_value) noexcept { + if (std::is_constant_evaluated()) { + return word_value; + } +#if (defined(__GNUC__) || defined(__clang__)) && !defined(__wasm__) + if constexpr (detail::memory_sanitizer) { + return detail::volatile_round_trip(word_value); + } else { + __asm__ volatile("" : "+r"(word_value)); + return word_value; + } +#else + return detail::volatile_round_trip(word_value); +#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 low_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 low_bit) noexcept { + return value_barrier(static_cast(U{0} - low_bit)); +} + +/** + * The all-ones mask when a word is zero, else the zero mask. + * + * @tparam U Any unsigned integral type but `bool`. + * @param word_value The word. + * @return The mask. + */ +template +[[nodiscard]] constexpr U is_zero_mask(U word_value) noexcept { + // ~word_value & (word_value - 1) has its top bit set exactly when word_value is zero. + return mask_from_bit(detail::top_bit( + static_cast(static_cast(~word_value) & static_cast(word_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_word The first word. + * @param second_word The second. + * @return The mask. + */ +template +[[nodiscard]] constexpr U is_equal_mask(U first_word, U second_word) noexcept { + return is_zero_mask(static_cast(first_word ^ second_word)); +} + +/** + * 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_word The first word. + * @param second_word The second. + * @return The mask of `first_word < second_word`. + */ +template +[[nodiscard]] constexpr U is_less_mask(U first_word, U second_word) noexcept { + // BoringSSL's constant_time_lt_w: the top bit of first_word ^ ((first_word ^ second_word) | + // ((first_word - second_word) ^ first_word)) is the borrow of first_word - second_word. + auto const word_difference = static_cast(first_word ^ second_word); + auto const wrapped_difference = + static_cast(static_cast(first_word - second_word) ^ first_word); + return mask_from_bit(detail::top_bit( + static_cast(first_word ^ static_cast(word_difference | wrapped_difference)))); +} + +/** + * The all-ones mask when a word lies in a closed range, `low_bound <= word_value <= high_bound`, + * else the zero mask: an alphabet's character class, a digit's range. + * + * @tparam U Any unsigned integral type but `bool`. + * @param word_value The word. + * @param low_bound The range's first value. + * @param high_bound Its last value; a range with `high_bound < low_bound` holds no value. + * @return The mask, through `value_barrier`. + */ +template +[[nodiscard]] constexpr U is_in_range_mask(U word_value, U low_bound, U high_bound) noexcept { + return value_barrier(static_cast(static_cast(~is_less_mask(word_value, low_bound)) & + static_cast(~is_less_mask(high_bound, word_value)))); +} + +/** + * Chooses between two words by a mask, with no branch: `choice_mask ? when_set : when_clear`. + * + * @tparam U Any unsigned integral type but `bool`. + * @param choice_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 choice_mask, U when_set, U when_clear) noexcept { + return static_cast(static_cast(value_barrier(choice_mask) & when_set) | + static_cast(static_cast(~value_barrier(choice_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. 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`. + * @param table_entries The table, whose size is public. + * @param entry_index The index, which may be secret. + * @return `table_entries[entry_index]`, or a value-initialised `Element` when `entry_index` is past + * the table. + */ +template +[[nodiscard]] constexpr Element lookup(std::span table_entries, + std::size_t entry_index) noexcept { + using index_word = + std::conditional_t<(sizeof(Element) > sizeof(std::size_t)), Element, std::size_t>; + Element selected_entry{}; + for (std::size_t entry_position = 0; entry_position < table_entries.size(); ++entry_position) { + auto const keep_mask = static_cast(is_equal_mask( + static_cast(entry_position), static_cast(entry_index))); + selected_entry = static_cast( + selected_entry | static_cast(table_entries[entry_position] & keep_mask)); + } + return selected_entry; +} + +/** + * 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 choice_mask The zero or the all-ones mask. + * @param destination_bytes 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 choice_mask, std::span destination_bytes, + std::span when_set, + std::span when_clear) noexcept { + BOOST_ASSERT(destination_bytes.size() == when_set.size() && + destination_bytes.size() == when_clear.size()); + if (destination_bytes.size() != when_set.size() || + destination_bytes.size() != when_clear.size()) { + return; + } + for (std::size_t byte_index = 0; byte_index < destination_bytes.size(); ++byte_index) { + destination_bytes[byte_index] = + select(choice_mask, when_set[byte_index], when_clear[byte_index]); + } +} + +/** + * 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_bytes The first sequence. + * @param second_bytes The second. + * @return The mask. + */ +[[nodiscard]] constexpr std::uint8_t equal_mask( + std::span first_bytes, + std::span second_bytes) noexcept { + BOOST_ASSERT(first_bytes.size() == second_bytes.size()); + if (first_bytes.size() != second_bytes.size()) { + return 0; + } + std::uint8_t byte_difference = 0; + for (std::size_t byte_index = 0; byte_index < first_bytes.size(); ++byte_index) { + byte_difference = static_cast( + byte_difference | + static_cast(first_bytes[byte_index] ^ second_bytes[byte_index])); + } + return is_zero_mask(byte_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 tested_bytes The sequence. + * @return The mask. + */ +[[nodiscard]] constexpr std::uint8_t is_zero_mask( + std::span tested_bytes) noexcept { + std::uint8_t accumulated_bits = 0; + for (std::uint8_t const tested_byte : tested_bytes) { + accumulated_bits = static_cast(accumulated_bits | tested_byte); + } + return is_zero_mask(accumulated_bits); +} + +/** + * 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_bytes The first number, most significant byte first. + * @param second_bytes The second. + * @return The mask of `first_bytes < second_bytes`. + */ +[[nodiscard]] constexpr std::uint8_t less_mask( + std::span first_bytes, + std::span second_bytes) noexcept { + BOOST_ASSERT(first_bytes.size() == second_bytes.size()); + if (first_bytes.size() != second_bytes.size()) { + return 0; + } + std::uint8_t borrow_bit = 0; + for (std::size_t byte_index = first_bytes.size(); byte_index != 0; --byte_index) { + auto const byte_difference = static_cast( + first_bytes[byte_index - 1] - second_bytes[byte_index - 1] - borrow_bit); + borrow_bit = static_cast((static_cast(byte_difference) >> 8U) & 1U); + } + return mask_from_bit(borrow_bit); +} + +} // namespace constant_time + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_CONSTANT_TIME_HPP diff --git a/include/webcpp/secure/constant_time_equal.hpp b/include/webcpp/secure/constant_time_equal.hpp new file mode 100644 index 0000000..bce3d94 --- /dev/null +++ b/include/webcpp/secure/constant_time_equal.hpp @@ -0,0 +1,148 @@ +// 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 +#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& sequence_value) { + { sequence_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; +}; + +/** + 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 byte_source The sequence. + @return Its `bytes()` result, else a reference to it. +*/ +template +[[nodiscard]] constexpr decltype(auto) held_bytes(Sequence const& byte_source) noexcept { + if constexpr (requires { + { byte_source.bytes() } -> std::convertible_to>; + }) { + return byte_source.bytes(); + } else { + return std::as_const(byte_source); + } +} + +/** + Views what `held_bytes` returned: the address and size of its bytes. + + @param held_source 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_source) noexcept { + if constexpr (std::convertible_to>) { + std::span const byte_span = held_source; + return byte_view{.first = byte_span.data(), .count = byte_span.size()}; + } else { + using element = std::remove_cv_t>; + return byte_view{ + .first = std::ranges::data(held_source), + .count = std::ranges::size(held_source), + }; + } +} + +} // 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&& first_held = detail::held_bytes(first_operand); + auto&& second_held = detail::held_bytes(second_operand); + auto const first_view = detail::view_bytes(first_held); + auto const second_view = detail::view_bytes(second_held); + if (first_view.count != second_view.count) { + return false; + } + unsigned volatile accumulated_difference = 0; + for (std::size_t byte_index = 0; byte_index < first_view.count; ++byte_index) { + auto const first_byte = static_cast(first_view.first[byte_index]); + auto const second_byte = static_cast(second_view.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..fca1ef7 --- /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 derived_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& derived_value) noexcept { +#ifdef WEBCPP_SECURE_CT_VALGRIND + static_cast(VALGRIND_MAKE_MEM_DEFINED(&derived_value, sizeof derived_value)); +#elif defined(WEBCPP_SECURE_CT_MSAN) + __msan_unpoison(&derived_value, sizeof derived_value); +#else + static_cast(derived_value); +#endif +} + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_DECLASSIFY_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/include/webcpp/secure/timing_guard.hpp b/include/webcpp/secure/timing_guard.hpp new file mode 100644 index 0000000..d02ef07 --- /dev/null +++ b/include/webcpp/secure/timing_guard.hpp @@ -0,0 +1,313 @@ +// 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 `guard_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 register_state = + static_cast(_ReadStatusReg(dit_register)); + static_cast(register_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. A guard that finds DIT set 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. Such a guard reads DIT again at its end and sets it if something inside its + * scope cleared it: Windows on ARM64 clears DIT whenever it resumes a thread after a catch (or in + * an `__except` block), so that an exception caught inside the scope would otherwise leave it + * clear. DIT is a thread's own state, so a guard never changes another thread's. The destructor + * runs as well when an exception ends the scope, with DIT as it was in the scope (Windows clears + * it only on resuming after the catch, outside the guard). 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 `guard_engaged`, runs the seam, then sets DIT where the CPU has it and it is clear: a + * test's build alone. + * + * @param guard_engaged Whether the call computes on a secret; false makes the guard do nothing, + * the seam included. + * @param entry_location Where the guard is declared, the default: the seam's argument alone. + */ + explicit timing_guard(bool guard_engaged = true, std::source_location entry_location = + std::source_location::current()) noexcept { + if (!guard_engaged) { + return; + } + WEBCPP_SECURE_TIMING_ENTERED(entry_location); + enter(); + } +#else + /** + * Where `guard_engaged`, sets DIT where the CPU has it and it is clear. + * + * @param guard_engaged Whether the call computes on a secret; false makes the guard do nothing. + */ + explicit timing_guard(bool guard_engaged = true) noexcept { + if (guard_engaged) { + enter(); + } + } +#endif + + /** Leaves DIT as this guard found it: clears it when the guard set it, else sets it again. */ + ~timing_guard() { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (found_ == found_dit::clear) { + detail::write_dit(0); + } else if (found_ == found_dit::set && !dit_is_set()) { + detail::write_dit(detail::dit_bit); + } +#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: +#ifdef WEBCPP_SECURE_TIMING_COVERED + /** What an engaged guard found on a CPU with DIT, and so restores at its end. */ + enum class found_dit : unsigned char { + /** Nothing to restore: the guard is disengaged, or the CPU has no DIT. */ + nothing, + /** DIT was clear: the guard set it, and clears it at its end. */ + clear, + /** DIT was set: the guard sets it again at its end if something cleared it. */ + set, + }; +#endif + + /** Sets DIT where the CPU has it and it is clear, and remembers what it found. */ + void enter() noexcept { +#ifdef WEBCPP_SECURE_TIMING_COVERED + if (!cpu_has_dit()) { + return; + } + if (dit_is_set()) { + found_ = found_dit::set; + } else { + detail::write_dit(detail::dit_bit); + found_ = found_dit::clear; + } +#endif + } + +#ifdef WEBCPP_SECURE_TIMING_COVERED + /** What this guard found, and so restores. */ + found_dit found_ = found_dit::nothing; +#endif +}; + +} // namespace webcpp::secure + +#endif // WEBCPP_SECURE_TIMING_GUARD_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..0ce79a9 --- /dev/null +++ b/test/Jamfile @@ -0,0 +1,116 @@ +# 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 ; + +# 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 ; +# A guard leaves DIT as it found it also when its scope changed DIT (as a catch +# does on Windows on ARM64, which clears DIT on resuming after any catch) and +# when an exception ends its scope: nested, in every order, from clear and from +# set; after a catch outside every guard, DIT is what the system leaves. +secure-run timing_guard_exceptions : timing_guard_exceptions_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. +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 ; + +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 ; +# 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 + : 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 ; + +# 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 ; +# No local name in a header hides a program's global: every public header after +# a global of each one-word name a header's local once had, which MSVC's C4459 +# reports at /W4 /WX (clang and GCC never warn across namespaces). +secure-run user_globals : user_globals_test.cpp : : native ; +# With timing_guard's seam, its own parameter, which only the seam compiles. +secure-run user_globals_seam : user_globals_test.cpp + : WEBCPP_TEST_SECURE_USER_GLOBALS_SEAM : native ; + +build-project messages ; +# On MSVC, each message stops the build (test/msvc); elsewhere nothing is built. +build-project msvc ; +# The guard's cost: the correctness test of the program collect.py measures. +build-project ../bench ; +# The own lane constant-time: memcheck, MemorySanitizer and dudect. +build-project constant_time ; diff --git a/test/allocation_test.cpp b/test/allocation_test.cpp new file mode 100644 index 0000000..d4aa9c2 --- /dev/null +++ b/test/allocation_test.cpp @@ -0,0 +1,290 @@ +// 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 +#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); + }); + // The standard allocator's storage, which every container takes: not a container's own, since + // MSVC's debug library (_ITERATOR_DEBUG_LEVEL 1 or 2) also allocates a proxy per container. + expect_counted("std::allocator's storage", [] { + std::allocator allocator; + std::uint8_t* volatile block = allocator.allocate(16); + BOOST_TEST(block != nullptr); + allocator.deallocate(block, 16); + }); + 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); + // 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> const 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/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; +} diff --git a/test/constant_time/Jamfile b/test/constant_time/Jamfile new file mode 100644 index 0000000..89a906b --- /dev/null +++ b/test/constant_time/Jamfile @@ -0,0 +1,127 @@ +# 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 arm64 where the CPU has it, the other blocks are measured +# inside one, as the guarded functions that call them run them (on 64-bit ARM +# only DIT makes an instruction's time independent of its data: without it, +# MSVC 14.5's lookup, branch-free and index-free, gave |t| 11 to 17.5 on +# Windows on ARM64), 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..34dc725 --- /dev/null +++ b/test/constant_time/dudect.hpp @@ -0,0 +1,699 @@ +// 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 +#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 dudect_blocks measures each inside one, as the guarded functions that call them run + * them. 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 arm64 under macOS, Linux or Windows: x86 and WebAssembly, where the engine decides). + */ +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 measured " + "call, 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 arm64 under macOS, Linux or " + "Windows)\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=