diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e413c59 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.vs +_Build +*.vcxproj.user \ No newline at end of file diff --git a/Common/Common.vcxproj b/Common/Common.vcxproj new file mode 100644 index 0000000..2d51f18 --- /dev/null +++ b/Common/Common.vcxproj @@ -0,0 +1,211 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + 16.0 + Win32Proj + {f364b2ab-f34a-4bcf-9362-22720020ddbf} + Common + 10.0 + + + + StaticLibrary + true + v142 + Unicode + + + StaticLibrary + false + v142 + true + Unicode + + + StaticLibrary + true + v142 + Unicode + + + StaticLibrary + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + + + false + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + + + true + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + + + false + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + + + $(PlatformTarget)-windows-static + true + + + $(PlatformTarget)-windows-static + true + + + $(PlatformTarget)-windows-static + true + + + $(PlatformTarget)-windows-static + true + + + + Level3 + true + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + Use + pch.h + %(AdditionalIncludeDirectories) + MultiThreadedDebug + stdcpp17 + + + + + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + Use + pch.h + %(AdditionalIncludeDirectories) + MultiThreaded + stdcpp17 + + + + + true + true + true + + + + + Level3 + true + _DEBUG;_LIB;%(PreprocessorDefinitions) + true + Use + pch.h + %(AdditionalIncludeDirectories) + MultiThreadedDebug + stdcpp17 + + + + + true + + + + + Level3 + true + true + true + NDEBUG;_LIB;%(PreprocessorDefinitions) + true + Use + pch.h + %(AdditionalIncludeDirectories) + MultiThreaded + stdcpp17 + + + + + true + true + true + + + + + + \ No newline at end of file diff --git a/Common/Common.vcxproj.filters b/Common/Common.vcxproj.filters new file mode 100644 index 0000000..cd51572 --- /dev/null +++ b/Common/Common.vcxproj.filters @@ -0,0 +1,47 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/Common/src/Config.cpp b/Common/src/Config.cpp new file mode 100644 index 0000000..3cef775 --- /dev/null +++ b/Common/src/Config.cpp @@ -0,0 +1,55 @@ +#include "pch.h" +#include "Config.h" +#include "util.h" + +using nlohmann::json; + +// Source: https://stackoverflow.com/a/54394658/3805929 +#define GET(j, key) this->key = j[#key].get() + +void from_json(const json& j, Platform& p) +{ + j["enabled"].get_to(p.enabled); + j["process"].get_to(p.process); + j["replicate"].get_to(p.replicate); + j["ignore"].get_to(p.ignore); + j["blacklist"].get_to(p.blacklist); +} + +Config::Config() +{ + auto fullPath = getWorkingDirPath() / L"Config.jsonc"; + + std::ifstream ifs(fullPath, std::ios::in); + + if(!ifs.good()) + { + MessageBox(NULL, fullPath.c_str(), L"Config not found at: ", MB_ICONERROR | MB_ICONERROR); + exit(1); + } + + try + { + auto j = json::parse(ifs, nullptr, true, true); + + GET(j, log_level); + GET(j, platforms); + GET(j, ignore); + GET(j, terminate); + } catch(json::exception e) + { + MessageBoxA(NULL, e.what(), "Error parsing config file", MB_ICONERROR | MB_ICONERROR); + exit(1); + } +} + +void Config::init() +{ + if(config != nullptr) + return; + + config = new Config(); +} + +// Every app must call the config constructor first. +Config* config = nullptr; diff --git a/Common/src/Config.h b/Common/src/Config.h new file mode 100644 index 0000000..5d474e5 --- /dev/null +++ b/Common/src/Config.h @@ -0,0 +1,27 @@ +#pragma once +#include "framework.h" +#include "util.h" + +struct Platform +{ + bool enabled = true; + string process; + bool replicate = false; + vector ignore; + vector blacklist; +}; + +class Config +{ +protected: + Config(); +public: + string log_level; + map platforms; + vector ignore; + vector terminate; + + static void init(); +}; + +extern Config* config; diff --git a/Common/src/Logger.cpp b/Common/src/Logger.cpp new file mode 100644 index 0000000..717c586 --- /dev/null +++ b/Common/src/Logger.cpp @@ -0,0 +1,35 @@ +#include "pch.h" +#include "Logger.h" +#include "Config.h" + +namespace Logger +{ + +void init(string loggerName, bool truncate) +{ + Config::init(); + if(config->log_level == "off") + return; + + try + { + auto processPath = getProcessPath(); + auto fileName = fmt::format("{}.{}.log", loggerName, processPath.stem().string()); + auto path = getWorkingDirPath() / "logs" / fileName; + logger = spdlog::basic_logger_mt(loggerName, path.u8string(), truncate); + logger->set_pattern("[%H:%M:%S.%e] [%l]\t%v"); + logger->set_level(spdlog::level::from_str(config->log_level)); + logger->flush_on(spdlog::level::debug); + } catch(const spdlog::spdlog_ex& ex) + { + // Now if we can't open log file, something must be really wrong, hence we exit. + auto message = stow(string(ex.what())); + MessageBox(NULL, message.c_str(), L"Failed to initialize the log file", MB_ICONERROR | MB_OK); + exit(1); + } + +} + +} + +shared_ptr logger = spdlog::null_logger_mt("null"); diff --git a/Common/src/Logger.h b/Common/src/Logger.h new file mode 100644 index 0000000..c30afe1 --- /dev/null +++ b/Common/src/Logger.h @@ -0,0 +1,11 @@ +#pragma once +#include "util.h" + +extern shared_ptr logger; + +namespace Logger +{ + +void init(string loggerName, bool truncate); + +} diff --git a/Common/src/constants.h b/Common/src/constants.h new file mode 100644 index 0000000..21a2e84 --- /dev/null +++ b/Common/src/constants.h @@ -0,0 +1,23 @@ +#pragma once + +constexpr auto VERSION = "1.0.0"; +constexpr auto WORKING_DIR = L"WORKING_DIR"; + +constexpr auto INTEGRATION_64 = L"Integration64.dll"; +constexpr auto INTEGRATION_32 = L"Integration32.dll"; + +#ifdef _WIN64 + +constexpr auto EOSSDK = L"EOSSDK-Win64-Shipping.dll"; +constexpr auto STEAMAPI = L"steam_api64.dll"; +constexpr auto UPLAY_R2 = L"uplay_r2_loader64.dll"; + +#else + +constexpr auto EOSSDK = L"EOSSDK-Win32-Shipping.dll"; +constexpr auto STEAMAPI = L"steam_api.dll"; +constexpr auto UPLAY_R2 = L"uplay_r2_loader.dll"; + +#endif + +constexpr auto ORIGINCLIENT = L"OriginClient.dll"; diff --git a/Common/src/framework.h b/Common/src/framework.h new file mode 100644 index 0000000..c8926e6 --- /dev/null +++ b/Common/src/framework.h @@ -0,0 +1,35 @@ +#pragma once +#include + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Following definitions are required for static build of libcurl +#pragma comment(lib,"Ws2_32.lib") +#pragma comment(lib,"Wldap32.lib") +#pragma comment(lib,"Crypt32.lib") + +#pragma warning(push) // Disable 3rd party library warnings +#pragma warning(disable: ALL_CODE_ANALYSIS_WARNINGS) + +#define SPDLOG_WCHAR_TO_UTF8_SUPPORT +#include +#include +#include +#include +#include +#include +#include +#include +#pragma warning(pop) diff --git a/Common/src/pch.cpp b/Common/src/pch.cpp new file mode 100644 index 0000000..1d9f38c --- /dev/null +++ b/Common/src/pch.cpp @@ -0,0 +1 @@ +#include "pch.h" diff --git a/Common/src/pch.h b/Common/src/pch.h new file mode 100644 index 0000000..c9c7883 --- /dev/null +++ b/Common/src/pch.h @@ -0,0 +1,2 @@ +#pragma once +#include "framework.h" diff --git a/Common/src/util.cpp b/Common/src/util.cpp new file mode 100644 index 0000000..58ee7d2 --- /dev/null +++ b/Common/src/util.cpp @@ -0,0 +1,227 @@ +#include "pch.h" +#include "util.h" +#include "Logger.h" +#include "constants.h" +#include // ??? + + +bool contains(wstring haystack, wstring needle) +{ + return haystack.find(needle) != wstring::npos; +} + +bool startsWith(string word, string prefix) +{ + return word.find(prefix, 0) == 0; +} + +bool endsWith(string word, string postfix) +{ + return word.find(postfix, 0) == word.length() - postfix.length(); +} + +string toLower(string str) +{ + string lowerString = str; // Copy constructor. + std::for_each(lowerString.begin(), lowerString.end(), [](char& c){ + c = ::tolower(c); + }); + return lowerString; +} + +/// Case-insensitive string comparison. Returns true if strings are equal. +bool stringsAreEqual(string one, string two) +{ + return toLower(one) == toLower(two); +} + +wstring getProcessName(DWORD pid) +{ + auto defaultName = wstring(L""); + auto hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); + if(hProcess == NULL) + { + logger->error("Failed to open handle to a process with id: {}. Error code: 0x{0:}", pid, GetLastError()); + return defaultName; + } + + TCHAR buffer[MAX_PATH]; + auto result = GetModuleFileNameEx(hProcess, NULL, buffer, MAX_PATH); + if(result == NULL) + { + logger->error("Failed to get process name with id: {}s. Error code: 0x{0:}", pid, GetLastError()); + return defaultName; + } + + return wstring(buffer); +} + +wstring getCurrentModuleName() +{ + wchar_t name[MAX_PATH]; + auto result = GetModuleFileName(NULL, name, MAX_PATH); + + if(result == NULL) + logger->error("Failed to get current module's file name. Error code: {}", GetLastError()); + + return wstring(name); +} + +/** +Returns std::filesystem::path of the process identified by the +provided handle. If handle is not provided, then currently running +process path is returned. +*/ +path getProcessPath(HANDLE handle) +{ + TCHAR buffer[MAX_PATH]; + DWORD result = 0; + if(handle == NULL) + result = GetModuleFileName(NULL, buffer, MAX_PATH); + else + result = GetModuleFileNameEx(handle, NULL, buffer, MAX_PATH); + + if(result == NULL) + { + auto message = fmt::format("Failed to obtain process path. Error code: 0x{:X}", GetLastError()); + throw std::exception(message.c_str()); + } + + return absolute(buffer); +} + +path getWorkingDirPath() +{ + return absolute(getReg(WORKING_DIR)); +} + +bool is32bit(DWORD PID) +{ + BOOL isWow64; + + auto process = OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, PID); + if(process == NULL) + { // Should not happen often. If it does, worst case is failed injection. + logger->error("Failed to get a handle to process with PID: {}", PID); + return true; + } + + IsWow64Process(process, &isWow64); + CloseHandle(process); + + // If a process is running under WOW64, then it means it is 32-bit. + return isWow64; +} + +bool is32bit(HANDLE hProcess) +{ + // Cannot use IsWow64Process2 since it is supported by Win 10 only + BOOL isWow64 = NULL; + IsWow64Process(hProcess, &isWow64); + return isWow64; +} + +void killProcess(HANDLE hProcess, DWORD sleepMS) +{ + TerminateProcess(hProcess, 0); + auto result = WaitForSingleObject(hProcess, 3 * 1000); // 3s should be enough + if(result != WAIT_OBJECT_0) + { + auto processName = getProcessPath(hProcess).string(); + throw std::exception(fmt::format("Failed to terminate process: {}", processName).c_str()); + } + else + { + Sleep(sleepMS); // Some other process may still be locking the file + } +} + + +// Source: https://stackoverflow.com/a/3999597/3805929 + +// Convert a wide Unicode string to a UTF8 string +std::string wtos(const std::wstring& wstr) +{ + if(wstr.empty()) return std::string(); + int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int) wstr.size(), NULL, 0, NULL, NULL); + std::string strTo(size_needed, 0); + WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int) wstr.size(), &strTo[0], size_needed, NULL, NULL); + return strTo; +} + +// Convert a UTF8 string to a wide Unicode String +std::wstring stow(const std::string& str) +{ + if(str.empty()) return std::wstring(); + int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int) str.size(), NULL, 0); + std::wstring wstrTo(size_needed, 0); + MultiByteToWideChar(CP_UTF8, 0, &str[0], (int) str.size(), &wstrTo[0], size_needed); + return wstrTo; +} + + +char* makeCStringCopy(string src) +{ + const auto len = src.length(); + char* dest = new char[len + 1]; + std::size_t length = src.copy(dest, len, 0); + dest[len] = '\0'; + return dest; +} + +wstring getReg(LPCWSTR key) +{ + static winreg::RegKey regKey{ HKEY_CURRENT_USER, L"SOFTWARE\\acidicoala\\Koalageddon" }; + return regKey.GetStringValue(key); +} + +void setReg(LPCWSTR key, LPCWSTR val) +{ + static winreg::RegKey regKey{ HKEY_CURRENT_USER, L"SOFTWARE\\acidicoala\\Koalageddon" }; + regKey.SetStringValue(key, val); +} +string readFileContents(string path) +{ + std::ifstream fileStream(path); + if(fileStream.good()) + return string(std::istreambuf_iterator{fileStream}, {}); + else + return ""; +} + +bool writeFileContents(path filePath, string contents) +{ + if(!std::filesystem::exists(filePath)) + std::filesystem::create_directories(filePath.parent_path()); + + std::ofstream fileStream(filePath); + if(fileStream.good()) + { + fileStream << contents; + return true; + } + else + { + logger->error("Failed to write to file: {}", filePath.string()); + return false; + } +} + +void showFatalError(string message, bool terminate) +{ + message = fmt::format("{}\nLast error: 0x{:X}", message, GetLastError()); + logger->error(message); + MessageBoxA(NULL, message.c_str(), "Fatal Error", MB_ICONERROR | MB_OK); + + if(terminate) + exit(1); +} + +void showInfo(string message, string title, bool shouldLog) +{ + if(shouldLog) + logger->info(message); + + MessageBoxA(NULL, message.c_str(), title.c_str(), MB_ICONINFORMATION | MB_OK); +} + diff --git a/Common/src/util.h b/Common/src/util.h new file mode 100644 index 0000000..4d8e4ed --- /dev/null +++ b/Common/src/util.h @@ -0,0 +1,65 @@ +#pragma once +#include "framework.h" + +// Import into global namespace commonly used classes +using std::string; +using std::wstring; +using std::vector; +using std::pair; +using std::map; +using std::shared_ptr; +using std::unique_ptr; +using std::make_unique; +using std::filesystem::absolute; +using std::filesystem::path; +using std::filesystem::copy_options; + +constexpr auto INJECTOR_64 = L"Injector64.exe"; +constexpr auto INJECTOR_32 = L"Injector32.exe"; + +constexpr auto UNLOCKER_64 = L"Unlocker64.dll"; +constexpr auto UNLOCKER_32 = L"Unlocker32.dll"; + +#ifdef _WIN64 +constexpr auto UNLOCKER_NAME = "Unlocker64"; +#else +constexpr auto UNLOCKER_NAME = "Unlocker32"; +#endif + +// Process info +wstring getProcessName(DWORD pid); +wstring getCurrentModuleName(); +path getProcessPath(HANDLE handle = NULL); +bool is32bit(DWORD PID); +bool is32bit(HANDLE hProcess); +void killProcess(HANDLE hProcess, DWORD sleepMS = 0); + +// String utils +string wtos(const wstring& wstr); +wstring stow(const string& wstr); +char* makeCStringCopy(string src); +bool contains(wstring haystack, wstring needle); +bool startsWith(string word, string prefix); +bool endsWith(string word, string postfix); +string toLower(string str); +bool stringsAreEqual(string one, string two); + +// Registry +wstring getReg(LPCWSTR key); +void setReg(LPCWSTR key, LPCWSTR val); +path getWorkingDirPath(); + +// File access +string readFileContents(string path); +bool writeFileContents(path filePath, string contents); + +// Message Box helpers +void showFatalError(string message, bool terminate); +void showInfo(string message, string title = "Information", bool shouldLog = false); + + +template +bool vectorContains(vector elements, T element) +{ + return std::find(elements.begin(), elements.end(), element) != elements.end(); +} diff --git a/Injector/Injector.vcxproj b/Injector/Injector.vcxproj new file mode 100644 index 0000000..54cea96 --- /dev/null +++ b/Injector/Injector.vcxproj @@ -0,0 +1,212 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {5d2b330b-73e9-4b02-8203-be7078da646b} + Injector + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + MultiThreadedDebug + $(SolutionDir)Common\src + Use + pch.h + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + MultiThreaded + $(SolutionDir)Common\src + Use + pch.h + + + Console + true + true + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + MultiThreadedDebug + $(SolutionDir)Common\src + Use + pch.h + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + MultiThreaded + $(SolutionDir)Common\src + Use + pch.h + + + Console + true + true + true + + + + + {f364b2ab-f34a-4bcf-9362-22720020ddbf} + + + + + + + + + + + + Create + Create + Create + Create + + + + + + \ No newline at end of file diff --git a/Injector/Injector.vcxproj.filters b/Injector/Injector.vcxproj.filters new file mode 100644 index 0000000..50622c9 --- /dev/null +++ b/Injector/Injector.vcxproj.filters @@ -0,0 +1,35 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/Injector/src/Injector.cpp b/Injector/src/Injector.cpp new file mode 100644 index 0000000..9f5d5c7 --- /dev/null +++ b/Injector/src/Injector.cpp @@ -0,0 +1,51 @@ +#include "pch.h" +#include "Injector.h" +#include "Logger.h" + +// Source: https://github.com/saeedirha/DLL-Injector +int injectDLL(const int pid, wstring dllPath) +{ + // 1. Get handle to the process + auto processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); + if(processHandle == NULL) + { + logger->error("Failed to open the target process. Error code: {}", GetLastError()); + return ERROR_PROCESS_OPEN; + } + + // 2. Allocte memory in that process + auto dllPathSize = 2 * (dllPath.length() + 1); + auto dllPathAddress = VirtualAllocEx(processHandle, NULL, dllPathSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if(dllPathAddress == NULL) + { + logger->error("Failed to allocate memory in the target process. Error code: {}", GetLastError()); + CloseHandle(processHandle); + return ERROR_TARGET_MALLOC; + } + + // 3. Write DLL path into the newly allocated memory space + auto writeSuccess = WriteProcessMemory(processHandle, dllPathAddress, dllPath.c_str(), dllPathSize, NULL); + if(!writeSuccess) + { + logger->error("Failed to write in memory of the target process. Error code: {}", GetLastError()); + CloseHandle(processHandle); + return ERROR_TARGET_WRITE; + } + + // 4. Create new thread in the target process + auto threadHandle = CreateRemoteThread(processHandle, NULL, NULL, (LPTHREAD_START_ROUTINE) LoadLibraryW, dllPathAddress, NULL, NULL); + if(threadHandle == NULL) + { + logger->error("Failed to create a remote thread in the target process. Error code: {}", GetLastError()); + logger->error("\tprocHandle: {}", (void*) processHandle); + logger->error("\tloadLibraryAddress: {}", (void*) &LoadLibraryA); + logger->error("\tdllPathAddress: {}", (void*) dllPathAddress); + CloseHandle(processHandle); + return ERROR_REMOTE_THREAD; + } + + CloseHandle(threadHandle); + CloseHandle(processHandle); + + return OK; +} diff --git a/Injector/src/Injector.h b/Injector/src/Injector.h new file mode 100644 index 0000000..c7d6609 --- /dev/null +++ b/Injector/src/Injector.h @@ -0,0 +1,17 @@ +#pragma once +#include "framework.h" +#include "util.h" + +enum ExitCode +{ + OK, + ERROR_INVALID_ARGUMENTS, + ERROR_PROCESS_OPEN, + ERROR_TARGET_MALLOC, + ERROR_TARGET_WRITE, + ERROR_KERNEL_HANDLE, + ERROR_PROC_ADDRESS, + ERROR_REMOTE_THREAD +}; + +int injectDLL(const int pid, wstring DLL_Path); diff --git a/Injector/src/framework.h b/Injector/src/framework.h new file mode 100644 index 0000000..05653a6 --- /dev/null +++ b/Injector/src/framework.h @@ -0,0 +1,7 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#include + +#include +#include diff --git a/Injector/src/main.cpp b/Injector/src/main.cpp new file mode 100644 index 0000000..0e17279 --- /dev/null +++ b/Injector/src/main.cpp @@ -0,0 +1,49 @@ +#include "pch.h" +#include "util.h" +#include "constants.h" +#include "Injector.h" +#include "Logger.h" +#include "Config.h" + +// Hide console window +#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") + +int main(int argc, char** argv) +{ + Config::init(); + Logger::init("Injector", false); + + logger->debug("Injector v{}", VERSION); + + if(argc != 3) + { + logger->error("Expected 2 arguments, received: {}", argc - 1); + return ERROR_INVALID_ARGUMENTS; + } + + try + { + auto PID = (DWORD) std::stoi(argv[1]); + auto dllPath = stow(argv[2]); + + logger->info(L"Injecting DLL into \"{}\"", getProcessName(PID)); + logger->debug(L"PID: {}, dllPath: \"{}\"", PID, dllPath); + + auto result = injectDLL(PID, dllPath); + + if(result == OK) + { + logger->info("DLL was successully injected"); + } + else + { + logger->error("Failed to inject the DLL. Error code: 0x{0:}", result); + } + + return result; + } catch(std::logic_error&) + { + logger->error("Failed to convert PID {} to int", argv[1]); + return ERROR_INVALID_ARGUMENTS; + } +} diff --git a/Injector/src/pch.cpp b/Injector/src/pch.cpp new file mode 100644 index 0000000..1d9f38c --- /dev/null +++ b/Injector/src/pch.cpp @@ -0,0 +1 @@ +#include "pch.h" diff --git a/Injector/src/pch.h b/Injector/src/pch.h new file mode 100644 index 0000000..c9c7883 --- /dev/null +++ b/Injector/src/pch.h @@ -0,0 +1,2 @@ +#pragma once +#include "framework.h" diff --git a/Integration/Integration.vcxproj b/Integration/Integration.vcxproj new file mode 100644 index 0000000..26de0de --- /dev/null +++ b/Integration/Integration.vcxproj @@ -0,0 +1,213 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {6b6f6e00-a196-4815-8d24-d9890798fd09} + Integration + 10.0 + + + + DynamicLibrary + true + v142 + Unicode + + + DynamicLibrary + false + v142 + true + Unicode + + + DynamicLibrary + true + v142 + Unicode + + + DynamicLibrary + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + + Level3 + true + WIN32;_DEBUG;INTEGRATION_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreadedDebug + $(SolutionDir)Common\src + + + Windows + true + false + + + + + Level3 + true + true + true + WIN32;NDEBUG;INTEGRATION_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreaded + $(SolutionDir)Common\src + + + Windows + true + true + true + false + + + + + Level3 + true + _DEBUG;INTEGRATION_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreadedDebug + $(SolutionDir)Common\src + + + Windows + true + false + + + + + Level3 + true + true + true + NDEBUG;INTEGRATION_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreaded + $(SolutionDir)Common\src + + + Windows + true + true + true + false + + + + + {f364b2ab-f34a-4bcf-9362-22720020ddbf} + + + + + + + + + + + Create + Create + + + + + + \ No newline at end of file diff --git a/Integration/Integration.vcxproj.filters b/Integration/Integration.vcxproj.filters new file mode 100644 index 0000000..5141be1 --- /dev/null +++ b/Integration/Integration.vcxproj.filters @@ -0,0 +1,32 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/Integration/src/dllmain.cpp b/Integration/src/dllmain.cpp new file mode 100644 index 0000000..e51b1d8 --- /dev/null +++ b/Integration/src/dllmain.cpp @@ -0,0 +1,59 @@ +#include "pch.h" +#include "Logger.h" +#include "Config.h" +#include "constants.h" + +using std::filesystem::path; + +path thisDllPath; +HMODULE hUnlocker = NULL; + +void init(HMODULE hModule) +{ + + Logger::init("Integration", true); + logger->info("Integration v{}", VERSION); + + DisableThreadLibraryCalls(hModule); + + auto currentProcess = getProcessPath(); + logger->debug("Current process: {}", currentProcess.string()); + + for(const auto& [key, platform] : config->platforms) + { + if(stringsAreEqual(currentProcess.filename().string(), platform.process)) + { + logger->info("Target platform detected: {}", platform.process); + auto unlockerPath = absolute(getReg(WORKING_DIR)) / (UNLOCKER_NAME + string(".dll")); + logger->debug("Unlocker path: {}", unlockerPath.string()); + hUnlocker = LoadLibrary(unlockerPath.wstring().c_str()); + if(hUnlocker == NULL) + { + logger->error("Failed to load the Unlocker. Error code: 0x{:X}", GetLastError()); + } + else + { + logger->info("Successfully loaded the Unlocker"); + } + } + } +} + +void shutdown() +{ + if(hUnlocker != NULL) + FreeLibrary(hUnlocker); + +} + +BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) +{ + + if(ul_reason_for_call == DLL_PROCESS_ATTACH) + init(hModule); + else if(ul_reason_for_call == DLL_PROCESS_DETACH) + shutdown(); + + return TRUE; +} + diff --git a/Integration/src/framework.h b/Integration/src/framework.h new file mode 100644 index 0000000..3965caf --- /dev/null +++ b/Integration/src/framework.h @@ -0,0 +1,8 @@ +#pragma once + +#define WIN32_LEAN_AND_MEAN +#include + +#include + +#include "version_exports.h" diff --git a/Integration/src/pch.cpp b/Integration/src/pch.cpp new file mode 100644 index 0000000..64b7eef --- /dev/null +++ b/Integration/src/pch.cpp @@ -0,0 +1,5 @@ +// pch.cpp: source file corresponding to the pre-compiled header + +#include "pch.h" + +// When you are using pre-compiled headers, this source file is necessary for compilation to succeed. diff --git a/Integration/src/pch.h b/Integration/src/pch.h new file mode 100644 index 0000000..885d5d6 --- /dev/null +++ b/Integration/src/pch.h @@ -0,0 +1,13 @@ +// pch.h: This is a precompiled header file. +// Files listed below are compiled only once, improving build performance for future builds. +// This also affects IntelliSense performance, including code completion and many code browsing features. +// However, files listed here are ALL re-compiled if any one of them is updated between builds. +// Do not add files here that you will be updating frequently as this negates the performance advantage. + +#ifndef PCH_H +#define PCH_H + +// add headers that you want to pre-compile here +#include "framework.h" + +#endif //PCH_H diff --git a/Integration/src/version_exports.h b/Integration/src/version_exports.h new file mode 100644 index 0000000..e9535f5 --- /dev/null +++ b/Integration/src/version_exports.h @@ -0,0 +1,19 @@ +#pragma once + +#pragma comment(linker, "/export:GetFileVersionInfoA=version_o.GetFileVersionInfoA") +#pragma comment(linker, "/export:GetFileVersionInfoByHandle=version_o.GetFileVersionInfoByHandle") +#pragma comment(linker, "/export:GetFileVersionInfoExA=version_o.GetFileVersionInfoExA") +#pragma comment(linker, "/export:GetFileVersionInfoExW=version_o.GetFileVersionInfoExW") +#pragma comment(linker, "/export:GetFileVersionInfoSizeA=version_o.GetFileVersionInfoSizeA") +#pragma comment(linker, "/export:GetFileVersionInfoSizeExA=version_o.GetFileVersionInfoSizeExA") +#pragma comment(linker, "/export:GetFileVersionInfoSizeExW=version_o.GetFileVersionInfoSizeExW") +#pragma comment(linker, "/export:GetFileVersionInfoSizeW=version_o.GetFileVersionInfoSizeW") +#pragma comment(linker, "/export:GetFileVersionInfoW=version_o.GetFileVersionInfoW") +#pragma comment(linker, "/export:VerFindFileA=version_o.VerFindFileA") +#pragma comment(linker, "/export:VerFindFileW=version_o.VerFindFileW") +#pragma comment(linker, "/export:VerInstallFileA=version_o.VerInstallFileA") +#pragma comment(linker, "/export:VerInstallFileW=version_o.VerInstallFileW") +#pragma comment(linker, "/export:VerLanguageNameA=version_o.VerLanguageNameA") +#pragma comment(linker, "/export:VerLanguageNameW=version_o.VerLanguageNameW") +#pragma comment(linker, "/export:VerQueryValueA=version_o.VerQueryValueA") +#pragma comment(linker, "/export:VerQueryValueW=version_o.VerQueryValueW") diff --git a/IntegrationWizard/Config.jsonc b/IntegrationWizard/Config.jsonc new file mode 100644 index 0000000..9b09d47 --- /dev/null +++ b/IntegrationWizard/Config.jsonc @@ -0,0 +1,84 @@ +{ + "config_version": 1, // DO NOT EDIT THIS VALUE + "log_level": "debug", + "platforms": { + "Steam": { + "enabled": true, + "process": "steam.exe", + "replicate": true, + "ignore": [ + "x86launcher.exe", + "x64launcher.exe", + "SteamService.exe", + "steamwebhelper.exe", + "GameOverlayUI.exe", + "gldriverquery.exe", + "gldriverquery64.exe", + "vulkandriverquery.exe", + "vulkandriverquery64.exe" + ], + "blacklist": [ // Get App ID from SteamDB + "22618", // Alien Breed: Impact - PL Check [Do not force polish language] + "67379" // Darkness II Low Violence [Do not censor violence] + ] + }, + "Epic Games": { + "enabled": true, + "process": "EpicGamesLauncher.exe", + "replicate": true, + "ignore": [ + "EpicWebHelper.exe", + "EpicOnlineServicesHost.exe", + "EpicOnlineServicesUserHelper.exe", + "UnrealCEFSubProcess.exe" + ], + "blacklist": [ // Get DLC ID from ScreamDB + "ffffffffffffffffffffffffffffffff" // A Total War Sage: TROY [It actually asks this ID...] + ] + }, + "Origin": { + "enabled": true, + "process": "Origin.exe", + "replicate": false, + "ignore": [], + "blacklist": [ // Use ItemId from Unlocker32.Origin.log + // "SIMS4.OFF.SOLP.0x0000000000030553" // Sims 4: Get Famous [Better stay anonymous] + ] + }, + "Ubisoft Connect": { + "enabled": false, // Ubisoft games unload the Unlocker DLL :( + "process": "upc.exe", + "replicate": true, + "ignore": [ + "UplayService.exe", + "UplayWebCore.exe" + ], + "blacklist": [] + } + }, + "ignore": [ + // Do not inject our own injector + "Injector32.exe", + "Injector64.exe", + // System + "reg.exe", + "cmd.exe", + "regsvr32.exe", + // Unreal Engine + "CrashReportClient.exe", + // Origin integration with other stores + "EALink.exe", + // Ubisoft integration with other stores + "UbisoftGameLauncher.exe", + "UbisoftGameLauncher64.exe" + ], + "terminate": [ + // Steam + "steamerrorreporter.exe", + // Origin + "OriginER.exe", + "OriginCrashReporter.exe", + // Ubisoft + "UplayCrashReporter.exe" + ] +} diff --git a/IntegrationWizard/IntegrationWizard.vcxproj b/IntegrationWizard/IntegrationWizard.vcxproj new file mode 100644 index 0000000..0a06000 --- /dev/null +++ b/IntegrationWizard/IntegrationWizard.vcxproj @@ -0,0 +1,237 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {4e88d0ed-22df-4db8-985b-22b778059f11} + IntegrationWizard + 10.0 + + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + Application + true + v142 + Unicode + + + Application + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + $(SolutionDir)Common\src + MultiThreadedDebug + Use + pch.h + + + Windows + true + RequireAdministrator + + + + + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + $(SolutionDir)Common\src + MultiThreaded + Use + pch.h + + + Windows + true + true + true + RequireAdministrator + + + + + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + $(SolutionDir)Common\src + MultiThreadedDebug + Use + pch.h + + + Windows + true + RequireAdministrator + + + + + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp17 + $(SolutionDir)Common\src + MultiThreaded + Use + pch.h + + + Windows + true + true + true + RequireAdministrator + + + + + + + + + {f364b2ab-f34a-4bcf-9362-22720020ddbf} + + + + + + + + + + + + + + + + + + Create + Create + + + + + + + \ No newline at end of file diff --git a/IntegrationWizard/IntegrationWizard.vcxproj.filters b/IntegrationWizard/IntegrationWizard.vcxproj.filters new file mode 100644 index 0000000..5266d91 --- /dev/null +++ b/IntegrationWizard/IntegrationWizard.vcxproj.filters @@ -0,0 +1,52 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Resource Files + + + + + Resource Files + + + + + Header Files + + + Header Files + + + Header Files + + + Resource Files + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/IntegrationWizard/Resource.rc b/IntegrationWizard/Resource.rc new file mode 100644 index 0000000..3093b7f --- /dev/null +++ b/IntegrationWizard/Resource.rc @@ -0,0 +1,79 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// CONFIG +// + +IDR_DEFAULT_CONFIG CONFIG ".\\Config.jsonc" + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_ICON1 ICON "D:\\Dev\\VisualStudioProjects\\Koalageddon\\icon.ico" + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/IntegrationWizard/resource.h b/IntegrationWizard/resource.h new file mode 100644 index 0000000..176c9aa --- /dev/null +++ b/IntegrationWizard/resource.h @@ -0,0 +1,17 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Resource.rc +// +#define IDR_DEFAULT_CONFIG 101 +#define IDI_ICON1 103 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 104 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/IntegrationWizard/src/IntegrationWizard.cpp b/IntegrationWizard/src/IntegrationWizard.cpp new file mode 100644 index 0000000..8437d12 --- /dev/null +++ b/IntegrationWizard/src/IntegrationWizard.cpp @@ -0,0 +1,165 @@ +#include "pch.h" +#include "IntegrationWizard.h" +#include "Logger.h" +#include "Config.h" +#include "constants.h" + +vector alteredPlatforms; + + +/* +Returns the path to original version.dll based on the architecture +of the provided process handle. +*/ +path getVersionDllPath(HANDLE hProcess) +{ + PWSTR rawPath; + auto folderID = is32bit(hProcess) ? FOLDERID_SystemX86 : FOLDERID_System; + SHGetKnownFolderPath(folderID, NULL, NULL, &rawPath); + auto systemPath = absolute(rawPath); + CoTaskMemFree(rawPath); + return systemPath / "version.dll"; +} + +// Source: https://docs.microsoft.com/en-us/windows/win32/psapi/enumerating-all-processes +void enumerateProcesses(function callback) +{ + DWORD aProcesses[1024], cbNeeded, cProcesses; + + if(!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)) + showFatalError("Failed to enumerate processes.", true); + + // Calculate how many process identifiers were returned. + cProcesses = cbNeeded / sizeof(DWORD); + + logger->debug("Found running processes:"); + + // Print the name and process identifier for each process. + for(DWORD i = 0; i < cProcesses; i++) + { + auto pid = aProcesses[i]; + if(pid == 0) + continue; + + // Get a handle to the process. + HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); + + if(hProcess == NULL) + continue; // Not a big deal, just skip it. + + try + { + auto processPath = getProcessPath(hProcess); + auto processName = processPath.filename().string(); + logger->debug("\tName: '{}', pid: {}", processName, pid); + + for(const auto& [key, platform] : config->platforms) + { + if(stringsAreEqual(processName, platform.process) && platform.enabled) + { + logger->info("Target process detected: '{}'", processName); + callback(hProcess, processPath, processName); + } + } + } catch(std::exception& ex) + { + logger->warn("Error in handling a process with PID: {}. Reason: {}", pid, ex.what()); + } + + + CloseHandle(hProcess); + } +} + +void installCallback(HANDLE hProcess, path processPath, string processName) +{ + try + { + logger->info("Installing platform integration"); + + auto originalDllPath = getVersionDllPath(hProcess); + auto originalVersionDllPath = processPath.parent_path() / "version_o.dll"; + logger->debug("Original DLL path: '{}', Destination: '{}'", originalDllPath.string(), originalVersionDllPath.string()); + + auto integrationDllPath = getWorkingDirPath() / (is32bit(hProcess) ? INTEGRATION_32 : INTEGRATION_64); + auto versionDLLPath = processPath.parent_path() / "version.dll"; + logger->debug("Integration DLL path: '{}', Destination: '{}'", integrationDllPath.string(), versionDLLPath.string()); + + // Terminate the process to release a possible lock on the files + killProcess(hProcess); + + copy_file(originalDllPath, originalVersionDllPath, copy_options::overwrite_existing); + copy_file(integrationDllPath, versionDLLPath, copy_options::overwrite_existing); + + alteredPlatforms.push_back(processName); + logger->info("Platform integration was successfully installed"); + + } catch(std::exception& ex) + { + showFatalError(fmt::format("Failed to install integrations: {}", ex.what()), false); + } +} + +void removeCallback(HANDLE hProcess, path processPath, string processName) +{ + try + { + logger->info("Removing platform integration"); + + auto versionDLLPath = stow((processPath.parent_path() / "version.dll").string()); + auto originalDllPath = stow((processPath.parent_path() / "version_o.dll").string()); + logger->debug(L"Version DLL path: '{}', Original DLL path: '{}'", versionDLLPath, originalDllPath); + + // Terminate the process to release a lock on the files + killProcess(hProcess, 250); + + DeleteFile(versionDLLPath.c_str()); + DeleteFile(originalDllPath.c_str()); + + alteredPlatforms.push_back(processName); + logger->info("Platform integration was successfully removed"); + + } catch(std::exception& ex) + { + showFatalError(fmt::format("Failed to remove integrations: {}", ex.what()), false); + } +} + +void showPostActionReport(Action action) +{ + if(alteredPlatforms.size() == 0) + { + showInfo("No target processes were found. No actions were taken.", "Nothing found", true); + } + else + { + string targets; + for(const auto& target : alteredPlatforms) + { + auto symbol = action == Action::INSTALL_INTEGRATIONS ? "+" : "-"; + targets += fmt::format("[{}] {}\n", symbol, target); + } + + auto actionStr = action == Action::INSTALL_INTEGRATIONS ? "installed" : "removed"; + auto message = fmt::format("The following target platforms integrations were sucessfully {}:\n\n{}", actionStr, targets); + showInfo(message, "Success"); + } +} + +void IntegrationWizard::install() +{ + logger->info("Installing integrations"); + + enumerateProcesses(installCallback); + + showPostActionReport(Action::INSTALL_INTEGRATIONS); +} + +void IntegrationWizard::remove() +{ + logger->info("Removing integrations"); + + enumerateProcesses(removeCallback); + + showPostActionReport(Action::REMOVE_INTEGRATIONS); +} diff --git a/IntegrationWizard/src/IntegrationWizard.h b/IntegrationWizard/src/IntegrationWizard.h new file mode 100644 index 0000000..3204d75 --- /dev/null +++ b/IntegrationWizard/src/IntegrationWizard.h @@ -0,0 +1,17 @@ +#pragma once + +namespace IntegrationWizard +{ + +void install(); +void remove(); + +} + +enum class Action +{ + NO_ACTION = 1000, + UNEXPECTED_ERROR = 1001, + INSTALL_INTEGRATIONS = 1002, + REMOVE_INTEGRATIONS = 1003, +}; diff --git a/IntegrationWizard/src/framework.h b/IntegrationWizard/src/framework.h new file mode 100644 index 0000000..fd05e2d --- /dev/null +++ b/IntegrationWizard/src/framework.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +#include +#pragma comment(lib, "comctl32.lib") +#if defined _M_IX86 +#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") +#elif defined _M_IA64 +#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"") +#elif defined _M_X64 +#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") +#else +#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") +#endif + +#include + +using std::function; diff --git a/IntegrationWizard/src/pch.cpp b/IntegrationWizard/src/pch.cpp new file mode 100644 index 0000000..1d9f38c --- /dev/null +++ b/IntegrationWizard/src/pch.cpp @@ -0,0 +1 @@ +#include "pch.h" diff --git a/IntegrationWizard/src/pch.h b/IntegrationWizard/src/pch.h new file mode 100644 index 0000000..8909fe2 --- /dev/null +++ b/IntegrationWizard/src/pch.h @@ -0,0 +1,3 @@ +#pragma once + +#include "framework.h" diff --git a/IntegrationWizard/src/winmain.cpp b/IntegrationWizard/src/winmain.cpp new file mode 100644 index 0000000..f466a33 --- /dev/null +++ b/IntegrationWizard/src/winmain.cpp @@ -0,0 +1,128 @@ +#include "pch.h" +#include "Logger.h" +#include "constants.h" +#include "IntegrationWizard.h" +#include "../resource.h" + +Action askForAction(HINSTANCE hInstance) +{ + TASKDIALOGCONFIG tdc = { sizeof(TASKDIALOGCONFIG) }; + int nClickedBtn; + auto szTitle = L"Koalageddon"; + auto szHeader = L"Welcome to the Koalageddon wizard. Please choose the desired action."; + LPCWSTR szBodyText = + L"The wizard will scan running processes to find target platforms. " \ + L"During installation/removal target processes will be terminated, " \ + L"so make sure to close all games and save all data."; + + TASKDIALOG_BUTTON aCustomButtons[] = { + { (int) Action::INSTALL_INTEGRATIONS, L"&Install platform integrations" }, + { (int) Action::REMOVE_INTEGRATIONS, L"&Remove platform integrations" } + }; + + tdc.hInstance = hInstance; + tdc.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_USE_COMMAND_LINKS | TDF_EXPAND_FOOTER_AREA; + tdc.pButtons = aCustomButtons; + tdc.cButtons = _countof(aCustomButtons); + tdc.pszWindowTitle = szTitle; + tdc.pszMainIcon = TD_INFORMATION_ICON; + tdc.pszMainInstruction = szHeader; + //tdc.pszContent = szBodyText; + tdc.pszExpandedInformation = szBodyText; + + if(SUCCEEDED(TaskDialogIndirect(&tdc, &nClickedBtn, NULL, NULL))) + { + logger->debug("Clicked button: {}", nClickedBtn); + + if(nClickedBtn == (int) Action::INSTALL_INTEGRATIONS || + nClickedBtn == (int) Action::REMOVE_INTEGRATIONS) + return (Action) nClickedBtn; + else + return Action::NO_ACTION; + } + else + { + return Action::UNEXPECTED_ERROR; + } + +} + +void fatalError(string message) +{ + message = fmt::format("{}. Error code: 0x{:X}", message, GetLastError()); + MessageBoxA(NULL, message.c_str(), "Fatal Error", MB_ICONERROR | MB_OK); + exit(1); +} + +void firstSetup() +{ + setReg(WORKING_DIR, getProcessPath().parent_path().c_str()); + + auto configPath = getWorkingDirPath() / L"Config.jsonc"; + + if(!std::filesystem::exists(configPath)) + { // Copy the default config is none was found + HRSRC hResource = FindResource(nullptr, MAKEINTRESOURCE(IDR_DEFAULT_CONFIG), L"CONFIG"); + if(hResource == NULL) + fatalError("Failed to find config resource"); + + HGLOBAL hMemory = LoadResource(nullptr, hResource); + if(hMemory == NULL) + fatalError("Failed to load config resource"); + + auto size = SizeofResource(nullptr, hResource); + auto dataPtr = LockResource(hMemory); + + std::ofstream configFile(configPath, std::ios::out | std::ios::binary); + if(!configFile.good()) + fatalError("Failed to open output file stream"); + + configFile.write((char*) dataPtr, size); + configFile.close(); + } +} + + +int APIENTRY wWinMain( + _In_ HINSTANCE hInstance, + _In_opt_ HINSTANCE hPrevInstance, + _In_ LPWSTR lpCmdLine, + _In_ int nCmdShow +) +{ + firstSetup(); + Logger::init("IntegrationWizard", true); + logger->info("Integration Wizard v{}", VERSION); + + // We need to disable WOW64 redirections because otherwise 32bit application + // uses SysWOW64 directory even if System32 was explicitly provided. + void* oldVal = NULL; + Wow64DisableWow64FsRedirection(&oldVal); + + auto action = askForAction(hInstance); + + switch(action) + { + case Action::UNEXPECTED_ERROR: + logger->error("Unexpected action result. Error code: 0x{:X}", GetLastError()); + exit(1); + break; + case Action::NO_ACTION: + logger->info("No action was taken. Terminating."); + exit(0); + break; + case Action::INSTALL_INTEGRATIONS: + IntegrationWizard::install(); + break; + case Action::REMOVE_INTEGRATIONS: + IntegrationWizard::remove(); + break; + default: + logger->error("Unexpected action result"); + exit(1); + } + + Wow64RevertWow64FsRedirection(oldVal); + return 0; +} + diff --git a/Koalageddon.sln b/Koalageddon.sln new file mode 100644 index 0000000..48e5069 --- /dev/null +++ b/Koalageddon.sln @@ -0,0 +1,81 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30804.86 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Injector", "Injector\Injector.vcxproj", "{5D2B330B-73E9-4B02-8203-BE7078DA646B}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Unlocker", "Unlocker\Unlocker.vcxproj", "{0AB35179-BF08-40C1-8961-0D6AEAF22770}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C813944E-EC8B-46E0-9251-D5856A1E2F06}" + ProjectSection(SolutionItems) = preProject + .gitignore = .gitignore + build_installer.bat = build_installer.bat + IntegrationWizard\Config.jsonc = IntegrationWizard\Config.jsonc + inno_setup.iss = inno_setup.iss + LICENSE.txt = LICENSE.txt + README.md = README.md + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Common", "Common\Common.vcxproj", "{F364B2AB-F34A-4BCF-9362-22720020DDBF}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Integration", "Integration\Integration.vcxproj", "{6B6F6E00-A196-4815-8D24-D9890798FD09}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "IntegrationWizard", "IntegrationWizard\IntegrationWizard.vcxproj", "{4E88D0ED-22DF-4DB8-985B-22B778059F11}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Debug|x64.ActiveCfg = Debug|x64 + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Debug|x64.Build.0 = Debug|x64 + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Debug|x86.ActiveCfg = Debug|Win32 + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Debug|x86.Build.0 = Debug|Win32 + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Release|x64.ActiveCfg = Release|x64 + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Release|x64.Build.0 = Release|x64 + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Release|x86.ActiveCfg = Release|Win32 + {5D2B330B-73E9-4B02-8203-BE7078DA646B}.Release|x86.Build.0 = Release|Win32 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Debug|x64.ActiveCfg = Debug|x64 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Debug|x64.Build.0 = Debug|x64 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Debug|x86.ActiveCfg = Debug|Win32 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Debug|x86.Build.0 = Debug|Win32 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Release|x64.ActiveCfg = Release|x64 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Release|x64.Build.0 = Release|x64 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Release|x86.ActiveCfg = Release|Win32 + {0AB35179-BF08-40C1-8961-0D6AEAF22770}.Release|x86.Build.0 = Release|Win32 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Debug|x64.ActiveCfg = Debug|x64 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Debug|x64.Build.0 = Debug|x64 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Debug|x86.ActiveCfg = Debug|Win32 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Debug|x86.Build.0 = Debug|Win32 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Release|x64.ActiveCfg = Release|x64 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Release|x64.Build.0 = Release|x64 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Release|x86.ActiveCfg = Release|Win32 + {F364B2AB-F34A-4BCF-9362-22720020DDBF}.Release|x86.Build.0 = Release|Win32 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Debug|x64.ActiveCfg = Debug|x64 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Debug|x64.Build.0 = Debug|x64 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Debug|x86.ActiveCfg = Debug|Win32 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Debug|x86.Build.0 = Debug|Win32 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Release|x64.ActiveCfg = Release|x64 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Release|x64.Build.0 = Release|x64 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Release|x86.ActiveCfg = Release|Win32 + {6B6F6E00-A196-4815-8D24-D9890798FD09}.Release|x86.Build.0 = Release|Win32 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Debug|x64.ActiveCfg = Debug|x64 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Debug|x64.Build.0 = Debug|x64 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Debug|x86.ActiveCfg = Debug|Win32 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Debug|x86.Build.0 = Debug|Win32 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Release|x64.ActiveCfg = Release|x64 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Release|x64.Build.0 = Release|x64 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Release|x86.ActiveCfg = Release|Win32 + {4E88D0ED-22DF-4DB8-985B-22B778059F11}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F89341C3-622D-4EE2-B1D8-25BCE64E1F13} + EndGlobalSection +EndGlobal diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..63a2560 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (C) 2021 by acidicoala + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..fbf9e4d --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ +# 🐨 Koalageddon 💥 +#### Legit DLC Unlocker for Steam, Epic & Origin +Welcome to the DreamAPI repository. +For user-friendly introduction or support, please check out the official forum thread. This document is meant for software developers. + +## 🗜 Solution Projects +#### 🧰 Common +This project is a static library that houses common functions of all other projects. For example, all projects need to access config file and loggin utilites, so they are defined in this module. + +#### 💉 Injector +This project is a simple DLL injector executable. The injector can be used as a command line utility that accepts 2 arguments: ID of the process which should be injected and DLL to inject. + +#### 🔗 Integration +This project is a dynamic library that pretends to be `version.dll`. Nothing much going on here except for loading of the unlocker module. + +#### 🧙🏼‍ Integration Wizard +This project is a trivial GUI utility that automatically installs the integration files and copies the original ones. The GUI is using [Task Dialog] available in Windows API. + +#### 🔓 Unlocker +This project is a dynamic library which performs the main function of Koalageddon - DLC unlocking. It monitors DRM DLLs using undocumented WinAPI functions and suspends new processes before injection using undocumented functions as well. Once target DLLs have been identified, appropriate functions are hooked using the great PolyHook 2 library. A total of 4 hooking techniques are used in this project. + +## 🛠 Dependencies +The solution uses a number of third party dependencies, which are available via [vcpkg]. +Projects in the solution are configured to use static libraries instead of dynamic. If you wish to build the solution yourself, you would need to install following libraries: + +* [PolyHook 2.0]: + ``` + vcpkg install polyhook2:x86-windows-static + vcpkg install polyhook2:x64-windows-static + ``` +* [WinReg]: + ``` + vcpkg install winreg:x86-windows-static + vcpkg install winreg:x64-windows-static + ``` +* [spdlog]: + ``` + vcpkg install spdlog:x86-windows-static + vcpkg install spdlog:x64-windows-static + ``` +* [nlohmann JSON]: + ``` + vcpkg install nlohmann-json:x86-windows-static + vcpkg install nlohmann-json:x64-windows-static + ``` +* [TinyXML-2] + ``` + vcpkg install tinyxml2:x86-windows-static + vcpkg install tinyxml2:x64-windows-static + ``` +* [C++ Requests] + ``` + vcpkg install cpr:x86-windows-static + vcpkg install cpr:x64-windows-static + ``` + +You can verify installations via `vcpkg list` + +## 📄 License +This software is licensed under [Zero Clause BSD] license, terms of which are available in [LICENSE.txt] + +___ + +[Task Dialog]: https://docs.microsoft.com/en-us/windows/win32/controls/task-dialogs-overview#:~:text=A%20task%20dialog%20is%20a,features%20than%20a%20message%20box. +[vcpkg]: https://github.com/Microsoft/vcpkg#quick-start-windows +[spdlog]: https://github.com/gabime/spdlog +[nlohmann JSON]: https://github.com/nlohmann/json/ +[PolyHook 2.0]: https://github.com/stevemk14ebr/PolyHook_2_0 +[WinReg]: https://github.com/GiovanniDicanio/WinReg +[C++ Requests]: https://github.com/whoshuu/cpr +[TinyXML-2]: https://github.com/leethomason/tinyxml2 + +[Zero Clause BSD]: https://choosealicense.com/licenses/0bsd/ +[LICENSE.txt]: ./LICENSE.txt diff --git a/Unlocker/Unlocker.vcxproj b/Unlocker/Unlocker.vcxproj new file mode 100644 index 0000000..7bc958d --- /dev/null +++ b/Unlocker/Unlocker.vcxproj @@ -0,0 +1,260 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 16.0 + Win32Proj + {0ab35179-bf08-40c1-8961-0d6aeaf22770} + Hooker + 10.0 + Unlocker + + + + DynamicLibrary + true + v142 + Unicode + + + DynamicLibrary + false + v142 + true + Unicode + + + DynamicLibrary + true + v142 + Unicode + + + DynamicLibrary + false + v142 + true + Unicode + + + + + + + + + + + + + + + + + + + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + false + $(SolutionDir)_Build\$(Configuration)\ + $(ProjectDir)_Build\$(Configuration)\$(Platform)\ + $(ProjectName)$(PlatformArchitecture) + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + true + $(PlatformTarget)-windows-static + + + + Level3 + true + WIN32;_DEBUG;_WINDOWS;_USRDLL;_SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreadedDebug + $(SolutionDir)Common\src;$(ProjectDir)src + + + + + Windows + true + false + ntdll.lib;%(AdditionalDependencies) + %(AdditionalLibraryDirectories) + + + + + Level3 + true + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;_SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreaded + $(SolutionDir)Common\src;$(ProjectDir)src + + + Windows + true + true + true + false + ntdll.lib;%(AdditionalDependencies) + %(AdditionalLibraryDirectories) + + + + + Level3 + true + _DEBUG;HOOKER_EXPORTS;_WINDOWS;_USRDLL;_SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreadedDebug + $(SolutionDir)Common\src;$(ProjectDir)src + + + + + Windows + true + false + ntdll.lib;%(AdditionalDependencies) + %(AdditionalLibraryDirectories) + + + + + Level3 + true + true + true + NDEBUG;_WINDOWS;_USRDLL;_SILENCE_CXX17_C_HEADER_DEPRECATION_WARNING;%(PreprocessorDefinitions) + true + Use + pch.h + stdcpp17 + MultiThreaded + $(SolutionDir)Common\src;$(ProjectDir)src + + + Windows + true + true + true + false + ntdll.lib;%(AdditionalDependencies) + %(AdditionalLibraryDirectories) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + + + + {f364b2ab-f34a-4bcf-9362-22720020ddbf} + + + + + + \ No newline at end of file diff --git a/Unlocker/Unlocker.vcxproj.filters b/Unlocker/Unlocker.vcxproj.filters new file mode 100644 index 0000000..8aef070 --- /dev/null +++ b/Unlocker/Unlocker.vcxproj.filters @@ -0,0 +1,158 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {2f8b53cc-53f7-4c05-b716-9a9dce829c39} + + + {98be62ef-dbe5-4a06-8a7d-ac1b58d5b605} + + + {5965e26f-a8eb-4666-9ceb-f8518526d6b6} + + + {9377a090-30bd-4d9d-9536-e01ec9e80c6b} + + + {57aa9d64-b2f5-43dd-a97e-06c77c18d5cf} + + + {a416250b-0b77-4aa1-a50e-d7e34fa6b974} + + + {a09035ba-a888-4765-86c3-5d1df17bdf5a} + + + {3fa38e81-3df5-4991-ab87-30a327edacfe} + + + {e6dd8cef-5536-4417-88af-da4931ab890d} + + + {dead7396-6b35-46bc-9107-d06731daa0cc} + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files\platforms\epic + + + Header Files\platforms\epic + + + Header Files\platforms\epic + + + Header Files\platforms\epic + + + Header Files\platforms\epic + + + Header Files\platforms\epic + + + Header Files\platforms\epic + + + Header Files\platforms\steam + + + Header Files\platforms\steam + + + Header Files\platforms\steam + + + Header Files + + + Header Files\platforms\origin + + + Header Files\platforms\origin + + + Header Files\platforms\ubisoft + + + Header Files\platforms\ubisoft + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files\platforms\epic + + + Source Files\platforms\epic + + + Source Files + + + Source Files\platforms\steam + + + Source Files\platforms\steam + + + Source Files\platforms\origin + + + Source Files\platforms\origin + + + Source Files\platforms\ubisoft + + + Source Files\platforms\ubisoft + + + \ No newline at end of file diff --git a/Unlocker/src/DLLMonitor.cpp b/Unlocker/src/DLLMonitor.cpp new file mode 100644 index 0000000..4c2ed2d --- /dev/null +++ b/Unlocker/src/DLLMonitor.cpp @@ -0,0 +1,152 @@ +#include "pch.h" +#include "DLLMonitor.h" +#include "ntapi.h" +#include "constants.h" +#include "platforms/epic/Epic.h" +#include "platforms/steam/Steam.h" +#include +#include + + +_LdrRegisterDllNotification LdrRegisterDllNotification = NULL; +_LdrUnregisterDllNotification LdrUnregisterDllNotification = NULL; + +vector> platforms; + +bool getNtFunctions() +{ + HMODULE hNtDll = GetModuleHandle(L"ntdll.dll"); + if(hNtDll == NULL) + { + logger->error("Failed to get a handle for ntdll.dll module. Error code: {}", GetLastError()); + return false; + } + LdrRegisterDllNotification = (_LdrRegisterDllNotification) GetProcAddress(hNtDll, "LdrRegisterDllNotification"); + LdrUnregisterDllNotification = (_LdrUnregisterDllNotification) GetProcAddress(hNtDll, "LdrUnregisterDllNotification"); + + if(!LdrRegisterDllNotification || !LdrUnregisterDllNotification) + { + logger->error("Some ntdll procedures were not found. Error code: {}", GetLastError()); + return false; + } + + return true; +} + + +void CALLBACK dllCallback(ULONG NotificationReason, PLDR_DLL_NOTIFICATION_DATA NotificationData, PVOID Context) +{ + if(NotificationReason == LDR_DLL_NOTIFICATION_REASON_LOADED) + { + auto dllName = wstring(NotificationData->Loaded.BaseDllName->Buffer); + + // This log line sometimes crashes some games on Steam >:( + // logger->debug(L"DLL has been loaded: {}", dllName); + + if(dllName == EOSSDK) + { + logger->info(L"Epic Games DLL has been detected"); + platforms.push_back(make_unique(NotificationData->Loaded.FullDllName->Buffer)); + platforms.back()->init(); + } + else if(dllName == STEAMAPI) + { + logger->info(L"Steam DLL has been detected"); + platforms.push_back(make_unique(NotificationData->Loaded.FullDllName->Buffer)); + platforms.back()->init(); + } + else if(dllName == ORIGINCLIENT) + { + logger->info(L"Origin DLL has been detected"); + platforms.push_back(make_unique(NotificationData->Loaded.FullDllName->Buffer)); + platforms.back()->init(); + } + else if(dllName == UPLAY_R2) + { + logger->info(L"Ubisoft DLL has been detected"); + platforms.push_back(make_unique(NotificationData->Loaded.FullDllName->Buffer)); + platforms.back()->init(); + } + } +} + + +void checkLoadedDlls() +{ + logger->debug("Checking already loaded DLLs"); + + HMODULE handle; + + if(handle = GetModuleHandle(EOSSDK)) + { + logger->info("Epic DLL is already loaded"); + platforms.push_back(make_unique(handle)); + platforms.back()->init(); + } + else if(handle = GetModuleHandle(STEAMAPI)) + { + logger->info("Steam DLL is already loaded"); + platforms.push_back(make_unique(handle)); + platforms.back()->init(); + } + else if(handle = GetModuleHandle(ORIGINCLIENT)) + { + logger->info(L"Origin DLL is already loaded"); + platforms.push_back(make_unique(handle)); + platforms.back()->init(); + } + else if(handle = GetModuleHandle(UPLAY_R2)) + { + logger->info(L"Ubisoft DLL is already loaded"); + platforms.push_back(make_unique(handle)); + platforms.back()->init(); + } + else + { + return; + } + + CloseHandle(handle); +} + +PVOID cookie = NULL; + +void DLLMonitor::init() +{ + logger->debug("Initializing DLL monitor"); + + if(!getNtFunctions()) + { + return; + } + + auto status = LdrRegisterDllNotification(0, &dllCallback, NULL, &cookie); + if(status != STATUS_SUCCESS) + { + logger->error("Failed to register DLL notifications. Status code: {}", (unsigned long) status); + } + else + { + logger->debug("Registered DLL listener"); + } + + checkLoadedDlls(); + + logger->debug("DLL monitor was successfully initialized"); +} + +void DLLMonitor::shutdown() +{ + logger->debug("Shutting down DLL monitor"); + + for(auto& platform : platforms) + { + platform->shutdown(); + } + + platforms.clear(); + + LdrUnregisterDllNotification(cookie); + + logger->debug("DLL monitor was successfully shut down"); +} \ No newline at end of file diff --git a/Unlocker/src/DLLMonitor.h b/Unlocker/src/DLLMonitor.h new file mode 100644 index 0000000..12472bc --- /dev/null +++ b/Unlocker/src/DLLMonitor.h @@ -0,0 +1,9 @@ +#pragma once + +namespace DLLMonitor +{ + +void init(); +void shutdown(); + +} diff --git a/Unlocker/src/ProcessHooker.cpp b/Unlocker/src/ProcessHooker.cpp new file mode 100644 index 0000000..ca3edd4 --- /dev/null +++ b/Unlocker/src/ProcessHooker.cpp @@ -0,0 +1,262 @@ +#include "pch.h" +#include "ProcessHooker.h" +#include "util.h" +#include "Logger.h" +#include "Config.h" +#include "constants.h" +#include "hook_util.h" + +typedef LONG NTSTATUS; + +// Undocumented functions + +#pragma comment(lib,"ntdll.lib") +EXTERN_C NTSTATUS NTAPI NtSuspendProcess(HANDLE ProcessHandle); + +#pragma comment(lib,"ntdll.lib") +EXTERN_C NTSTATUS NTAPI NtResumeProcess(HANDLE ProcessHandle); + + +uint64_t createProcTrampoline = NULL; + +void inject(std::wstring wPID, uint64_t funcAddr) +{ + DWORD PID = std::stoi(wPID); + + // Determine the target executable's architecture to launch correponding injector + bool is32 = is32bit(PID); + + auto workingDir = getWorkingDirPath(); + auto injectorPath = workingDir / (is32 ? INJECTOR_32 : INJECTOR_64); + auto unlockerPath = workingDir / (is32 ? UNLOCKER_32 : UNLOCKER_64); + + // Validate paths + if(!std::filesystem::exists(injectorPath)) + { + logger->error(L"Injector exe was not found at: {}", injectorPath.c_str()); + return; + } + if(!std::filesystem::exists(unlockerPath)) + { + logger->error(L"Unlocker dll was not found at: {}", unlockerPath.c_str()); + return; + } + + auto args = fmt::format(L"\"{}\" {} \"{}\"", injectorPath.c_str(), wPID, unlockerPath.c_str()); + logger->debug(L"Starting Injector with cmdline: {}", args); + + // Need to make a non const copy since CreateProcessW might modify the argument + auto size = args.size() + 1; + auto cArgs = new WCHAR[size]; + wcscpy_s(cArgs, size, args.c_str()); + cArgs[size - 1] = '\0'; + + // additional information + STARTUPINFO si = {}; + PROCESS_INFORMATION pi = {}; + + // We make sure to call the original function, to avoid recursively calling ourselves + if(funcAddr == 0) + funcAddr = (uint64_t) &CreateProcessW; + + auto Original_CreateProcessW = PLH::FnCast(funcAddr, &CreateProcessW); + + auto success = Original_CreateProcessW( + injectorPath.c_str(), // the path + cArgs, // Command line + NULL, // Process handle not inheritable + NULL, // Thread handle not inheritable + FALSE, // Set handle inheritance to FALSE + 0, // No creation flags + NULL, // Use parent's environment block + NULL, // Use parent's starting directory + &si, // Pointer to STARTUPINFO structure + &pi // Pointer to PROCESS_INFORMATION structure (removed extra parentheses) + ); + + if(!success) + { + logger->error("Failed to start Injector process. Error code: 0x{:X}", GetLastError()); + return; + } + + delete[] cArgs; + + auto hProcess = pi.hProcess; + if(hProcess == NULL) + { + logger->error("Process handle is NULL. Error code: 0x{:X}", GetLastError()); + return; + } + + // Wait until injector process exits + WaitForSingleObject(hProcess, INFINITE); + + DWORD exit_code; + GetExitCodeProcess(hProcess, &exit_code); + + if(exit_code == 0) + { + logger->info(L"Successfully injected DLL into: {}", getProcessName(PID)); + } + else + { + logger->error("Failed to inject DLL. Exit code: 0x{:X}", exit_code); + } + + // Close process and thread handles + CloseHandle(hProcess); + + if(pi.hThread != NULL) + CloseHandle(pi.hThread); +} + + +void injectIfNecessary(wstring cmdLine, LPPROCESS_INFORMATION lpProcessInformation) +{ + std::wsmatch match; + std::wregex pattern(LR"(\w+\.exe)"); + + if(!regex_search(cmdLine.cbegin(), cmdLine.cend(), match, pattern)) + { + logger->debug("Failed to find exe name in the command line"); + return; + } + + auto newProcName = wtos(match.str()); + + // Iterate over platforms + for(const auto& [key, platform] : config->platforms) + { + if(stringsAreEqual(getProcessPath().filename().string(), platform.process)) + { + // This is a platform process + if(!platform.replicate) + { + // Do not inject since platform is configured with disabled replication + logger->debug("Skipping injection since platform is set to disable replication"); + return; + } + for(const auto& ignoredProcess : platform.ignore) + { + if(stringsAreEqual(newProcName, ignoredProcess)) + { + // Do not inject since the process is ignored for this platforms + logger->debug("Skipping injection since the new process is ignored for this platform"); + return; + } + } + } + } + + // Iterate over ignored processes + for(const auto& ignoredProcess : config->ignore) + { + if(ignoredProcess == newProcName) + { + // Don't inject the DLL, just let it run as usual + logger->debug("Skipping injection for the globally ignored process: {}", ignoredProcess); + return; + } + } + + // Iterate over terminate processes + for(const auto& terminatedProcess : config->terminate) + { + if(terminatedProcess == newProcName) + { + // Kill the process if it is in the terminate list + logger->warn("Terminating the process: {}", terminatedProcess); + killProcess(lpProcessInformation->hProcess); + return; + } + } + + // At this point we are sure that we want to inject the DLL + + inject(std::to_wstring(lpProcessInformation->dwProcessId), createProcTrampoline); +} + +/** + * We hook CreateProcessW to catch any new process that the current process creates, + * so that we could inject unlocker there too. This is effectively a recursive + * DLL injection which makes sure that we always reach the game executable, + * even if it was started by a chain of launchers. + */ +BOOL WINAPI Hooked_CreateProcessW( + LPCWSTR lpApplicationName, + LPWSTR lpCommandLine, + LPSECURITY_ATTRIBUTES lpProcessAttributes, + LPSECURITY_ATTRIBUTES lpThreadAttributes, + BOOL bInheritHandles, + DWORD dwCreationFlags, + LPVOID lpEnvironment, + LPCWSTR lpCurrentDirectory, + LPSTARTUPINFOW lpStartupInfo, + LPPROCESS_INFORMATION lpProcessInformation +) +{ + std::wstring appName(L""); + std::wstring cmdLine(L""); + + if(lpApplicationName != NULL) + appName = lpApplicationName; + + if(lpCommandLine != NULL) + cmdLine = lpCommandLine; + + // Get the original function + static auto Original_CreateProcessW = PLH::FnCast(createProcTrampoline, &CreateProcessW); + + // Call the original function + auto result = Original_CreateProcessW( + lpApplicationName, + lpCommandLine, + lpProcessAttributes, + lpThreadAttributes, + bInheritHandles, + dwCreationFlags, + lpEnvironment, + lpCurrentDirectory, + lpStartupInfo, + lpProcessInformation + ); + + logger->debug(L"CreateProcessW -> PID: {}, command line: {}", lpProcessInformation->dwProcessId, cmdLine); + + if(result == FALSE) + return result; // Some app made a messed up WINAPI call. Nothing to do for us here. + + NtSuspendProcess(lpProcessInformation->hProcess); + + injectIfNecessary(cmdLine, lpProcessInformation); + + NtResumeProcess(lpProcessInformation->hProcess); + + return result; +} +Detour detour((char*) &CreateProcessW, (char*) &Hooked_CreateProcessW, &createProcTrampoline, disassembler); + +void ProcessHooker::init() +{ + logger->debug("Setting up process hooks"); + + if(detour.hook()) + { + logger->debug("Process hooks were successfully set up"); + } + else + { + logger->error("Failed to hook CreateProcessW"); + } + +} + +void ProcessHooker::shutdown() +{ + logger->debug("Removing process hooks"); + + detour.unHook(); + + logger->debug("Process hooks were successfully removed"); +} diff --git a/Unlocker/src/ProcessHooker.h b/Unlocker/src/ProcessHooker.h new file mode 100644 index 0000000..db09739 --- /dev/null +++ b/Unlocker/src/ProcessHooker.h @@ -0,0 +1,9 @@ +#pragma once + +namespace ProcessHooker +{ + +void init(); +void shutdown(); + +} diff --git a/Unlocker/src/Unlocker.cpp b/Unlocker/src/Unlocker.cpp new file mode 100644 index 0000000..0b4ba71 --- /dev/null +++ b/Unlocker/src/Unlocker.cpp @@ -0,0 +1,51 @@ +#include "pch.h" +#include "Unlocker.h" +#include "constants.h" +#include "constants.h" +#include "DLLMonitor.h" +#include "ProcessHooker.h" +#include "Config.h" + +static bool initialized = false; + +void Unlocker::init(HMODULE hModule) +{ + // Lock the thread to prevent init deadlock + static std::mutex mutex; + const std::lock_guard lock(mutex); + + if(initialized) + return; + + DisableThreadLibraryCalls(hModule); + + Config::init(); + + Logger::init(UNLOCKER_NAME, true); + + logger->info("Unlocker v{}", VERSION); + logger->info(L"Hooking into \"{}\"", getCurrentModuleName()); + + DLLMonitor::init(); + ProcessHooker::init(); + + initialized = true; + logger->debug("Unlocker initialization complete"); +} + +void Unlocker::shutdown() +{ + static std::mutex mutex; + const std::lock_guard lock(mutex); + + if(!initialized) + return; + + logger->debug("Unlocker shutting down"); + + DLLMonitor::shutdown(); + ProcessHooker::shutdown(); + + initialized = false; + logger->debug("Unlocker was successfully shut down"); +} diff --git a/Unlocker/src/Unlocker.h b/Unlocker/src/Unlocker.h new file mode 100644 index 0000000..18866bd --- /dev/null +++ b/Unlocker/src/Unlocker.h @@ -0,0 +1,10 @@ +#pragma once +#include "framework.h" + +namespace Unlocker +{ + +void init(HMODULE hModule); +void shutdown(); + +} diff --git a/Unlocker/src/dllmain.cpp b/Unlocker/src/dllmain.cpp new file mode 100644 index 0000000..15c1f3a --- /dev/null +++ b/Unlocker/src/dllmain.cpp @@ -0,0 +1,17 @@ +#include "pch.h" +#include "Unlocker.h" + +BOOL WINAPI DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) +{ + switch(ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + Unlocker::init(hModule); + break; + case DLL_PROCESS_DETACH: + Unlocker::shutdown(); + break; + } + + return TRUE; +} diff --git a/Unlocker/src/framework.h b/Unlocker/src/framework.h new file mode 100644 index 0000000..b8ad5bd --- /dev/null +++ b/Unlocker/src/framework.h @@ -0,0 +1,19 @@ +#pragma once +#include + +#include +#include + +// Disable 3rd party library warnings +#pragma warning(push) +#pragma warning(disable: ALL_CODE_ANALYSIS_WARNINGS) + +#include +#include +#include "polyhook2/PE/EatHook.hpp" +#include "polyhook2/PE/IatHook.hpp" +#include +#include +#include + +#pragma warning(pop) diff --git a/Unlocker/src/hook_util.cpp b/Unlocker/src/hook_util.cpp new file mode 100644 index 0000000..1af0d33 --- /dev/null +++ b/Unlocker/src/hook_util.cpp @@ -0,0 +1,8 @@ +#include "pch.h" +#include "hook_util.h" + +#ifdef _WIN64 +PLH::CapstoneDisassembler disassembler(PLH::Mode::x64); +#else +PLH::CapstoneDisassembler disassembler(PLH::Mode::x86); +#endif diff --git a/Unlocker/src/hook_util.h b/Unlocker/src/hook_util.h new file mode 100644 index 0000000..6f6afc9 --- /dev/null +++ b/Unlocker/src/hook_util.h @@ -0,0 +1,42 @@ +#pragma once +#include "framework.h" + +#ifdef _WIN64 +typedef PLH::x64Detour Detour; +#else +typedef PLH::x86Detour Detour; +#endif + +extern PLH::CapstoneDisassembler disassembler; + +/** + * By default, virtual functions are declared with __thiscall + * convention, which is normal since they are class members. + * But it presents an issue for us, since we cannot pass *this + * pointer as a function argument. This is because *this + * pointer is passed via register ECX in __thiscall + * convention. Hence, to resolve this issue we declare our + * hooked functions with __fastcall convention, to trick + * the compiler into reading ECX & EDX registers as 1st + * and 2nd function arguments respectively. Similarly, __fastcall + * makes the compiler push the first argument into the ECX register, + * which mimics the __thiscall calling convention. Register EDX + * is not used anywhere in this case, but we still pass it along + * to conform to the __fastcall convention. This all applies + * to the x86 architecture. + * + * In x86-64 however, there is only one calling convention, + * so __fastcall is simply ignored. However, RDX in this case + * will store the 1st actual argument to the function, so we + * have to omit it from the function signature. + * + * The macros below implement the above-mentioned considerations. + */ + +#ifdef _WIN64 +#define PARAMS(...) void* RCX, ##__VA_ARGS__ +#define ARGS(...) RCX, ##__VA_ARGS__ +#else +#define PARAMS(...) void* ECX, void* EDX, ##__VA_ARGS__ +#define ARGS(...) ECX, EDX, ##__VA_ARGS__ +#endif diff --git a/Unlocker/src/ntapi.h b/Unlocker/src/ntapi.h new file mode 100644 index 0000000..18a80ea --- /dev/null +++ b/Unlocker/src/ntapi.h @@ -0,0 +1,76 @@ +#pragma once + +// Source: https://github.com/blaquee/dllnotif/blob/master/LdrDllNotification/ntapi.h + +#include + +typedef __success(return >= 0) LONG NTSTATUS; + +#ifndef NT_STATUS_OK +#define NT_STATUS_OK 0 +#endif + + +#define STATUS_SUCCESS ((NTSTATUS)0) +#define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001) +#define STATUS_PROCEDURE_NOT_FOUND ((NTSTATUS)0xC000007A) +#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004) +#define STATUS_NOT_FOUND ((NTSTATUS)0xC0000225) +#define STATUS_THREAD_IS_TERMINATING ((NTSTATUS)0xc000004b) +#define STATUS_NOT_SUPPORTED ((NTSTATUS)0xC00000BB) + +enum LDR_DLL_NOTIFICATION_REASON +{ + LDR_DLL_NOTIFICATION_REASON_LOADED = 1, + LDR_DLL_NOTIFICATION_REASON_UNLOADED = 2, +}; + +typedef struct tag_UNICODE_STRING +{ + USHORT Length; + USHORT MaximumLength; + PWSTR Buffer; +} __UNICODE_STRING, * PCUNICODE_STRING; // Removed * PUNICODE_STRING to avoid conflicts with PLH's PEB.hpp + +typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA +{ + ULONG Flags; //Reserved. + PCUNICODE_STRING FullDllName; //The full path name of the DLL module. + PCUNICODE_STRING BaseDllName; //The base file name of the DLL module. + PVOID DllBase; //A pointer to the base address for the DLL in memory. + ULONG SizeOfImage; //The size of the DLL image, in bytes. +} LDR_DLL_LOADED_NOTIFICATION_DATA, * PLDR_DLL_LOADED_NOTIFICATION_DATA; + +typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA +{ + ULONG Flags; //Reserved. + PCUNICODE_STRING FullDllName; //The full path name of the DLL module. + PCUNICODE_STRING BaseDllName; //The base file name of the DLL module. + PVOID DllBase; //A pointer to the base address for the DLL in memory. + ULONG SizeOfImage; //The size of the DLL image, in bytes. +} LDR_DLL_UNLOADED_NOTIFICATION_DATA, * PLDR_DLL_UNLOADED_NOTIFICATION_DATA; + +typedef union _LDR_DLL_NOTIFICATION_DATA +{ + LDR_DLL_LOADED_NOTIFICATION_DATA Loaded; + LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded; +} LDR_DLL_NOTIFICATION_DATA, * PLDR_DLL_NOTIFICATION_DATA; +typedef const LDR_DLL_NOTIFICATION_DATA* PCLDR_DLL_NOTIFICATION_DATA; + + +typedef VOID(CALLBACK* PLDR_DLL_NOTIFICATION_FUNCTION)( + _In_ ULONG NotificationReason, + _In_ PLDR_DLL_NOTIFICATION_DATA NotificationData, + _In_opt_ PVOID Context +); + +typedef NTSTATUS(NTAPI* _LdrRegisterDllNotification)( + _In_ ULONG Flags, + _In_ PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction, + _In_opt_ PVOID Context, + _Out_ PVOID* cookie +); + +typedef NTSTATUS(NTAPI* _LdrUnregisterDllNotification)( + _In_ PVOID cookie +); diff --git a/Unlocker/src/pch.cpp b/Unlocker/src/pch.cpp new file mode 100644 index 0000000..64b7eef --- /dev/null +++ b/Unlocker/src/pch.cpp @@ -0,0 +1,5 @@ +// pch.cpp: source file corresponding to the pre-compiled header + +#include "pch.h" + +// When you are using pre-compiled headers, this source file is necessary for compilation to succeed. diff --git a/Unlocker/src/pch.h b/Unlocker/src/pch.h new file mode 100644 index 0000000..c9c7883 --- /dev/null +++ b/Unlocker/src/pch.h @@ -0,0 +1,2 @@ +#pragma once +#include "framework.h" diff --git a/Unlocker/src/platforms/BasePlatform.cpp b/Unlocker/src/platforms/BasePlatform.cpp new file mode 100644 index 0000000..5219d90 --- /dev/null +++ b/Unlocker/src/platforms/BasePlatform.cpp @@ -0,0 +1,86 @@ +#include "pch.h" +#include "BasePlatform.h" + +BasePlatform::BasePlatform(const HMODULE handle) +{ + this->handle = handle; + + auto buffer = new WCHAR[MAX_PATH]; + GetModuleBaseName(GetCurrentProcess(), handle, buffer, MAX_PATH); + this->moduleName = wtos(wstring(buffer)); + delete[] buffer; +} + +BasePlatform::BasePlatform(const wstring& fullDllName) +{ + moduleName = wtos(fullDllName); + + auto handle = GetModuleHandle(fullDllName.c_str()); + if(handle == NULL) + { + logger->error(L"Failed to get a handle to the module: {}", fullDllName); + return; + } + + this->handle = handle; +} + +void BasePlatform::installDetourHook(Hooks& hooks, void* hookedFunc, const char* funcName) +{ + static std::mutex mutex; + const std::lock_guard lock(mutex); + + if(auto original_func_address = GetProcAddress(handle, funcName)) + { + hooks.push_back(make_unique + ((char*) original_func_address, (char*) hookedFunc, &trampolineMap[funcName], disassembler) + ); + + if(hooks.back()->hook()) + { + logger->debug("Hooked \"{}\" via Detour.", funcName); + } + else + { + hooks.pop_back(); + logger->warn("Failed to hook \"{}\" via Detour. Trying with IAT.", funcName); + installIatHook(hooks, hookedFunc, funcName); + } + } +} + +void BasePlatform::installIatHook(Hooks& hooks, void* hookedFunc, const char* funcName) +{ + hooks.push_back(make_unique + (moduleName, funcName, (char*) hookedFunc, &trampolineMap[funcName], L"") + ); + + if(hooks.back()->hook()) + { + logger->debug("Hooked \"{}\" via IAT", funcName); + } + else + { + hooks.pop_back(); + logger->warn("Failed to hook \"{}\" via IAT. Trying with EAT.", funcName); + installEatHook(hooks, hookedFunc, funcName); + } +} + +void BasePlatform::installEatHook(Hooks& hooks, void* hookedFunc, const char* funcName) +{ + hooks.push_back(make_unique + (funcName, stow(moduleName), (char*) hookedFunc, &trampolineMap[funcName]) + ); + + if(hooks.back()->hook()) + { + logger->debug("Hooked \"{}\" via EAT", funcName); + } + else + { + hooks.pop_back(); + logger->error("Failed to hook \"{}\" via EAT.", funcName); + } +} + diff --git a/Unlocker/src/platforms/BasePlatform.h b/Unlocker/src/platforms/BasePlatform.h new file mode 100644 index 0000000..7fbfd43 --- /dev/null +++ b/Unlocker/src/platforms/BasePlatform.h @@ -0,0 +1,34 @@ +#pragma once +#include "util.h" +#include "hook_util.h" + +typedef vector> Hooks; + +class BasePlatform +{ +protected: + string moduleName; + HMODULE handle = NULL; + bool initialized = false; + + // To learn the basics of each type of hook, you can consult this article by the + // author of the hooking library that is used by this projet: PolyHook 2. + // The article was written for the v1 of the library, but the principles are the same in v2. + // https://www.codeproject.com/articles/1100579/polyhook-the-cplusplus-x-x-hooking-library + void installDetourHook(Hooks& hooks, void* hookedFunc, const char* funcName); + void installIatHook(Hooks& hooks, void* hookedFunc, const char* funcName); + void installEatHook(Hooks& hooks, void* hookedFunc, const char* funcName); + +public: + // we can safely store original functions from all platforms + // in the corresponding single static container. + inline static map trampolineMap; + inline static map origVFuncMap; + + BasePlatform() = delete; + BasePlatform(const HMODULE handle); + BasePlatform(const wstring& fullDllName); + + virtual void init() = 0; + virtual void shutdown() = 0; +}; diff --git a/Unlocker/src/platforms/epic/Epic.cpp b/Unlocker/src/platforms/epic/Epic.cpp new file mode 100644 index 0000000..58a198a --- /dev/null +++ b/Unlocker/src/platforms/epic/Epic.cpp @@ -0,0 +1,41 @@ +#include "pch.h" +#include "Epic.h" +#include "util.h" +#include "constants.h" +#include "eos_hooks.h" + +// Macro to avoid repetition +# define HOOK(FUNC) installDetourHook(hooks, FUNC, STR_##FUNC) + +void Epic::init() +{ + if(initialized || handle == NULL) + return; + + logger->debug("Initializing Epic platform"); + + HOOK(EOS_Ecom_QueryOwnership); + HOOK(EOS_Ecom_QueryEntitlements); + HOOK(EOS_Ecom_GetEntitlementsCount); + HOOK(EOS_Ecom_CopyEntitlementByIndex); + HOOK(EOS_Ecom_Entitlement_Release); + + logger->info("Epic platform was initialized"); + initialized = true; +} + +void Epic::shutdown() +{ + if(!initialized) + return; + + logger->debug("Shutting down Epic platform"); + + for(auto& hook : hooks) + { + hook->unHook(); + } + hooks.clear(); + + logger->debug("Epic platform was shut down"); +} diff --git a/Unlocker/src/platforms/epic/Epic.h b/Unlocker/src/platforms/epic/Epic.h new file mode 100644 index 0000000..26077bd --- /dev/null +++ b/Unlocker/src/platforms/epic/Epic.h @@ -0,0 +1,29 @@ +#pragma once + +#include "platforms/BasePlatform.h" +#include "util.h" + +#ifdef _WIN64 +constexpr auto STR_EOS_Ecom_QueryOwnership = "EOS_Ecom_QueryOwnership"; +constexpr auto STR_EOS_Ecom_QueryEntitlements = "EOS_Ecom_QueryEntitlements"; +constexpr auto STR_EOS_Ecom_GetEntitlementsCount = "EOS_Ecom_GetEntitlementsCount"; +constexpr auto STR_EOS_Ecom_CopyEntitlementByIndex = "EOS_Ecom_CopyEntitlementByIndex"; +constexpr auto STR_EOS_Ecom_Entitlement_Release = "EOS_Ecom_Entitlement_Release"; +#else +constexpr auto STR_EOS_Ecom_QueryOwnership = "_EOS_Ecom_QueryOwnership@16"; +constexpr auto STR_EOS_Ecom_QueryEntitlements = "_EOS_Ecom_QueryEntitlements@16"; +constexpr auto STR_EOS_Ecom_GetEntitlementsCount = "_EOS_Ecom_GetEntitlementsCount@8"; +constexpr auto STR_EOS_Ecom_CopyEntitlementByIndex = "_EOS_Ecom_CopyEntitlementByIndex@12"; +constexpr auto STR_EOS_Ecom_Entitlement_Release = "_EOS_Ecom_Entitlement_Release@4"; +#endif + +class Epic : public BasePlatform +{ +public: + using BasePlatform::BasePlatform; + + inline static Hooks hooks; + + void init() override; + void shutdown() override; +}; diff --git a/Unlocker/src/platforms/epic/eos_base.h b/Unlocker/src/platforms/epic/eos_base.h new file mode 100644 index 0000000..20e9453 --- /dev/null +++ b/Unlocker/src/platforms/epic/eos_base.h @@ -0,0 +1,148 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + + +#if !defined(EOS_MEMORY_CALL) || !defined(EOS_CALL) || !defined(EOS_USE_DLLEXPORT) +#if !defined(_WIN32) && !defined(_WIN64) && !defined(__ANDROID__) && !defined(__linux__) && !defined(__APPLE__) +#error \ +This platform expected a `eos__base.h` include before this header. \ +Please refer to https://dev.epicgames.com/docs/services or `eos_platform_prereqs.h` for details. +#endif +#endif + +#ifndef EOS_USE_DLLEXPORT +#if defined(_WIN32) || defined(__CYGWIN__) +#define EOS_USE_DLLEXPORT 1 +#else +#define EOS_USE_DLLEXPORT 0 +#endif +#endif + +#ifndef EOS_CALL +#if defined(_WIN32) && (defined(__i386) || defined(_M_IX86)) +#define EOS_CALL __stdcall +#define EOS_MEMORY_CALL __stdcall +#else +#define EOS_CALL +#define EOS_MEMORY_CALL +#endif +#endif + +#if !defined(EOS_MEMORY_CALL) || !defined(EOS_CALL) || !defined(EOS_USE_DLLEXPORT) +#error \ +The expected macros EOS_MEMORY_CALL, EOS_CALL, and EOS_USE_DLLEXPORT where not all defined. \ +Please refer to https://dev.epicgames.com/docs/services or `eos_platform_prereqs.h` for details. +#endif + + +#if defined(__cplusplus) + #if defined(_MSC_VER) && _MSC_VER >= 1800 + /* Visual Studio 2013 or later */ + #include + #else + #include + #include + #endif + + #if __cplusplus >= 201103L + #define EOS_HAS_ENUM_CLASS + #elif defined(_MSC_VER) && defined(_MSVC_LANG) && _MSVC_LANG >= 201103L + #define EOS_HAS_ENUM_CLASS + #endif +#else + /* C Compiler */ + #include + #include +#endif + + +typedef int32_t EOS_Bool; +#define EOS_TRUE 1 +#define EOS_FALSE 0 + + +#if defined(EOS_BUILDING_SDK) && EOS_BUILDING_SDK > 0 + #if EOS_USE_DLLEXPORT + #ifdef __GNUC__ + #define EOS_API __attribute__ ((dllexport)) + #else + #define EOS_API __declspec(dllexport) + #endif + #else + #if __GNUC__ >= 4 + #define EOS_API __attribute__ ((visibility ("default"))) + #else + #define EOS_API + #endif + #endif + +#else + + #if EOS_USE_DLLEXPORT + #if defined(EOS_MONOLITHIC) && EOS_MONOLITHIC > 0 + #define EOS_API + #elif defined(EOS_BUILD_DLL) && EOS_BUILD_DLL > 0 + #ifdef __GNUC__ + #define EOS_API __attribute__ ((dllexport)) + #else + #define EOS_API __declspec(dllexport) + #endif + #else + #ifdef __GNUC__ + #define EOS_API __attribute__ ((dllimport)) + #else + #define EOS_API __declspec(dllimport) + #endif + #endif + #else + #if __GNUC__ >= 4 + #define EOS_API __attribute__ ((visibility ("default"))) + #else + #define EOS_API + #endif + #endif +#endif + +#ifdef __cplusplus +#define EXTERN_C extern "C" +#else +#define EXTERN_C +#endif + +#define EOS_DECLARE_FUNC(return_type) EXTERN_C EOS_API return_type EOS_CALL +#define EOS_DECLARE_CALLBACK(CallbackName, ...) EXTERN_C typedef void (EOS_CALL * CallbackName)(__VA_ARGS__) +#define EOS_DECLARE_CALLBACK_RETVALUE(ReturnType, CallbackName, ...) EXTERN_C typedef ReturnType (EOS_CALL * CallbackName)(__VA_ARGS__) +#define EOS_PASTE(...) __VA_ARGS__ +#define EOS_STRUCT(struct_name, struct_def) \ + EXTERN_C typedef struct _tag ## struct_name { \ + EOS_PASTE struct_def \ + } struct_name + + +#ifdef EOS_HAS_ENUM_CLASS +#define EOS_ENUM_START(name) enum class name : int32_t { +#define EOS_ENUM_END(name) } +#else +#define EOS_ENUM_START(name) typedef enum name { +#define EOS_ENUM_END(name) , __##name##_PAD_INT32__ = 0x7FFFFFFF } name +#endif +#define EOS_ENUM(name, ...) EOS_ENUM_START(name) __VA_ARGS__ EOS_ENUM_END(name) + + +#ifdef EOS_HAS_ENUM_CLASS +#define EOS_ENUM_BOOLEAN_OPERATORS(name) \ +/** A set of bitwise operators provided when the enum is provided as an `enum class`. */ \ +inline constexpr name operator|(name Left, name Right) { return static_cast((__underlying_type(name))Left | (__underlying_type(name))Right); } \ +inline constexpr name operator&(name Left, name Right) { return static_cast((__underlying_type(name))Left & (__underlying_type(name))Right); } \ +inline constexpr name operator^(name Left, name Right) { return static_cast((__underlying_type(name))Left ^ (__underlying_type(name))Right); } \ +inline constexpr name& operator|=(name& Left, name Right) { return Left = Left | Right; } \ +inline constexpr name& operator&=(name& Left, name Right) { return Left = Left & Right; } \ +inline constexpr name& operator^=(name& Left, name Right) { return Left = Left ^ Right; } \ +/**/ +#else +#define EOS_ENUM_BOOLEAN_OPERATORS(name) +#endif + + +#undef EOS_HAS_ENUM_CLASS diff --git a/Unlocker/src/platforms/epic/eos_common.h b/Unlocker/src/platforms/epic/eos_common.h new file mode 100644 index 0000000..d08d436 --- /dev/null +++ b/Unlocker/src/platforms/epic/eos_common.h @@ -0,0 +1,39 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "eos_base.h" + +#pragma pack(push, 8) + +#undef EOS_RESULT_VALUE +#undef EOS_RESULT_VALUE_LAST +#define EOS_RESULT_VALUE(Name, Value) Name = Value, +#define EOS_RESULT_VALUE_LAST(Name, Value) Name = Value + +EOS_ENUM_START(EOS_EResult) +#include "eos_result.h" +EOS_ENUM_END(EOS_EResult); + +#undef EOS_RESULT_VALUE +#undef EOS_RESULT_VALUE_LAST + +/** + * A handle to a user's Epic Online Services Account ID + * This ID is associated with a specific login associated with Epic Account Services + * + * @see EOS_Auth_Login + */ +typedef struct EOS_EpicAccountIdDetails* EOS_EpicAccountId; + +/** + * A handle to a user's Product User ID (game services related ecosystem) + * This ID is associated with any of the external account providers (of which Epic Account Services is one) + * + * @see EOS_Connect_Login + * @see EOS_EExternalCredentialType + */ +typedef struct EOS_ProductUserIdDetails* EOS_ProductUserId; + + +#pragma pack(pop) diff --git a/Unlocker/src/platforms/epic/eos_ecom_types.h b/Unlocker/src/platforms/epic/eos_ecom_types.h new file mode 100644 index 0000000..3bad878 --- /dev/null +++ b/Unlocker/src/platforms/epic/eos_ecom_types.h @@ -0,0 +1,387 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "eos_common.h" + +#pragma pack(push, 8) + +EXTERN_C typedef struct EOS_EcomHandle* EOS_HEcom; + +/** + * This handle is copied when EOS_Ecom_CopyTransactionById or EOS_Ecom_CopyTransactionByIndex is called. + * A EOS_Ecom_CheckoutCallbackInfo provides the ID for the copy. + * After being copied, EOS_Ecom_Transaction_Release must be called. + * + * @see EOS_Ecom_CheckoutCallbackInfo + * @see EOS_Ecom_CopyTransactionById + * @see EOS_Ecom_CopyTransactionByIndex + * @see EOS_Ecom_Transaction_Release + */ +EXTERN_C typedef struct EOS_Ecom_TransactionHandle* EOS_Ecom_HTransaction; + +/** + * A unique identifier for a catalog item defined and stored with the backend catalog service. + * A catalog item represents a distinct object within the catalog. When acquired by an account, an + * entitlement is granted that references a specific catalog item. + */ +EXTERN_C typedef const char* EOS_Ecom_CatalogItemId; + +/** + * A unique identifier for a catalog offer defined and stored with the backend catalog service. + * A catalog offer is a purchasable collection of 1 or more items, associated with a price (which + * could be 0). When an offer is purchased an entitlement is granted for each of the items + * referenced by the offer. + */ +EXTERN_C typedef const char* EOS_Ecom_CatalogOfferId; + +/** + * An identifier which is defined on a catalog item and stored with the backend catalog service. + * The entitlement name may not be unique. A catalog may be configured with multiple items with the + * same entitlement name in order to define a logical grouping of entitlements. This is used to + * retrieve all entitlements granted to an account grouped in this way. + * + * @see EOS_Ecom_QueryEntitlements + */ +EXTERN_C typedef const char* EOS_Ecom_EntitlementName; + +/** + * A unique identifier for an entitlement owned by an account. An entitlement is always associated + * with a single account. The entitlement ID is provided to allow redeeming the entitlement as + * well as identify individual entitlement grants. + * + * @see EOS_Ecom_QueryEntitlements + * @see EOS_Ecom_RedeemEntitlements + */ +EXTERN_C typedef const char* EOS_Ecom_EntitlementId; + + +/** + * An enumeration of the different ownership statuses. + */ +EOS_ENUM(EOS_EOwnershipStatus, + /** The catalog item is not owned by the local user */ + EOS_OS_NotOwned = 0, + /** The catalog item is owned by the local user */ + EOS_OS_Owned = 1 +); + +/** + * An enumeration defining the type of catalog item. The primary use is to identify how the item is expended. + */ +EOS_ENUM(EOS_EEcomItemType, + /** This entitlement is intended to persist. */ + EOS_EIT_Durable = 0, + /** + * This entitlement is intended to be transient and redeemed. + * + * @see EOS_Ecom_RedeemEntitlements + */ + EOS_EIT_Consumable = 1, + /** This entitlement has a type that is not currently intneded for an in-game store. */ + EOS_EIT_Other = 2 +); + +/** The most recent version of the EOS_Ecom_Entitlement struct. */ +#define EOS_ECOM_ENTITLEMENT_API_LATEST 2 + +/** Timestamp value representing an undefined EndTimestamp for EOS_Ecom_Entitlement */ +#define EOS_ECOM_ENTITLEMENT_ENDTIMESTAMP_UNDEFINED -1 + +/** + * Contains information about a single entitlement associated with an account. Instances of this structure are + * created by EOS_Ecom_CopyEntitlementByIndex, EOS_Ecom_CopyEntitlementByNameAndIndex, or EOS_Ecom_CopyEntitlementById. + * They must be passed to EOS_Ecom_Entitlement_Release. + */ +EOS_STRUCT(EOS_Ecom_Entitlement, ( + /** API Version: Set this to EOS_ECOM_ENTITLEMENT_API_LATEST. */ + int32_t ApiVersion; + /** Name of the entitlement */ + EOS_Ecom_EntitlementName EntitlementName; + /** ID of the entitlement owned by an account */ + EOS_Ecom_EntitlementId EntitlementId; + /** ID of the item associated with the offer which granted this entitlement */ + EOS_Ecom_CatalogItemId CatalogItemId; + /** + * If queried using pagination then ServerIndex represents the index of the entitlement as it + * exists on the server. If not queried using pagination then ServerIndex will be -1. + */ + int32_t ServerIndex; + /** If true then the catalog has this entitlement marked as redeemed */ + EOS_Bool bRedeemed; + /** If not -1 then this is a POSIX timestamp that this entitlement will end */ + int64_t EndTimestamp; +)); + + +/** The most recent version of the EOS_Ecom_ItemOwnership struct. */ +#define EOS_ECOM_ITEMOWNERSHIP_API_LATEST 1 + +/** + * Contains information about a single item ownership associated with an account. This structure is + * returned as part of the EOS_Ecom_QueryOwnershipCallbackInfo structure. + */ +EOS_STRUCT(EOS_Ecom_ItemOwnership, ( + /** API Version: Set this to EOS_ECOM_ITEMOWNERSHIP_API_LATEST. */ + int32_t ApiVersion; + /** ID of the catalog item */ + EOS_Ecom_CatalogItemId Id; + /** Is this catalog item owned by the local user */ + EOS_EOwnershipStatus OwnershipStatus; +)); + +/** The most recent version of the EOS_Ecom_QueryOwnership API. */ +#define EOS_ECOM_QUERYOWNERSHIP_API_LATEST 2 + +/** + * The maximum number of catalog items that may be queried in a single pass + */ +#define EOS_ECOM_QUERYOWNERSHIP_MAX_CATALOG_IDS 32 + +/** + * Input parameters for the EOS_Ecom_QueryOwnership function. + */ +EOS_STRUCT(EOS_Ecom_QueryOwnershipOptions, ( + /** API Version: Set this to EOS_ECOM_QUERYOWNERSHIP_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose ownership to query */ + EOS_EpicAccountId LocalUserId; + /** The array of Catalog Item IDs to check for ownership */ + EOS_Ecom_CatalogItemId* CatalogItemIds; + /** The number of Catalog Item IDs to in the array */ + uint32_t CatalogItemIdCount; + /** Optional product namespace, if not the one specified during initialization */ + const char* CatalogNamespace; +)); + +/** + * Output parameters for the EOS_Ecom_QueryOwnership Function. + */ +EOS_STRUCT(EOS_Ecom_QueryOwnershipCallbackInfo, ( + /** The EOS_EResult code for the operation. EOS_Success indicates that the operation succeeded; other codes indicate errors. */ + EOS_EResult ResultCode; + /** Context that was passed into EOS_Ecom_QueryOwnership */ + void* ClientData; + /** The Epic Online Services Account ID of the local user whose ownership was queried */ + EOS_EpicAccountId LocalUserId; + /** List of catalog items and their ownership status */ + const EOS_Ecom_ItemOwnership* ItemOwnership; + /** Number of ownership results are included in this callback */ + uint32_t ItemOwnershipCount; +)); + +/** + * Function prototype definition for callbacks passed to EOS_Ecom_QueryOwnership + * @param Data A EOS_Ecom_QueryOwnershipCallbackInfo containing the output information and result + */ +EOS_DECLARE_CALLBACK(EOS_Ecom_OnQueryOwnershipCallback, const EOS_Ecom_QueryOwnershipCallbackInfo* Data); + +/** The most recent version of the EOS_Ecom_QueryOwnershipToken API. */ +#define EOS_ECOM_QUERYOWNERSHIPTOKEN_API_LATEST 2 + +/** + * The maximum number of catalog items that may be queried in a single pass + */ +#define EOS_ECOM_QUERYOWNERSHIPTOKEN_MAX_CATALOGITEM_IDS 32 + +/** + * Input parameters for the EOS_Ecom_QueryOwnershipToken function. + */ +EOS_STRUCT(EOS_Ecom_QueryOwnershipTokenOptions, ( + /** API Version: Set this to EOS_ECOM_QUERYOWNERSHIPTOKEN_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose ownership token you want to query */ + EOS_EpicAccountId LocalUserId; + /** The array of Catalog Item IDs to check for ownership, matching in number to the CatalogItemIdCount */ + EOS_Ecom_CatalogItemId* CatalogItemIds; + /** The number of catalog item IDs to query */ + uint32_t CatalogItemIdCount; + /** Optional product namespace, if not the one specified during initialization */ + const char* CatalogNamespace; +)); + +/** + * Output parameters for the EOS_Ecom_QueryOwnershipToken Function. + */ +EOS_STRUCT(EOS_Ecom_QueryOwnershipTokenCallbackInfo, ( + /** The EOS_EResult code for the operation. EOS_Success indicates that the operation succeeded; other codes indicate errors. */ + EOS_EResult ResultCode; + /** Context that was passed into EOS_Ecom_QueryOwnershipToken */ + void* ClientData; + /** The Epic Online Services Account ID of the local user whose ownership token was queried */ + EOS_EpicAccountId LocalUserId; + /** Ownership token containing details about the catalog items queried */ + const char* OwnershipToken; +)); + +/** + * Function prototype definition for callbacks passed to EOS_Ecom_QueryOwnershipToken + * @param Data A EOS_Ecom_QueryOwnershipTokenCallbackInfo containing the output information and result + */ +EOS_DECLARE_CALLBACK(EOS_Ecom_OnQueryOwnershipTokenCallback, const EOS_Ecom_QueryOwnershipTokenCallbackInfo* Data); + +/** The most recent version of the EOS_Ecom_QueryEntitlements API. */ +#define EOS_ECOM_QUERYENTITLEMENTS_API_LATEST 2 + +/** + * The maximum number of entitlements that may be queried in a single pass + */ +#define EOS_ECOM_QUERYENTITLEMENTS_MAX_ENTITLEMENT_IDS 32 + +/** + * Input parameters for the EOS_Ecom_QueryEntitlements function. + */ +EOS_STRUCT(EOS_Ecom_QueryEntitlementsOptions, ( + /** API Version: Set this to EOS_ECOM_QUERYENTITLEMENTS_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose Entitlements you want to retrieve */ + EOS_EpicAccountId LocalUserId; + /** An array of Entitlement Names that you want to check */ + EOS_Ecom_EntitlementName* EntitlementNames; + /** The number of Entitlement Names included in the array, up to EOS_ECOM_QUERYENTITLEMENTS_MAX_ENTITLEMENT_IDS; use zero to request all Entitlements associated with the user's Epic Online Services account. */ + uint32_t EntitlementNameCount; + /** If true, Entitlements that have been redeemed will be included in the results. */ + EOS_Bool bIncludeRedeemed; +)); + +/** + * Output parameters for the EOS_Ecom_QueryEntitlements Function. + */ +EOS_STRUCT(EOS_Ecom_QueryEntitlementsCallbackInfo, ( + EOS_EResult ResultCode; + /** Context that was passed into EOS_Ecom_QueryEntitlements */ + void* ClientData; + /** The Epic Online Services Account ID of the local user whose entitlement was queried */ + EOS_EpicAccountId LocalUserId; +)); + +/** + * Function prototype definition for callbacks passed to EOS_Ecom_QueryOwnershipToken + * @param Data A EOS_Ecom_QueryEntitlementsCallbackInfo containing the output information and result + */ +EOS_DECLARE_CALLBACK(EOS_Ecom_OnQueryEntitlementsCallback, const EOS_Ecom_QueryEntitlementsCallbackInfo* Data); + +/** The most recent version of the EOS_Ecom_GetEntitlementsCount API. */ +#define EOS_ECOM_GETENTITLEMENTSCOUNT_API_LATEST 1 + +/** + * Input parameters for the EOS_Ecom_GetEntitlementsCount function. + */ +EOS_STRUCT(EOS_Ecom_GetEntitlementsCountOptions, ( + /** API Version: Set this to EOS_ECOM_GETENTITLEMENTSCOUNT_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user for which to retrieve the entitlement count */ + EOS_EpicAccountId LocalUserId; +)); + +/** The most recent version of the EOS_Ecom_GetEntitlementsByNameCount API. */ +#define EOS_ECOM_GETENTITLEMENTSBYNAMECOUNT_API_LATEST 1 + +/** + * Input parameters for the EOS_Ecom_GetEntitlementsByNameCount function. + */ +EOS_STRUCT(EOS_Ecom_GetEntitlementsByNameCountOptions, ( + /** API Version: Set this to EOS_ECOM_GETENTITLEMENTSBYNAMECOUNT_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user for which to retrieve the entitlement count */ + EOS_EpicAccountId LocalUserId; + /** Name of the entitlement to count in the cache */ + EOS_Ecom_EntitlementName EntitlementName; +)); + +/** The most recent version of the EOS_Ecom_CopyEntitlementByIndex API. */ +#define EOS_ECOM_COPYENTITLEMENTBYINDEX_API_LATEST 1 + +/** + * Input parameters for the EOS_Ecom_CopyEntitlementByIndex function. + */ +EOS_STRUCT(EOS_Ecom_CopyEntitlementByIndexOptions, ( + /** API Version: Set this to EOS_ECOM_COPYENTITLEMENTBYINDEX_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose entitlement is being copied */ + EOS_EpicAccountId LocalUserId; + /** Index of the entitlement to retrieve from the cache */ + uint32_t EntitlementIndex; +)); + +/** The most recent version of the EOS_Ecom_CopyEntitlementByNameAndIndex API. */ +#define EOS_ECOM_COPYENTITLEMENTBYNAMEANDINDEX_API_LATEST 1 + +/** + * Input parameters for the EOS_Ecom_CopyEntitlementByNameAndIndex function. + */ +EOS_STRUCT(EOS_Ecom_CopyEntitlementByNameAndIndexOptions, ( + /** API Version: Set this to EOS_ECOM_COPYENTITLEMENTBYNAMEANDINDEX_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose entitlement is being copied */ + EOS_EpicAccountId LocalUserId; + /** Name of the entitlement to retrieve from the cache */ + EOS_Ecom_EntitlementName EntitlementName; + /** Index of the entitlement within the named set to retrieve from the cache. */ + uint32_t Index; +)); + +/** The most recent version of the EOS_Ecom_CopyEntitlementById API. */ +#define EOS_ECOM_COPYENTITLEMENTBYID_API_LATEST 2 + +/** + * Input parameters for the EOS_Ecom_CopyEntitlementById function. + */ +EOS_STRUCT(EOS_Ecom_CopyEntitlementByIdOptions, ( + /** API Version: Set this to EOS_ECOM_COPYENTITLEMENTBYID_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose entitlement is being copied */ + EOS_EpicAccountId LocalUserId; + /** ID of the entitlement to retrieve from the cache */ + EOS_Ecom_EntitlementId EntitlementId; +)); + +/** The most recent version of the EOS_Ecom_CopyItemById API. */ +#define EOS_ECOM_COPYITEMBYID_API_LATEST 1 + +/** + * Input parameters for the EOS_Ecom_CopyItemById function. + */ +EOS_STRUCT(EOS_Ecom_CopyItemByIdOptions, ( + /** API Version: Set this to EOS_ECOM_COPYITEMBYID_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose item is being copied */ + EOS_EpicAccountId LocalUserId; + /** The ID of the item to get. */ + EOS_Ecom_CatalogItemId ItemId; +)); + + +/** The most recent version of the EOS_Ecom_GetItemReleaseCount API. */ +#define EOS_ECOM_GETITEMRELEASECOUNT_API_LATEST 1 + +/** + * Input parameters for the EOS_Ecom_GetItemReleaseCount function. + */ +EOS_STRUCT(EOS_Ecom_GetItemReleaseCountOptions, ( + /** API Version: Set this to EOS_ECOM_GETITEMRELEASECOUNT_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose item release is being accessed */ + EOS_EpicAccountId LocalUserId; + /** The ID of the item to get the releases for. */ + EOS_Ecom_CatalogItemId ItemId; +)); + +/** The most recent version of the EOS_Ecom_CopyItemReleaseByIndex API. */ +#define EOS_ECOM_COPYITEMRELEASEBYINDEX_API_LATEST 1 + +/** + * Input parameters for the EOS_Ecom_CopyItemReleaseByIndex function. + */ +EOS_STRUCT(EOS_Ecom_CopyItemReleaseByIndexOptions, ( + /** API Version: Set this to EOS_ECOM_COPYITEMRELEASEBYINDEX_API_LATEST. */ + int32_t ApiVersion; + /** The Epic Online Services Account ID of the local user whose item release is being copied */ + EOS_EpicAccountId LocalUserId; + /** The ID of the item to get the releases for. */ + EOS_Ecom_CatalogItemId ItemId; + /** The index of the release to get. */ + uint32_t ReleaseIndex; +)); + +#pragma pack(pop) diff --git a/Unlocker/src/platforms/epic/eos_hooks.cpp b/Unlocker/src/platforms/epic/eos_hooks.cpp new file mode 100644 index 0000000..a72207a --- /dev/null +++ b/Unlocker/src/platforms/epic/eos_hooks.cpp @@ -0,0 +1,145 @@ +#include "pch.h" +#include "eos_hooks.h" +#include "Epic.h" + +#define GET_PROXY_FUNC(FUNC) \ + static auto proxyFunc = PLH::FnCast(BasePlatform::trampolineMap[#FUNC], FUNC); + +static vector entitlements; + +auto getEpicConfig() +{ + return config->platforms["Epic Games"]; +} + +void EOS_CALL EOS_Ecom_QueryOwnership( + EOS_HEcom Handle, + const EOS_Ecom_QueryOwnershipOptions* Options, + void* ClientData, + const EOS_Ecom_OnQueryOwnershipCallback CompletionDelegate +) +{ + auto itemCount = Options->CatalogItemIdCount; + auto ownerships = new EOS_Ecom_ItemOwnership[itemCount]; + + logger->info("Game requested ownership of {} items", itemCount); + for(uint32_t i = 0; i < itemCount; i++) + { + // Epic magic happens here + ownerships[i].ApiVersion = EOS_ECOM_ITEMOWNERSHIP_API_LATEST; + ownerships[i].Id = Options->CatalogItemIds[i]; + auto isBlacklisted = vectorContains(getEpicConfig().blacklist, string(ownerships[i].Id)); + ownerships[i].OwnershipStatus = isBlacklisted ? EOS_EOwnershipStatus::EOS_OS_NotOwned : EOS_EOwnershipStatus::EOS_OS_Owned; + + logger->info("\t{} [{}]", ownerships[i].Id, (bool) ownerships[i].OwnershipStatus ? "Owned" : "NotOwned"); + } + + EOS_Ecom_QueryOwnershipCallbackInfo callbackInfo = + { + EOS_EResult::EOS_Success, + ClientData, + Options->LocalUserId, + ownerships, + Options->CatalogItemIdCount + }; + + CompletionDelegate(&callbackInfo); + + delete[] ownerships; +} + +void EOS_CALL EOS_Ecom_QueryEntitlements( + EOS_HEcom Handle, + const EOS_Ecom_QueryEntitlementsOptions* Options, + void* ClientData, + const EOS_Ecom_OnQueryEntitlementsCallback CompletionDelegate +) +{ + auto entitlementCount = Options->EntitlementNameCount; + + logger->info("Game requested ownership of {} entitlements", entitlementCount); + + entitlements.clear(); + for(uint32_t i = 0; i < entitlementCount; i++) + { + auto isBlacklisted = vectorContains(getEpicConfig().blacklist, string(Options->EntitlementNames[i])); + if(!isBlacklisted) + { + // Save the entitlements id for response in subsequent queries + entitlements.push_back(Options->EntitlementNames[i]); + } + } + + EOS_Ecom_QueryEntitlementsCallbackInfo callbackData = { + EOS_EResult::EOS_Success, + ClientData, + Options->LocalUserId + }; + + CompletionDelegate(&callbackData); +} + +uint32_t EOS_CALL EOS_Ecom_GetEntitlementsCount( + EOS_HEcom Handle, + const EOS_Ecom_GetEntitlementsCountOptions* Options +) +{ + logger->debug("Game requested count of user entitlements"); + + auto entitlementCount = (uint32_t) entitlements.size(); + if(entitlementCount == 0) + { + logger->warn("No entitlements were queried. Redirecting to original function."); + GET_PROXY_FUNC(EOS_Ecom_GetEntitlementsCount); + entitlementCount = proxyFunc(Handle, Options); + } + + logger->info("Responding with {} entitlements", entitlementCount); + + return entitlementCount; +} + +EOS_EResult EOS_CALL EOS_Ecom_CopyEntitlementByIndex( + EOS_HEcom Handle, + const EOS_Ecom_CopyEntitlementByIndexOptions* Options, + EOS_Ecom_Entitlement** OutEntitlement +) +{ + logger->debug("EOS_Ecom_CopyEntitlementByIndex -> ApiVersion: {}", Options->ApiVersion); + logger->debug("Game requested entitlement with index: {}", Options->EntitlementIndex); + + if(Options->EntitlementIndex >= entitlements.size()) + { + logger->warn("Out of bounds entitlement index. Redirecting to original function."); + GET_PROXY_FUNC(EOS_Ecom_CopyEntitlementByIndex); + return proxyFunc(Handle, Options, OutEntitlement); + } + else + { + // Epic magic happens here (2) + + const char* id = makeCStringCopy(entitlements.at(Options->EntitlementIndex)); + + logger->info("\t{}", id); + + *OutEntitlement = new EOS_Ecom_Entitlement{ + EOS_ECOM_ENTITLEMENT_API_LATEST, + id, // EntitlementName + id, // EntitlementId + id, // CatalogItemId + -1, // ServerIndex + false, // bRedeemed + -1 // EndTimestamp + }; + + return EOS_EResult::EOS_Success; + } +} + +void EOS_CALL EOS_Ecom_Entitlement_Release(EOS_Ecom_Entitlement* Entitlement) +{ + logger->debug("Game requested to release entitlement: {}", Entitlement->EntitlementId); + + delete[] Entitlement->EntitlementId; + delete Entitlement; +} diff --git a/Unlocker/src/platforms/epic/eos_hooks.h b/Unlocker/src/platforms/epic/eos_hooks.h new file mode 100644 index 0000000..d68a048 --- /dev/null +++ b/Unlocker/src/platforms/epic/eos_hooks.h @@ -0,0 +1,82 @@ +#pragma once +#include "eos_ecom_types.h" + +/** + * Query the ownership status for a given list of catalog item IDs defined with Epic Online Services. + * This data will be cached for a limited time and retrieved again from the backend when necessary + * + * @param Options structure containing the account and catalog item IDs to retrieve + * @param ClientData arbitrary data that is passed back to you in the CompletionDelegate + * @param CompletionDelegate a callback that is fired when the async operation completes, either successfully or in error + */ +void EOS_CALL EOS_Ecom_QueryOwnership( + EOS_HEcom Handle, + const EOS_Ecom_QueryOwnershipOptions* Options, + void* ClientData, + const EOS_Ecom_OnQueryOwnershipCallback CompletionDelegate +); + +/** + * Query the entitlement information defined with Epic Online Services. + * A set of entitlement names can be provided to filter the set of entitlements associated with the account. + * This data will be cached for a limited time and retrieved again from the backend when necessary. + * Use EOS_Ecom_CopyEntitlementByIndex, EOS_Ecom_CopyEntitlementByNameAndIndex, and EOS_Ecom_CopyEntitlementById to get the entitlement details. + * Use EOS_Ecom_GetEntitlementsByNameCount to retrieve the number of entitlements with a specific entitlement name. + * + * @param Options structure containing the account and entitlement names to retrieve + * @param ClientData arbitrary data that is passed back to you in the CompletionDelegate + * @param CompletionDelegate a callback that is fired when the async operation completes, either successfully or in error + */ +void EOS_CALL EOS_Ecom_QueryEntitlements( + EOS_HEcom Handle, + const EOS_Ecom_QueryEntitlementsOptions* Options, + void* ClientData, + const EOS_Ecom_OnQueryEntitlementsCallback CompletionDelegate +); + +/** + * Fetch the number of entitlements that are cached for a given local user. + * + * @param Options structure containing the Epic Online Services Account ID being accessed + * + * @see EOS_Ecom_CopyEntitlementByIndex + * + * @return the number of entitlements found. + */ +uint32_t EOS_CALL EOS_Ecom_GetEntitlementsCount( + EOS_HEcom Handle, + const EOS_Ecom_GetEntitlementsCountOptions* Options +); + +/** + * Fetches an entitlement from a given index. + * + * @param Options structure containing the Epic Online Services Account ID and index being accessed + * @param OutEntitlement the entitlement for the given index, if it exists and is valid, use EOS_Ecom_Entitlement_Release when finished + * + * @see EOS_Ecom_Entitlement_Release + * + * @return EOS_Success if the information is available and passed out in OutEntitlement + * EOS_Ecom_EntitlementStale if the entitlement information is stale and passed out in OutEntitlement + * EOS_InvalidParameters if you pass a null pointer for the out parameter + * EOS_NotFound if the entitlement is not found + */ +EOS_EResult EOS_CALL EOS_Ecom_CopyEntitlementByIndex( + EOS_HEcom Handle, + const EOS_Ecom_CopyEntitlementByIndexOptions* Options, + EOS_Ecom_Entitlement** OutEntitlement +); + +/** + * Release the memory associated with an EOS_Ecom_Entitlement structure. This must be called on data + * retrieved from EOS_Ecom_CopyEntitlementByIndex and EOS_Ecom_CopyEntitlementById. + * + * @param Entitlement - The entitlement structure to be released + * + * @see EOS_Ecom_Entitlement + * @see EOS_Ecom_CopyEntitlementByIndex + * @see EOS_Ecom_CopyEntitlementById + */ +void EOS_CALL EOS_Ecom_Entitlement_Release( + EOS_Ecom_Entitlement* Entitlement +); diff --git a/Unlocker/src/platforms/epic/eos_result.h b/Unlocker/src/platforms/epic/eos_result.h new file mode 100644 index 0000000..be515d2 --- /dev/null +++ b/Unlocker/src/platforms/epic/eos_result.h @@ -0,0 +1,384 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +// This file is not intended to be included directly. Include eos_common.h instead. + +/** Successful result. no further error processing needed */ +EOS_RESULT_VALUE(EOS_Success, 0) + +/** Failed due to no connection */ +EOS_RESULT_VALUE(EOS_NoConnection, 1) +/** Failed login due to invalid credentials */ +EOS_RESULT_VALUE(EOS_InvalidCredentials, 2) +/** Failed due to invalid or missing user */ +EOS_RESULT_VALUE(EOS_InvalidUser, 3) +/** Failed due to invalid or missing authentication token for user (e.g. not logged in) */ +EOS_RESULT_VALUE(EOS_InvalidAuth, 4) +/** Failed due to invalid access */ +EOS_RESULT_VALUE(EOS_AccessDenied, 5) +/** If the client does not possess the permission required */ +EOS_RESULT_VALUE(EOS_MissingPermissions, 6) +/** If the token provided does not represent an account */ +EOS_RESULT_VALUE(EOS_Token_Not_Account, 7) +/** Throttled due to too many requests */ +EOS_RESULT_VALUE(EOS_TooManyRequests, 8) +/** Async request was already pending */ +EOS_RESULT_VALUE(EOS_AlreadyPending, 9) +/** Invalid parameters specified for request */ +EOS_RESULT_VALUE(EOS_InvalidParameters, 10) +/** Invalid request */ +EOS_RESULT_VALUE(EOS_InvalidRequest, 11) +/** Failed due to unable to parse or recognize a backend response */ +EOS_RESULT_VALUE(EOS_UnrecognizedResponse, 12) +/** Incompatible client for backend version */ +EOS_RESULT_VALUE(EOS_IncompatibleVersion, 13) +/** Not configured correctly for use */ +EOS_RESULT_VALUE(EOS_NotConfigured, 14) +/** Already configured for use. */ +EOS_RESULT_VALUE(EOS_AlreadyConfigured, 15) +/** Feature not available on this implementation */ +EOS_RESULT_VALUE(EOS_NotImplemented, 16) +/** Operation was canceled (likely by user) */ +EOS_RESULT_VALUE(EOS_Canceled, 17) +/** The requested information was not found */ +EOS_RESULT_VALUE(EOS_NotFound, 18) +/** An error occurred during an asynchronous operation, and it will be retried. Callbacks receiving this result will be called again in the future. */ +EOS_RESULT_VALUE(EOS_OperationWillRetry, 19) +/** The request had no effect */ +EOS_RESULT_VALUE(EOS_NoChange, 20) +/** The request attempted to use multiple or inconsistent API versions */ +EOS_RESULT_VALUE(EOS_VersionMismatch, 21) +/** A maximum limit was exceeded on the client, different from EOS_TooManyRequests */ +EOS_RESULT_VALUE(EOS_LimitExceeded, 22) +/** Feature or client ID performing the operation has been disabled. */ +EOS_RESULT_VALUE(EOS_Disabled, 23) +/** Duplicate entry not allowed */ +EOS_RESULT_VALUE(EOS_DuplicateNotAllowed, 24) +/** Required parameters are missing. DEPRECATED: This error is no longer used. */ +EOS_RESULT_VALUE(EOS_MissingParameters_DEPRECATED, 25) +/** Sandbox ID is invalid */ +EOS_RESULT_VALUE(EOS_InvalidSandboxId, 26) +/** Request timed out */ +EOS_RESULT_VALUE(EOS_TimedOut, 27) +/** A query returned some but not all of the requested results. */ +EOS_RESULT_VALUE(EOS_PartialResult, 28) +/** Client is missing the whitelisted role */ +EOS_RESULT_VALUE(EOS_Missing_Role, 29) +/** Client is missing the whitelisted feature */ +EOS_RESULT_VALUE(EOS_Missing_Feature, 30) +/** The sandbox given to the backend is invalid */ +EOS_RESULT_VALUE(EOS_Invalid_Sandbox, 31) +/** The deployment given to the backend is invalid */ +EOS_RESULT_VALUE(EOS_Invalid_Deployment, 32) +/** The product ID specified to the backend is invalid */ +EOS_RESULT_VALUE(EOS_Invalid_Product, 33) +/** The product user ID specified to the backend is invalid */ +EOS_RESULT_VALUE(EOS_Invalid_ProductUserID, 34) +/** There was a failure with the backend service */ +EOS_RESULT_VALUE(EOS_ServiceFailure, 35) +/** Cache directory is not set in platform options. */ +EOS_RESULT_VALUE(EOS_CacheDirectoryMissing, 36) +/** Cache directory is not accessible. */ +EOS_RESULT_VALUE(EOS_CacheDirectoryInvalid, 37) +/** The request failed because resource was in an invalid state */ +EOS_RESULT_VALUE(EOS_InvalidState, 38) +/** Request is in progress */ +EOS_RESULT_VALUE(EOS_RequestInProgress, 39) + +/** Account locked due to login failures */ +EOS_RESULT_VALUE(EOS_Auth_AccountLocked, 1001) +/** Account locked by update operation. */ +EOS_RESULT_VALUE(EOS_Auth_AccountLockedForUpdate, 1002) +/** Refresh token used was invalid */ +EOS_RESULT_VALUE(EOS_Auth_InvalidRefreshToken, 1003) +/** Invalid access token, typically when switching between backend environments */ +EOS_RESULT_VALUE(EOS_Auth_InvalidToken, 1004) +/** Invalid bearer token */ +EOS_RESULT_VALUE(EOS_Auth_AuthenticationFailure, 1005) +/** Invalid platform token */ +EOS_RESULT_VALUE(EOS_Auth_InvalidPlatformToken, 1006) +/** Auth parameters are not associated with this account */ +EOS_RESULT_VALUE(EOS_Auth_WrongAccount, 1007) +/** Auth parameters are not associated with this client */ +EOS_RESULT_VALUE(EOS_Auth_WrongClient, 1008) +/** Full account is required */ +EOS_RESULT_VALUE(EOS_Auth_FullAccountRequired, 1009) +/** Headless account is required */ +EOS_RESULT_VALUE(EOS_Auth_HeadlessAccountRequired, 1010) +/** Password reset is required */ +EOS_RESULT_VALUE(EOS_Auth_PasswordResetRequired, 1011) +/** Password was previously used and cannot be reused */ +EOS_RESULT_VALUE(EOS_Auth_PasswordCannotBeReused, 1012) +/** Authorization code/exchange code has expired */ +EOS_RESULT_VALUE(EOS_Auth_Expired, 1013) +/** Consent has not been given by the user */ +EOS_RESULT_VALUE(EOS_Auth_ScopeConsentRequired, 1014) +/** The application has no profile on the backend */ +EOS_RESULT_VALUE(EOS_Auth_ApplicationNotFound, 1015) +/** The requested consent wasn't found on the backend */ +EOS_RESULT_VALUE(EOS_Auth_ScopeNotFound, 1016) +/** This account has been denied access to login */ +EOS_RESULT_VALUE(EOS_Auth_AccountFeatureRestricted, 1017) + +/** Pin grant code initiated */ +EOS_RESULT_VALUE(EOS_Auth_PinGrantCode, 1020) +/** Pin grant code attempt expired */ +EOS_RESULT_VALUE(EOS_Auth_PinGrantExpired, 1021) +/** Pin grant code attempt pending */ +EOS_RESULT_VALUE(EOS_Auth_PinGrantPending, 1022) + +/** External auth source did not yield an account */ +EOS_RESULT_VALUE(EOS_Auth_ExternalAuthNotLinked, 1030) +/** External auth access revoked */ +EOS_RESULT_VALUE(EOS_Auth_ExternalAuthRevoked, 1032) +/** External auth token cannot be interpreted */ +EOS_RESULT_VALUE(EOS_Auth_ExternalAuthInvalid, 1033) +/** External auth cannot be linked to his account due to restrictions */ +EOS_RESULT_VALUE(EOS_Auth_ExternalAuthRestricted, 1034) +/** External auth cannot be used for login */ +EOS_RESULT_VALUE(EOS_Auth_ExternalAuthCannotLogin, 1035) +/** External auth is expired */ +EOS_RESULT_VALUE(EOS_Auth_ExternalAuthExpired, 1036) +/** External auth cannot be removed since it's the last possible way to login */ +EOS_RESULT_VALUE(EOS_Auth_ExternalAuthIsLastLoginType, 1037) + +/** Exchange code not found */ +EOS_RESULT_VALUE(EOS_Auth_ExchangeCodeNotFound, 1040) +/** Originating exchange code session has expired */ +EOS_RESULT_VALUE(EOS_Auth_OriginatingExchangeCodeSessionExpired, 1041) + +/** The account has been disabled and cannot be used for authentication */ +EOS_RESULT_VALUE(EOS_Auth_PersistentAuth_AccountNotActive, 1050) + +/** MFA challenge required */ +EOS_RESULT_VALUE(EOS_Auth_MFARequired, 1060) + +/** Parental locks are in place */ +EOS_RESULT_VALUE(EOS_Auth_ParentalControls, 1070) + +/** Korea real ID association required but missing */ +EOS_RESULT_VALUE(EOS_Auth_NoRealId, 1080) + +/** An outgoing friend invitation is awaiting acceptance; sending another invite to the same user is erroneous */ +EOS_RESULT_VALUE(EOS_Friends_InviteAwaitingAcceptance, 2000) +/** There is no friend invitation to accept/reject */ +EOS_RESULT_VALUE(EOS_Friends_NoInvitation, 2001) +/** Users are already friends, so sending another invite is erroneous */ +EOS_RESULT_VALUE(EOS_Friends_AlreadyFriends, 2003) +/** Users are not friends, so deleting the friend is erroneous */ +EOS_RESULT_VALUE(EOS_Friends_NotFriends, 2004) +/** Remote user has too many invites to receive new invites */ +EOS_RESULT_VALUE(EOS_Friends_TargetUserTooManyInvites, 2005) +/** Local user has too many invites to send new invites */ +EOS_RESULT_VALUE(EOS_Friends_LocalUserTooManyInvites, 2006) +/** Remote user has too many friends to make a new friendship */ +EOS_RESULT_VALUE(EOS_Friends_TargetUserFriendLimitExceeded, 2007) +/** Local user has too many friends to make a new friendship */ +EOS_RESULT_VALUE(EOS_Friends_LocalUserFriendLimitExceeded, 2008) + +/** Request data was null or invalid */ +EOS_RESULT_VALUE(EOS_Presence_DataInvalid, 3000) +/** Request contained too many or too few unique data items, or the request would overflow the maximum amount of data allowed */ +EOS_RESULT_VALUE(EOS_Presence_DataLengthInvalid, 3001) +/** Request contained data with an invalid key */ +EOS_RESULT_VALUE(EOS_Presence_DataKeyInvalid, 3002) +/** Request contained data with a key too long or too short */ +EOS_RESULT_VALUE(EOS_Presence_DataKeyLengthInvalid, 3003) +/** Request contained data with an invalid value */ +EOS_RESULT_VALUE(EOS_Presence_DataValueInvalid, 3004) +/** Request contained data with a value too long */ +EOS_RESULT_VALUE(EOS_Presence_DataValueLengthInvalid, 3005) +/** Request contained an invalid rich text string */ +EOS_RESULT_VALUE(EOS_Presence_RichTextInvalid, 3006) +/** Request contained a rich text string that was too long */ +EOS_RESULT_VALUE(EOS_Presence_RichTextLengthInvalid, 3007) +/** Request contained an invalid status state */ +EOS_RESULT_VALUE(EOS_Presence_StatusInvalid, 3008) + +/** The entitlement retrieved is stale, requery for updated information */ +EOS_RESULT_VALUE(EOS_Ecom_EntitlementStale, 4000) +/** The offer retrieved is stale, requery for updated information */ +EOS_RESULT_VALUE(EOS_Ecom_CatalogOfferStale, 4001) +/** The item or associated structure retrieved is stale, requery for updated information */ +EOS_RESULT_VALUE(EOS_Ecom_CatalogItemStale, 4002) +/** The one or more offers has an invalid price. This may be caused by the price setup. */ +EOS_RESULT_VALUE(EOS_Ecom_CatalogOfferPriceInvalid, 4003) +/** The checkout page failed to load */ +EOS_RESULT_VALUE(EOS_Ecom_CheckoutLoadError, 4004) + +/** Session is already in progress */ +EOS_RESULT_VALUE(EOS_Sessions_SessionInProgress, 5000) +/** Too many players to register with this session */ +EOS_RESULT_VALUE(EOS_Sessions_TooManyPlayers, 5001) +/** Client has no permissions to access this session */ +EOS_RESULT_VALUE(EOS_Sessions_NoPermission, 5002) +/** Session already exists in the system */ +EOS_RESULT_VALUE(EOS_Sessions_SessionAlreadyExists, 5003) +/** Session lock required for operation */ +EOS_RESULT_VALUE(EOS_Sessions_InvalidLock, 5004) +/** Invalid session reference */ +EOS_RESULT_VALUE(EOS_Sessions_InvalidSession, 5005) +/** Sandbox ID associated with auth didn't match */ +EOS_RESULT_VALUE(EOS_Sessions_SandboxNotAllowed, 5006) +/** Invite failed to send */ +EOS_RESULT_VALUE(EOS_Sessions_InviteFailed, 5007) +/** Invite was not found with the service */ +EOS_RESULT_VALUE(EOS_Sessions_InviteNotFound, 5008) +/** This client may not modify the session */ +EOS_RESULT_VALUE(EOS_Sessions_UpsertNotAllowed, 5009) +/** Backend nodes unavailable to process request */ +EOS_RESULT_VALUE(EOS_Sessions_AggregationFailed, 5010) +/** Individual backend node is as capacity */ +EOS_RESULT_VALUE(EOS_Sessions_HostAtCapacity, 5011) +/** Sandbox on node is at capacity */ +EOS_RESULT_VALUE(EOS_Sessions_SandboxAtCapacity, 5012) +/** An anonymous operation was attempted on a non anonymous session */ +EOS_RESULT_VALUE(EOS_Sessions_SessionNotAnonymous, 5013) +/** Session is currently out of sync with the backend, data is saved locally but needs to sync with backend */ +EOS_RESULT_VALUE(EOS_Sessions_OutOfSync, 5014) +/** User has received too many invites */ +EOS_RESULT_VALUE(EOS_Sessions_TooManyInvites, 5015) +/** Presence session already exists for the client */ +EOS_RESULT_VALUE(EOS_Sessions_PresenceSessionExists, 5016) +/** Deployment on node is at capacity */ +EOS_RESULT_VALUE(EOS_Sessions_DeploymentAtCapacity, 5017) +/** Session operation not allowed */ +EOS_RESULT_VALUE(EOS_Sessions_NotAllowed, 5018) + +/** Request filename was invalid */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FilenameInvalid, 6000) +/** Request filename was too long */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FilenameLengthInvalid, 6001) +/** Request filename contained invalid characters */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FilenameInvalidChars, 6002) +/** Request operation would grow file too large */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FileSizeTooLarge, 6003) +/** Request file length is not valid */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FileSizeInvalid, 6004) +/** Request file handle is not valid */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FileHandleInvalid, 6005) +/** Request data is invalid */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_DataInvalid, 6006) +/** Request data length was invalid */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_DataLengthInvalid, 6007) +/** Request start index was invalid */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_StartIndexInvalid, 6008) +/** Request is in progress */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_RequestInProgress, 6009) +/** User is marked as throttled which means he can't perform some operations because limits are exceeded. */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_UserThrottled, 6010) +/** Encryption key is not set during SDK init. */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_EncryptionKeyNotSet, 6011) +/** User data callback returned error (EOS_PlayerDataStorage_EWriteResult::EOS_WR_FailRequest or EOS_PlayerDataStorage_EReadResult::EOS_RR_FailRequest) */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_UserErrorFromDataCallback, 6012) +/** User is trying to read file that has header from newer version of SDK. Game/SDK needs to be updated. */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FileHeaderHasNewerVersion, 6013) +/** The file is corrupted. In some cases retry can fix the issue. */ +EOS_RESULT_VALUE(EOS_PlayerDataStorage_FileCorrupted, 6014) + +/** EOS Auth service deemed the external token invalid */ +EOS_RESULT_VALUE(EOS_Connect_ExternalTokenValidationFailed, 7000) +/** EOS Auth user already exists */ +EOS_RESULT_VALUE(EOS_Connect_UserAlreadyExists, 7001) +/** EOS Auth expired */ +EOS_RESULT_VALUE(EOS_Connect_AuthExpired, 7002) +/** EOS Auth invalid token */ +EOS_RESULT_VALUE(EOS_Connect_InvalidToken, 7003) +/** EOS Auth doesn't support this token type */ +EOS_RESULT_VALUE(EOS_Connect_UnsupportedTokenType, 7004) +/** EOS Auth Account link failure */ +EOS_RESULT_VALUE(EOS_Connect_LinkAccountFailed, 7005) +/** EOS Auth External service for validation was unavailable */ +EOS_RESULT_VALUE(EOS_Connect_ExternalServiceUnavailable, 7006) +/** EOS Auth External Service configuration failure with Dev Portal */ +EOS_RESULT_VALUE(EOS_Connect_ExternalServiceConfigurationFailure, 7007) +/** EOS Auth Account link failure. Tried to link Nintendo Network Service Account without first linking Nintendo Account. DEPRECATED: The requirement has been removed and this error is no longer used. */ +EOS_RESULT_VALUE(EOS_Connect_LinkAccountFailedMissingNintendoIdAccount_DEPRECATED, 7008) + +/** The social overlay page failed to load */ +EOS_RESULT_VALUE(EOS_UI_SocialOverlayLoadError, 8000) + +/** Client has no permissions to modify this lobby */ +EOS_RESULT_VALUE(EOS_Lobby_NotOwner, 9000) +/** Lobby lock required for operation */ +EOS_RESULT_VALUE(EOS_Lobby_InvalidLock, 9001) +/** Lobby already exists in the system */ +EOS_RESULT_VALUE(EOS_Lobby_LobbyAlreadyExists, 9002) +/** Lobby is already in progress */ +EOS_RESULT_VALUE(EOS_Lobby_SessionInProgress, 9003) +/** Too many players to register with this lobby */ +EOS_RESULT_VALUE(EOS_Lobby_TooManyPlayers, 9004) +/** Client has no permissions to access this lobby */ +EOS_RESULT_VALUE(EOS_Lobby_NoPermission, 9005) +/** Invalid lobby session reference */ +EOS_RESULT_VALUE(EOS_Lobby_InvalidSession, 9006) +/** Sandbox ID associated with auth didn't match */ +EOS_RESULT_VALUE(EOS_Lobby_SandboxNotAllowed, 9007) +/** Invite failed to send */ +EOS_RESULT_VALUE(EOS_Lobby_InviteFailed, 9008) +/** Invite was not found with the service */ +EOS_RESULT_VALUE(EOS_Lobby_InviteNotFound, 9009) +/** This client may not modify the lobby */ +EOS_RESULT_VALUE(EOS_Lobby_UpsertNotAllowed, 9010) +/** Backend nodes unavailable to process request */ +EOS_RESULT_VALUE(EOS_Lobby_AggregationFailed, 9011) +/** Individual backend node is as capacity */ +EOS_RESULT_VALUE(EOS_Lobby_HostAtCapacity, 9012) +/** Sandbox on node is at capacity */ +EOS_RESULT_VALUE(EOS_Lobby_SandboxAtCapacity, 9013) +/** User has received too many invites */ +EOS_RESULT_VALUE(EOS_Lobby_TooManyInvites, 9014) +/** Deployment on node is at capacity */ +EOS_RESULT_VALUE(EOS_Lobby_DeploymentAtCapacity, 9015) +/** Lobby operation not allowed */ +EOS_RESULT_VALUE(EOS_Lobby_NotAllowed, 9016) +/** While restoring a lost connection lobby ownership changed and only local member data was updated */ +EOS_RESULT_VALUE(EOS_Lobby_MemberUpdateOnly, 9017) +/** Presence lobby already exists for the client */ +EOS_RESULT_VALUE(EOS_Lobby_PresenceLobbyExists, 9018) + +/** User callback that receives data from storage returned error. */ +EOS_RESULT_VALUE(EOS_TitleStorage_UserErrorFromDataCallback, 10000) +/** User forgot to set Encryption key during platform init. Title Storage can't work without it. */ +EOS_RESULT_VALUE(EOS_TitleStorage_EncryptionKeyNotSet, 10001) +/** Downloaded file is corrupted. */ +EOS_RESULT_VALUE(EOS_TitleStorage_FileCorrupted, 10002) +/** Downloaded file's format is newer than client SDK version. */ +EOS_RESULT_VALUE(EOS_TitleStorage_FileHeaderHasNewerVersion, 10003) + +/** ModSdk process is already running. This error comes from the EOSSDK. */ +EOS_RESULT_VALUE(EOS_Mods_ModSdkProcessIsAlreadyRunning, 11000) +/** ModSdk command is empty. Either the ModSdk configuration file is missing or the manifest location is empty. */ +EOS_RESULT_VALUE(EOS_Mods_ModSdkCommandIsEmpty, 11001) +/** Creation of the ModSdk process failed. This error comes from the SDK. */ +EOS_RESULT_VALUE(EOS_Mods_ModSdkProcessCreationFailed, 11002) +/** A critical error occurred in the external ModSdk process that we were unable to resolve. */ +EOS_RESULT_VALUE(EOS_Mods_CriticalError, 11003) +/** A internal error occurred in the external ModSdk process that we were unable to resolve. */ +EOS_RESULT_VALUE(EOS_Mods_ToolInternalError, 11004) +/** A IPC failure occurred in the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_IPCFailure, 11005) +/** A invalid IPC response received in the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_InvalidIPCResponse, 11006) +/** A URI Launch failure occurred in the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_URILaunchFailure, 11007) +/** Attempting to perform an action with a mod that is not installed. This error comes from the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_ModIsNotInstalled, 11008) +/** Attempting to perform an action on a game that the user doesn't own. This error comes from the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_UserDoesNotOwnTheGame, 11009) +/** Invalid result of the request to get the offer for the mod. This error comes from the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_OfferRequestByIdInvalidResult, 11010) +/** Could not find the offer for the mod. This error comes from the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_CouldNotFindOffer, 11011) +/** Request to get the offer for the mod failed. This error comes from the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_OfferRequestByIdFailure, 11012) +/** Request to purchase the mod failed. This error comes from the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_PurchaseFailure, 11013) +/** Attempting to perform an action on a game that is not installed or is partially installed. This error comes from the external ModSdk process. */ +EOS_RESULT_VALUE(EOS_Mods_InvalidGameInstallInfo, 11014) +/** Failed to get manifest location. Either the ModSdk configuration file is missing or the manifest location is empty */ +EOS_RESULT_VALUE(EOS_Mods_CannotGetManifestLocation, 11015) +/** Attempting to perform an action with a mod that does not support the current operating system. */ +EOS_RESULT_VALUE(EOS_Mods_UnsupportedOS, 11016) + +/** An unexpected error that we cannot identify has occurred. */ +EOS_RESULT_VALUE_LAST(EOS_UnexpectedError, 0x7FFFFFFF) diff --git a/Unlocker/src/platforms/origin/Origin.cpp b/Unlocker/src/platforms/origin/Origin.cpp new file mode 100644 index 0000000..a486503 --- /dev/null +++ b/Unlocker/src/platforms/origin/Origin.cpp @@ -0,0 +1,174 @@ +#include "pch.h" +#include "Origin.h" +#include "origin_hooks.h" +#include "util.h" + +// Can't include it globally because it pollutes global namespace. +// More specifically, the `interface` name is colliding with steam hooks +#pragma warning(push) // Disable 3rd party library warnings +#pragma warning(disable: ALL_CODE_ANALYSIS_WARNINGS) +#include +#include +#pragma warning(pop) + +using nlohmann::json; + +constexpr auto url = "https://raw.githubusercontent.com/acidicoala/public-entitlements/main/origin/v1/entitlements.json"; + +const auto XML_PATH = getWorkingDirPath() / "cache" / "origin-entitlements.xml"; +const auto ETAG_PATH = getWorkingDirPath() / "cache" / "origin-entitlements.etag"; + +struct Entitlement +{ + string entitlementTag; + string entitlementType; + string groupName; + string productId; +}; + +void from_json(const json& j, Entitlement& p) +{ + j["entitlementTag"].get_to(p.entitlementTag); + j["entitlementType"].get_to(p.entitlementType); + j["groupName"].get_to(p.groupName); + j["productId"].get_to(p.productId); +} + +void fetchEntitlements() +{ + logger->debug("Fetching Origin entitlements"); + + auto xml = readFileContents(XML_PATH.string()); + auto etag = readFileContents(ETAG_PATH.string()); + + // If the file is empty, then reset etag + if(xml.empty()) + etag = ""; + + cpr::Response r = cpr::Get( + cpr::Url{ url }, + cpr::Header{ {"If-None-Match", etag} }, + cpr::Timeout{ 3 * 1000 } // 3s + ); + + if(r.status_code == 304) + { + logger->debug("Cached Origin entitlements have not changed"); + return; + } + + if(r.status_code != 200) + { + logger->error("Failed to fetch Origin entitlements: {} - {}", r.error.code, r.error.message); + return; + } + + vector jsonEntitlements; + + try + { + // Parse json into our vector + json::parse(r.text, nullptr, true, true).get_to(jsonEntitlements); + } catch(json::exception& ex) + { + logger->error("Error parsing Origin entitlements json: {}", ex.what()); + return; + } + + entitlementsXML.Clear(); + auto pEntitlements = entitlementsXML.NewElement("Entitlements"); + entitlementsXML.InsertFirstChild(pEntitlements); + + int index = 1000000; + for(const auto& e : jsonEntitlements) + { + auto pEntitlement = entitlementsXML.NewElement("Entitlement"); + pEntitlement->SetAttribute("EntitlementTag", e.entitlementTag.c_str()); + pEntitlement->SetAttribute("ItemId", e.productId.c_str()); + pEntitlement->SetAttribute("Group", e.groupName.c_str()); + pEntitlement->SetAttribute("Type", e.entitlementType.c_str()); + pEntitlement->SetAttribute("EntitlementId", index++); + pEntitlement->SetAttribute("Source", "ORIGIN-OIG"); + pEntitlement->SetAttribute("UseCount", 0); + pEntitlement->SetAttribute("Version", 0); + pEntitlement->SetAttribute("ResourceId", ""); + pEntitlement->SetAttribute("LastModifiedDate", "2021-01-01T00:00:00Z"); + pEntitlement->SetAttribute("Expiration", "0000-00-00T00:00:00"); + pEntitlement->SetAttribute("GrantDate", "2021-01-01T00:00:00Z"); + + pEntitlements->InsertEndChild(pEntitlement); + } + + // Make a printer to convert the document object into string + XMLPrinter printer; + entitlementsXML.Print(&printer); + + // Cache entitlements + auto r1 = writeFileContents(XML_PATH, printer.CStr()); + + // Cache etag + auto r2 = writeFileContents(ETAG_PATH, r.header["etag"]); + + if(r1 && r2) + logger->info("Origin entitlements were successfully fetched and cached"); +} + +void readEntitlementsFromFile() +{ + logger->debug("Reading origin entitlements from cache"); + + auto text = readFileContents(XML_PATH.string()); + + if(text.empty()) + { + logger->error("Origin entitlements file is empty"); + return; + } + + auto result = entitlementsXML.Parse(text.c_str()); + if(result != XMLError::XML_SUCCESS) + { + logger->error("Failed to parse entitlements xml file"); + return; + } + + logger->info("Origin entitlements were successfully read from file"); +} + +void Origin::init() +{ + if(initialized || handle == NULL) + return; + + logger->debug("Initializing Origin platform"); + + // Execute blocking operations in a new thread + std::thread fetchingThread([]{ + logger->debug("Entitlement fetching thread started"); + fetchEntitlements(); + readEntitlementsFromFile(); + logger->debug("Entitlement fetching thread finished"); + }); + fetchingThread.detach(); + + installDetourHook(hooks, encrypt, mangled_encrypt); + + logger->info("Origin platform was initialized"); + initialized = true; +} + +void Origin::shutdown() +{ + if(!initialized) + return; + + logger->debug("Shutting down Origin platform"); + + for(auto& hook : hooks) + { + hook->unHook(); + } + hooks.clear(); + + logger->debug("Origin platform was shut down"); +} diff --git a/Unlocker/src/platforms/origin/Origin.h b/Unlocker/src/platforms/origin/Origin.h new file mode 100644 index 0000000..f8f18f3 --- /dev/null +++ b/Unlocker/src/platforms/origin/Origin.h @@ -0,0 +1,16 @@ +#pragma once + +#include "platforms/BasePlatform.h" +#include "util.h" + +class Origin : public BasePlatform +{ +public: + using BasePlatform::BasePlatform; + + inline static Hooks hooks; + + void init() override; + void shutdown() override; +}; + diff --git a/Unlocker/src/platforms/origin/origin_hooks.cpp b/Unlocker/src/platforms/origin/origin_hooks.cpp new file mode 100644 index 0000000..bf46d52 --- /dev/null +++ b/Unlocker/src/platforms/origin/origin_hooks.cpp @@ -0,0 +1,73 @@ +#include "pch.h" +#include "origin_hooks.h" +#include "platforms/origin/Origin.h" + +XMLDocument entitlementsXML; + +auto getOriginConfig() +{ + return config->platforms["Origin"]; +} + +bool isEntitlementBlacklisted(XMLElement* pEntitlement) +{ + return vectorContains(config->platforms["Origin"].blacklist, string(pEntitlement->FindAttribute("ItemId")->Value())); + +} +string* __fastcall encrypt(PARAMS(void* aes, string* message)) +{ + do + { + XMLDocument xmlDoc; + if(xmlDoc.Parse(message->c_str()) != XMLError::XML_SUCCESS) + break; + + auto pLSX = xmlDoc.FirstChildElement("LSX"); + if(pLSX == nullptr) + break; + + auto pResponse = pLSX->FirstChildElement("Response"); + if(pResponse == nullptr) + break; + + auto pQueryEntitlementsResponse = pResponse->FirstChildElement("QueryEntitlementsResponse"); + if(pQueryEntitlementsResponse == nullptr) + break; + + logger->info("Intercepted QueryEntitlementsResponse"); + + // Origin magic happens here + + // First filter out blacklisted DLCs from the legit response + auto pEntitlement = pQueryEntitlementsResponse->FirstChildElement("Entitlement"); + while(pEntitlement != nullptr) + { + if(isEntitlementBlacklisted(pEntitlement)) + pQueryEntitlementsResponse->DeleteChild(pEntitlement); + pEntitlement = pEntitlement->NextSiblingElement("Entitlement"); + } + + // Insert our entitlements into the original response + pEntitlement = entitlementsXML.FirstChildElement("Entitlements")->FirstChildElement("Entitlement"); + while(pEntitlement != nullptr) + { + // Have to make a copy because TinyXML2 doesn't allow insertion of elements from another doc... + if(!isEntitlementBlacklisted(pEntitlement)) + pQueryEntitlementsResponse->InsertEndChild(pEntitlement->DeepClone(&xmlDoc)); + pEntitlement = pEntitlement->NextSiblingElement("Entitlement"); + } + + XMLPrinter printer; + xmlDoc.Print(&printer); + *message = printer.CStr(); // copy constructor + + logger->info("Modified response: \n{}", printer.CStr()); + } while(false); + + auto result = PLH::FnCast( + BasePlatform::trampolineMap[mangled_encrypt], + encrypt + )(ARGS(aes, message)); + + return result; +} diff --git a/Unlocker/src/platforms/origin/origin_hooks.h b/Unlocker/src/platforms/origin/origin_hooks.h new file mode 100644 index 0000000..3830ed6 --- /dev/null +++ b/Unlocker/src/platforms/origin/origin_hooks.h @@ -0,0 +1,14 @@ +#pragma once +#include "util.h" +#include "hook_util.h" + +constexpr auto mangled_encrypt = "?encrypt@SimpleEncryption@Crypto@Services@Origin@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV56@@Z"; + +using namespace tinyxml2; + +extern XMLDocument entitlementsXML; + +// The demangled signature is this: +// std::string __thiscall Origin::Services::Crypto::SimpleEncryption::encrypt(std::string const &) +// But it doesn't work. It needs strings to be pointers and some mystery argument. Why? +string* __fastcall encrypt(PARAMS(void* aes, string* message)); diff --git a/Unlocker/src/platforms/steam/Steam.cpp b/Unlocker/src/platforms/steam/Steam.cpp new file mode 100644 index 0000000..c5762da --- /dev/null +++ b/Unlocker/src/platforms/steam/Steam.cpp @@ -0,0 +1,45 @@ +#include "pch.h" +#include "Steam.h" +#include "steam_hooks.h" +#include "constants.h" + +#define HOOK(FUNC) installDetourHook(hooks, FUNC, #FUNC) + +void Steam::init() +{ + if(initialized || handle == NULL) + return; + + logger->debug("Initializing Steam platform"); + + HOOK(SteamInternal_FindOrCreateUserInterface); + HOOK(SteamInternal_CreateInterface); + HOOK(SteamApps); + HOOK(SteamClient); + + logger->info("Steam platform was initialized"); + initialized = true; +} + +void Steam::shutdown() +{ + if(!initialized) + return; + + logger->debug("Shutting down Steam platform"); + + + for(auto& hook : hooks) + { + try + { + hook->unHook(); + } catch(std::exception& e) + { + logger->error("Failed to unhook: {}", e.what()); + } + } + hooks.clear(); + + logger->debug("Steam platform was shut down"); +} diff --git a/Unlocker/src/platforms/steam/Steam.h b/Unlocker/src/platforms/steam/Steam.h new file mode 100644 index 0000000..4ea930d --- /dev/null +++ b/Unlocker/src/platforms/steam/Steam.h @@ -0,0 +1,14 @@ +#pragma once +#include "../BasePlatform.h" +#include "steamtypes.h" + +class Steam : public BasePlatform +{ +public: + using BasePlatform::BasePlatform; + + inline static Hooks hooks; + + void init() override; + void shutdown() override; +}; diff --git a/Unlocker/src/platforms/steam/steam_hooks.cpp b/Unlocker/src/platforms/steam/steam_hooks.cpp new file mode 100644 index 0000000..5fc41ac --- /dev/null +++ b/Unlocker/src/platforms/steam/steam_hooks.cpp @@ -0,0 +1,238 @@ +#include "pch.h" +#include "steam_hooks.h" +#include "hook_util.h" +#include "steam_ordinals.h" +#include "platforms/steam/Steam.h" + +auto getSteamConfig() +{ + return config->platforms["Steam"]; +} + +// forward declaration +void hookVirtualFunctions(void* interface, string version); + +///////////////////////// +/// Virtual functions /// +///////////////////////// + +bool __fastcall ISteamApps_BIsSubscribedApp(PARAMS(AppId_t appID)) +{ + // Steam magic happens here + auto subscribed = !vectorContains(getSteamConfig().blacklist, std::to_string(appID)); + logger->info("\tISteamApps_BIsSubscribedApp -> App ID: {}, Subscribed: {}", appID, subscribed); + return subscribed; +} + +bool __fastcall ISteamApps_BIsDlcInstalled(PARAMS(AppId_t appID)) +{ + // Steam magic happens here (2) + auto installed = !vectorContains(getSteamConfig().blacklist, std::to_string(appID)); + logger->info("\tISteamApps_BIsDlcInstalled -> App ID: {}, Installed: {}", appID, installed); + return installed; +} + +int __fastcall ISteamApps_GetDLCCount(PARAMS()) +{ + logger->debug("ISteamApps_GetDLCCount"); + + auto result = PLH::FnCast( + BasePlatform::origVFuncMap[STEAM_APPS][ordinalMap[STEAM_APPS]["GetDLCCount"]], + ISteamApps_GetDLCCount + )(ARGS()); + + logger->info("\tDLC count: {}", result); + + return result; +} + +bool __fastcall ISteamApps_BGetDLCDataByIndex(PARAMS(int iDLC, AppId_t* pAppID, bool* pbAvailable, char* pchName, int cchNameBufferSize)) +{ + logger->debug("\tISteamApps_BGetDLCDataByIndex -> index: {}", iDLC); + + auto result = PLH::FnCast( + BasePlatform::origVFuncMap[STEAM_APPS][ordinalMap[STEAM_APPS]["BGetDLCDataByIndex"]], + ISteamApps_BGetDLCDataByIndex + )(ARGS(iDLC, pAppID, pbAvailable, pchName, cchNameBufferSize)); + + // Steam magic happens here (3) + *pbAvailable = !vectorContains(getSteamConfig().blacklist, std::to_string(*pAppID)); + + logger->info("\tDLC Data -> index: {}, App ID: {}, available: {}, name: {}", iDLC, *pAppID, *pbAvailable, pchName); + + return result; +} + +// I'm not sure if we need to hook this +EUserHasLicenseForAppResult __stdcall ISteamUser_UserHasLicenseForApp(PARAMS(CSteamID* steamID, AppId_t appID)) +{ + logger->debug("UserHasLicenseForApp -> appID: {}", appID); + + return EUserHasLicenseForAppResult::k_EUserHasLicenseResultHasLicense; +} + +ISteamApps* __fastcall ISteamClient_GetISteamApps(PARAMS(HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char* version)) +{ + logger->debug("ISteamClient_GetISteamApps -> version: \"{}\"", version); + + auto interface = PLH::FnCast( + BasePlatform::origVFuncMap[STEAM_CLIENT][ordinalMap[STEAM_CLIENT]["GetISteamApps"]], + ISteamClient_GetISteamApps + )(ARGS(hSteamUser, hSteamPipe, version)); + + hookVirtualFunctions(interface, version); + + return interface; +} + +/////////////////////// +// Global functions /// +/////////////////////// + +void* SteamInternal_FindOrCreateUserInterface(HSteamUser hSteamUser, const char* version) +{ + logger->debug("SteamInternal_FindOrCreateUserInterface -> User: {}, Version: \"{}\"", hSteamUser, version); + + auto interface = PLH::FnCast( + BasePlatform::trampolineMap[__func__], + SteamInternal_FindOrCreateUserInterface + )(hSteamUser, version); + + hookVirtualFunctions(interface, version); + + return interface; +} + +void* SteamInternal_CreateInterface(const char* version) +{ + logger->debug("SteamInternal_CreateInterface -> Version: \"{}\"", version); + + auto interface = PLH::FnCast( + BasePlatform::trampolineMap[__func__], + SteamInternal_CreateInterface + )(version); + + hookVirtualFunctions(interface, version); + + return interface; +} + + +// TODO: We don't know the interface version that games expects when it uses unversioned interface. +// For now let's assume earliest supported, but ideally we need to somehow determine exact version, +// since different SteamClient versions have different ordinals for interfaces. + +void* SteamApps() +{ + logger->debug("SteamApps -> Version: {}", "UNVERSIONED"); + + auto interface = PLH::FnCast( + BasePlatform::trampolineMap["SteamApps"], + SteamApps + )(); + + hookVirtualFunctions(interface, STEAM_APPS + "003"); + + return interface; +} + +void* SteamClient() +{ + logger->debug("SteamClient -> Version: {}", "UNVERSIONED"); + + auto interface = PLH::FnCast( + BasePlatform::trampolineMap[STEAM_CLIENT], + SteamClient + )(); + + hookVirtualFunctions(interface, STEAM_CLIENT + "012"); + + return interface; +} + + +void hookVirtualFunctions(void* interface, string version) +{ + logger->debug("hookVirtualFunctions -> interface: 0x{:X}, version: {}", (uint64_t) interface, version); + + if(interface == NULL) // Nothing to hook + return; // This means that the game has tried to use an interface before initializing steam api + + if(startsWith(version, STEAM_CLIENT) && BasePlatform::origVFuncMap.count(STEAM_CLIENT) == 0) + { + logger->info("Hooking SteamClient interface: \"{}\"", version); + + const auto versionNumber = stoi(version.substr(STEAM_CLIENT.length())); + if(versionNumber < 12) + { + logger->error("Not implemented version of SteamUser"); + return; + } + + PLH::VFuncMap redirect = { + { ordinalMap[STEAM_CLIENT]["GetISteamApps"], (uint64_t) ISteamClient_GetISteamApps}, + }; + + Steam::hooks.push_back(make_unique((char*) interface, redirect, &BasePlatform::origVFuncMap[STEAM_CLIENT])); + if(!Steam::hooks.back()->hook()) + { + logger->error("Failed to hook"); + Steam::hooks.pop_back(); + } + } + + + if(startsWith(version, STEAM_APPS) && BasePlatform::origVFuncMap.count(STEAM_APPS) == 0) + { + logger->debug("Hooking SteamApps interface: \"{}\"", version); + + PLH::VFuncMap redirect = { + {ordinalMap[STEAM_APPS]["BIsSubscribedApp"], (uint64_t) ISteamApps_BIsSubscribedApp}, + {ordinalMap[STEAM_APPS]["BIsDlcInstalled"], (uint64_t) ISteamApps_BIsDlcInstalled}, + }; + const auto versionNumber = stoi(version.substr(STEAM_APPS.length())); + if(versionNumber >= 4) + { + redirect.emplace(ordinalMap[STEAM_APPS]["GetDLCCount"], (uint64_t) ISteamApps_GetDLCCount); + redirect.emplace(ordinalMap[STEAM_APPS]["BGetDLCDataByIndex"], (uint64_t) ISteamApps_BGetDLCDataByIndex); + } + + Steam::hooks.push_back(make_unique((char*) interface, redirect, &BasePlatform::origVFuncMap[STEAM_APPS])); + if(Steam::hooks.back()->hook()) + { + logger->debug("Steam apps interface was successfully hooked"); + } + else + { + logger->error("Failed to hook"); + Steam::hooks.pop_back(); + } + } + + if(startsWith(version, STEAM_USER) && Steam::origVFuncMap.count(STEAM_USER) == 0) + { + logger->debug("Hooking SteamUser interface: \"{}\"", version); + + const auto versionNumber = stoi(version.substr(STEAM_USER.length())); + if(versionNumber < 15) + { + logger->error("Not implemented version of SteamUser"); + return; + } + + PLH::VFuncMap redirect = { + {ordinalMap[STEAM_USER]["UserHasLicenseForApp"], (uint64_t) ISteamUser_UserHasLicenseForApp}, + }; + + Steam::hooks.push_back(make_unique((char*) interface, redirect, &Steam::origVFuncMap[STEAM_USER])); + if(Steam::hooks.back()->hook()) + { + logger->debug("Steam user interface was successfully hooked"); + } + else + { + logger->error("Failed to hook"); + Steam::hooks.pop_back(); + } + } +} diff --git a/Unlocker/src/platforms/steam/steam_hooks.h b/Unlocker/src/platforms/steam/steam_hooks.h new file mode 100644 index 0000000..7677778 --- /dev/null +++ b/Unlocker/src/platforms/steam/steam_hooks.h @@ -0,0 +1,15 @@ +#include "steamtypes.h" + +// TODO: This only works if SteamAPI dll is loaded only once. +// Multiple loaded SteamAPI dlls will result in undefined behaviour. +// One solution is to store all global objects into a map, +// with key being the handle to the dll. + + +// Safe interfaces +void* S_CALLTYPE SteamInternal_FindOrCreateUserInterface(HSteamUser hSteamUser, const char* pszVersion); +void* S_CALLTYPE SteamInternal_CreateInterface(const char* pszVersion); + +// Legacy interfaces +void* S_CALLTYPE SteamApps(); +void* S_CALLTYPE SteamClient(); diff --git a/Unlocker/src/platforms/steam/steam_ordinals.h b/Unlocker/src/platforms/steam/steam_ordinals.h new file mode 100644 index 0000000..5498a64 --- /dev/null +++ b/Unlocker/src/platforms/steam/steam_ordinals.h @@ -0,0 +1,52 @@ +#pragma once +#include "util.h" + +// IMPORTANT: Since this files directly defines members, +// it can only be included once. + +const auto STEAM_APPS = string("STEAMAPPS_INTERFACE_VERSION"); +const auto STEAM_CLIENT = string("SteamClient"); +const auto STEAM_USER = string("SteamUser"); + +typedef map VFuncOrdinalMap; +typedef map InterfaceMap; + +// https://github.com/SteamRE/open-steamworks/tree/master/Steam4NET2/Steam4NET2/autogen +// Maps interfaces to their function ordinals +InterfaceMap ordinalMap = { + {STEAM_APPS, { // This is a rather stable interface + {"BIsSubscribedApp", 6}, // [002 - 008]. Missing in [001] + {"BIsDlcInstalled", 7}, // [003 - 008]. Missing in [001 - 002] + {"GetDLCCount", 10}, // [004 - 008]. Missing in [001 - 003] + {"BGetDLCDataByIndex", 11} // [004 - 008]. Missing in [001 - 003] + }}, + {STEAM_CLIENT, { // TODO: Patche the ordinal dynamically? + /* + 001: N/A. + ... + 006: 16 + 007: 18 + 008: 15 + 009: 16 + ... + 011: 16 + 012: 15 + ... + 020: 15 + */ + {"GetISteamApps", 15} // Missing in [001 - 005] + }}, + {STEAM_USER, { // Do we really need it anyway? + /* + 001: N/A + ... + 012: 15 + 013: 16 + ... + 015: 17 + ... + 021: 17 + */ + {"UserHasLicenseForApp", 17} // Missing in [001 - 011]. + }} +}; diff --git a/Unlocker/src/platforms/steam/steamtypes.h b/Unlocker/src/platforms/steam/steamtypes.h new file mode 100644 index 0000000..c2f62e9 --- /dev/null +++ b/Unlocker/src/platforms/steam/steamtypes.h @@ -0,0 +1,203 @@ +//========= Copyright 1996-2008, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMTYPES_H +#define STEAMTYPES_H +#ifdef _WIN32 +#pragma once +#endif + +#define S_CALLTYPE __cdecl + +// Steam-specific types. Defined here so this header file can be included in other code bases. +#ifndef WCHARTYPES_H +typedef unsigned char uint8; +#endif + +#if defined( __GNUC__ ) && !defined(POSIX) + #if __GNUC__ < 4 + #error "Steamworks requires GCC 4.X (4.2 or 4.4 have been tested)" + #endif + #define POSIX 1 +#endif + +#if defined(__x86_64__) || defined(_WIN64) || defined(__aarch64__) +#define X64BITS +#endif + +// Make sure VALVE_BIG_ENDIAN gets set on PS3, may already be set previously in Valve internal code. +#if !defined(VALVE_BIG_ENDIAN) && defined(_PS3) +#define VALVE_BIG_ENDIAN +#endif + +typedef unsigned char uint8; +typedef signed char int8; + +#if defined( _WIN32 ) + +typedef __int16 int16; +typedef unsigned __int16 uint16; +typedef __int32 int32; +typedef unsigned __int32 uint32; +typedef __int64 int64; +typedef unsigned __int64 uint64; + +typedef int64 lint64; +typedef uint64 ulint64; + +#ifdef X64BITS +typedef __int64 intp; // intp is an integer that can accomodate a pointer +typedef unsigned __int64 uintp; // (ie, sizeof(intp) >= sizeof(int) && sizeof(intp) >= sizeof(void *) +#else +typedef __int32 intp; +typedef unsigned __int32 uintp; +#endif + +#else // _WIN32 + +typedef short int16; +typedef unsigned short uint16; +typedef int int32; +typedef unsigned int uint32; +typedef long long int64; +typedef unsigned long long uint64; + +// [u]int64 are actually defined as 'long long' and gcc 64-bit +// doesn't automatically consider them the same as 'long int'. +// Changing the types for [u]int64 is complicated by +// there being many definitions, so we just +// define a 'long int' here and use it in places that would +// otherwise confuse the compiler. +typedef long int lint64; +typedef unsigned long int ulint64; + +#ifdef X64BITS +typedef long long intp; +typedef unsigned long long uintp; +#else +typedef int intp; +typedef unsigned int uintp; +#endif + +#endif // else _WIN32 + +#ifdef API_GEN +# define STEAM_CLANG_ATTR(ATTR) __attribute__((annotate( ATTR ))) +#else +# define STEAM_CLANG_ATTR(ATTR) +#endif + +#define STEAM_METHOD_DESC(DESC) STEAM_CLANG_ATTR( "desc:" #DESC ";" ) +#define STEAM_IGNOREATTR() STEAM_CLANG_ATTR( "ignore" ) +#define STEAM_OUT_STRUCT() STEAM_CLANG_ATTR( "out_struct: ;" ) +#define STEAM_OUT_STRING() STEAM_CLANG_ATTR( "out_string: ;" ) +#define STEAM_OUT_ARRAY_CALL(COUNTER,FUNCTION,PARAMS) STEAM_CLANG_ATTR( "out_array_call:" #COUNTER "," #FUNCTION "," #PARAMS ";" ) +#define STEAM_OUT_ARRAY_COUNT(COUNTER, DESC) STEAM_CLANG_ATTR( "out_array_count:" #COUNTER ";desc:" #DESC ) +#define STEAM_ARRAY_COUNT(COUNTER) STEAM_CLANG_ATTR( "array_count:" #COUNTER ";" ) +#define STEAM_ARRAY_COUNT_D(COUNTER, DESC) STEAM_CLANG_ATTR( "array_count:" #COUNTER ";desc:" #DESC ) +#define STEAM_BUFFER_COUNT(COUNTER) STEAM_CLANG_ATTR( "buffer_count:" #COUNTER ";" ) +#define STEAM_OUT_BUFFER_COUNT(COUNTER) STEAM_CLANG_ATTR( "out_buffer_count:" #COUNTER ";" ) +#define STEAM_OUT_STRING_COUNT(COUNTER) STEAM_CLANG_ATTR( "out_string_count:" #COUNTER ";" ) +#define STEAM_DESC(DESC) STEAM_CLANG_ATTR("desc:" #DESC ";") +#define STEAM_CALL_RESULT(RESULT_TYPE) STEAM_CLANG_ATTR("callresult:" #RESULT_TYPE ";") +#define STEAM_CALL_BACK(RESULT_TYPE) STEAM_CLANG_ATTR("callback:" #RESULT_TYPE ";") +#define STEAM_FLAT_NAME(NAME) STEAM_CLANG_ATTR("flat_name:" #NAME ";") + +const int k_cubSaltSize = 8; +typedef uint8 Salt_t[ k_cubSaltSize ]; + +//----------------------------------------------------------------------------- +// GID (GlobalID) stuff +// This is a globally unique identifier. It's guaranteed to be unique across all +// racks and servers for as long as a given universe persists. +//----------------------------------------------------------------------------- +// NOTE: for GID parsing/rendering and other utils, see gid.h +typedef uint64 GID_t; + +const GID_t k_GIDNil = 0xffffffffffffffffull; + +// For convenience, we define a number of types that are just new names for GIDs +typedef uint64 JobID_t; // Each Job has a unique ID +typedef GID_t TxnID_t; // Each financial transaction has a unique ID + +const GID_t k_TxnIDNil = k_GIDNil; +const GID_t k_TxnIDUnknown = 0; + +const JobID_t k_JobIDNil = 0xffffffffffffffffull; + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. +typedef uint32 PackageId_t; +const PackageId_t k_uPackageIdInvalid = 0xFFFFFFFF; + +typedef uint32 BundleId_t; +const BundleId_t k_uBundleIdInvalid = 0; + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. +typedef uint32 AppId_t; +const AppId_t k_uAppIdInvalid = 0x0; + +typedef uint64 AssetClassId_t; +const AssetClassId_t k_ulAssetClassIdInvalid = 0x0; + +typedef uint32 PhysicalItemId_t; +const PhysicalItemId_t k_uPhysicalItemIdInvalid = 0x0; + + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. AppIds and DepotIDs also presently +// share the same namespace, but since we'd like to change that in the future +// I've defined it seperately here. +typedef uint32 DepotId_t; +const DepotId_t k_uDepotIdInvalid = 0x0; + +// RTime32 +// We use this 32 bit time representing real world time. +// It offers 1 second resolution beginning on January 1, 1970 (Unix time) +typedef uint32 RTime32; + +typedef uint32 CellID_t; +const CellID_t k_uCellIDInvalid = 0xFFFFFFFF; + +// handle to a Steam API call +typedef uint64 SteamAPICall_t; +const SteamAPICall_t k_uAPICallInvalid = 0x0; + +typedef uint32 AccountID_t; + +typedef uint32 PartnerId_t; +const PartnerId_t k_uPartnerIdInvalid = 0; + +// ID for a depot content manifest +typedef uint64 ManifestId_t; +const ManifestId_t k_uManifestIdInvalid = 0; + +// ID for cafe sites +typedef uint64 SiteId_t; +const SiteId_t k_ulSiteIdInvalid = 0; + +// Party Beacon ID +typedef uint64 PartyBeaconID_t; +const PartyBeaconID_t k_ulPartyBeaconIdInvalid = 0; + + +// Custom additions +typedef int32 HSteamUser; +typedef int32 HSteamPipe; +typedef void ISteamApps; +typedef void CSteamID; // some struct, nobody cares + +// results from UserHasLicenseForApp +enum class EUserHasLicenseForAppResult +{ + k_EUserHasLicenseResultHasLicense = 0, // User has a license for specified app + k_EUserHasLicenseResultDoesNotHaveLicense = 1, // User does not have a license for the specified app + k_EUserHasLicenseResultNoAuth = 2, // User has not been authenticated +}; + + +#endif // STEAMTYPES_H diff --git a/Unlocker/src/platforms/ubisoft/Ubisoft.cpp b/Unlocker/src/platforms/ubisoft/Ubisoft.cpp new file mode 100644 index 0000000..b4ae50d --- /dev/null +++ b/Unlocker/src/platforms/ubisoft/Ubisoft.cpp @@ -0,0 +1,36 @@ +#include "pch.h" +#include "Ubisoft.h" +#include "ubisoft_hooks.h" + +#define HOOK(FUNC) installDetourHook(hooks, FUNC, #FUNC); + +void Ubisoft::init() +{ + if(initialized || handle == NULL) + return; + + logger->debug("Initializing Ubisoft platform"); + + HOOK(UPC_Init); + HOOK(UPC_ProductListGet); + HOOK(UPC_ProductListFree); + + logger->info("Ubisoft platform was initialized"); + initialized = true; +} + +void Ubisoft::shutdown() +{ + if(!initialized) + return; + + logger->debug("Shutting down Ubisoft platform"); + + for(auto& hook : hooks) + { + hook->unHook(); + } + hooks.clear(); + + logger->debug("Ubisoft platform was shut down"); +} diff --git a/Unlocker/src/platforms/ubisoft/Ubisoft.h b/Unlocker/src/platforms/ubisoft/Ubisoft.h new file mode 100644 index 0000000..db8c8e7 --- /dev/null +++ b/Unlocker/src/platforms/ubisoft/Ubisoft.h @@ -0,0 +1,13 @@ +#pragma once +#include "platforms/BasePlatform.h" +class Ubisoft : public BasePlatform +{ +public: + using BasePlatform::BasePlatform; + + inline static Hooks hooks; + + void init() override; + void shutdown() override; +}; + diff --git a/Unlocker/src/platforms/ubisoft/ubisoft_hooks.cpp b/Unlocker/src/platforms/ubisoft/ubisoft_hooks.cpp new file mode 100644 index 0000000..71a927e --- /dev/null +++ b/Unlocker/src/platforms/ubisoft/ubisoft_hooks.cpp @@ -0,0 +1,140 @@ +#include "pch.h" +#include "ubisoft_hooks.h" +#include "platforms/ubisoft/Ubisoft.h" + +#define GET_PROXY_FUNC(FUNC) \ + static auto proxyFunc = PLH::FnCast(BasePlatform::trampolineMap[#FUNC], FUNC); + +using namespace UPC; + +vector products; + +vector dlcs; +vector items; + + +string productTypeToString(ProductType type) +{ + switch(type) + { + case ProductType::App: + return "App"; + case ProductType::DLC: + return "DLC"; + case ProductType::Item: + return "Item"; + default: + return "Unexpected Type"; + } +} + +int UPC_Init(unsigned int version, unsigned int appID) +{ + logger->info("{} -> version: {}, appid: {}", __func__, version, appID); + + products.push_back(Product(appID, ProductType::App)); + for(auto& dlc : dlcs) + { + products.push_back(Product(dlc, ProductType::DLC)); + } + + for(auto& item : items) + { + products.push_back(Product(item, ProductType::Item)); + } + + GET_PROXY_FUNC(UPC_Init); + + return proxyFunc(version, appID); +} + +int UPC_ProductListFree(void* context, ProductList* inProductList) +{ + logger->debug(__func__); + if(inProductList) + { + for(unsigned i = 0; i < inProductList->length; ++i) + { + delete inProductList->data[i]; + } + + delete[] inProductList->data; + } + + delete inProductList; + return 0; +} + +void ProductListGetCallback(unsigned long arg1, void* data) +{ + logger->debug("{} -> arg1: {}, data: {}", arg1, data); + + auto callbackContainer = (CallbackContainer*) data; + + logger->debug("Legit product list:"); + + vector missingProducts; + auto list = callbackContainer->legitProductList; + for(uint32_t i = 0; i < list->length; i++) + { + auto product = list->data[i]; + + logger->debug( + "\tApp ID: {}, Type: {}, Mystery1: {}, Mystery2: {}, Always0: {}, Always3: {}", + product->appid, product->type, product->mystery1, product->mystery2, product->always_0, product->always_3 + ); + + if(!(vectorContains(dlcs, product->appid) || vectorContains(items, product->appid))) + if(product->type != ProductType::App) + missingProducts.push_back(product); + } + + if(missingProducts.size() != 0) + logger->warn("Some of the legitimately owned products are missing from the config: "); + + for(const auto& missingProduct : missingProducts) + { + logger->warn("\tApp ID: {}, Type: {}", missingProduct->appid, productTypeToString(missingProduct->type)); + } + + // Free the legit product list + GET_PROXY_FUNC(UPC_ProductListFree); + proxyFunc(callbackContainer->context, callbackContainer->legitProductList); + + callbackContainer->originalCallback(arg1, callbackContainer->callbackData); + logger->debug("Game callback was called"); + + delete callbackContainer; +} + +int UPC_ProductListGet( + void* context, + char* inOptUserIdUtf8, + unsigned int filter, + UPC::ProductList** outProductList, + UPC::UplayCallback callback, + void* callbackData +) +{ + logger->debug("{}", __func__); + + auto productList = new ProductList(); + productList->data = new Product * [products.size()]; + for(unsigned int i = 0; i < products.size(); i++) + { + productList->data[i] = new Product(products.at(i)); + } + + productList->length = (uint32_t) products.size(); + *outProductList = productList; + + auto callbackContainer = new CallbackContainer{ + context, + callback, + callbackData + }; + + GET_PROXY_FUNC(UPC_ProductListGet); + return proxyFunc(context, inOptUserIdUtf8, filter, &callbackContainer->legitProductList, ProductListGetCallback, callbackContainer); +} + diff --git a/Unlocker/src/platforms/ubisoft/ubisoft_hooks.h b/Unlocker/src/platforms/ubisoft/ubisoft_hooks.h new file mode 100644 index 0000000..c531dc5 --- /dev/null +++ b/Unlocker/src/platforms/ubisoft/ubisoft_hooks.h @@ -0,0 +1,65 @@ +#pragma once + +#include "hook_util.h" + +namespace UPC +{ + +enum class ProductType +{ + App = 1, + DLC = 2, + Item = 4 +}; + +struct Product +{ + Product(uint32_t appid, ProductType type) + { + this->appid = appid; + this->type = type; + this->mystery1 = type == ProductType::Item ? 4 : 1; + this->mystery2 = type == ProductType::Item ? 1 : 3; + } + + unsigned int appid; + ProductType type; + unsigned int mystery1; + unsigned int always_3 = 3; + unsigned int always_0 = 0; + unsigned int mystery2; +}; + +struct ProductList +{ + unsigned int length = 0; + unsigned int padding = 0; // What is this? offset? + Product** data = NULL; // Array of pointers +}; + +typedef void (*UplayCallback)(unsigned long, void*); + + +struct CallbackContainer +{ + void* context = NULL; + UplayCallback originalCallback = NULL; + void* callbackData = NULL; + ProductList* legitProductList = NULL; +}; + +} + +extern vector dlcs; +extern vector items; + +int UPC_Init(unsigned int version, unsigned int appid); +int UPC_ProductListFree(void* context, UPC::ProductList* inProductList); +int UPC_ProductListGet( + void* context, + char* inOptUserIdUtf8, + unsigned int filter, + UPC::ProductList** outProductList, + UPC::UplayCallback callback, + void* callbackData +); diff --git a/build_installer.bat b/build_installer.bat new file mode 100644 index 0000000..0d1d0ae --- /dev/null +++ b/build_installer.bat @@ -0,0 +1,8 @@ +cd /D "%~dp0" + +rem This script compiles Koalageddon installer using Inno Setup + +iscc inno_setup.iss + +pause +exit diff --git a/icon.ico b/icon.ico new file mode 100644 index 0000000..c2a8ae8 Binary files /dev/null and b/icon.ico differ diff --git a/inno_setup.iss b/inno_setup.iss new file mode 100644 index 0000000..f06aa34 --- /dev/null +++ b/inno_setup.iss @@ -0,0 +1,59 @@ +; Script generated by the Inno Setup Script Wizard. +; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES! + +#define MyAppName "Koalageddon" +#define MyAppVersion "1.0.0" +#define MyAppPublisher "acidicoala" +#define MyAppURL "https://github.com/acidicoala/Koalageddon" +#define MyAppExeName "IntegrationWizard32.exe" +#define MyOutputFileName "Koalageddon Installer" + +[Setup] +; NOTE: The value of AppId uniquely identifies this application. Do not use the same AppId value in installers for other applications. +; (To generate a new GUID, click Tools | Generate GUID inside the IDE.) +AppId={{42B0E81F-EF53-474B-B4A3-262EDC67D93A} +AppName={#MyAppName} +AppVersion={#MyAppVersion} +;AppVerName={#MyAppName} {#MyAppVersion} +AppPublisher={#MyAppPublisher} +AppPublisherURL={#MyAppURL} +AppSupportURL={#MyAppURL} +AppUpdatesURL={#MyAppURL} +DefaultDirName={autopf}\{#MyAppName} +DefaultGroupName={#MyAppName} +AllowNoIcons=yes +LicenseFile=LICENSE.txt +; Remove the following line to run in administrative install mode (install for all users.) +PrivilegesRequired=lowest +PrivilegesRequiredOverridesAllowed=dialog +OutputDir=_Build +OutputBaseFilename={#MyOutputFileName} +Compression=lzma +SolidCompression=yes +WizardStyle=modern + +[Languages] +Name: "english"; MessagesFile: "compiler:Default.isl" + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; + +[Files] +Source: "_Build\Release\{#MyAppExeName}"; DestDir: "{app}"; Flags: ignoreversion +Source: "_Build\Release\Injector32.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "_Build\Release\Injector64.exe"; DestDir: "{app}"; Flags: ignoreversion +Source: "_Build\Release\Integration32.dll"; DestDir: "{app}"; Flags: ignoreversion +Source: "_Build\Release\Integration64.dll"; DestDir: "{app}"; Flags: ignoreversion +Source: "_Build\Release\Unlocker32.dll"; DestDir: "{app}"; Flags: ignoreversion +Source: "_Build\Release\Unlocker64.dll"; DestDir: "{app}"; Flags: ignoreversion +; NOTE: Don't use "Flags: ignoreversion" on any shared system files + +[Icons] +Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}" +Name: "{group}\{cm:ProgramOnTheWeb,{#MyAppName}}"; Filename: "{#MyAppURL}" +Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}" +Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon + +[Run] +; Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent +