AzerothCore 3.3.5a
OpenSource WoW Emulator
Loading...
Searching...
No Matches
SecretMgr Class Reference

#include "SecretMgr.h"

Classes

struct  Secret
 

Public Member Functions

 SecretMgr (SecretMgr const &)=delete
 
void Initialize ()
 
Secret const & GetSecret (Secrets i)
 

Static Public Member Functions

static SecretMgrinstance ()
 

Private Member Functions

 SecretMgr ()=default
 
 ~SecretMgr ()=default
 
void AttemptLoad (Secrets i, LogLevel errorLevel, std::unique_lock< std::mutex > const &)
 
Optional< std::string > AttemptTransition (Secrets i, Optional< BigNumber > const &newSecret, Optional< BigNumber > const &oldSecret, bool hadOldSecret) const
 

Private Attributes

std::array< Secret, NUM_SECRETS_secrets
 

Detailed Description

Constructor & Destructor Documentation

◆ SecretMgr() [1/2]

SecretMgr::SecretMgr ( )
privatedefault

◆ ~SecretMgr()

SecretMgr::~SecretMgr ( )
privatedefault

◆ SecretMgr() [2/2]

SecretMgr::SecretMgr ( SecretMgr const &  )
delete

Member Function Documentation

◆ AttemptLoad()

void SecretMgr::AttemptLoad ( Secrets  i,
LogLevel  errorLevel,
std::unique_lock< std::mutex > const &   
)
private
108{
109 auto const& info = secret_info[i];
110
111 Optional<std::string> oldDigest;
112 {
113 auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SECRET_DIGEST);
114 stmt->SetData(0, i);
115 PreparedQueryResult result = LoginDatabase.Query(stmt);
116 if (result)
117 oldDigest = result->Fetch()->Get<std::string>();
118 }
119
120 Optional<BigNumber> currentValue = GetHexFromConfig(info.configKey, info.bits);
121
122 // verify digest
123 if (
124 ((!oldDigest) != (!currentValue)) || // there is an old digest, but no current secret (or vice versa)
125 (oldDigest && !Acore::Crypto::Argon2::Verify(currentValue->AsHexStr(), *oldDigest)) // there is an old digest, and the current secret does not match it
126 )
127 {
128 if (info.owner != THIS_SERVER_PROCESS)
129 {
130 if (currentValue)
131 LOG_MESSAGE_BODY("server.loading", errorLevel, "Invalid value for '{}' specified - this is not actually the secret being used in your auth DB.", info.configKey);
132 else
133 LOG_MESSAGE_BODY("server.loading", errorLevel, "No value for '{}' specified - please specify the secret currently being used in your auth DB.", info.configKey);
134 _secrets[i].state = Secret::LOAD_FAILED;
135 return;
136 }
137
138 Optional<BigNumber> oldSecret;
139 if (oldDigest && info.oldKey) // there is an old digest, so there might be an old secret (if possible)
140 {
141 oldSecret = GetHexFromConfig(info.oldKey, info.bits);
142 if (oldSecret && !Acore::Crypto::Argon2::Verify(oldSecret->AsHexStr(), *oldDigest))
143 {
144 LOG_MESSAGE_BODY("server.loading", errorLevel, "Invalid value for '{}' specified - this is not actually the secret previously used in your auth DB.", info.oldKey);
145 _secrets[i].state = Secret::LOAD_FAILED;
146 return;
147 }
148 }
149
150 // attempt to transition us to the new key, if possible
151 Optional<std::string> error = AttemptTransition(Secrets(i), currentValue, oldSecret, static_cast<bool>(oldDigest));
152 if (error)
153 {
154 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());
155 _secrets[i].state = Secret::LOAD_FAILED;
156 return;
157 }
158
159 LOG_INFO("server.loading", "Successfully transitioned database to new '{}' value.", info.configKey);
160 }
161
162 if (currentValue)
163 {
164 _secrets[i].state = Secret::PRESENT;
165 _secrets[i].value = *currentValue;
166 }
167 else
168 _secrets[i].state = Secret::NOT_PRESENT;
169}
std::shared_ptr< PreparedResultSet > PreparedQueryResult
Definition DatabaseEnvFwd.h:45
DatabaseWorkerPool< LoginDatabaseConnection > LoginDatabase
Accessor to the realm/login database.
Definition DatabaseEnv.cpp:22
#define LOG_MESSAGE_BODY(filterType__, level__,...)
Definition Log.h:144
#define LOG_INFO(filterType__,...)
Definition Log.h:165
@ LOGIN_SEL_SECRET_DIGEST
Definition LoginDatabase.h:118
std::optional< T > Optional
Optional helper class to wrap optional values within.
Definition Optional.h:24
static Optional< BigNumber > GetHexFromConfig(char const *configKey, int bits)
Definition SecretMgr.cpp:59
static constexpr SecretInfo secret_info[NUM_SECRETS]
Definition SecretMgr.cpp:48
Secrets
Definition SecretMgr.h:29
#define THIS_SERVER_PROCESS
Definition SharedDefines.h:3766
std::array< Secret, NUM_SECRETS > _secrets
Definition SecretMgr.h:69
Optional< std::string > AttemptTransition(Secrets i, Optional< BigNumber > const &newSecret, Optional< BigNumber > const &oldSecret, bool hadOldSecret) const
Definition SecretMgr.cpp:171
static bool Verify(std::string const &password, std::string const &hash)
Definition Argon2.cpp:40
@ LOAD_FAILED
Definition SecretMgr.h:56
@ PRESENT
Definition SecretMgr.h:56
@ NOT_PRESENT
Definition SecretMgr.h:56

