1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 20:07:34 +00:00

AK: Add naive implementations of AK::timing_safe_compare

For security critical code we need to have some way of performing
constant time buffer comparisons.
This commit is contained in:
Brian Gianforcaro 2022-03-12 21:42:01 -08:00 committed by Brian Gianforcaro
parent 02b2f2787a
commit 390666b9fa
2 changed files with 37 additions and 1 deletions

View file

@ -1,5 +1,6 @@
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021-2022, Brian Gianforcaro <bgianf@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@ -42,6 +43,7 @@ ALWAYS_INLINE void fast_u32_fill(u32* dest, u32 value, size_t count)
}
namespace AK {
inline void secure_zero(void* ptr, size_t size)
{
__builtin_memset(ptr, 0, size);
@ -50,6 +52,29 @@ inline void secure_zero(void* ptr, size_t size)
asm volatile("" ::
: "memory");
}
// Naive implementation of a constant time buffer comparison function.
// The goal being to not use any conditional branching so calls are
// guarded against potential timing attacks.
//
// See OpenBSD's timingsafe_memcmp for more advanced implementations.
inline bool timing_safe_compare(const void* b1, const void* b2, size_t len)
{
auto* c1 = static_cast<const char*>(b1);
auto* c2 = static_cast<const char*>(b2);
u8 res = 0;
for (size_t i = 0; i < len; i++) {
res |= c1[i] ^ c2[i];
}
// FIXME: !res can potentially inject branches depending
// on which toolchain is being used for compilation. Ideally
// we would use a more advanced algorithm.
return !res;
}
}
using AK::secure_zero;
using AK::timing_safe_compare;