Files
WoW-Hybrid-gateway/native/remember_credentials.cpp

288 lines
11 KiB
C++

#include "remember_credentials.hpp"
#include <array>
#include <algorithm>
#include <cstring>
#include <mutex>
#include <vector>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <wincrypt.h>
#else
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace gw::remember {
namespace {
void erase(std::string &s) {
for (volatile char *p = s.empty() ? nullptr : &s[0];
p && p < &s[0] + s.size(); ++p)
*p = 0;
s.clear();
}
bool valid(const Credential &c) {
if (c.account.empty() || c.account.size() > 32 || c.password.empty() ||
c.password.size() > 64)
return false;
for (unsigned char v : c.account)
if (v < 0x21 || v > 0x7e)
return false;
return c.password.find('\0') == std::string::npos;
}
bool parent_ok(const std::filesystem::path &f) {
#ifdef _WIN32
const DWORD attributes = GetFileAttributesW(f.parent_path().c_str());
if (attributes == INVALID_FILE_ATTRIBUTES ||
(attributes & FILE_ATTRIBUTE_REPARSE_POINT))
return false;
#endif
std::error_code ec;
auto s = std::filesystem::symlink_status(f.parent_path(), ec);
return !ec && std::filesystem::is_directory(s) &&
!std::filesystem::is_symlink(s);
}
} // namespace
void wipe(Credential &c) {
erase(c.account);
erase(c.password);
c.automatic = false;
}
bool clear(const std::filesystem::path &file) {
if (!parent_ok(file))
return false;
std::error_code ec;
std::filesystem::remove(file, ec);
return !ec;
}
static bool save_plain(const std::filesystem::path &file, std::string plain) {
if (plain.empty() || plain.size()>4096 || !parent_ok(file)) { erase(plain); return false; }
bool ok = false;
#ifdef _WIN32
DATA_BLOB in{DWORD(plain.size()), reinterpret_cast<BYTE *>(plain.data())},
out{};
if (CryptProtectData(&in, L"Forever remembered game credential", nullptr,
nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &out)) {
// A temporary file is never plaintext on Windows.
wchar_t temporary[MAX_PATH]{};
if (GetTempFileNameW(file.parent_path().c_str(), L"gwc", 0, temporary)) {
HANDLE h = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr,
TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h != INVALID_HANDLE_VALUE) {
DWORD n = 0;
ok = WriteFile(h, out.pbData, out.cbData, &n, nullptr) &&
n == out.cbData && FlushFileBuffers(h);
CloseHandle(h);
}
if (ok)
ok = MoveFileExW(temporary, file.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) !=
0;
if (!ok)
DeleteFileW(temporary);
}
SecureZeroMemory(out.pbData, out.cbData);
LocalFree(out.pbData);
}
#else
std::string pattern = file.string() + ".XXXXXX";
std::vector<char> tmp(pattern.begin(), pattern.end());
tmp.push_back(0);
int fd = mkstemp(tmp.data());
if (fd >= 0) {
ok = fchmod(fd, 0600) == 0;
size_t done = 0;
while (ok && done < plain.size()) {
ssize_t n = write(fd, plain.data() + done, plain.size() - done);
if (n <= 0)
ok = false;
else
done += size_t(n);
}
if (ok)
ok = fsync(fd) == 0;
if (close(fd) != 0)
ok = false;
if (ok)
ok = rename(tmp.data(), file.c_str()) == 0;
if (!ok)
unlink(tmp.data());
}
#endif
erase(plain);
return ok;
}
static bool load_plain(const std::filesystem::path &file, std::string &plain) {
erase(plain);
if (!parent_ok(file))
return false;
#ifdef _WIN32
HANDLE h = CreateFileW(file.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
if (h == INVALID_HANDLE_VALUE)
return false;
BY_HANDLE_FILE_INFORMATION info{};
DWORD length = GetFileSize(h, nullptr);
bool ok = GetFileInformationByHandle(h, &info) &&
!(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
length > 0 && length <= 16384;
std::vector<BYTE> encrypted(ok ? length : 0);
DWORD got = 0;
if (ok) {
ok = ReadFile(h, encrypted.data(), length, &got, nullptr) && got == length;
}
CloseHandle(h);
DATA_BLOB in{length, encrypted.data()}, out{};
if (!ok || !CryptUnprotectData(&in, nullptr, nullptr, nullptr, nullptr,
CRYPTPROTECT_UI_FORBIDDEN, &out))
return false;
plain.assign(reinterpret_cast<char *>(out.pbData), out.cbData);
SecureZeroMemory(out.pbData, out.cbData);
LocalFree(out.pbData);
#else
int fd = open(file.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0)
return false;
struct stat st{};
bool ok = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
st.st_uid == geteuid() && (st.st_mode & 0777) == 0600 &&
st.st_nlink == 1 && st.st_size >= 6 && st.st_size <= 4096;
if (ok) {
plain.resize(size_t(st.st_size));
size_t done = 0;
while (done < plain.size()) {
ssize_t n = read(fd, plain.data() + done, plain.size() - done);
if (n <= 0) {
ok = false;
break;
}
done += size_t(n);
}
}
close(fd);
if (!ok) {
erase(plain);
return false;
}
#endif
return !plain.empty() && plain.size()<=4096;
}
static bool legacy(const std::string& plain, Credential& value) {
wipe(value);
if(plain.size()<7 || plain.compare(0,4,"GWC1")!=0)return false;
const auto a=uint8_t(plain[4]),p=uint8_t(plain[5]);
if(uint8_t(plain[6])>1 || plain.size()!=size_t(7+a+p))return false;
value.account=plain.substr(7,a);value.password=plain.substr(7+a,p);value.automatic=plain[6]!=0;
if(!valid(value)){wipe(value);return false;}return true;
}
bool save(const std::filesystem::path& file,const Credential& c){
if(!valid(c))return false;
std::string plain="GWC1";plain+=char(c.account.size());plain+=char(c.password.size());plain+=char(c.automatic);
plain+=c.account;plain+=c.password;const bool ok=save_plain(file,plain);erase(plain);return ok;
}
bool load(const std::filesystem::path& file,Credential& c){
std::string plain;const bool ok=load_plain(file,plain)&&legacy(plain,c);erase(plain);if(!ok)wipe(c);return ok;
}
void wipe(Vault& v){for(auto& a:v.accounts){erase(a.account);erase(a.password);erase(a.label);erase(a.character);}v.accounts.clear();v.locked=v.streamer=false;}
static bool valid_account(const Account& a){
Credential c{a.account,a.password,false};const bool ok=valid(c);wipe(c);
if(!ok || a.label.size()>64 || a.character.size()>64 || a.character_index>1000)return false;
for(const auto* s:{&a.label,&a.character})for(unsigned char ch:*s)if(ch<32 || ch==127)return false;
return true;
}
bool encode(const Vault& v,std::string& plain){
erase(plain);if(v.accounts.size()>16)return false;
std::vector<std::string> names;
for(const auto& a:v.accounts){
if(!valid_account(a))return false;
std::string name=a.account;for(auto& c:name)if(c>='a'&&c<='z')c-=32;
for(const auto& seen:names){if(seen==name)return false;}
names.push_back(name);
}
plain="GWC2";plain+=char(v.accounts.size());plain+=char((v.locked?1:0)|(v.streamer?2:0));
for(const auto& a:v.accounts){
for(const auto* field:{&a.account,&a.password,&a.label,&a.character})plain+=char(field->size());
plain+=char(a.character_index&255);plain+=char(a.character_index>>8);
plain+=a.account;plain+=a.password;plain+=a.label;plain+=a.character;
}
return true;
}
bool decode(const std::string& plain,Vault& v){
wipe(v);
if(plain.compare(0,4,"GWC1")==0){Credential c;if(!legacy(plain,c))return false;v.accounts.push_back({c.account,c.password,"","",0});wipe(c);return true;}
if(plain.size()<6 || plain.size()>4096 || plain.compare(0,4,"GWC2") || uint8_t(plain[4])>16 || uint8_t(plain[5])>3)return false;
Vault temp;temp.locked=plain[5]&1;temp.streamer=plain[5]&2;size_t at=6;
for(unsigned i=0;i<uint8_t(plain[4]);++i){
if(at+6>plain.size()){wipe(temp);return false;}
unsigned lengths[4];for(auto& n:lengths)n=uint8_t(plain[at++]);
Account a;a.character_index=uint8_t(plain[at])|(uint16_t(uint8_t(plain[at+1]))<<8);at+=2;
size_t total=0;for(auto n:lengths)total+=n;
if(at+total>plain.size()){wipe(temp);return false;}
unsigned j=0;for(auto* field:{&a.account,&a.password,&a.label,&a.character}){*field=plain.substr(at,lengths[j]);at+=lengths[j++];}
temp.accounts.push_back(std::move(a));
}
std::string canonical;const bool ok=at==plain.size()&&encode(temp,canonical);erase(canonical);
if(!ok){wipe(temp);return false;}v=std::move(temp);return true;
}
bool save(const std::filesystem::path& file,const Vault& v){std::string plain;bool ok=encode(v,plain)&&save_plain(file,plain);erase(plain);return ok;}
bool load(const std::filesystem::path& file,Vault& v){std::string plain;bool ok=load_plain(file,plain)&&decode(plain,v);erase(plain);if(!ok)wipe(v);return ok;}
void Exchange::reset(){erase(staging_);expected_=offset_=0;writing_=reading_=false;}
Exchange::~Exchange(){reset();}
int64_t Exchange::query(uint32_t op,uint32_t row,uint32_t chunk){
if(op==16){
reset();if(row || chunk)return -1;
Vault v;if(!load(file_,v)){std::error_code ec;return std::filesystem::exists(file_,ec)||ec?-1:0;}
const bool ok=encode(v,staging_);wipe(v);if(!ok){reset();return -1;}
reading_=true;return staging_.size();
}
if(op==17){
if(!reading_ || chunk || row!=offset_ || offset_>=staging_.size()){reset();return -1;}
uint32_t out=0;for(unsigned i=0;i<3 && offset_<staging_.size();++i)out|=uint32_t(uint8_t(staging_[offset_++]))<<(8*i);
if(offset_==staging_.size())reset();
return out;
}
if(op==18){reset();if(chunk!=2 || row<6 || row>4096)return -1;expected_=row;writing_=true;return 0;}
if(op==19){
if(!writing_ || row!=offset_ || offset_>=expected_ || chunk>0xffffff){reset();return -1;}
const auto n=std::min<uint32_t>(3,expected_-offset_);
if(n<3 && (chunk>>(n*8))){reset();return -1;}
for(unsigned i=0;i<n;++i){staging_+=char((chunk>>(8*i))&255);++offset_;}return 0;
}
if(op==20){
if(row || chunk || !writing_ || offset_!=expected_){reset();return -1;}
Vault v;const bool ok=staging_.compare(0,4,"GWC2")==0 && decode(staging_,v) && save(file_,v);wipe(v);reset();return ok?0:-1;
}
if(op==21){reset();return !row && !chunk && clear(file_)?0:-1;}
reset();return -1;
}
} // namespace gw::remember
#ifdef _WIN32
extern "C" LONG WINAPI gw_source_profile_kind(void);
extern "C" __declspec(dllexport) int64_t WINAPI
gw_wire_remember_password_query(uint32_t op, uint32_t row, uint32_t chunk) {
// Never-destroyed statics: a function-local static with a destructor makes the DLL call ucrtbase atexit on
// first use, which crashes on real Windows when the first call comes from the glue thread (report 49379a).
static std::mutex &mutex = *new std::mutex;
std::lock_guard<std::mutex> guard(mutex);
static const std::filesystem::path &path = *new std::filesystem::path([]() {
wchar_t exe[32768]{};
DWORD n = GetModuleFileNameW(nullptr, exe, 32768);
if (!n || n >= 32768)
return std::filesystem::path{};
auto dir = std::filesystem::path(exe).parent_path() / L"WTF";
std::error_code ec;
std::filesystem::create_directory(dir, ec);
const auto kind = gw_source_profile_kind();
if (kind != 5 && kind != 2)
return std::filesystem::path{};
return dir / (kind == 2 ? L"remember-octo.dat" : L"remember-local.dat");
}());
if (path.empty())
return -1;
static gw::remember::Exchange &exchange = *new gw::remember::Exchange(path);
return exchange.query(op, row, chunk);
}
#endif