References _secrets, AttemptTransition(), GetHexFromConfig(), SecretMgr::Secret::LOAD_FAILED, LOG_INFO, LOG_MESSAGE_BODY, LOGIN_SEL_SECRET_DIGEST, LoginDatabase, SecretMgr::Secret::NOT_PRESENT, SecretMgr::Secret::PRESENT, secret_info, THIS_SERVER_PROCESS, and Acore::Crypto::Argon2::Verify().

Referenced by GetSecret(), and Initialize().

◆ AttemptTransition()

Optional< std::string > SecretMgr::AttemptTransition ( Secrets  i,
Optional< BigNumber > const &  newSecret,
Optional< BigNumber > const &  oldSecret,
bool  hadOldSecret 
) const
private
172{
173 auto trans = LoginDatabase.BeginTransaction();
174
175 switch (i)
176 {
178 {
179 QueryResult result = LoginDatabase.Query("SELECT id, totp_secret FROM account");
180 if (result) do
181 {
182 Field* fields = result->Fetch();
183 if (fields[1].IsNull())
184 continue;
185
186 uint32 id = fields[0].Get<uint32>();
187 std::vector<uint8> totpSecret = fields[1].Get<Binary>();
188
189 if (hadOldSecret)
190 {
191 if (!oldSecret)
192 return Acore::StringFormat("Cannot decrypt old TOTP tokens - add config key '{}' to authserver.conf!", secret_info[i].oldKey);
193
194 bool success = Acore::Crypto::AEDecrypt<Acore::Crypto::AES>(totpSecret, oldSecret->ToByteArray<Acore::Crypto::AES::KEY_SIZE_BYTES>());
195 if (!success)
196 return Acore::StringFormat("Cannot decrypt old TOTP tokens - value of '{}' is incorrect for some users!", secret_info[i].oldKey);
197 }
198
199 if (newSecret)
200 Acore::Crypto::AEEncryptWithRandomIV<Acore::Crypto::AES>(totpSecret, newSecret->ToByteArray<Acore::Crypto::AES::KEY_SIZE_BYTES>());
201
202 auto* updateStmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET);
203 updateStmt->SetData(0, totpSecret);
204 updateStmt->SetData(1, id);
205 trans->Append(updateStmt);
206 } while (result->NextRow());
207
208 break;
209 }
210 default:
211 return std::string("Unknown secret index - huh?");
212 }
213
214 if (hadOldSecret)
215 {
216 auto* deleteStmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_SECRET_DIGEST);
217 deleteStmt->SetData(0, i);
218 trans->Append(deleteStmt);
219 }
220
221 if (newSecret)
222 {
223 BigNumber salt;
224 salt.SetRand(128);
225 Optional<std::string> hash = Acore::Crypto::Argon2::Hash(newSecret->AsHexStr(), salt);
226 if (!hash)
227 return std::string("Failed to hash new secret");
228
229 auto* insertStmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_SECRET_DIGEST);
230 insertStmt->SetData(0, i);
231 insertStmt->SetData(1, *hash);
232 trans->Append(insertStmt);
233 }
234
235 LoginDatabase.CommitTransaction(trans);
236 return {};
237}
std::shared_ptr< ResultSet > QueryResult
Definition DatabaseEnvFwd.h:27
std::uint32_t uint32
Definition Define.h:107
std::vector< uint8 > Binary
Definition Field.h:40
@ LOGIN_UPD_ACCOUNT_TOTP_SECRET
Definition LoginDatabase.h:123
@ LOGIN_INS_SECRET_DIGEST
Definition LoginDatabase.h:119
@ LOGIN_DEL_SECRET_DIGEST
Definition LoginDatabase.h:120
@ SECRET_TOTP_MASTER_KEY
Definition SecretMgr.h:30
static constexpr std::size_t KEY_SIZE_BYTES
Definition AES.h:31
Definition BigNumber.h:29
void SetRand(int32 numbits)
Definition BigNumber.cpp:71
Class used to access individual fields of database query result.
Definition Field.h:98
std::enable_if_t< std::is_arithmetic_v< T >, T > Get() const
Definition Field.h:112
std::string StringFormat(FormatString< Args... > fmt, Args &&... args)
Default AC string format function.
Definition StringFormat.h:34
static Optional< std::string > Hash(std::string const &password, BigNumber const &salt, uint32 nIterations=DEFAULT_ITERATIONS, uint32 kibMemoryCost=DEFAULT_MEMORY_COST)
Definition Argon2.cpp:21

