The length is not the secret: why constant-time equals returns early
A constant-time comparison is supposed to contain no branch that depends on its input. The span form of ctsafe::equals opens with exactly one: if the two sizes differ, it returns false before a single byte gets read. That looks like a hole in the discipline, and it isn't one. Constant-time code protects the contents of a buffer, so a comparison routine has to decide whether the length counts as contents. Call it public and you buy the one early return worth having, and you close an overread that is a far more realistic bug than the leak it admits.
What the timing channel actually carries#
The bug the routine exists for is older than most of the code that still contains it:
if (memcmp(mac, expected, 16) == 0) { ... } // CWE-208memcmp returns as soon as two bytes differ. Someone who can time the call learns how many leading bytes they guessed correctly, and walks the tag out one byte at a time. The defence is to read every byte, fold the differences into an accumulator, push that accumulator through a barrier the compiler is not allowed to see into, and answer by arithmetic rather than by a branch. In ctsafe that answer comes back as a mask, 0xFF or 0x00, and equals is equals_mask with the test moved to the one place a bool is wanted, so the two cannot disagree about an answer.
Look at what is being protected: the position of the first differing byte, which is a fact about the contents. Nothing in that argument extends to the size. A verifier's expected tag is a fixed width fixed by the scheme, and the presented value's width was chosen by whoever sent it. To hide a size mismatch you would have to read some fixed number of bytes regardless and then answer false anyway. You would be spending an overread to keep a secret the attacker brought with them.
The length that gets retyped#
The pointer form takes one length for two buffers:
if (ctsafe::equals(mac, expected, 16)) { /* accept */ }That is honest when the caller holds both buffers and knows both are that wide. It stops being honest the moment one side comes off the wire. A signature in a header, a token in a JSON field, a MAC in a query parameter: the length of the presented value is attacker-controlled, and the 16 describes the expected side only. The comparison then reads sixteen bytes of a buffer that may hold three. On a heap allocation that is an overread, near a page boundary it is a crash, and in both cases it is a worse outcome than disclosing that two lengths differed.
So the span form exists in order that the size is never retyped at the call site:
if (ctsafe::equals(expected_tag, presented_tag)) { /* accept */ }byte_view is a non-owning pointer and length that travel together, so a comparison reads its size off the buffer instead of off a number someone typed again. You can construct it from a const void* and a std::size_t, from a C array whose element satisfies sizeof(T) == 1, and from any range the library recognises as a range of bytes. None of those constructors is explicit, and that is deliberate: a byte_view is something you form at a call site, not an object you declare. secret_span, which owns an erase rather than a reading, makes the opposite choice. Its constructors are explicit precisely so that a buffer handed to a function cannot be wrapped into a temporary that zeroes it at the end of the statement that passed it.
The one early return#
With both lengths present, a mismatch has exactly one correct answer, and the routine gives it immediately. The span overload of equals returns false when left.size() != right.size(), and only then calls the pointer overload with left.size(). The span overload of equals_mask returns 0x00 on the same test before delegating. The test file states the policy, edges included:
void equals_mask_over_spans_rejects_a_length_mismatch() {
const std::array<std::uint8_t, 4> tag{0x01, 0x02, 0x03, 0x04};
const std::vector<unsigned char> nothing;
CHECK(ctsafe::equals_mask(tag, nothing) == 0x00);
CHECK(ctsafe::equals_mask(nothing, tag) == 0x00);
CHECK(ctsafe::equals_mask(nothing, nothing) == 0xFF);
CHECK(ctsafe::equals_mask(ctsafe::byte_view(), ctsafe::byte_view()) == 0xFF);
CHECK(ctsafe::equals(tag, nothing) == (ctsafe::equals_mask(tag, nothing) == 0xFF));
}The empty side is the case that makes the design visible. A routine trying to stay length-blind by reading the longer buffer would, against an empty presented value, read all of the expected one and still answer false: the maximum overread for zero information gained. Two empty views compare equal because they are, which is also what the pointer form says when handed nullptr, nullptr and a length of zero.
The last line of that test is the one I care about most in review. It asserts that the bool and the mask agree about a length mismatch, not only about contents. A library with two entry points has two chances to get a policy wrong, and pinning them to each other in a test is cheaper than remembering.
A count is not a byte count#
The other half of "never retype the length" is refusing a number that was never a byte count in the first place. The range constructor is gated on a trait that detects a size() member and checks that sizeof(*data()) == 1. std::array, std::vector, std::string and std::string_view over byte-sized elements convert; a range of wider elements does not compile. That matters because size() on a container of 32-bit elements is an element count, and accepting it silently would produce a view a quarter of the length of the buffer it names. The result is a comparison that reads too little and accepts too easily, which is the failure mode nobody notices, because everything still passes.
secret_span reaches equals through the same door, with the mutable form of the trait:
template <typename Range,
typename = std::enable_if_t<detail::is_mutable_byte_range<Range>::value>>
explicit secret_span(Range& range) noexcept
: data_(reinterpret_cast<std::uint8_t*>(range.data())), size_(range.size()) {}so a secret is compared by the routine that reads all of it, while == on the type is a deleted function rather than a missing one.
Ordering has no such answer#
The same reasoning is what withholds a span form from less_than, and I want to be precise about why, because "for symmetry" is how a library ends up guessing on behalf of its callers.
less_than compares two big-endian magnitudes and takes two pointers and one length:
ctsafe::mask below = ctsafe::less_than(a, b, 32);
ctsafe::select(below, smaller, a, b, 32);It subtracts least significant byte first and carries the borrow out of each byte into the next, so the borrow out of the top byte is the answer and the chain runs its full length whatever the values are. The test suite keeps the order it has to agree with written the way only a test is allowed to write it:
[[nodiscard]] bool reference_below(const std::uint8_t* a, const std::uint8_t* b,
std::size_t length) {
for (std::size_t i = 0; i < length; ++i) {
if (a[i] != b[i]) return a[i] < b[i];
}
return false;
}Now hand that routine two spans of different widths. For equality, a mismatch has one answer and no assumption standing behind it. For ordering there is no answer that is not an assumption: a 31-byte buffer against a 32-byte one is the smaller value if the short side is a zero-padded magnitude of the same width, and is a different question entirely if it is a field of its own. The header cannot know which, and an overload that answered anyway would have invented which side was padded. These are magnitudes rather than strings, so the widths belong to the caller, and leaving them there is the whole of the decision.
What I would do differently#
I verified tags with the pointer form and a constant from the spec for years before I thought carefully about where that constant came from. It is correct for the case the author had in mind and wrong for the case the attacker has in mind, which is probably the shape of most bugs in this class. I would now make the span form the default spelling in any codebase that verifies something arriving off the wire, and keep the pointer form for the callers that genuinely hold a pointer and a length originating from the same place.
The second thing I would do earlier is write the policy into the header rather than leave it to be inferred from the code. A reader who has just been told that no branch may depend on the input, and who then finds a branch on the first line of the function, is entitled to assume it is a bug. "The length is public; a size mismatch is a structural error, answered before any byte is read, because reading the shorter buffer past its end would be worse than the leak" is one sentence. It is the difference between a reviewer trusting the routine and a reviewer helpfully deleting the only early return in it.
Constant time is not a property of a function. It is a claim about which of its inputs are secret, and it is worth no more than that list is. The contents of a tag are on the list. The number of bytes in it never was.