0
0
mirror of https://github.com/OpenVPN/openvpn3.git synced 2024-09-20 12:12:15 +02:00

Added constant-time memcmp.

This commit is contained in:
James Yonan 2012-01-24 01:54:35 +00:00
parent 667297ffcc
commit f7067d817c
4 changed files with 47 additions and 3 deletions

41
openvpn/common/memcmp.hpp Normal file
View File

@ -0,0 +1,41 @@
#ifndef OPENVPN_COMMON_MEMCMP_H
#define OPENVPN_COMMON_MEMCMP_H
#include <cstddef> // defines size_t and NULL
namespace openvpn {
// Is value of type T aligned on A boundary?
// NOTE: requires that sizeof(A) is a power of 2
template <typename T, typename A>
inline bool is_aligned(const T value)
{
return (size_t(value) & (sizeof(A)-1)) == 0;
}
// constant-time memcmp
inline bool memcmp_secure(const unsigned char *p1, const unsigned char *p2, size_t size)
{
typedef unsigned int altword;
if (is_aligned<const unsigned char *, altword>(p1) && is_aligned<const unsigned char *, altword>(p2) && is_aligned<size_t, altword>(size))
{
altword *u1 = (altword *)p1;
altword *u2 = (altword *)p2;
altword a = 0;
size /= sizeof(altword);
while (size--)
a |= (*u1++ ^ *u2++);
return a;
}
else
{
unsigned char a = 0;
while (size--)
a |= (*p1++ ^ *p2++);
return a;
}
}
} // namespace openvpn
#endif // OPENVPN_COMMON_MEMCMP_H

View File

@ -5,6 +5,7 @@
#include <openvpn/common/types.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/memcmp.hpp>
#include <openvpn/buffer/buffer.hpp>
#include <openvpn/random/prng.hpp>
#include <openvpn/frame/frame.hpp>
@ -33,7 +34,7 @@ namespace openvpn {
const size_t hmac_size = hmac.output_size();
const unsigned char *packet_hmac = buf.read_alloc(hmac_size);
hmac.hmac(local_hmac, hmac_size, buf.c_data(), buf.size());
if (std::memcmp(local_hmac, packet_hmac, hmac_size))
if (memcmp_secure(local_hmac, packet_hmac, hmac_size))
{
buf.reset_size();
if (stats)

View File

@ -10,6 +10,7 @@
#include <openvpn/gencrypto/evphmac.hpp>
#include <openvpn/common/types.hpp>
#include <openvpn/common/memcmp.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/crypto/static_key.hpp>
@ -197,7 +198,7 @@ namespace openvpn {
if (c)
{
HMAC_Final (c, local_hmac, &outlen);
return !std::memcmp(data + l1, local_hmac, l2);
return !memcmp_secure(data + l1, local_hmac, l2);
}
else
return false;

View File

@ -7,6 +7,7 @@
#include <openvpn/buffer/buffer.hpp>
#include <openvpn/random/prng.hpp>
#include <openvpn/common/hexstr.hpp>
#include <openvpn/common/memcmp.hpp>
namespace openvpn {
@ -60,7 +61,7 @@ namespace openvpn {
bool match(const ProtoSessionID& other) const
{
return defined_ && other.defined_ && !std::memcmp(id_, other.id_, SIZE);
return defined_ && other.defined_ && !memcmp_secure(id_, other.id_, SIZE);
}
std::string str() const