Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // cl /nologo /std:c++17 /EHsc /W4 evasion-score-poc.cpp /Fe:evasion-score-poc.exe
- #define NOMINMAX
- #include <windows.h>
- #include <winternl.h>
- #include <tlhelp32.h>
- #include <mfapi.h>
- #include <mfidl.h>
- #include <mftransform.h>
- #include <intrin.h>
- #include <algorithm>
- #include <array>
- #include <cstdint>
- #include <cstring>
- #include <iomanip>
- #include <iterator>
- #include <iostream>
- #include <optional>
- #include <sstream>
- #include <string>
- #include <utility>
- #include <vector>
- #pragma comment(lib, "mfuuid.lib")
- #pragma comment(lib, "ole32.lib")
- #pragma comment(lib, "advapi32.lib")
- #pragma comment(lib, "user32.lib")
- namespace evasion_poc {
- /*
- * This cpp POC reproduces only the environment observations, delays,
- * score accumulation, and decisions recovered from FUN_140005470.
- *
- * VEH control flow, PEB walking, hashed API resolution, lazy string decoding,
- * and unrelated RDTSC/backoff routines are anti-analysis implementation
- * details but do not contribute to this score, so they are not reproduced.
- */
- constexpr int TERMINATION_THRESHOLD = 7;
- constexpr uint32_t SCORE_XOR_KEY = 0xC1172093u;
- constexpr uint32_t HASH_INITIAL = 0x11DDE2E3u;
- constexpr uint32_t HASH_MULTIPLIER = 0x01000259u;
- constexpr ULONG MF_VERSION_USED_BY_SAMPLE = 0x00020070u;
- // The suite does not execute checks in numeric order. These two tables are
- // stored at RVA 0x425C0 and 0x425E8 and are byte-identical in both samples.
- constexpr std::array<unsigned, 10> CHECK_DISPATCH_ORDER = {
- 9, 3, 1, 0, 2, 5, 6, 4, 7, 8
- };
- constexpr std::array<DWORD, 10> PRE_CHECK_DELAYS_MS = {
- 111, 341, 453, 390, 406, 166, 336, 430, 146, 326
- };
- using Observation = std::pair<std::string, std::string>;
- using Observations = std::vector<Observation>;
- using TextItems = std::vector<std::string>;
- struct CheckResult {
- std::string name;
- int score = 0;
- Observations observed;
- TextItems matches;
- TextItems logic;
- bool immediate_gate_match = false;
- bool is_direct_gate = false;
- };
- CheckResult make_check_result(
- std::string name,
- int score,
- Observations observed,
- TextItems matches,
- TextItems logic,
- bool immediate_gate_match = false,
- bool is_direct_gate = false) {
- CheckResult result;
- result.name = std::move(name);
- result.score = score;
- result.observed = std::move(observed);
- result.matches = std::move(matches);
- result.logic = std::move(logic);
- result.immediate_gate_match = immediate_gate_match;
- result.is_direct_gate = is_direct_gate;
- return result;
- }
- std::string hex_value(uint32_t value, int width) {
- std::ostringstream out;
- out << "0x" << std::uppercase << std::hex
- << std::setw(width) << std::setfill('0') << value;
- return out.str();
- }
- std::string wide_to_utf8(const wchar_t* value) {
- if (!value || *value == L'\0') return "<empty>";
- const int required = WideCharToMultiByte(
- CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr);
- if (required <= 1) return "<conversion-failed>";
- std::string output(static_cast<size_t>(required), '\0');
- WideCharToMultiByte(
- CP_UTF8, 0, value, -1, output.data(), required, nullptr, nullptr);
- output.pop_back(); // remove the converted NUL terminator
- return output;
- }
- std::string format_fields(
- const Observations& fields) {
- std::string output;
- if (fields.empty()) return "\n none";
- for (const auto& field : fields) {
- output += "\n " + field.first + ": " + field.second;
- }
- return output;
- }
- std::string format_items(const TextItems& items) {
- std::string output;
- if (items.empty()) return "\n - none";
- for (const auto& item : items) {
- output += "\n - " + item;
- }
- return output;
- }
- std::string language_name(LANGID language_id) {
- wchar_t name[128]{};
- const LCID locale_id = MAKELCID(language_id, SORT_DEFAULT);
- if (GetLocaleInfoW(
- locale_id,
- LOCALE_SENGLISHDISPLAYNAME,
- name,
- static_cast<int>(std::size(name))) > 0) {
- return wide_to_utf8(name);
- }
- return "unknown language";
- }
- const char* display_vendor_name(uint32_t vendor) {
- switch (vendor) {
- case 0x1234: return "QEMU/Bochs virtual VGA";
- case 0x15AD: return "VMware";
- case 0x80EE: return "Oracle VirtualBox";
- case 0x1B36: return "Red Hat QXL";
- case 0x1AF4: return "Red Hat VirtIO";
- case 0x1AE0: return "Google virtual hardware";
- case 0x10DE: return "NVIDIA";
- case 0x1002: return "AMD/ATI";
- case 0x8086: return "Intel";
- case 0x5143: return "Qualcomm";
- default: return "unknown vendor";
- }
- }
- std::wstring lowercase(std::wstring s) {
- // The sample only folds ASCII A-Z, rather than using locale-sensitive
- // Unicode case conversion.
- std::transform(s.begin(), s.end(), s.begin(), [](wchar_t ch) {
- if (ch >= L'A' && ch <= L'Z') return static_cast<wchar_t>(ch + 0x20);
- return ch;
- });
- return s;
- }
- uint32_t hash_bytes(const uint8_t* data, size_t size) {
- uint32_t h = HASH_INITIAL;
- for (size_t i = 0; i < size; ++i) {
- h = (h ^ data[i]) * HASH_MULTIPLIER;
- }
- return h;
- }
- uint32_t hash_lowercase_utf16le(const std::wstring& input) {
- const std::wstring lower = lowercase(input);
- std::vector<uint8_t> bytes;
- bytes.reserve(lower.size() * 2);
- for (wchar_t ch : lower) {
- const uint16_t u = static_cast<uint16_t>(ch);
- bytes.push_back(static_cast<uint8_t>(u & 0xFF));
- bytes.push_back(static_cast<uint8_t>((u >> 8) & 0xFF));
- }
- return hash_bytes(bytes.data(), bytes.size());
- }
- uint32_t hash_primary_language_id(LANGID language_id) {
- const uint16_t primary = static_cast<uint16_t>(language_id & 0x03FFu);
- const uint8_t bytes[2] = {
- static_cast<uint8_t>(primary & 0xFF),
- static_cast<uint8_t>((primary >> 8) & 0xFF)
- };
- return hash_bytes(bytes, 2);
- }
- template <size_t N>
- bool hash_in_table(uint32_t value, const std::array<uint32_t, N>& table) {
- return std::find(table.begin(), table.end(), value) != table.end();
- }
- constexpr std::array<uint32_t, 10> LANGUAGE_HASHES = {
- 0xC207A15A, 0x1ECD79B1, 0x6CC7F6C0, 0xE562491C, 0x2C1798A0,
- 0x42282173, 0xDE1D1B91, 0x1304971B, 0xFCF40E48, 0xDB1AA2DF
- };
- constexpr std::array<uint32_t, 74> PROCESS_HASHES = {
- 0x09519D8D, 0x2094991E, 0x01DF72C4, 0x2EE27352, 0x9276E989,
- 0x14C8FBCB, 0xEEC68898, 0xB96C24DA, 0x05D400AD, 0x43139C6F,
- 0x9FE58E56, 0xD040A394, 0x8648793D, 0x36885C35, 0xC8884BCF,
- 0xD9D10B01, 0xA66FF643, 0xC74DFE5D, 0x987FA3B8, 0xE34D4614,
- 0xB428E51D, 0x0AC62710, 0x2395BA29, 0x783150A6, 0x2A6F17C7,
- 0x8E23D946, 0xE3728F6A, 0x995CDA05, 0x4B690E00, 0x685FAFAF,
- 0xB5232951, 0x74DFB190, 0x94547A1C, 0xAC6614B7, 0xCF06E47E,
- 0x71DFBD44, 0x3A601014, 0xF4557BD1, 0xE0CC6228, 0xA5A93A43,
- 0xBA42BF26, 0xF2427F3B, 0xC5B94BE3, 0x20899E9B, 0xE5204F02,
- 0x5E0B7867, 0x778C9825, 0x04001DA6, 0x15C7C164, 0x86A8FE8F,
- 0x88650340, 0x2F8F38FF, 0x33C2DC49, 0x92C365C8, 0x9E179F0A,
- 0x9EA60B3D, 0x9080C7AC, 0x2DE8A4F2, 0x67074B90, 0x639393B5,
- 0x369A7FB4, 0xABBF6A5D, 0x5DFBBA07, 0xC69E76E5, 0xAE67993B,
- 0x1E8717F8, 0x62CE2DE1, 0x810D7F11, 0xF560ED9E, 0xB4E7E5BA,
- 0x4CB7C91F, 0xFD643CFF, 0x7CA0EFE4, 0x0C137440
- };
- constexpr std::array<uint32_t, 18> HOST_IDENTITY_HASHES = {
- 0xCBB7E8D2, 0x61646C80, 0x15CBCEC2, 0x6384F985, 0x4C009DEE,
- 0x3FC28A0E, 0x869FE768, 0xCC8D3CCE, 0xB1861E30, 0x87D5C8DE,
- 0xF480AA57, 0xD2E77172, 0xE4D589E5, 0x541B17A5, 0x143FCEF1,
- 0x20A4E88D, 0x84C267E9, 0xF798BB83
- };
- // These are substring hashes used to recognize physical GPU naming tokens
- // before parsing a VEN_XXXX identifier from the display-device ID.
- constexpr std::array<uint32_t, 4> DISPLAY_TOKEN_HASHES = {
- 0x02C172CE, // nvidia
- 0x61A8D6F0, // radeon
- 0xA3B4D6D9, // intel
- 0xB74790D6 // qualcomm
- };
- // FUN_14002AE88 stores these values XOR-obfuscated. The decoded PCI vendor
- // identifiers are virtualization/synthetic display vendors.
- constexpr std::array<uint32_t, 6> BLOCKED_DISPLAY_VENDOR_IDS = {
- 0x1234, // QEMU/Bochs
- 0x15AD, // VMware
- 0x80EE, // VirtualBox
- 0x1B36, // Red Hat/QXL
- 0x1AF4, // Red Hat/VirtIO
- 0x1AE0 // Google virtual hardware
- };
- CheckResult check_language_gate() {
- // Export-hash resolution confirms these exact APIs:
- // GetUserDefaultUILanguage, GetSystemDefaultUILanguage, GetKeyboardLayout.
- const LANGID a = GetUserDefaultUILanguage();
- const LANGID b = GetSystemDefaultUILanguage();
- const LANGID c = LOWORD(reinterpret_cast<ULONG_PTR>(GetKeyboardLayout(0)));
- const uint32_t hash_a = hash_primary_language_id(a);
- const uint32_t hash_b = hash_primary_language_id(b);
- const uint32_t hash_c = hash_primary_language_id(c);
- const bool blocked_a = hash_in_table(hash_a, LANGUAGE_HASHES);
- const bool blocked_b = hash_in_table(hash_b, LANGUAGE_HASHES);
- const bool blocked_c = hash_in_table(hash_c, LANGUAGE_HASHES);
- const bool blocked = blocked_a || blocked_b || blocked_c;
- std::vector<std::string> hits;
- if (blocked_a) {
- hits.push_back(
- "userUI='" + language_name(a) + "' (" + hex_value(a, 4) + ")");
- }
- if (blocked_b) {
- hits.push_back(
- "systemUI='" + language_name(b) + "' (" + hex_value(b, 4) + ")");
- }
- if (blocked_c) {
- hits.push_back(
- "keyboard='" + language_name(c) + "' (" + hex_value(c, 4) + ")");
- }
- return make_check_result(
- "language gate",
- 0,
- {
- {"user UI",
- "'" + language_name(a) + "', LANGID=" + hex_value(a, 4) +
- ", hash=" + hex_value(hash_a, 8)},
- {"system UI",
- "'" + language_name(b) + "', LANGID=" + hex_value(b, 4) +
- ", hash=" + hex_value(hash_b, 8)},
- {"keyboard",
- "'" + language_name(c) + "', LANGID=" + hex_value(c, 4) +
- ", hash=" + hex_value(hash_c, 8)}
- },
- hits,
- {
- "Mask each LANGID to its 10-bit primary-language ID and hash it.",
- "Any hash in the 10-entry language blocklist triggers immediate termination.",
- "This is a direct gate outside the ten-entry scorer; it is not a score input."
- },
- blocked,
- true);
- }
- CheckResult check_process_environment() {
- unsigned count = 0;
- bool blacklisted = false;
- bool snapshot_available = false;
- std::vector<std::string> blacklist_hits;
- HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- if (snapshot != INVALID_HANDLE_VALUE) {
- snapshot_available = true;
- PROCESSENTRY32W pe{};
- pe.dwSize = sizeof(pe);
- if (Process32FirstW(snapshot, &pe)) {
- do {
- ++count;
- const uint32_t h = hash_lowercase_utf16le(pe.szExeFile);
- if (hash_in_table(h, PROCESS_HASHES)) {
- blacklisted = true;
- const std::string hit =
- "'" + wide_to_utf8(pe.szExeFile) +
- "' hash=" + hex_value(h, 8);
- if (std::find(
- blacklist_hits.begin(),
- blacklist_hits.end(),
- hit) == blacklist_hits.end()) {
- blacklist_hits.push_back(hit);
- }
- }
- } while (Process32NextW(snapshot, &pe));
- }
- CloseHandle(snapshot);
- }
- // A blacklist hit adds 99; it does not suppress the process-count score.
- // Consequently a hit on a <=50-process host contributes 104, not 99.
- int score = 0;
- if (blacklisted) score += 99;
- if (count <= 50) score += 5;
- else if (count <= 75) score += 2;
- else if (count <= 100) score += 1;
- return make_check_result(
- "process environment",
- score,
- {
- {"snapshot", snapshot_available ? "success" : "failed"},
- {"process count", std::to_string(count)}
- },
- blacklist_hits,
- {
- "Any process-name hash in the 74-entry blocklist adds 99.",
- "Then process count <=50 adds 5.",
- "Process count 51..75 adds 2.",
- "Process count 76..100 adds 1.",
- "Process count >100 adds 0.",
- "Snapshot failure leaves count at zero and therefore still adds 5."
- });
- }
- struct CpuTopology {
- unsigned cores = 0;
- unsigned logical = 0;
- bool available = false;
- };
- CpuTopology query_cpu_topology() {
- CpuTopology out{};
- // The sample uses the legacy fixed-size API with a 0x600-byte buffer.
- std::array<SYSTEM_LOGICAL_PROCESSOR_INFORMATION,
- 0x600 / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)> buffer{};
- DWORD length = static_cast<DWORD>(sizeof(buffer));
- if (!GetLogicalProcessorInformation(buffer.data(), &length)) return out;
- out.available = true;
- const size_t count =
- std::min<size_t>(buffer.size(), length / sizeof(buffer.front()));
- for (size_t i = 0; i < count; ++i) {
- const auto& info = buffer[i];
- if (info.Relationship == RelationProcessorCore) {
- ++out.cores;
- out.logical +=
- static_cast<unsigned>(__popcnt64(info.ProcessorMask));
- }
- }
- return out;
- }
- CheckResult check_cpu_topology() {
- const CpuTopology cpu = query_cpu_topology();
- if (!cpu.available) {
- // FUN_140005470 adds zero if GetLogicalProcessorInformation fails.
- return make_check_result(
- "CPU topology",
- 0,
- {{"API result", "GetLogicalProcessorInformation failed"}},
- {},
- {"Query failure adds 0."});
- }
- // Exact branches at 0x1400057D7..0x140005805. The logical<=4 branch is
- // reachable only when cores==2; systems with more than two cores score 0.
- int score = 0;
- if (cpu.cores < 2) score = 7;
- else if (cpu.cores == 2 && cpu.logical <= 2) score = 3;
- else if (cpu.cores == 2 && cpu.logical <= 4) score = 1;
- return make_check_result(
- "CPU topology",
- score,
- {
- {"physical cores", std::to_string(cpu.cores)},
- {"logical processors", std::to_string(cpu.logical)}
- },
- {},
- {
- "Fewer than 2 cores adds 7.",
- "Exactly 2 cores and <=2 logical processors adds 3.",
- "Exactly 2 cores and 3..4 logical processors adds 1.",
- "Every other topology adds 0."
- });
- }
- CheckResult check_physical_memory() {
- MEMORYSTATUSEX ms{};
- ms.dwLength = sizeof(ms);
- if (!GlobalMemoryStatusEx(&ms)) {
- return make_check_result(
- "physical memory",
- 0,
- {{"API result", "GlobalMemoryStatusEx failed"}},
- {},
- {"Query failure adds 0."});
- }
- const uint64_t mib = ms.ullTotalPhys / (1024ull * 1024ull);
- int score = 0;
- if (mib <= 1536) score = 7;
- else if (mib <= 3584) score = 2;
- else if (mib <= 5632) score = 1;
- return make_check_result(
- "physical memory",
- score,
- {{"total RAM", std::to_string(mib) + " MiB"}},
- {},
- {
- "<=1536 MiB adds 7.",
- "1537..3584 MiB adds 2.",
- "3585..5632 MiB adds 1.",
- ">5632 MiB adds 0."
- });
- }
- bool contains_recognized_display_token(const std::wstring& text);
- std::optional<uint32_t> parse_display_vendor_id(const std::wstring& device_id);
- bool is_blocked_display_vendor(uint32_t vendor) {
- return std::find(BLOCKED_DISPLAY_VENDOR_IDS.begin(),
- BLOCKED_DISPLAY_VENDOR_IDS.end(),
- vendor) != BLOCKED_DISPLAY_VENDOR_IDS.end();
- }
- std::string describe_display_device(const DISPLAY_DEVICEW& device) {
- const std::optional<uint32_t> vendor =
- parse_display_vendor_id(device.DeviceID);
- std::string description =
- "'" + wide_to_utf8(device.DeviceString) +
- "' [DeviceID='" + wide_to_utf8(device.DeviceID) + "'";
- if (vendor) {
- description +=
- ", vendor=" + std::string(display_vendor_name(*vendor)) +
- " (VEN_" + hex_value(*vendor, 4).substr(2) + ")";
- } else {
- description += ", vendor=not present";
- }
- description += "]";
- return description;
- }
- CheckResult check_primary_display() {
- /*
- * Index 3 searches overlapping substrings of DeviceString for one of the
- * four physical-GPU tokens on attached desktop devices. A device is
- * accepted only when its DeviceID does not contain one of the six blocked
- * virtual VEN_ identifiers.
- */
- unsigned enumerated = 0;
- unsigned attached = 0;
- unsigned token_matches = 0;
- std::vector<std::string> attached_devices;
- std::vector<std::string> blocked_vendor_hits;
- DISPLAY_DEVICEW dd{};
- dd.cb = sizeof(dd);
- for (DWORD i = 0; EnumDisplayDevicesW(nullptr, i, &dd, 0); ++i) {
- ++enumerated;
- const bool is_attached =
- (dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) != 0;
- if (is_attached) {
- ++attached;
- attached_devices.push_back(describe_display_device(dd));
- }
- if (is_attached && contains_recognized_display_token(dd.DeviceString)) {
- ++token_matches;
- const std::optional<uint32_t> vendor =
- parse_display_vendor_id(dd.DeviceID);
- if (!vendor || !is_blocked_display_vendor(*vendor)) {
- return make_check_result(
- "primary display validation",
- 0,
- {
- {"enumerated devices", std::to_string(enumerated)},
- {"attached devices", std::to_string(attached)},
- {"recognized token matches", std::to_string(token_matches)},
- {"accepted device", describe_display_device(dd)}
- },
- {},
- {
- "Consider only devices attached to the desktop.",
- "DeviceString must contain nvidia, radeon, intel, or qualcomm.",
- "Its VEN value must be absent or outside the six-entry virtual-vendor blocklist.",
- "At least one accepted device adds 0; otherwise add 5."
- });
- }
- blocked_vendor_hits.push_back(describe_display_device(dd));
- }
- dd = {};
- dd.cb = sizeof(dd);
- }
- std::vector<std::pair<std::string, std::string>> observed = {
- {"enumerated devices", std::to_string(enumerated)},
- {"attached devices", std::to_string(attached)},
- {"recognized token matches", std::to_string(token_matches)}
- };
- for (const auto& device : attached_devices) {
- observed.push_back({"attached device", device});
- }
- return make_check_result(
- "primary display validation",
- 5,
- std::move(observed),
- blocked_vendor_hits,
- {
- "Consider only devices attached to the desktop.",
- "DeviceString must contain nvidia, radeon, intel, or qualcomm.",
- "Its VEN value must be absent or outside the six-entry virtual-vendor blocklist.",
- "No acceptable token/vendor pair adds 5."
- });
- }
- bool contains_recognized_display_token(const std::wstring& text) {
- const std::wstring lower = lowercase(text);
- // The sample hashes overlapping UTF-16 substrings of lengths 5..15.
- for (size_t start = 0; start < lower.size(); ++start) {
- const size_t max_length = std::min<size_t>(15, lower.size() - start);
- for (size_t length = 5; length <= max_length; ++length) {
- if (hash_in_table(
- hash_lowercase_utf16le(lower.substr(start, length)),
- DISPLAY_TOKEN_HASHES)) {
- return true;
- }
- }
- }
- return false;
- }
- std::optional<uint32_t> parse_display_vendor_id(const std::wstring& device_id) {
- const std::wstring folded = lowercase(device_id);
- const size_t marker = folded.find(L"ven_");
- if (marker == std::wstring::npos) return std::nullopt;
- // FUN_14002AE88 accumulates every valid hex digit after VEN_ until '&'
- // or NUL. Unexpected characters are skipped rather than ending parsing.
- uint32_t value = 0;
- size_t digits = 0;
- for (size_t i = marker + 4;
- i < device_id.size() && device_id[i] != L'&';
- ++i) {
- const wchar_t ch = device_id[i];
- unsigned nibble = 0;
- if (ch >= L'0' && ch <= L'9') nibble = static_cast<unsigned>(ch - L'0');
- else if (ch >= L'A' && ch <= L'F') nibble = 10u + static_cast<unsigned>(ch - L'A');
- else if (ch >= L'a' && ch <= L'f') nibble = 10u + static_cast<unsigned>(ch - L'a');
- else continue;
- value = (value << 4) | nibble;
- ++digits;
- }
- if (digits == 0) return std::nullopt;
- return value;
- }
- CheckResult check_additional_display_vendor() {
- unsigned enumerated = 0;
- unsigned attached = 0;
- std::vector<std::string> attached_devices;
- // Index 9 is independent of the token table: any attached desktop
- // DeviceID whose VEN_ value is in the virtual-vendor set contributes 5.
- DISPLAY_DEVICEW dd{};
- dd.cb = sizeof(dd);
- for (DWORD i = 0; EnumDisplayDevicesW(nullptr, i, &dd, 0); ++i) {
- ++enumerated;
- const bool is_attached =
- (dd.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) != 0;
- if (is_attached) {
- ++attached;
- attached_devices.push_back(describe_display_device(dd));
- }
- const std::optional<uint32_t> vendor =
- parse_display_vendor_id(dd.DeviceID);
- if (is_attached && vendor && is_blocked_display_vendor(*vendor)) {
- return make_check_result(
- "additional display vendor scan",
- 5,
- {
- {"enumerated devices", std::to_string(enumerated)},
- {"attached devices", std::to_string(attached)}
- },
- {describe_display_device(dd)},
- {
- "Consider only devices attached to the desktop.",
- "Any VEN value in the six-entry virtual-vendor blocklist adds 5.",
- "No blocked VEN match adds 0."
- });
- }
- dd = {};
- dd.cb = sizeof(dd);
- }
- std::vector<std::pair<std::string, std::string>> observed = {
- {"enumerated devices", std::to_string(enumerated)},
- {"attached devices", std::to_string(attached)}
- };
- for (const auto& device : attached_devices) {
- observed.push_back({"attached device", device});
- }
- return make_check_result(
- "additional display vendor scan",
- 0,
- std::move(observed),
- {},
- {
- "Consider only devices attached to the desktop.",
- "Any VEN value in the six-entry virtual-vendor blocklist adds 5.",
- "No blocked VEN match adds 0."
- });
- }
- CheckResult check_computer_name_and_username_gate() {
- /*
- * The entry suite applies the same 18-hash table first to
- * GetComputerNameW and then to GetUserNameW. The sample uses a 256-WCHAR
- * computer-name buffer and a 16-WCHAR username buffer. Failure of either
- * query is non-fatal; any successful hash match terminates immediately.
- */
- bool computer_name_match = false;
- bool username_match = false;
- bool computer_name_available = false;
- bool username_available = false;
- uint32_t computer_name_hash = 0;
- uint32_t username_hash = 0;
- wchar_t computer_name[256]{};
- DWORD computer_name_size = static_cast<DWORD>(std::size(computer_name));
- if (GetComputerNameW(computer_name, &computer_name_size)) {
- computer_name_available = true;
- computer_name_hash = hash_lowercase_utf16le(computer_name);
- computer_name_match =
- hash_in_table(computer_name_hash, HOST_IDENTITY_HASHES);
- }
- wchar_t username[16]{};
- DWORD username_size = static_cast<DWORD>(std::size(username));
- if (GetUserNameW(username, &username_size)) {
- username_available = true;
- username_hash = hash_lowercase_utf16le(username);
- username_match = hash_in_table(username_hash, HOST_IDENTITY_HASHES);
- }
- const bool blocked = computer_name_match || username_match;
- std::vector<std::string> identity_hits;
- if (computer_name_match) {
- identity_hits.push_back(
- "computer-name='" + wide_to_utf8(computer_name) +
- "' hash=" + hex_value(computer_name_hash, 8));
- }
- if (username_match) {
- identity_hits.push_back(
- "username='" + wide_to_utf8(username) +
- "' hash=" + hex_value(username_hash, 8));
- }
- return make_check_result(
- "computer-name / username gate",
- 0,
- {
- {"computer name",
- "'" +
- (computer_name_available
- ? wide_to_utf8(computer_name)
- : "unavailable") +
- "', hash=" +
- (computer_name_available
- ? hex_value(computer_name_hash, 8)
- : "n/a")},
- {"username",
- "'" +
- (username_available
- ? wide_to_utf8(username)
- : "unavailable") +
- "', hash=" +
- (username_available ? hex_value(username_hash, 8) : "n/a")}
- },
- identity_hits,
- {
- "Hash computer name and username with the shared 18-entry table.",
- "Either hash matching takes the delayed-termination branch immediately.",
- "Dispatcher index 4 is a direct gate inside the suite; it is not a score input."
- },
- blocked,
- true);
- }
- CheckResult check_uptime() {
- const uint64_t ms = GetTickCount64();
- int score = 0;
- if (ms <= 120000) score = 3;
- else if (ms <= 600000) score = 1;
- return make_check_result(
- "system uptime",
- score,
- {{"current uptime", std::to_string(ms) + " ms"}},
- {},
- {
- "<=120000 ms adds 3.",
- "120001..600000 ms adds 1.",
- ">600000 ms adds 0."
- });
- }
- CheckResult check_sleep_acceleration() {
- const uint64_t before = GetTickCount64();
- Sleep(1000);
- const uint64_t observed = GetTickCount64() - before;
- const int score = observed < 400 ? 7 : 0;
- return make_check_result(
- "sleep acceleration",
- score,
- {
- {"requested sleep", "1000 ms"},
- {"observed elapsed", std::to_string(observed) + " ms"}
- },
- {},
- {
- "Observed elapsed time <400 ms adds 7.",
- "Observed elapsed time >=400 ms adds 0."
- });
- }
- struct OsVersion {
- DWORD major = 0;
- DWORD minor = 0;
- bool available = false;
- };
- OsVersion query_os_version() {
- using RtlGetVersionFn = LONG(WINAPI*)(PRTL_OSVERSIONINFOW);
- OsVersion out{};
- HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
- auto fn = reinterpret_cast<RtlGetVersionFn>(GetProcAddress(ntdll, "RtlGetVersion"));
- if (!fn) return out;
- RTL_OSVERSIONINFOW vi{};
- vi.dwOSVersionInfoSize = sizeof(vi);
- if (fn(&vi) == 0) {
- out.major = vi.dwMajorVersion;
- out.minor = vi.dwMinorVersion;
- out.available = true;
- }
- return out;
- }
- CheckResult check_h264_hardware_encoder() {
- const OsVersion os = query_os_version();
- const std::string os_detail = os.available
- ? std::to_string(os.major) + "." + std::to_string(os.minor)
- : "unavailable";
- const std::vector<std::string> h264_logic = {
- "Windows 6.0..6.3 bypasses the Media Foundation probe and adds 0.",
- "Module, API, COM, or MFStartup initialization failure adds 0.",
- "MFTEnumEx failure or zero hardware H.264 encoders adds 5.",
- "One or more hardware H.264 encoders adds 0."
- };
- if (os.major == 6 && os.minor <= 3) {
- return make_check_result(
- "hardware H.264 encoder",
- 0,
- {
- {"OS version", os_detail},
- {"probe status", "bypassed for Windows 6.0..6.3"}
- },
- {},
- h264_logic);
- }
- using CoInitializeExFn = HRESULT(WINAPI*)(LPVOID, DWORD);
- using CoUninitializeFn = void(WINAPI*)();
- using MFStartupFn = HRESULT(WINAPI*)(ULONG, DWORD);
- using MFShutdownFn = HRESULT(WINAPI*)();
- using MFTEnumExFn = HRESULT(WINAPI*)(
- GUID, UINT32, const MFT_REGISTER_TYPE_INFO*,
- const MFT_REGISTER_TYPE_INFO*, IMFActivate***, UINT32*);
- /*
- * The original resolves these APIs after loading combase.dll/mfplat.dll.
- * Missing modules or any of the four initialization APIs bypass the probe
- * with score 0; failure to resolve MFTEnumEx is an enumeration failure and
- * therefore contributes 5.
- */
- HMODULE combase = LoadLibraryW(L"combase.dll");
- HMODULE mfplat = LoadLibraryW(L"mfplat.dll");
- const auto release_modules = [&]() {
- if (mfplat) FreeLibrary(mfplat);
- if (combase) FreeLibrary(combase);
- };
- if (!combase || !mfplat) {
- release_modules();
- return make_check_result(
- "hardware H.264 encoder",
- 0,
- {
- {"OS version", os_detail},
- {"combase.dll", combase ? "available" : "unavailable"},
- {"mfplat.dll", mfplat ? "available" : "unavailable"}
- },
- {},
- h264_logic);
- }
- const auto co_initialize = reinterpret_cast<CoInitializeExFn>(
- GetProcAddress(combase, "CoInitializeEx"));
- const auto co_uninitialize = reinterpret_cast<CoUninitializeFn>(
- GetProcAddress(combase, "CoUninitialize"));
- const auto mf_startup = reinterpret_cast<MFStartupFn>(
- GetProcAddress(mfplat, "MFStartup"));
- const auto mf_shutdown = reinterpret_cast<MFShutdownFn>(
- GetProcAddress(mfplat, "MFShutdown"));
- const auto mft_enum = reinterpret_cast<MFTEnumExFn>(
- GetProcAddress(mfplat, "MFTEnumEx"));
- if (!co_initialize || !co_uninitialize || !mf_startup || !mf_shutdown) {
- release_modules();
- return make_check_result(
- "hardware H.264 encoder",
- 0,
- {
- {"OS version", os_detail},
- {"CoInitializeEx", co_initialize ? "resolved" : "missing"},
- {"CoUninitialize", co_uninitialize ? "resolved" : "missing"},
- {"MFStartup", mf_startup ? "resolved" : "missing"},
- {"MFShutdown", mf_shutdown ? "resolved" : "missing"}
- },
- {},
- h264_logic);
- }
- /*
- * The sample first requests MTA (flags 0), retries STA (flags 2) after a
- * normal failure, and accepts RPC_E_CHANGED_MODE as usable.
- */
- HRESULT hr_co = co_initialize(nullptr, COINIT_MULTITHREADED);
- if (FAILED(hr_co) && hr_co != RPC_E_CHANGED_MODE) {
- hr_co = co_initialize(nullptr, COINIT_APARTMENTTHREADED);
- }
- if (FAILED(hr_co) && hr_co != RPC_E_CHANGED_MODE) {
- release_modules();
- return make_check_result(
- "hardware H.264 encoder",
- 0,
- {
- {"OS version", os_detail},
- {"CoInitializeEx HRESULT",
- hex_value(static_cast<uint32_t>(hr_co), 8)},
- {"COM status", "initialization failed"}
- },
- {},
- h264_logic);
- }
- // The sample calls MFStartup(0x00020070, 0), i.e. MFSTARTUP_FULL.
- HRESULT hr_mf = mf_startup(MF_VERSION_USED_BY_SAMPLE, MFSTARTUP_FULL);
- if (FAILED(hr_mf)) {
- // It balances CoInitializeEx only when the returned HRESULT was S_OK.
- if (hr_co == S_OK) co_uninitialize();
- release_modules();
- return make_check_result(
- "hardware H.264 encoder",
- 0,
- {
- {"OS version", os_detail},
- {"CoInitializeEx HRESULT",
- hex_value(static_cast<uint32_t>(hr_co), 8)},
- {"MFStartup HRESULT",
- hex_value(static_cast<uint32_t>(hr_mf), 8)},
- {"Media Foundation status", "startup failed"}
- },
- {},
- h264_logic);
- }
- MFT_REGISTER_TYPE_INFO output{};
- output.guidMajorType = MFMediaType_Video;
- output.guidSubtype = MFVideoFormat_H264;
- IMFActivate** activates = nullptr;
- UINT32 count = 0;
- HRESULT hr = E_NOINTERFACE;
- if (mft_enum) {
- hr = mft_enum(
- MFT_CATEGORY_VIDEO_ENCODER,
- MFT_ENUM_FLAG_HARDWARE,
- nullptr,
- &output,
- &activates,
- &count);
- }
- if (activates != nullptr) {
- for (UINT32 i = 0; i < count; ++i) activates[i]->Release();
- CoTaskMemFree(activates);
- }
- mf_shutdown();
- if (hr_co == S_OK) co_uninitialize();
- release_modules();
- const int score = (FAILED(hr) || count == 0) ? 5 : 0;
- return make_check_result(
- "hardware H.264 encoder",
- score,
- {
- {"OS version", os_detail},
- {"MFTEnumEx HRESULT", hex_value(static_cast<uint32_t>(hr), 8)},
- {"enumeration status", FAILED(hr) ? "failed" : "success"},
- {"hardware H.264 encoders", std::to_string(count)}
- },
- {},
- h264_logic);
- }
- std::string cpuid_vendor() {
- int regs[4]{};
- __cpuid(regs, 0);
- char vendor[13]{};
- std::memcpy(vendor + 0, ®s[1], 4); // EBX
- std::memcpy(vendor + 4, ®s[3], 4); // EDX
- std::memcpy(vendor + 8, ®s[2], 4); // ECX
- return vendor;
- }
- std::string cpuid_brand() {
- int regs[4]{};
- __cpuid(regs, 0x80000000);
- const unsigned max_leaf = static_cast<unsigned>(regs[0]);
- if (max_leaf < 0x80000004) return {};
- char brand[49]{};
- for (unsigned leaf = 0x80000002, off = 0; leaf <= 0x80000004; ++leaf, off += 16) {
- __cpuid(regs, static_cast<int>(leaf));
- std::memcpy(brand + off, regs, 16);
- }
- return brand;
- }
- bool contains_with_folded_first(const std::string& text,
- const std::string& token) {
- if (token.empty()) return true;
- if (token.size() > text.size()) return false;
- // FUN_140025010 ASCII-folds the candidate's first byte at each position;
- // the remaining bytes are compared directly with "intel", "amd", "aMD".
- for (size_t start = 0; start + token.size() <= text.size(); ++start) {
- unsigned char first = static_cast<unsigned char>(text[start]);
- if (first >= 'A' && first <= 'Z') first += 0x20;
- if (first != static_cast<unsigned char>(token[0])) continue;
- if (text.compare(start + 1, token.size() - 1, token, 1) == 0) {
- return true;
- }
- }
- return false;
- }
- CheckResult check_cpuid_consistency() {
- const std::string vendor = cpuid_vendor();
- const std::string brand = cpuid_brand();
- // The binary compares only CPUID.0:EBX: "Genu" or "Auth".
- const bool vendor_intel = vendor.rfind("Genu", 0) == 0;
- const bool vendor_amd = vendor.rfind("Auth", 0) == 0;
- const bool brand_intel = contains_with_folded_first(brand, "intel");
- const bool brand_amd =
- contains_with_folded_first(brand, "amd") ||
- contains_with_folded_first(brand, "aMD");
- // A brand containing both families is not scored by the original branch.
- const bool mismatch =
- (vendor_amd && brand_intel && !brand_amd) ||
- (vendor_intel && brand_amd && !brand_intel);
- return make_check_result(
- "CPUID consistency",
- mismatch ? 5 : 0,
- {
- {"CPUID vendor", "'" + vendor + "'"},
- {"CPUID brand", "'" + brand + "'"},
- {"vendor family",
- vendor_intel ? "Intel" : (vendor_amd ? "AMD" : "other")},
- {"Intel token in brand", brand_intel ? "yes" : "no"},
- {"AMD token in brand", brand_amd ? "yes" : "no"}
- },
- {},
- {
- "AMD vendor plus Intel-only brand adds 5.",
- "Intel vendor plus AMD-only brand adds 5.",
- "Every other combination adds 0."
- });
- }
- void print_wrapped_field(const std::string& label,
- const std::string& value) {
- constexpr size_t LINE_WIDTH = 100;
- constexpr size_t LABEL_WIDTH = 15;
- const std::string prefix =
- label + std::string(LABEL_WIDTH - label.size(), ' ') + ": ";
- const std::string continuation(prefix.size(), ' ');
- std::istringstream explicit_lines(value);
- std::string explicit_line;
- bool first_output_line = true;
- while (std::getline(explicit_lines, explicit_line)) {
- const size_t leading_spaces =
- explicit_line.find_first_not_of(' ') == std::string::npos
- ? explicit_line.size()
- : explicit_line.find_first_not_of(' ');
- const std::string indent(leading_spaces, ' ');
- const std::string content = explicit_line.substr(leading_spaces);
- std::string wrap_indent = indent;
- if (content.rfind("- ", 0) == 0) {
- wrap_indent += " ";
- } else {
- const size_t value_separator = content.find(": ");
- if (value_separator != std::string::npos) {
- wrap_indent += std::string(value_separator + 2, ' ');
- }
- }
- std::istringstream words(content);
- std::string word;
- bool wrote_word = false;
- size_t column = continuation.size() + indent.size();
- std::cout << (first_output_line ? prefix : continuation) << indent;
- first_output_line = false;
- while (words >> word) {
- const size_t separator = wrote_word ? 1 : 0;
- if (wrote_word &&
- column + separator + word.size() > LINE_WIDTH) {
- std::cout << "\n" << continuation << wrap_indent;
- column = continuation.size() + wrap_indent.size();
- wrote_word = false;
- }
- if (wrote_word) {
- std::cout << ' ';
- ++column;
- }
- std::cout << word;
- column += word.size();
- wrote_word = true;
- }
- std::cout << "\n";
- }
- }
- void print_check_block(const CheckResult& result,
- const std::string& check_id,
- std::optional<DWORD> pre_delay_ms,
- uint32_t cumulative_score) {
- std::cout << "\n------------------------------------------------------------\n";
- print_wrapped_field("CHECK ID", check_id);
- print_wrapped_field("NAME", result.name);
- print_wrapped_field(
- "CLASSIFICATION",
- result.is_direct_gate
- ? "DIRECT TERMINATION GATE (not scored)"
- : "SCORED ENVIRONMENT CHECK");
- print_wrapped_field("OBSERVED", format_fields(result.observed));
- print_wrapped_field("MATCHES", format_items(result.matches));
- print_wrapped_field("LOGIC", format_items(result.logic));
- std::cout << "CONTRIBUTION : ";
- if (result.is_direct_gate) {
- std::cout << "n/a (direct gate; score unchanged)\n";
- } else {
- std::cout << (result.score >= 0 ? "+" : "") << result.score << "\n";
- }
- std::cout << "CUMULATIVE : " << cumulative_score;
- if (result.is_direct_gate) std::cout << " (unchanged)";
- std::cout << "\n";
- std::cout << "PRE-CHECK DELAY: ";
- if (pre_delay_ms) std::cout << *pre_delay_ms << " ms\n";
- else std::cout << "n/a\n";
- std::cout << "DIRECT GATE : ";
- if (result.is_direct_gate) {
- std::cout << (result.immediate_gate_match ? "MATCH" : "no match");
- } else {
- std::cout << "n/a";
- }
- std::cout << "\n";
- }
- } // namespace evasion_poc
- int wmain() {
- using namespace evasion_poc;
- const CheckResult language = check_language_gate();
- print_check_block(language, "LANG", std::nullopt, 0);
- /*
- * The physical-GPU predicate is computed before the ten-entry dispatcher
- * in FUN_140005470, although its result is consumed by check index 3.
- */
- const CheckResult primary_display = check_primary_display();
- bool identity_gate_match = false;
- uint32_t encoded_score = SCORE_XOR_KEY; // encoded representation of zero
- for (size_t slot = 0; slot < CHECK_DISPATCH_ORDER.size(); ++slot) {
- // These short sleeps are benign and reproduce the table-driven suite
- // cadence. Check 6 performs its separate measured 1000 ms sleep.
- Sleep(PRE_CHECK_DELAYS_MS[slot]);
- const unsigned index = CHECK_DISPATCH_ORDER[slot];
- CheckResult result;
- switch (index) {
- case 0: result = check_process_environment(); break;
- case 1: result = check_cpu_topology(); break;
- case 2: result = check_physical_memory(); break;
- case 3: result = primary_display; break;
- case 4:
- result = check_computer_name_and_username_gate();
- identity_gate_match = result.immediate_gate_match;
- break;
- case 5: result = check_uptime(); break;
- case 6: result = check_sleep_acceleration(); break;
- case 7: result = check_h264_hardware_encoder(); break;
- case 8: result = check_cpuid_consistency(); break;
- case 9: result = check_additional_display_vendor(); break;
- default:
- result = make_check_result(
- "invalid dispatcher index",
- 0,
- {{"index", std::to_string(index)}},
- {},
- {"Unknown dispatcher index; adds 0."});
- break;
- }
- // Direct gates do not read or update the encoded score. Scored checks
- // update the global after their contribution.
- uint32_t plain_score = encoded_score ^ SCORE_XOR_KEY;
- if (!result.is_direct_gate) {
- plain_score += static_cast<uint32_t>(result.score);
- encoded_score = plain_score ^ SCORE_XOR_KEY;
- }
- print_check_block(
- result,
- std::to_string(index),
- PRE_CHECK_DELAYS_MS[slot],
- plain_score);
- }
- /*
- * This diagnostic intentionally completes every observation so it can
- * print a score. The original sample would stop immediately at either
- * direct gate and would not execute the later checks.
- */
- const uint32_t total = encoded_score ^ SCORE_XOR_KEY;
- std::string decision;
- if (language.immediate_gate_match) {
- decision = "WOULD TERMINATE at language gate";
- } else if (identity_gate_match) {
- decision = "WOULD TERMINATE at computer-name/username gate";
- } else if (total >= TERMINATION_THRESHOLD) {
- decision = "WOULD TERMINATE because score >= threshold";
- } else {
- decision = "WOULD ALLOW execution to continue";
- }
- std::cout << "\n============================================================\n";
- std::cout << "SUMMARY\n";
- print_wrapped_field("TOTAL SCORE", std::to_string(total));
- print_wrapped_field("THRESHOLD", std::to_string(TERMINATION_THRESHOLD));
- print_wrapped_field("DECISION", decision);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment