TrinityCore
Loading...
Searching...
No Matches
SecretMgr.cpp
Go to the documentation of this file.
1/*
2 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "SecretMgr.h"
19#include "AES.h"
20#include "Argon2Hash.h"
21#include "Config.h"
22#include "CryptoGenerics.h"
23#include "DatabaseEnv.h"
24#include "Errors.h"
25#include "Log.h"
26
27#define SECRET_FLAG_FOR(key, val, server) server ## _ ## key = (val ## ull << (16*SECRET_OWNER_ ## server))
28#define SECRET_FLAG(key, val) SECRET_FLAG_ ## key = val, SECRET_FLAG_FOR(key, val, BNETSERVER), SECRET_FLAG_FOR(key, val, WORLDSERVER)
30{
31 SECRET_FLAG(DEFER_LOAD, 0x1)
32};
33#undef SECRET_FLAG_FOR
34#undef SECRET_FLAG
35
37{
38 char const* configKey;
39 char const* oldKey;
40 int bits;
43 uint16 flags() const { return static_cast<uint16>(_flags >> (16*SecretMgr::OWNER)); }
44};
45
47{
48 { "TOTPMasterSecret", "TOTPOldMasterSecret", 128, SECRET_OWNER_BNETSERVER, WORLDSERVER_DEFER_LOAD }
49};
50
52
53SecretMgr::SecretMgr() = default;
54SecretMgr::~SecretMgr() = default;
55
57{
58 static SecretMgr instance;
59 return &instance;
60}
61
62static Optional<BigNumber> GetHexFromConfig(char const* configKey, int bits)
63{
64 ASSERT(bits > 0);
65 std::string str = sConfigMgr->GetStringDefault(configKey, "");
66 if (str.empty())
67 return {};
68
69 BigNumber secret;
70 if (!secret.SetHexStr(str.c_str()))
71 {
72 TC_LOG_FATAL("server.loading", "Invalid value for '{}' - specify a hexadecimal integer of up to {} bits with no prefix.", configKey, bits);
73 ABORT();
74 }
75
76 BigNumber threshold(2);
77 threshold <<= bits;
78 if (!((BigNumber(0) <= secret) && (secret < threshold)))
79 {
80 TC_LOG_ERROR("server.loading", "Value for '{}' is out of bounds (should be an integer of up to {} bits with no prefix). Truncated to {} bits.", configKey, bits, bits);
81 secret %= threshold;
82 }
83 ASSERT(((BigNumber(0) <= secret) && (secret < threshold)));
84
85 return secret;
86}
87
89{
90 OWNER = owner;
91
92 for (uint32 i = 0; i < NUM_SECRETS; ++i)
93 {
94 if (secret_info[i].flags() & SECRET_FLAG_DEFER_LOAD)
95 continue;
96 std::scoped_lock lock(_secrets[i].lock);
98 if (!_secrets[i].IsAvailable())
99 ABORT(); // load failed
100 }
101}
102
104{
105 std::scoped_lock lock(_secrets[i].lock);
106
107 if (_secrets[i].state == Secret::NOT_LOADED_YET)
109 return _secrets[i];
110}
111
112void SecretMgr::AttemptLoad(Secrets i, LogLevel errorLevel, std::scoped_lock<std::mutex> const&)
113{
114 auto const& info = secret_info[i];
115 Optional<std::string> oldDigest;
116 {
118 stmt->setUInt32(0, i);
119 PreparedQueryResult result = LoginDatabase.Query(stmt);
120 if (result)
121 oldDigest = result->Fetch()->GetString();
122 }
123 Optional<BigNumber> currentValue = GetHexFromConfig(info.configKey, info.bits);
124
125 // verify digest
126 if (
127 ((!oldDigest) != (!currentValue)) || // there is an old digest, but no current secret (or vice versa)
128 (oldDigest && !Trinity::Crypto::Argon2::Verify(currentValue->AsHexStr(), *oldDigest)) // there is an old digest, and the current secret does not match it
129 )
130 {
131 if (info.owner != OWNER)
132 {
133 if (currentValue)
134 TC_LOG_MESSAGE_BODY("server.loading", errorLevel, "Invalid value for '{}' specified - this is not actually the secret being used in your auth DB.", info.configKey);
135 else
136 TC_LOG_MESSAGE_BODY("server.loading", errorLevel, "No value for '{}' specified - please specify the secret currently being used in your auth DB.", info.configKey);
137 _secrets[i].state = Secret::LOAD_FAILED;
138 return;
139 }
140
141 Optional<BigNumber> oldSecret;
142 if (oldDigest && info.oldKey) // there is an old digest, so there might be an old secret (if possible)
143 {
144 oldSecret = GetHexFromConfig(info.oldKey, info.bits);
145 if (oldSecret && !Trinity::Crypto::Argon2::Verify(oldSecret->AsHexStr(), *oldDigest))
146 {
147 TC_LOG_MESSAGE_BODY("server.loading", errorLevel, "Invalid value for '{}' specified - this is not actually the secret previously used in your auth DB.", info.oldKey);
148 _secrets[i].state = Secret::LOAD_FAILED;
149 return;
150 }
151 }
152
153 // attempt to transition us to the new key, if possible
154 Optional<std::string> error = AttemptTransition(Secrets(i), currentValue, oldSecret, !!oldDigest);
155 if (error)
156 {
157 TC_LOG_MESSAGE_BODY("server.loading", errorLevel, "Your value of '{}' changed, but we cannot transition your database to the new value:\n{}", info.configKey, error->c_str());
158 _secrets[i].state = Secret::LOAD_FAILED;
159 return;
160 }
161
162 TC_LOG_INFO("server.loading", "Successfully transitioned database to new '{}' value.", info.configKey);
163 }
164
165 if (currentValue)
166 {
167 _secrets[i].state = Secret::PRESENT;
168 _secrets[i].value = *currentValue;
169 }
170 else
171 _secrets[i].state = Secret::NOT_PRESENT;
172}
173
174Optional<std::string> SecretMgr::AttemptTransition(Secrets i, Optional<BigNumber> const& newSecret, Optional<BigNumber> const& oldSecret, bool hadOldSecret) const
175{
176 LoginDatabaseTransaction trans = LoginDatabase.BeginTransaction();
177
178 switch (i)
179 {
181 {
182 QueryResult result = LoginDatabase.Query("SELECT id, totp_secret FROM account");
183 if (result) do
184 {
185 Field* fields = result->Fetch();
186 if (fields[1].IsNull())
187 continue;
188
189 uint32 id = fields[0].GetUInt32();
190 std::vector<uint8> totpSecret = fields[1].GetBinary();
191
192 if (hadOldSecret)
193 {
194 if (!oldSecret)
195 return Trinity::StringFormat("Cannot decrypt old TOTP tokens - add config key '{}' to authserver.conf!", secret_info[i].oldKey);
196
197 bool success = Trinity::Crypto::AEDecrypt<Trinity::Crypto::AES>(totpSecret, oldSecret->ToByteArray<Trinity::Crypto::AES::KEY_SIZE_BYTES>());
198 if (!success)
199 return Trinity::StringFormat("Cannot decrypt old TOTP tokens - value of '{}' is incorrect for some users!", secret_info[i].oldKey);
200 }
201
202 if (newSecret)
203 Trinity::Crypto::AEEncryptWithRandomIV<Trinity::Crypto::AES>(totpSecret, newSecret->ToByteArray<Trinity::Crypto::AES::KEY_SIZE_BYTES>());
204
206 updateStmt->setBinary(0, std::move(totpSecret));
207 updateStmt->setUInt32(1, id);
208 trans->Append(updateStmt);
209 } while (result->NextRow());
210
211 break;
212 }
213 default:
214 return std::string("Unknown secret index - huh?");
215 }
216
217 if (hadOldSecret)
218 {
219 LoginDatabasePreparedStatement* deleteStmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_SECRET_DIGEST);
220 deleteStmt->setUInt32(0, i);
221 trans->Append(deleteStmt);
222 }
223
224 if (newSecret)
225 {
226 BigNumber salt;
227 salt.SetRand(128);
228 Optional<std::string> hash = Trinity::Crypto::Argon2::Hash(newSecret->AsHexStr(), salt);
229 if (!hash)
230 return std::string("Failed to hash new secret");
231
232 LoginDatabasePreparedStatement* insertStmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_SECRET_DIGEST);
233 insertStmt->setUInt32(0, i);
234 insertStmt->setString(1, *hash);
235 trans->Append(insertStmt);
236 }
237
238 LoginDatabase.CommitTransaction(trans);
239 return {};
240}
#define sConfigMgr
Definition Config.h:64
SQLTransaction< LoginDatabaseConnection > LoginDatabaseTransaction
std::shared_ptr< ResultSet > QueryResult
std::shared_ptr< PreparedResultSet > PreparedQueryResult
DatabaseWorkerPool< LoginDatabaseConnection > LoginDatabase
Accessor to the realm/login database.
uint64_t uint64
Definition Define.h:153
uint16_t uint16
Definition Define.h:155
uint32_t uint32
Definition Define.h:154
uint16 flags
#define ABORT
Definition Errors.h:87
#define ASSERT
Definition Errors.h:80
LogLevel
Definition LogCommon.h:25
@ LOG_LEVEL_ERROR
Definition LogCommon.h:31
@ LOG_LEVEL_FATAL
Definition LogCommon.h:32
#define TC_LOG_ERROR(filterType__, message__,...)
Definition Log.h:190
#define TC_LOG_FATAL(filterType__, message__,...)
Definition Log.h:193
#define TC_LOG_INFO(filterType__, message__,...)
Definition Log.h:184
#define TC_LOG_MESSAGE_BODY(filterType__, level__, message__,...)
Definition Log.h:171
@ LOGIN_UPD_ACCOUNT_TOTP_SECRET
@ LOGIN_SEL_SECRET_DIGEST
@ LOGIN_INS_SECRET_DIGEST
@ LOGIN_DEL_SECRET_DIGEST
std::optional< T > Optional
Optional helper class to wrap optional values within.
Definition Optional.h:25
SecretFlags
Definition SecretMgr.cpp:30
static Optional< BigNumber > GetHexFromConfig(char const *configKey, int bits)
Definition SecretMgr.cpp:62
#define SECRET_FLAG(key, val)
Definition SecretMgr.cpp:28
static constexpr SecretInfo secret_info[NUM_SECRETS]
Definition SecretMgr.cpp:46
SecretOwner
Definition SecretMgr.h:38
@ SECRET_OWNER_BNETSERVER
Definition SecretMgr.h:39
Secrets
Definition SecretMgr.h:30
@ NUM_SECRETS
Definition SecretMgr.h:34
@ SECRET_TOTP_MASTER_KEY
Definition SecretMgr.h:31
void SetRand(int32 numbits)
Definition BigNumber.cpp:76
bool SetHexStr(char const *str)
Definition BigNumber.cpp:70
Class used to access individual fields of database query result.
Definition Field.h:94
std::vector< uint8 > GetBinary() const noexcept
Definition Field.cpp:125
uint32 GetUInt32() const noexcept
Definition Field.cpp:57
void setBinary(uint8 index, std::vector< uint8 > &&value)
void setString(uint8 index, std::string &&value)
void setUInt32(uint8 index, uint32 value)
std::array< Secret, NUM_SECRETS > _secrets
Definition SecretMgr.h:84
static SecretMgr * instance()
Definition SecretMgr.cpp:56
Optional< std::string > AttemptTransition(Secrets i, Optional< BigNumber > const &newSecret, Optional< BigNumber > const &oldSecret, bool hadOldSecret) const
void Initialize(SecretOwner owner)
Definition SecretMgr.cpp:88
void AttemptLoad(Secrets i, LogLevel errorLevel, std::scoped_lock< std::mutex > const &)
static SecretOwner OWNER
Definition SecretMgr.h:52
Secret const & GetSecret(Secrets i)
static constexpr size_t KEY_SIZE_BYTES
Definition AES.h:32
std::string StringFormat(FormatString< Args... > fmt, Args &&... args) noexcept
Default TC string format function.
uint16 flags() const
Definition SecretMgr.cpp:43
uint64 _flags
Definition SecretMgr.cpp:42
char const * oldKey
Definition SecretMgr.cpp:39
SecretOwner owner
Definition SecretMgr.cpp:41
char const * configKey
Definition SecretMgr.cpp:38
static Optional< std::string > Hash(std::string const &password, BigNumber const &salt, uint32 nIterations=DEFAULT_ITERATIONS, uint32 kibMemoryCost=DEFAULT_MEMORY_COST)
static bool Verify(std::string const &password, std::string const &hash)