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#include "SharedDefines.h"
27#include <functional>
28#include <unordered_map>
29
30#define SECRET_FLAG_FOR(key, val, server) server ## _ ## key = (val ## ull << (16*SERVER_PROCESS_ ## server))
31#define SECRET_FLAG(key, val) SECRET_FLAG_ ## key = val, SECRET_FLAG_FOR(key, val, AUTHSERVER), SECRET_FLAG_FOR(key, val, WORLDSERVER)
33{
34 SECRET_FLAG(DEFER_LOAD, 0x1)
35};
36#undef SECRET_FLAG_FOR
37#undef SECRET_FLAG
38
40{
41 char const* configKey;
42 char const* oldKey;
43 int bits;
46 uint16 flags() const { return static_cast<uint16>(_flags >> (16*THIS_SERVER_PROCESS)); }
47};
48
50{
51 { "TOTPMasterSecret", "TOTPOldMasterSecret", 128, SERVER_PROCESS_AUTHSERVER, WORLDSERVER_DEFER_LOAD }
52};
53
55{
56 static SecretMgr instance;
57 return &instance;
58}
59
60static Optional<BigNumber> GetHexFromConfig(char const* configKey, int bits)
61{
62 ASSERT(bits > 0);
63 std::string str = sConfigMgr->GetStringDefault(configKey, "");
64 if (str.empty())
65 return {};
66
67 BigNumber secret;
68 if (!secret.SetHexStr(str.c_str()))
69 {
70 TC_LOG_FATAL("server.loading", "Invalid value for '{}' - specify a hexadecimal integer of up to {} bits with no prefix.", configKey, bits);
71 ABORT();
72 }
73
74 BigNumber threshold(2);
75 threshold <<= bits;
76 if (!((BigNumber(0) <= secret) && (secret < threshold)))
77 {
78 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);
79 secret %= threshold;
80 }
81 ASSERT(((BigNumber(0) <= secret) && (secret < threshold)));
82
83 return secret;
84}
85
87{
88 for (uint32 i = 0; i < NUM_SECRETS; ++i)
89 {
90 if (secret_info[i].flags() & SECRET_FLAG_DEFER_LOAD)
91 continue;
92 std::unique_lock<std::mutex> lock(_secrets[i].lock);
94 if (!_secrets[i].IsAvailable())
95 ABORT(); // load failed
96 }
97}
98
100{
101 std::unique_lock<std::mutex> lock(_secrets[i].lock);
102
103 if (_secrets[i].state == Secret::NOT_LOADED_YET)
105 return _secrets[i];
106}
107
108void SecretMgr::AttemptLoad(Secrets i, LogLevel errorLevel, std::unique_lock<std::mutex> const&)
109{
110 auto const& info = secret_info[i];
111 Optional<std::string> oldDigest;
112 {
114 stmt->setUInt32(0, i);
115 PreparedQueryResult result = LoginDatabase.Query(stmt);
116 if (result)
117 oldDigest = result->Fetch()->GetString();
118 }
119 Optional<BigNumber> currentValue = GetHexFromConfig(info.configKey, info.bits);
120
121 // verify digest
122 if (
123 ((!oldDigest) != (!currentValue)) || // there is an old digest, but no current secret (or vice versa)
124 (oldDigest && !Trinity::Crypto::Argon2::Verify(currentValue->AsHexStr(), *oldDigest)) // there is an old digest, and the current secret does not match it
125 )
126 {
127 if (info.owner != THIS_SERVER_PROCESS)
128 {
129 if (currentValue)
130 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);
131 else
132 TC_LOG_MESSAGE_BODY("server.loading", errorLevel, "No value for '{}' specified - please specify the secret currently being used in your auth DB.", info.configKey);
133 _secrets[i].state = Secret::LOAD_FAILED;
134 return;
135 }
136
137 Optional<BigNumber> oldSecret;
138 if (oldDigest && info.oldKey) // there is an old digest, so there might be an old secret (if possible)
139 {
140 oldSecret = GetHexFromConfig(info.oldKey, info.bits);
141 if (oldSecret && !Trinity::Crypto::Argon2::Verify(oldSecret->AsHexStr(), *oldDigest))
142 {
143 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);
144 _secrets[i].state = Secret::LOAD_FAILED;
145 return;
146 }
147 }
148
149 // attempt to transition us to the new key, if possible
150 Optional<std::string> error = AttemptTransition(Secrets(i), currentValue, oldSecret, !!oldDigest);
151 if (error)
152 {
153 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());
154 _secrets[i].state = Secret::LOAD_FAILED;
155 return;
156 }
157
158 TC_LOG_INFO("server.loading", "Successfully transitioned database to new '{}' value.", info.configKey);
159 }
160
161 if (currentValue)
162 {
163 _secrets[i].state = Secret::PRESENT;
164 _secrets[i].value = *currentValue;
165 }
166 else
167 _secrets[i].state = Secret::NOT_PRESENT;
168}
169
170Optional<std::string> SecretMgr::AttemptTransition(Secrets i, Optional<BigNumber> const& newSecret, Optional<BigNumber> const& oldSecret, bool hadOldSecret) const
171{
172 LoginDatabaseTransaction trans = LoginDatabase.BeginTransaction();
173
174 switch (i)
175 {
177 {
178 QueryResult result = LoginDatabase.Query("SELECT id, totp_secret FROM account");
179 if (result) do
180 {
181 Field* fields = result->Fetch();
182 if (fields[1].IsNull())
183 continue;
184
185 uint32 id = fields[0].GetUInt32();
186 std::vector<uint8> totpSecret = fields[1].GetBinary();
187
188 if (hadOldSecret)
189 {
190 if (!oldSecret)
191 return Trinity::StringFormat("Cannot decrypt old TOTP tokens - add config key '{}' to authserver.conf!", secret_info[i].oldKey);
192
193 bool success = Trinity::Crypto::AEDecrypt<Trinity::Crypto::AES>(totpSecret, oldSecret->ToByteArray<Trinity::Crypto::AES::KEY_SIZE_BYTES>());
194 if (!success)
195 return Trinity::StringFormat("Cannot decrypt old TOTP tokens - value of '{}' is incorrect for some users!", secret_info[i].oldKey);
196 }
197
198 if (newSecret)
199 Trinity::Crypto::AEEncryptWithRandomIV<Trinity::Crypto::AES>(totpSecret, newSecret->ToByteArray<Trinity::Crypto::AES::KEY_SIZE_BYTES>());
200
202 updateStmt->setBinary(0, totpSecret);
203 updateStmt->setUInt32(1, id);
204 trans->Append(updateStmt);
205 } while (result->NextRow());
206
207 break;
208 }
209 default:
210 return std::string("Unknown secret index - huh?");
211 }
212
213 if (hadOldSecret)
214 {
215 LoginDatabasePreparedStatement* deleteStmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_SECRET_DIGEST);
216 deleteStmt->setUInt32(0, i);
217 trans->Append(deleteStmt);
218 }
219
220 if (newSecret)
221 {
222 BigNumber salt;
223 salt.SetRand(128);
224 Optional<std::string> hash = Trinity::Crypto::Argon2::Hash(newSecret->AsHexStr(), salt);
225 if (!hash)
226 return std::string("Failed to hash new secret");
227
228 LoginDatabasePreparedStatement* insertStmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_SECRET_DIGEST);
229 insertStmt->setUInt32(0, i);
230 insertStmt->setString(1, *hash);
231 trans->Append(insertStmt);
232 }
233
234 LoginDatabase.CommitTransaction(trans);
235 return {};
236}
#define sConfigMgr
Definition Config.h:60
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:132
uint16_t uint16
Definition Define.h:134
uint32_t uint32
Definition Define.h:133
uint16 flags
#define ABORT
Definition Errors.h:74
#define ASSERT
Definition Errors.h:68
LogLevel
Definition LogCommon.h:25
@ LOG_LEVEL_ERROR
Definition LogCommon.h:31
@ LOG_LEVEL_FATAL
Definition LogCommon.h:32
#define TC_LOG_ERROR(filterType__,...)
Definition Log.h:165
#define TC_LOG_MESSAGE_BODY(filterType__, level__,...)
Definition Log.h:143
#define TC_LOG_INFO(filterType__,...)
Definition Log.h:159
#define TC_LOG_FATAL(filterType__,...)
Definition Log.h:168
@ 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:33
static Optional< BigNumber > GetHexFromConfig(char const *configKey, int bits)
Definition SecretMgr.cpp:60
#define SECRET_FLAG(key, val)
Definition SecretMgr.cpp:31
static constexpr SecretInfo secret_info[NUM_SECRETS]
Definition SecretMgr.cpp:49
Secrets
Definition SecretMgr.h:30
@ NUM_SECRETS
Definition SecretMgr.h:34
@ SECRET_TOTP_MASTER_KEY
Definition SecretMgr.h:31
#define THIS_SERVER_PROCESS
ServerProcessTypes
@ SERVER_PROCESS_AUTHSERVER
void SetRand(int32 numbits)
Definition BigNumber.cpp:71
bool SetHexStr(char const *str)
Definition BigNumber.cpp:65
Class used to access individual fields of database query result.
Definition Field.h:92
std::vector< uint8 > GetBinary() const
Definition Field.cpp:149
uint32 GetUInt32() const
Definition Field.cpp:61
void setUInt32(uint8 index, uint32 value)
void setBinary(uint8 index, std::vector< uint8 > const &value)
void setString(uint8 index, std::string const &value)
std::array< Secret, NUM_SECRETS > _secrets
Definition SecretMgr.h:70
static SecretMgr * instance()
Definition SecretMgr.cpp:54
Optional< std::string > AttemptTransition(Secrets i, Optional< BigNumber > const &newSecret, Optional< BigNumber > const &oldSecret, bool hadOldSecret) const
void AttemptLoad(Secrets i, LogLevel errorLevel, std::unique_lock< std::mutex > const &)
void Initialize()
Definition SecretMgr.cpp:86
Secret const & GetSecret(Secrets i)
Definition SecretMgr.cpp:99
static constexpr size_t KEY_SIZE_BYTES
Definition AES.h:31
std::string StringFormat(FormatString< Args... > fmt, Args &&... args)
Default TC string format function.
uint16 flags() const
Definition SecretMgr.cpp:46
uint64 _flags
Definition SecretMgr.cpp:45
ServerProcessTypes owner
Definition SecretMgr.cpp:44
char const * oldKey
Definition SecretMgr.cpp:42
char const * configKey
Definition SecretMgr.cpp:41
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)