OpenVPN 3 Core Library
Loading...
Searching...
No Matches
strneq.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
14#include <string>
15#include <atomic>
16
17namespace openvpn::crypto {
18
19// Compare strings in a way that is more resistant to timing attacks.
20// s1 should be the string provided by the user, while s2 is the
21// "secret" string that we are comparing s1 against.
22// Our goal is to prevent timing data from leaking info about the
23// length or content of s2.
24// https://nachtimwald.com/2017/04/02/constant-time-string-comparison-in-c/
25inline bool str_neq(const char *s1, const char *s2)
26{
27 unsigned int neq = 0;
28 size_t i = 0;
29 size_t j = 0;
30
31 while (true)
32 {
33 neq |= s1[i] ^ s2[j];
34
35 if (s1[i] == '\0')
36 break;
37 i++;
38
39 atomic_thread_fence(std::memory_order_acq_rel);
40 if (s2[j] != '\0')
41 j++;
42 atomic_thread_fence(std::memory_order_acq_rel);
43 }
44 atomic_thread_fence(std::memory_order_acq_rel);
45 return bool(neq);
46}
47
48inline bool str_neq(const std::string &s1, const std::string &s2)
49{
50 return str_neq(s1.c_str(), s2.c_str());
51}
52} // namespace openvpn::crypto
bool str_neq(const char *s1, const char *s2)
Definition strneq.hpp:25