References Field::Get(), Acore::Crypto::Argon2::Hash(), Acore::Crypto::AES::KEY_SIZE_BYTES, LOGIN_DEL_SECRET_DIGEST, LOGIN_INS_SECRET_DIGEST, LOGIN_UPD_ACCOUNT_TOTP_SECRET, LoginDatabase, secret_info, SECRET_TOTP_MASTER_KEY, BigNumber::SetRand(), and Acore::StringFormat().

Referenced by AttemptLoad().

◆ GetSecret()

SecretMgr::Secret const & SecretMgr::GetSecret ( Secrets  i)
99{
100 std::unique_lock<std::mutex> lock(_secrets[i].lock);
101
102 if (_secrets[i].state == Secret::NOT_LOADED_YET)
104 return _secrets[i];
105}
@ LOG_LEVEL_ERROR
Definition LogCommon.h:28
void AttemptLoad(Secrets i, LogLevel errorLevel, std::unique_lock< std::mutex > const &)
Definition SecretMgr.cpp:107
@ NOT_LOADED_YET
Definition SecretMgr.h:56

References _secrets, AttemptLoad(), LOG_LEVEL_ERROR, and SecretMgr::Secret::NOT_LOADED_YET.

◆ Initialize()

void SecretMgr::Initialize ( )
86{
87 for (uint32 i = 0; i < NUM_SECRETS; ++i)
88 {
89 if (secret_info[i].flags() & SECRET_FLAG_DEFER_LOAD)
90 continue;
91 std::unique_lock<std::mutex> lock(_secrets[i].lock);
93 if (!_secrets[i].IsAvailable())
94 ABORT(); // load failed
95 }
96}
#define ABORT
Definition Errors.h:76
@ LOG_LEVEL_FATAL
Definition LogCommon.h:27
@ NUM_SECRETS
Definition SecretMgr.h:33

References _secrets, ABORT, AttemptLoad(), LOG_LEVEL_FATAL, NUM_SECRETS, and secret_info.

◆ instance()

SecretMgr * SecretMgr::instance ( )
static
54{
55 static SecretMgr instance;
56 return &instance;
57}
Definition SecretMgr.h:37
static SecretMgr * instance()
Definition SecretMgr.cpp:53

References instance().

Referenced by instance().

Member Data Documentation

◆ _secrets

std::array<Secret, NUM_SECRETS> SecretMgr::_secrets
private

Referenced by AttemptLoad(), GetSecret(), and Initialize().


The documentation for this class was generated from the following files: