Files
pbz-cppbypass/src/compatibility.cpp
T
KintaroModding cf57b151be Re-pin the bypass for game patch 1.0304629 (1.3)
The 2026-11-28 patch (Steam build 26936481, CL-304629_JKS-17496) moved
every pinned function and shrank the script table from 241 to 221 rows
(198 project scripts). The byte validator is unchanged; the lookup, text
validator, normalizer and free helper only changed their relative calls.

- build_profile.hpp: new exe hash, image size, timestamp, RVAs, counts
  and function digests.
- verify_build.py reads the validator RVAs from the profile instead of
  fixed numbers.
- Version 1.3; README, openmods files and mod.json name the new build.

Offline: native tests and verify_build.py pass against the new PBZ.exe
with UE4SS v4.0.0. The in-game test is pending.
2026-11-28 15:20:03 +01:00

280 lines
13 KiB
C++

#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <bcrypt.h>
#include <MinHook.h>
#include <array>
#include <atomic>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <mutex>
#include <stdexcept>
#include <string>
#include <vector>
#include <unordered_set>
#include "compatibility.hpp"
#include "policy.hpp"
#include "build_profile.hpp"
namespace compat {
namespace {
// Content stays opaque. New names use the game's own FString normalizer and
// matching allocator, as the original table lookup does.
using Validator = bool (*)(const void*, const void*);
using Lookup = const ScriptRecord* (*)(const void*);
using Normalize = GameString* (*)(GameString*, const void*);
using GameFree = void (*)(void*);
Validator original_bytes{}, original_text{};
Lookup lookup{};
Normalize normalize{};
GameFree game_free{};
const ScriptRecord* table{};
void* bytes_target{};
void* text_target{};
bool active{}, initialized{}, attempted{}, enable_attempted{};
HANDLE logfile = INVALID_HANDLE_VALUE;
std::mutex log_mutex;
std::array<std::atomic_bool, profile::record_count> seen{};
std::atomic_uint64_t accepted{}, retained{};
std::mutex additional_mutex;
std::unordered_set<std::wstring> additional_seen;
void log(const char* message) noexcept {
std::lock_guard guard(log_mutex);
if (logfile == INVALID_HANDLE_VALUE) return;
DWORD written;
WriteFile(logfile, message, static_cast<DWORD>(std::strlen(message)), &written, nullptr);
FlushFileBuffers(logfile);
}
class Hash {
BCRYPT_ALG_HANDLE algorithm{};
BCRYPT_HASH_HANDLE hash{};
std::vector<unsigned char> storage;
public:
Hash() {
if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0)
throw std::runtime_error("Cannot open SHA-256 provider");
DWORD size{}, returned{};
if (BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH,
reinterpret_cast<PUCHAR>(&size), sizeof(size), &returned, 0) < 0) {
BCryptCloseAlgorithmProvider(algorithm, 0);
throw std::runtime_error("Cannot read SHA-256 object size");
}
storage.resize(size);
if (BCryptCreateHash(algorithm, &hash, storage.data(), size, nullptr, 0, 0) < 0) {
BCryptCloseAlgorithmProvider(algorithm, 0);
throw std::runtime_error("Cannot create SHA-256 state");
}
}
~Hash() { if (hash) BCryptDestroyHash(hash); if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0); }
void update(const void* bytes, ULONG size) {
if (BCryptHashData(hash, const_cast<PUCHAR>(static_cast<const unsigned char*>(bytes)), size, 0) < 0)
throw std::runtime_error("SHA-256 update failed");
}
std::string finish() {
std::array<unsigned char, 32> digest{};
if (BCryptFinishHash(hash, digest.data(), static_cast<ULONG>(digest.size()), 0) < 0)
throw std::runtime_error("SHA-256 finish failed");
constexpr char hex[] = "0123456789abcdef";
std::string result;
for (auto byte : digest) { result += hex[byte >> 4]; result += hex[byte & 15]; }
return result;
}
};
std::string file_hash(const std::filesystem::path& path) {
std::ifstream file(path, std::ios::binary);
if (!file) throw std::runtime_error("Cannot open a required executable");
std::vector<char> buffer(1 << 20);
Hash hash;
while (file) {
file.read(buffer.data(), buffer.size());
if (file.gcount()) hash.update(buffer.data(), static_cast<ULONG>(file.gcount()));
}
if (!file.eof()) throw std::runtime_error("Executable read failed");
return hash.finish();
}
std::filesystem::path module_path(HMODULE module) {
std::vector<wchar_t> path(32768);
const auto size = GetModuleFileNameW(module, path.data(), static_cast<DWORD>(path.size()));
if (!size || size >= path.size()) throw std::runtime_error("Cannot resolve module path");
return {path.data(), path.data()+size};
}
bool permitted(const void* name) {
const auto* record = lookup(name);
if (!record) {
if (!normalize || !game_free) return false;
struct Normalized {
GameString value;
~Normalized() { if (value.data) game_free(value.data); }
} canonical{};
normalize(&canonical.value, name);
const auto& value = canonical.value;
if (!value.data || value.count < 2 || value.count > 32768 ||
value.capacity < value.count || value.data[value.count-1] != L'\0') return false;
const std::wstring_view path(value.data, static_cast<std::size_t>(value.count-1));
if (!is_project_script(path)) return false;
++accepted;
std::lock_guard guard(additional_mutex);
if (additional_seen.emplace(path).second) {
const auto size = WideCharToMultiByte(CP_UTF8, 0, value.data, -1, nullptr, 0, nullptr, nullptr);
if (size > 0) {
std::vector<char> utf8(static_cast<std::size_t>(size));
WideCharToMultiByte(CP_UTF8, 0, value.data, -1, utf8.data(), size, nullptr, nullptr);
const auto message = std::string("Allowed additional project script: ")+utf8.data()+"\r\n";
log(message.c_str());
}
}
return true;
}
if (!contains_record(record, table, profile::record_count)) return false;
// A pointer into the verified executable's immutable table; not user input.
if (!record->path || !is_project_script(record->path)) return false;
++accepted;
const auto index = static_cast<std::size_t>(record-table);
if (!seen[index].exchange(true)) {
char path[2048]{}, message[2200]{};
WideCharToMultiByte(CP_UTF8, 0, record->path, -1, path, sizeof(path), nullptr, nullptr);
std::snprintf(message, sizeof(message), "Allowed listed project script: %s\r\n", path);
log(message);
}
return true;
}
bool validate_bytes(const void* name, const void* content) noexcept {
try { if (permitted(name)) return true; } catch (...) { /* original validation below */ }
++retained;
return original_bytes(name, content);
}
bool validate_text(const void* name, const void* content) noexcept {
try { if (permitted(name)) return true; } catch (...) { /* original validation below */ }
++retained;
return original_text(name, content);
}
void require(MH_STATUS status, const char* operation) {
if (status != MH_OK) throw std::runtime_error(std::string(operation)+": "+MH_StatusToString(status));
}
void verify_memory(unsigned char* base) {
const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
if (dos->e_magic != IMAGE_DOS_SIGNATURE) throw std::runtime_error("Invalid PE header");
const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base+dos->e_lfanew);
if (nt->Signature != IMAGE_NT_SIGNATURE || nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64 ||
nt->OptionalHeader.SizeOfImage != profile::image_size ||
nt->FileHeader.TimeDateStamp != profile::timestamp)
throw std::runtime_error("Unsupported loaded game image");
for (const auto& function : profile::functions) {
Hash hash;
hash.update(base+function.rva, function.size);
if (hash.finish() != function.sha256)
throw std::runtime_error("Validator/lookup code differs in memory; no hooks installed");
}
const auto* records = reinterpret_cast<const ScriptRecord*>(base+profile::table_rva);
std::size_t project_count{};
for (std::size_t i=0; i<profile::record_count; ++i) {
const auto address = reinterpret_cast<std::uintptr_t>(records[i].path);
const auto image = reinterpret_cast<std::uintptr_t>(base);
if (address < image || address-image >= profile::image_size)
throw std::runtime_error("Script table pointer outside image");
const auto maximum = (profile::image_size-(address-image))/sizeof(wchar_t);
const auto length = wcsnlen_s(records[i].path, maximum < 2048 ? maximum : 2048);
if (!length || length >= maximum || length >= 2048)
throw std::runtime_error("Invalid script table path");
project_count += is_project_script(std::wstring_view(records[i].path, length));
}
if (project_count != profile::project_count)
throw std::runtime_error("Unexpected project script count");
}
}
bool install(const std::filesystem::path& directory) {
if (active) return true;
if (attempted) { log("Restart required before another installation attempt.\r\n"); return false; }
attempted = true;
logfile = CreateFileW((directory/L"compatibility.log").c_str(), FILE_APPEND_DATA,
FILE_SHARE_READ|FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
log("\r\nUE4SS C++ BYPASS 1.3 experimental: startup\r\n");
try {
auto* image = reinterpret_cast<unsigned char*>(GetModuleHandleW(nullptr));
if (file_hash(module_path(nullptr)) != profile::game_sha256)
throw std::runtime_error("Unsupported PBZ.exe SHA-256; no hooks installed");
auto ue4ss = GetModuleHandleW(L"UE4SS.dll");
if (!ue4ss) throw std::runtime_error("UE4SS.dll is not loaded; no hooks installed");
const auto ue4ss_hash = file_hash(module_path(ue4ss));
const char* ue4ss_build = nullptr;
for (const auto& build : profile::ue4ss_builds)
if (ue4ss_hash == build.sha256) ue4ss_build = build.name;
if (!ue4ss_build)
throw std::runtime_error("Requires a verified UE4SS DLL (v4.0.0 or v3.0.1-1195); no hooks installed");
log("Verified UE4SS "); log(ue4ss_build); log("\r\n");
verify_memory(image);
lookup = reinterpret_cast<Lookup>(image+profile::lookup_rva);
normalize = reinterpret_cast<Normalize>(image+profile::normalize_rva);
game_free = reinterpret_cast<GameFree>(image+profile::free_rva);
table = reinterpret_cast<const ScriptRecord*>(image+profile::table_rva);
bytes_target = image+profile::bytes_rva;
text_target = image+profile::text_rva;
require(MH_Initialize(), "Initialize hooks");
initialized = true;
require(MH_CreateHook(bytes_target, reinterpret_cast<void*>(&validate_bytes),
reinterpret_cast<void**>(&original_bytes)), "Create byte hook");
require(MH_CreateHook(text_target, reinterpret_cast<void*>(&validate_text),
reinterpret_cast<void**>(&original_text)), "Create text hook");
// Keep adapter/trampoline code resident even if UE4SS requests unload.
// The installed mod requires a full game restart for replacement.
HMODULE self{};
if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_PIN,
reinterpret_cast<LPCWSTR>(&install), &self))
throw std::runtime_error("Cannot retain adapter module");
require(MH_QueueEnableHook(bytes_target), "Queue byte hook");
require(MH_QueueEnableHook(text_target), "Queue text hook");
enable_attempted = true;
require(MH_ApplyQueued(), "Enable hooks");
active = true;
log("Both validators hooked; scope=listed and additional project JS/JSON scripts.\r\n");
return true;
} catch (const std::exception& error) {
log(error.what()); log("\r\n");
if (initialized) {
MH_DisableHook(bytes_target);
MH_DisableHook(text_target);
if (!enable_attempted) {
MH_RemoveHook(bytes_target);
MH_RemoveHook(text_target);
MH_Uninitialize();
initialized = false;
}
}
return false;
}
}
void shutdown() noexcept {
// Do not free trampolines: a suspended callback can still be using one.
// The DLL is pinned and this small allocation lives until process exit.
if (active) {
const auto first = MH_QueueDisableHook(bytes_target);
const auto second = MH_QueueDisableHook(text_target);
const auto applied = MH_ApplyQueued();
log(first == MH_OK && second == MH_OK && applied == MH_OK
? "Validation hooks disabled; restart required.\r\n"
: "Hook shutdown incomplete; restart the game.\r\n");
active = false;
}
// Callback code and logger remain valid until process termination.
}
#ifdef COMPAT_TESTING
void test_context(const ScriptRecord* records, Lookup resolve) { table = records; lookup = resolve; }
void test_normalizer(Normalize canonicalize, GameFree release) { normalize=canonicalize; game_free=release; }
void* test_bytes_adapter() { return reinterpret_cast<void*>(&validate_bytes); }
void* test_text_adapter() { return reinterpret_cast<void*>(&validate_text); }
void** test_original_bytes() { return reinterpret_cast<void**>(&original_bytes); }
void** test_original_text() { return reinterpret_cast<void**>(&original_text); }
#endif
}