1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "authutils.h"
#include <zencore/crypto.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/iobuffer.h>
#include <zencore/logging.h>
#include <zenhttp/auth/authmgr.h>
#include <zenhttp/httpclient.h>
#include <zenhttp/httpclientauth.h>
#include <zenutil/authutils.h>
ZEN_THIRD_PARTY_INCLUDES_START
#include <json11.hpp>
ZEN_THIRD_PARTY_INCLUDES_END
namespace zen {
using namespace std::literals;
std::string_view
GetDefaultAccessTokenEnvVariableName()
{
#if ZEN_PLATFORM_WINDOWS
return "UE-CloudDataCacheAccessToken"sv;
#endif
#if ZEN_PLATFORM_LINUX || ZEN_PLATFORM_MAC
return "UE_CloudDataCacheAccessToken"sv;
#endif
}
std::string
ReadAccessTokenFromJsonFile(const std::filesystem::path& Path)
{
if (!IsFile(Path))
{
throw std::runtime_error(fmt::format("the file '{}' does not exist", Path));
}
IoBuffer Body = IoBufferBuilder::MakeFromFile(Path);
std::string JsonText(reinterpret_cast<const char*>(Body.GetData()), Body.GetSize());
std::string JsonError;
json11::Json TokenInfo = json11::Json::parse(JsonText, JsonError);
if (!JsonError.empty())
{
throw std::runtime_error(fmt::format("failed parsing json file '{}'. Reason: '{}'", Path, JsonError));
}
const std::string AuthToken = TokenInfo["Token"].string_value();
if (AuthToken.empty())
{
throw std::runtime_error(fmt::format("the json file '{}' does not contain a value for \"Token\"", Path));
}
return AuthToken;
}
void
AuthCommandLineOptions::AddOptions(cxxopts::Options& Ops)
{
// Direct access token (may expire)
Ops.add_option("auth-token", "", "access-token", "Remote host access token", cxxopts::value(m_AccessToken), "<accesstoken>");
Ops.add_option("auth-token",
"",
"access-token-env",
"Name of environment variable that holds the remote host access token",
cxxopts::value(m_AccessTokenEnv)->default_value(std::string(GetDefaultAccessTokenEnvVariableName())),
"<envvariable>");
Ops.add_option("auth-token",
"",
"access-token-path",
"Path to json file that holds the remote host access token",
cxxopts::value(m_AccessTokenPath),
"<filepath>");
// Auth manager token encryption
Ops.add_option("security", "", "encryption-aes-key", "256 bit AES encryption key", cxxopts::value<std::string>(m_EncryptionKey), "");
Ops.add_option("security",
"",
"encryption-aes-iv",
"128 bit AES encryption initialization vector",
cxxopts::value<std::string>(m_EncryptionIV),
"");
// OpenId acccess token
Ops.add_option("openid",
"",
"openid-provider-name",
"Open ID provider name",
cxxopts::value<std::string>(m_OpenIdProviderName),
"Default");
Ops.add_option("openid", "", "openid-provider-url", "Open ID provider url", cxxopts::value<std::string>(m_OpenIdProviderUrl), "");
Ops.add_option("openid", "", "openid-client-id", "Open ID client id", cxxopts::value<std::string>(m_OpenIdClientId), "");
Ops.add_option("openid", "", "openid-refresh-token", "Open ID refresh token", cxxopts::value<std::string>(m_OpenIdRefreshToken), "");
// OAuth acccess token
Ops.add_option("oauth", "", "oauth-url", "OAuth provier url", cxxopts::value<std::string>(m_OAuthUrl)->default_value(""), "");
Ops.add_option("oauth", "", "oauth-clientid", "OAuth client id", cxxopts::value<std::string>(m_OAuthClientId)->default_value(""), "");
Ops.add_option("oauth",
"",
"oauth-clientsecret",
"OAuth client secret",
cxxopts::value<std::string>(m_OAuthClientSecret)->default_value(""),
"");
Ops.add_option("auth",
"",
"oidctoken-exe-path",
"Path to OidcToken executable",
cxxopts::value<std::string>(m_OidcTokenAuthExecutablePath)->default_value(""),
"");
Ops.add_option("auth",
"",
"oidctoken-exe-unattended",
"Set mode to unattended when launcing OidcToken executable",
cxxopts::value<bool>(m_OidcTokenUnattended),
"");
};
// Load or generate a per-install machine AES key+IV under AuthDir/machinekey.dat
// so the auth-state file is encrypted with bytes unique to this machine rather
// than a hardcoded constant.
//
// When per-user OS-protected storage is available (DPAPI on Windows) the key
// material is wrapped before it lands on disk, so a copy of the file off-machine
// or out of a backup cannot be unwrapped without also stealing the user's OS
// master key. On platforms without OS-level wrapping we fall back to persisting
// the raw bytes with restrictive file permissions (0600 on POSIX; user-only on
// Windows via inheritance from the profile dir).
//
// File format:
// [4-byte magic 'Z','E','N','\x01'] [1-byte flags] [payload]
// flags bit 0 set -> payload is OS-protected (DPAPI blob)
// flags bit 0 clear -> payload is raw KeyBytes+IvBytes bytes
// Legacy files without the magic are interpreted as raw bytes.
void
AuthCommandLineOptions::LoadOrCreateMachineKey(const std::filesystem::path& AuthDir, bool Quiet)
{
constexpr size_t KeyBytes = AesKey256Bit::ByteCount;
constexpr size_t IvBytes = AesIV128Bit::ByteCount;
static constexpr std::array<uint8_t, 4> FileMagic = {'Z', 'E', 'N', 0x01};
static constexpr uint8_t FlagProtected = 0x01;
const std::filesystem::path KeyFile = AuthDir / "machinekey.dat";
std::array<uint8_t, KeyBytes + IvBytes> KeyMaterial{};
bool Loaded = false;
auto ParseFile = [&](MemoryView FileBytes) -> bool {
// Legacy: raw KeyBytes+IvBytes payload.
if (FileBytes.GetSize() == KeyMaterial.size())
{
memcpy(KeyMaterial.data(), FileBytes.GetData(), KeyMaterial.size());
return true;
}
if (FileBytes.GetSize() < FileMagic.size() + 1)
{
return false;
}
if (memcmp(FileBytes.GetData(), FileMagic.data(), FileMagic.size()) != 0)
{
return false;
}
const uint8_t Flags = static_cast<const uint8_t*>(FileBytes.GetData())[FileMagic.size()];
const MemoryView Payload = FileBytes.Mid(FileMagic.size() + 1);
if (Flags & FlagProtected)
{
std::vector<uint8_t> Plaintext;
if (!TryUnprotectData(Payload, Plaintext))
{
if (!Quiet)
{
ZEN_CONSOLE_WARN("Auth: failed to unwrap OS-protected machine key at '{}', regenerating", KeyFile);
}
return false;
}
if (Plaintext.size() != KeyMaterial.size())
{
return false;
}
memcpy(KeyMaterial.data(), Plaintext.data(), KeyMaterial.size());
return true;
}
if (Payload.GetSize() != KeyMaterial.size())
{
return false;
}
memcpy(KeyMaterial.data(), Payload.GetData(), KeyMaterial.size());
return true;
};
std::error_code Ec;
if (std::filesystem::exists(KeyFile, Ec))
{
IoBuffer Data = ReadFile(KeyFile).Flatten();
if (ParseFile(Data.GetView()))
{
Loaded = true;
}
else if (!Quiet)
{
ZEN_CONSOLE_WARN("Auth: machine key file '{}' is unreadable (size {}), regenerating", KeyFile, Data.GetSize());
}
}
if (!Loaded)
{
CreateDirectories(AuthDir);
if (!SecureRandomBytes(MutableMemoryView(KeyMaterial.data(), KeyMaterial.size())))
{
throw std::runtime_error("failed to obtain secure random bytes for auth machine key");
}
std::vector<uint8_t> FileBytes;
FileBytes.reserve(FileMagic.size() + 1 + KeyMaterial.size());
FileBytes.insert(FileBytes.end(), FileMagic.begin(), FileMagic.end());
std::vector<uint8_t> Wrapped;
if (TryProtectData(MemoryView(KeyMaterial.data(), KeyMaterial.size()), Wrapped))
{
FileBytes.push_back(FlagProtected);
FileBytes.insert(FileBytes.end(), Wrapped.begin(), Wrapped.end());
if (!Quiet)
{
ZEN_CONSOLE_WARN("Auth: generated OS-protected machine-specific auth encryption key at '{}'", KeyFile);
}
}
else
{
FileBytes.push_back(0);
FileBytes.insert(FileBytes.end(), KeyMaterial.begin(), KeyMaterial.end());
if (!Quiet)
{
ZEN_CONSOLE_WARN("Auth: generated machine-specific auth encryption key at '{}' (no OS wrapping available)", KeyFile);
}
}
WriteFile(KeyFile, IoBufferBuilder::MakeCloneFromMemory(FileBytes.data(), FileBytes.size()));
// Belt and suspenders: restrict access on POSIX. On Windows the
// default DACL inherited from a per-user profile dir is already
// user-only in the common case; an explicit tighten there would
// require touching the DACL which is more code than it's worth
// while DPAPI wrapping is the primary defense.
#if !ZEN_PLATFORM_WINDOWS
std::error_code PermEc;
std::filesystem::permissions(KeyFile,
std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
std::filesystem::perm_options::replace,
PermEc);
#endif
}
m_EncryptionKey.assign(reinterpret_cast<const char*>(KeyMaterial.data()), KeyBytes);
m_EncryptionIV.assign(reinterpret_cast<const char*>(KeyMaterial.data() + KeyBytes), IvBytes);
}
void
AuthCommandLineOptions::CreateAuthMgr(cxxopts::Options& Ops,
const std::filesystem::path& SystemRootDir,
std::unique_ptr<AuthMgr>& InOutAuth,
bool Quiet,
bool Verbose)
{
ZEN_ASSERT(!SystemRootDir.empty());
if (InOutAuth)
{
return;
}
const std::filesystem::path AuthDir = SystemRootDir / "auth";
if (m_EncryptionKey.empty() != m_EncryptionIV.empty())
{
throw OptionParseException(
std::string("'--encryption-aes-key' and '--encryption-aes-iv' must be supplied together or both omitted"),
Ops.help());
}
if (m_EncryptionKey.empty() && m_EncryptionIV.empty())
{
LoadOrCreateMachineKey(AuthDir, Quiet);
}
AuthConfig AuthMgrConfig = {.RootDirectory = AuthDir,
.EncryptionKey = AesKey256Bit::FromString(m_EncryptionKey),
.EncryptionIV = AesIV128Bit::FromString(m_EncryptionIV)};
if (!AuthMgrConfig.EncryptionKey.IsValid())
{
throw OptionParseException(fmt::format("'--encryption-aes-key' ('{}') is malformed", m_EncryptionKey), Ops.help());
}
if (!AuthMgrConfig.EncryptionIV.IsValid())
{
throw OptionParseException(fmt::format("'--encryption-aes-iv' ('{}') is malformed", m_EncryptionIV), Ops.help());
}
if (Verbose)
{
ExtendableStringBuilder<128> SB;
SB << "\n RootDirectory: " << AuthMgrConfig.RootDirectory.string();
SB << "\n EncryptionKey: " << HideSensitiveString(m_EncryptionKey);
SB << "\n EncryptionIV: " << HideSensitiveString(m_EncryptionIV);
ZEN_CONSOLE("Auth: Creating auth manager with:{}", SB.ToString());
}
InOutAuth = AuthMgr::Create(AuthMgrConfig);
}
void
AuthCommandLineOptions::ParseOptions(cxxopts::Options& Ops,
const std::filesystem::path& SystemRootDir,
HttpClientSettings& ClientSettings,
std::string_view HostUrl,
std::unique_ptr<AuthMgr>& Auth,
bool Quiet,
bool Hidden,
bool Verbose)
{
if (!m_OpenIdProviderUrl.empty() && !m_OpenIdClientId.empty())
{
CreateAuthMgr(Ops, SystemRootDir, Auth, Quiet, Verbose);
std::string ProviderName = m_OpenIdProviderName.empty() ? "Default" : m_OpenIdProviderName;
if (Verbose)
{
ExtendableStringBuilder<128> SB;
SB << "\n Name: " << ProviderName;
SB << "\n Url: " << m_OpenIdProviderUrl;
SB << "\n ClientId: " << HideSensitiveString(m_OpenIdClientId);
ZEN_CONSOLE("Auth: Adding Open ID auth provider:{}", SB.ToString());
}
Auth->AddOpenIdProvider({.Name = ProviderName, .Url = m_OpenIdProviderUrl, .ClientId = m_OpenIdClientId});
if (!m_OpenIdRefreshToken.empty())
{
if (!Quiet)
{
ZEN_CONSOLE("Auth: Adding open id refresh token {} to provider {}",
HideSensitiveString(m_OpenIdRefreshToken),
ProviderName);
}
Auth->AddOpenIdToken({.ProviderName = ProviderName, .RefreshToken = m_OpenIdRefreshToken});
}
}
auto GetEnvAccessToken = [](const std::string& AccessTokenEnv) -> std::string {
if (!AccessTokenEnv.empty())
{
return GetEnvVariable(AccessTokenEnv);
}
return {};
};
if (!m_AccessToken.empty())
{
if (!Quiet)
{
ZEN_CONSOLE("Auth: Using static auth token: {}", HideSensitiveString(m_AccessToken));
}
ClientSettings.AccessTokenProvider = httpclientauth::CreateFromStaticToken(m_AccessToken);
}
else if (!m_AccessTokenPath.empty())
{
MakeSafeAbsolutePathInPlace(m_AccessTokenPath);
std::string ResolvedAccessToken = ReadAccessTokenFromJsonFile(m_AccessTokenPath);
if (!ResolvedAccessToken.empty())
{
if (!Quiet)
{
ZEN_CONSOLE("Auth: Adding static auth token from {}: {}", m_AccessTokenPath, HideSensitiveString(ResolvedAccessToken));
}
ClientSettings.AccessTokenProvider = httpclientauth::CreateFromStaticToken(ResolvedAccessToken);
}
}
else if (!m_OAuthUrl.empty())
{
if (Verbose)
{
ExtendableStringBuilder<128> SB;
SB << "\n Url: " << m_OAuthUrl;
SB << "\n ClientId: " << HideSensitiveString(m_OAuthClientId);
SB << "\n ClientSecret: " << HideSensitiveString(m_OAuthClientSecret);
ZEN_CONSOLE("Auth: Adding oauth provider:{}", SB.ToString());
}
ClientSettings.AccessTokenProvider = httpclientauth::CreateFromOAuthClientCredentials(
{.Url = m_OAuthUrl, .ClientId = m_OAuthClientId, .ClientSecret = m_OAuthClientSecret});
}
else if (!m_OpenIdProviderName.empty())
{
CreateAuthMgr(Ops, SystemRootDir, Auth, Quiet, Verbose);
if (!Quiet)
{
ZEN_CONSOLE("Auth: Using OpenId provider: {}", m_OpenIdProviderName);
}
ClientSettings.AccessTokenProvider = httpclientauth::CreateFromOpenIdProvider(*Auth, m_OpenIdProviderName);
}
else if (std::string ResolvedAccessToken = GetEnvAccessToken(m_AccessTokenEnv); !ResolvedAccessToken.empty())
{
if (!Quiet)
{
ZEN_CONSOLE("Auth: Resolved environment variable '{}' to access token '{}'",
m_AccessTokenEnv,
HideSensitiveString(ResolvedAccessToken));
}
ClientSettings.AccessTokenProvider = httpclientauth::CreateFromStaticToken(ResolvedAccessToken);
}
else if (std::filesystem::path OidcTokenExePath = FindOidcTokenExePath(m_OidcTokenAuthExecutablePath); !OidcTokenExePath.empty())
{
if (!Quiet)
{
ZEN_CONSOLE("Auth: Using oidctoken exe from path '{}'", OidcTokenExePath);
}
ClientSettings.AccessTokenProvider =
httpclientauth::CreateFromOidcTokenExecutable(OidcTokenExePath, HostUrl, Quiet, m_OidcTokenUnattended, Hidden);
}
else if (!m_OidcTokenAuthExecutablePath.empty())
{
throw OptionParseException(fmt::format("'--oidctoken-exe-path' ('{}') does not exist", m_OidcTokenAuthExecutablePath), Ops.help());
}
if (!ClientSettings.AccessTokenProvider)
{
CreateAuthMgr(Ops, SystemRootDir, Auth, Quiet, Verbose);
if (!Quiet)
{
ZEN_CONSOLE("Auth: Using default Open ID provider");
}
ClientSettings.AccessTokenProvider = httpclientauth::CreateFromDefaultOpenIdProvider(*Auth);
}
}
} // namespace zen
|