OpenVPN 3 Core Library
Loading...
Searching...
No Matches
memneq.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#pragma once
13
16#include <atomic>
17
18#if defined(USE_OPENSSL)
19#include <openssl/crypto.h>
20#endif
21
22// Does this architecture allow efficient unaligned access?
23
24#if defined(OPENVPN_ARCH_x86_64) || defined(OPENVPN_ARCH_i386)
25#define OPENVPN_HAVE_EFFICIENT_UNALIGNED_ACCESS
26#endif
27
28// Define a portable compiler memory access fence (from Boost).
29
30#if defined(__INTEL_COMPILER)
31
32#define OPENVPN_COMPILER_FENCE __memory_barrier();
33
34#elif defined(_MSC_VER) && _MSC_VER >= 1310
35
36extern "C" void _ReadWriteBarrier();
37#pragma intrinsic(_ReadWriteBarrier)
38
39#define OPENVPN_COMPILER_FENCE _ReadWriteBarrier();
40
41#elif defined(__GNUC__)
42
43#define OPENVPN_COMPILER_FENCE __asm__ __volatile__("" \
44 : \
45 : \
46 : "memory");
47
48#else
49
50#error need memory fence definition for this compiler
51
52#endif
53
54// C++ doesn't allow increment of void *
55
56#define OPENVPN_INCR_VOID_PTR(var, incr) (var) = static_cast<const unsigned char *>(var) + (incr)
57
58namespace openvpn::crypto {
68inline bool memneq(const void *a, const void *b, size_t size);
69
70#if defined(USE_OPENSSL)
71inline bool memneq(const void *a, const void *b, size_t size)
72{
73 // memcmp does return 0 (=false) when the memory is equal. It normally
74 // returns the position of first mismatch otherwise but the crypto
75 // variants only promise to return something != 0 (=true)
76 return (bool)(CRYPTO_memcmp(a, b, size));
77}
78#else
79inline bool memneq(const void *a, const void *b, size_t size)
80{
81 // This is inspired by mbedtls' internal safer_memcmp function:
82 const unsigned char *x = (const unsigned char *)a;
83 const unsigned char *y = (const unsigned char *)b;
84 unsigned char diff = 0;
85
86 for (size_t i = 0; i < size; i++)
87 {
88 unsigned char u = x[i], v = y[i];
89 diff |= u ^ v;
90 }
91 atomic_thread_fence(std::memory_order_release);
92 return bool(diff);
93}
94#endif
95} // namespace openvpn::crypto
bool memneq(const void *a, const void *b, size_t size)
Definition memneq.hpp:79