feat: spoof rdtsc timings

Previously, RDTSC in the VM always returned a constant value, which broke any non deterministic timing-based operations, or caused detections in heuristics of malware and ANTI-VM tools.

This patch introduces a spoofed rdtsc_fake counter that tracks and adjusts timing deltas to simulate realistic TSC increments. Can be extended to simulate rdtsc timings based on CPU clock speed.
This commit is contained in:
Soham Nandy
2025-04-10 06:58:01 +05:30
parent 3836f5d381
commit dbc1b4439e
2 changed files with 41 additions and 3 deletions

View File

@@ -3,6 +3,10 @@
#include <chrono>
#include "../platform/platform.hpp"
#if defined(_MSC_VER)
#include <intrin.h>
#pragma intrinsic(__rdtsc)
#endif
constexpr auto HUNDRED_NANOSECONDS_IN_ONE_SECOND = 10000000LL;
constexpr auto EPOCH_DIFFERENCE_1601_TO_1970_SECONDS = 11644473600LL;
@@ -29,6 +33,24 @@ namespace utils
{
return std::chrono::steady_clock::now();
}
// Returnds the current timestamp counter value. RDTSC on x86/x64, or just time since epoch for ARM
/// TODO: find better solution for ARM and Figure out better CPU base frequency heuristics
virtual uint64_t timestamp_counter()
{
#if defined(_MSC_VER)
#if defined(_M_X64) || defined(_M_AMD64) || defined(_M_IX86)
return __rdtsc(); // 64-bit with MSVC intrinsic
#endif
#elif defined(__x86_64__) || defined(__i386__) || defined(__amd64__) // If we are using clang or gcc
unsigned int lo, hi;
__asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)hi << 32) | lo;
#endif
return static_cast<uint64_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count()) *
3.8; // should be base cpu frequency here;
}
};
class tick_clock : public clock

View File

@@ -448,9 +448,25 @@ void windows_emulator::setup_hooks()
});
this->emu().hook_instruction(x64_hookable_instructions::rdtsc, [&] {
const auto instructions = this->executed_instructions_;
this->emu().reg(x64_register::rax, instructions & 0xFFFFFFFF);
this->emu().reg(x64_register::rdx, (instructions >> 32) & 0xFFFFFFFF);
uint64_t ticks = this->clock_.get()->timestamp_counter();
static uint64_t fake_ticks = ticks;
static uint64_t prev_ticks = 0;
if (prev_ticks != 0)
{
if (ticks > prev_ticks)
{
fake_ticks += (ticks - prev_ticks);
}
}
if (fake_ticks > ticks)
{
fake_ticks = ticks;
}
prev_ticks = ticks;
this->emu().reg(x64_register::rax, fake_ticks & 0xFFFFFFFF);
this->emu().reg(x64_register::rdx, (fake_ticks >> 32) & 0xFFFFFFFF);
return instruction_hook_continuation::skip_instruction;
});