Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions include/mp/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include <kj/string-tree.h>
#include <mutex>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <utility>
Expand Down Expand Up @@ -210,6 +211,22 @@ void Unlock(Lock& lock, Callback&& callback)
callback();
}

//! Compare two byte sequences in constant time.
//!
//! This avoids early exits and data-dependent branches so callers can compare
//! information via timing side channels
inline bool TimingResistantEqual(std::string_view a, std::string_view b)
{
const size_t max_size = a.size() > b.size() ? a.size() : b.size();
unsigned char diff = static_cast<unsigned char>(a.size() ^ b.size());
for (size_t i = 0; i < max_size; ++i) {
const unsigned char ac = i < a.size() ? static_cast<unsigned char>(a[i]) : 0;
const unsigned char bc = i < b.size() ? static_cast<unsigned char>(b[i]) : 0;
diff |= static_cast<unsigned char>(ac ^ bc);
}
return diff == 0;
}

//! Invoke a function and run a follow-up action before returning the original
//! result.
//!
Expand Down
13 changes: 13 additions & 0 deletions test/mp/test/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,19 @@ KJ_TEST("Call IPC method after client connection is closed")
KJ_EXPECT(disconnected);
}

KJ_TEST("TimingResistantEqual compares secret-like values without prefix leaks")
{
KJ_EXPECT(TimingResistantEqual("", ""));
KJ_EXPECT(TimingResistantEqual("abc123", "abc123"));
KJ_EXPECT(!TimingResistantEqual("abc123", "abc124"));
KJ_EXPECT(!TimingResistantEqual("abc123", "abc1234"));
KJ_EXPECT(!TimingResistantEqual("abc1234", "abc123"));

// Different prefix lengths should still be handled correctly.
KJ_EXPECT(!TimingResistantEqual("x", "zzzzzzzz"));
KJ_EXPECT(!TimingResistantEqual("zzzzzzzz", "x"));
}

KJ_TEST("Calling IPC method after server connection is closed")
{
TestSetup setup;
Expand Down
Loading